如何使用OpenCV和Python提取最大的连接组件? [英] How to extract the largest connected component using OpenCV and Python?

查看:183
本文介绍了如何使用OpenCV和Python提取最大的连接组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python中使用OpenCV来仅识别图像上显示的Leaf.我已经可以分割图像了,现在我的工作是在检测到所有图像后如何裁剪最大的图像.下面是代码,请看一下.

I am using OpenCV in Python to be able to identify only the Leaf presented on the image. I already be able to segment my image, and now I am currently stuck at "how to crop the largest component after I have detected all of them. Below is the codes, please have a look.

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

  1. Using scipy.ndimage, I was unable to advance after find the components:

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

  • 使用OpenCV connectedComponentsWithStats:

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

  • 但是,在两种方法中,我仍然得到了不止一个组件.在下面,您将找到二进制图像:

    However, in both approaches, I'm still getting more than one component as result. Below, you will find the binary image:

    推荐答案

    我将用以下代码替换您的代码:

    I would replace your code with something like this:

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

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

    The loop on components now finds the component with the biggest area and displays it at the end of the loop.

    告诉我是否对您有用,因为我自己还没有测试过.

    Tell me if this works for you as I haven't tested it myself.

    这篇关于如何使用OpenCV和Python提取最大的连接组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆