Skip to content

Instantly share code, notes, and snippets.

@stuarteberg
Last active December 19, 2023 09:51
Show Gist options
  • Save stuarteberg/8982d8e0419bea308326933860ecce30 to your computer and use it in GitHub Desktop.
Save stuarteberg/8982d8e0419bea308326933860ecce30 to your computer and use it in GitHub Desktop.
Compute a convex hull and create a mask from it
import numpy as np
import scipy
def fill_hull(image):
"""
Compute the convex hull of the given binary image and
return a mask of the filled hull.
Adapted from:
https://stackoverflow.com/a/46314485/162094
This version is slightly (~40%) faster for 3D volumes,
by being a little more stingy with RAM.
"""
# (The variable names below assume 3D input,
# but this would still work in 4D, etc.)
assert (np.array(image.shape) <= np.iinfo(np.int16).max).all(), \
f"This function assumes your image is smaller than {2**15} in each dimension"
points = np.argwhere(image).astype(np.int16)
hull = scipy.spatial.ConvexHull(points)
deln = scipy.spatial.Delaunay(points[hull.vertices])
# Instead of allocating a giant array for all indices in the volume,
# just iterate over the slices one at a time.
idx_2d = np.indices(image.shape[1:], np.int16)
idx_2d = np.moveaxis(idx_2d, 0, -1)
idx_3d = np.zeros((*image.shape[1:], image.ndim), np.int16)
idx_3d[:, :, 1:] = idx_2d
mask = np.zeros_like(image, dtype=bool)
for z in range(len(image)):
idx_3d[:,:,0] = z
s = deln.find_simplex(idx_3d)
mask[z, (s != -1)] = 1
return mask
@stuarteberg
Copy link
Author

I suppose this could be improved even further by limiting the analysis to the bounding-box of the convex hull, assuming the hull doesn't span the entire volume...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment