|
a |
|
b/CLI/MusculoskeletalAnalysisCLITools/largestCC.py |
|
|
1 |
def largestCC(mask): |
|
|
2 |
"""Finds the largest connected component. |
|
|
3 |
|
|
|
4 |
Takes a binary numpy array. |
|
|
5 |
|
|
|
6 |
Returns the mask with only the largest component |
|
|
7 |
""" |
|
|
8 |
import numpy as np |
|
|
9 |
from skimage.measure import label |
|
|
10 |
|
|
|
11 |
# Creates a labelmap of the mask, where connected components have the same label |
|
|
12 |
labels = label(mask) |
|
|
13 |
# labels[np.nonzero(labels)] is a list of all nonzero values in the labelmap. np.argmax(np.bincount()) returns the most common number in that list. largest is set to a mask showing where the labelmap is equal to that value. |
|
|
14 |
largest = labels == np.argmax(np.bincount(labels[np.nonzero(labels)])) |
|
|
15 |
if np.count_nonzero(largest) == 0: |
|
|
16 |
# Throw an exception if the output mask is empty. This could happen if the input mask is also empty |
|
|
17 |
raise Exception("Largest connected component not found") |
|
|
18 |
return largest |