API
- skimage.measure
https://scikit-image.org/docs/dev/api/skimage.measure.html
out_arr 爲得到的結果mask矩陣。
from skimage import measure
labels = measure.label(out_arr, neighbors=8)
print(np.unique(labels))
[ 0 , 1 , 2 , 3 , 4 ]
0 爲背景
max_num = 0
for j in range(1, np.max(labels)+1):
if np.sum(labels==j) > max_num:
max_num = np.sum(labels==j)
max_pixel = j
if np.sum(labels==j)>0.1*np.sum(labels!=0):
labels[labels==j] = max_pixel
labels[labels != max_pixel]=0
labels[labels == max_pixel]=1
labels = np.array(labels,dtype=np.int8)
此時只保留了面積最大的聯通區域。
measure.label 有參數爲聯通選擇——neighbors
neighbors : {4, 8}, int, optional
Whether to use 4- or 8-“connectivity”. In 3D, 4-“connectivity” means connected pixels have to share face, whereas with 8-“connectivity”, they have to share only edge or vertex. Deprecated, use connectivity instead.