# SimpleITK: Extract largest Connected component from binary image

**URL:** https://discourse.itk.org/t/simpleitk-extract-largest-connected-component-from-binary-image/4958
**Category:** Beginner Questions
**Tags:** python, simpleitk
**Created:** [May 3, 2022, 3:05pm UTC](https://discourse.itk.org/t/simpleitk-extract-largest-connected-component-from-binary-image/4958 "2022-05-03T15:05:42Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![pythonuser](https://discourse.itk.org/letter_avatar_proxy/v4/letter/p/7ba0ec/32.png) [@pythonuser](https://discourse.itk.org/u/pythonuser)
#### Post date: [May 3, 2022, 3:05pm UTC](https://discourse.itk.org/t/simpleitk-extract-largest-connected-component-from-binary-image/4958/1 "2022-05-03T15:05:42Z")

</div>

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!

---

<div class="post-metadata">

### Author: ![zivy](https://discourse.itk.org/user_avatar/discourse.itk.org/zivy/32/1726_2.png) [@zivy](https://discourse.itk.org/u/zivy)
#### Post date: [May 3, 2022, 4:13pm UTC](https://discourse.itk.org/t/simpleitk-extract-largest-connected-component-from-binary-image/4958/2 "2022-05-03T16:13:23Z")

</div>

Hello @pythonuser,

Here you go:

```auto
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')

```

---

<div class="post-metadata">

### Author: ![pythonuser](https://discourse.itk.org/letter_avatar_proxy/v4/letter/p/7ba0ec/32.png) [@pythonuser](https://discourse.itk.org/u/pythonuser)
#### Post date: [May 3, 2022, 5:21pm UTC](https://discourse.itk.org/t/simpleitk-extract-largest-connected-component-from-binary-image/4958/3 "2022-05-03T17:21:39Z")

</div>

That works, Thank you!
