Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jpeoples/43682a7c0251184f75ae047ed9394488 to your computer and use it in GitHub Desktop.
Save jpeoples/43682a7c0251184f75ae047ed9394488 to your computer and use it in GitHub Desktop.
Getting the connected components from a 3D segmentation mask with SimpleITK
import SimpleITK as sitk
def get_components(mask):
f = sitk.ConnectedComponentImageFilter()
labeled = f.Execute(mask)
count = f.GetObjectCount()
return count, labeled

The SimpleITK library has an easy to use class for computing connected components in a segmentation mask: sitk.ConnectedComponentImageFilter.

Here is a sample usage (here the “mask” argument would be a binary mask (0 = background, 1 = foreground)

def get_components(mask):
    f = sitk.ConnectedComponentImageFilter()
    labeled = f.Execute(mask)
    count = f.GetObjectCount()
    return count, labeled

That function returns the number of connected components and a mask image with the components separated (i.e. background is 0, first component is 1, second component is 2, etc, up to count components). You can then get the mask for each one like

for i in range(1, count+1):
    mask_i = labeled==i
from components import get_components
def yield_all_components(mask):
"""Yield all connected components in mask, sequentially."""
count, labeled = get_components(mask)
for i in range(1, i+1):
yield labeled == i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment