如何使用OpenCV和Python提取最大的连接组件?

时间:2017-11-01 13:17:07

标签: python opencv image-segmentation

我在Python中使用OpenCV只能识别图像上显示的Leaf。我已经能够对我的图像进行分割,现在我正处于"在检测到所有这些图像后如何裁剪最大的组件。以下是代码,请看一下。

  1. 使用scipy.ndimage,找到组件后我无法前进:

    def undesired_objects ( image ):
        components, n = ndimage.label( image )
        components = skimage.morphology.remove_small_objects( components, min_size = 50 )
        components, n = ndimage.label( components )
        plot.imshow( components )
        plot.show()
    
  2. 使用OpenCV connectedComponentsWithStats:

    def undesired_objects ( image ):
        image = image.astype( 'uint8' )
        nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4)
        sizes = stats[1:, -1]; nb_components = nb_components - 1
        min_size = 150
        img2 = np.zeros(( output.shape ))
        for i in range(0, nb_components):
            if sizes[i] >= min_size:
                img2[output == i + 1] = 255
                plot.imshow( img2 )
                plot.show()
    
  3. 然而,在这两种方法中,我仍然得到多个组件。下面,您将找到二进制图像:

    Binary Image

2 个答案:

答案 0 :(得分:2)

我会用这样的代码替换你的代码:

def undesired_objects (image):
    image = image.astype('uint8')
    nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4)
    sizes = stats[:, -1]

    max_label = 1
    max_size = sizes[1]
    for i in range(2, nb_components):
        if sizes[i] > max_size:
            max_label = i
            max_size = sizes[i]

    img2 = np.zeros(output.shape)
    img2[output == max_label] = 255
    cv2.imshow("Biggest component", img2)
    cv2.waitKey()

组件上的循环现在找到具有最大区域的组件,并在循环结束时显示它。

告诉我这是否适合你,因为我自己没有测试过。

答案 1 :(得分:1)

使用cv2.CC_STAT_AREA来提高可读性:

# Connected components with stats.
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4)

# Find the largest non background component.
# Note: range() starts from 1 since 0 is the background label.
max_label, max_size = max([(i, stats[i, cv2.CC_STAT_AREA]) for i in range(1, nb_components)], key=lambda x: x[1])

更多内容:https://stackoverflow.com/a/35854198/650885