图片连通区域检测(Label connected regions)与去除小连通区域(remove small regions)

图片连通区域检测(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
返回删除了小块区域的二值图像。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章