如何使用OpenCV和Python提取最大连通分量?

How to extract the largest connected component using OpenCV and Python?

我在 Python 中使用 OpenCV,以便能够仅识别图像上出现的叶子。我已经可以分割我的图像了,现在我卡在“如何在检测到所有的最大部分后裁剪最大的部分。下面是代码,请看一下。

  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()
    

然而,在这两种方法中,结果我仍然得到了不止一个组件。下面,您将找到二进制图像:

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

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()

组件上的循环现在会找到面积最大的组件并在循环结束时显示它。

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

使用 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])

更多信息: