Skip to content

Instantly share code, notes, and snippets.

@mistycheney
Last active April 13, 2016 02:45
Show Gist options
  • Save mistycheney/fa35f6ee15599558829e70f24d196197 to your computer and use it in GitHub Desktop.
Save mistycheney/fa35f6ee15599558829e70f24d196197 to your computer and use it in GitHub Desktop.
bounding box for 2d or 3d binary images
# http://stackoverflow.com/a/31402351
def bbox_2d(img):
rows = np.any(img, axis=1)
cols = np.any(img, axis=0)
rmin, rmax = np.where(rows)[0][[0, -1]]
cmin, cmax = np.where(cols)[0][[0, -1]]
return cmin, cmax, rmin, rmax
def bbox_3d(img):
r = np.any(img, axis=(1, 2))
c = np.any(img, axis=(0, 2))
z = np.any(img, axis=(0, 1))
rmin, rmax = np.where(r)[0][[0, -1]]
cmin, cmax = np.where(c)[0][[0, -1]]
zmin, zmax = np.where(z)[0][[0, -1]]
return cmin, cmax, rmin, rmax, zmin, zmax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment