SCDA_pytorch/util/largestConnectComponent.py
CaoGang2018 7e25bc99d5 init
2020-05-29 18:05:22 +08:00

37 lines
826 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from skimage.measure import label
import numpy as np
def largestConnectComponent(bw_img, neighbor=2):
'''
compute largest Connect component of a binary image
Parameters:
---
bw_img: ndarray
binary image
Returns:
---
lcc: ndarray
largest connect component.
Example:
---
>>> lcc = largestConnectComponent(bw_img)
'''
labeled_img, num = label(bw_img, connectivity=neighbor, background=0, return_num=True)
# plt.figure(), plt.imshow(labeled_img, 'gray')
max_label = 0
max_num = 0
for i in range(1, num+1): # 这里从1开始防止将背景设置为最大连通域
if np.sum(labeled_img == i) > max_num:
max_num = np.sum(labeled_img == i)
max_label = i
lcc = (labeled_img == max_label)
return lcc