圖片連通區域檢測(Label connected regions of an integer array)
更多關注:
1.原圖
2.連通區域結果
3.編碼實現
#coding=utf-8
from skimage import measure, color
import cv2
import numpy as np
import matplotlib.pyplot as plt
def detect(image):
label_img, num = measure.label(image, neighbors=8, background=0, return_num=True, connectivity=2)
return label_img, num
if __name__=='__main__':
in_image_path = 'binary.bmp'
out_image_path = 'labeled.bmp'
img = cv2.imread(in_image_path, 0)
assert img is not None
ret, thresh = cv2.threshold(img, 170, 255, cv2.THRESH_BINARY)
label_img, num = detect(thresh)
dst = color.label2rgb(label_img)
# plt.imshow(dst)
# print('for_debug: thresh.dtype={}, shape={}'.format(thresh.dtype, thresh.shape))
# cv2.imshow('1', label_img.astype(np.uint8))
cv2.imshow('1', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
# cv2.imwrite(out_image_path, label_img.astype(np.uint8))
PS: (有一個比較關鍵的問題)保存用作顯示效果的圖片最好是採用bmp格式,而jpg格式會對圖片進行灰度值的差值,查看時會出現很多小雜點。
4.去除小連通區域
函數格式:skimage.morphology.remove_small_objects(ar, min_size=64, connectivity=1, in_place=False)
參數:
ar: 待操作的bool型數組
min_size: 最小連通區域尺寸,小於該尺寸的都將被刪除。默認爲64
connectivity: 鄰接模式,1表示4鄰接,2表示8鄰接
in_place: bool型值,如果爲True,表示直接在輸入圖像中刪除小塊區域,否則進行復制後再刪除。默認爲False
返回刪除了小塊區域的二值圖像。