SimpleITK: Extract largest Connected component from binary image

Hi,
I am trying to extract the largest connected component from a binary image / (delete all connected components but the largest one), I tried using the Label filters, but couldn’t make it work.

Thanks in advance!

Hello @pythonuser,

Here you go:

import SimpleITK as sitk

binary_image = sitk.Image([256,256], sitk.sitkUInt8)
binary_image[20:50, 25:125] = 1
binary_image[70:95, 40:60] = 1
binary_image[70:95, 80:140] = 1

# 1. Convert binary image into a connected component image, each component has an integer label.
# 2. Relabel components so that they are sorted according to size (there is an
#    optional minimumObjectSize parameter to get rid of small components).
# 3. Get largest connected componet, label==1 in sorted component image.
component_image = sitk.ConnectedComponent(binary_image)
sorted_component_image = sitk.RelabelComponent(component_image, sortByObjectSize=True)
largest_component_binary_image = sorted_component_image == 1

sitk.Show(sitk.Cast(binary_image,sitk.sitkFloat32) + 255, 'original')
sitk.Show(sitk.Cast(component_image,sitk.sitkFloat32) + 255, 'component')
sitk.Show(sitk.Cast(sorted_component_image,sitk.sitkFloat32) + 255, 'sorted component')
sitk.Show(sitk.Cast(largest_component_binary_image,sitk.sitkFloat32) + 255, 'largest component')

2 Likes

That works, Thank you!