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

Tar*_*ofl 5 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()
    
    Run Code Online (Sandbox Code Playgroud)
  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()
    
    Run Code Online (Sandbox Code Playgroud)

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

二进制图像

Sun*_*eef 6

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

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()
Run Code Online (Sandbox Code Playgroud)

组件上的循环现在会找到面积最大的组件并将其显示在循环的末尾。

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