【问题标题】:Find contours of touching objects as two distinct contours将触摸对象的轮廓查找为两个不同的轮廓
【发布时间】:2020-07-09 13:15:00
【问题描述】:

我想知道如何在 Python 中使用 cv2.findContours 将相互连接的对象计算为两个不同的对象

例如这张图片:

contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

将输出一个轮廓。 我该怎么做才能得到两个轮廓?

【问题讨论】:

    标签: python opencv contour


    【解决方案1】:

    这可以通过将输入图像转换为边缘图像然后检测轮廓来完成。但是在这种情况下,在两个对象的交点处边缘图像(我用 canny 试过)有一个中断,如下所示。

    进入 Canny:

    而预期的边缘图像应将边界处的所有像素都设为白色。

    预期的边缘图像:

    为了得到这个完美的边缘图像,我创建了一个在下面共享的算法(这个算法只适用于像这样的二进制图像,对象填充为白色)。

    在使用此算法之前,请确保对象不位于边界上,即图像的所有边界像素应为黑色。如果不是黑色,则在黑色和长度为 1 像素的图像的所有边添加边框。

    # Creating black image of same shape and single channel
    edge = np.zeros(img.shape, dtype = np.uint8)
    h, w = img.shape[:2]
    
    # Iterating over each pixel except those at the boundary
    for i in range(1, h-1):
        for j in range(1, w-1):
            # if current pixel is white
            if img[i][j] == 255:
                # roi is the image of 9 pixel from around the current pixel
                roi = img[i-1:i+2, j-1:j+2].copy()
                # Counting number of black pixel in the neighbourhood of current pixel
                blackCount = np.sum(roi == 0)
                # if a neighbouring pixel is black, then current pixel is a boundary pixel.
                if blackCount > 0:
                    edge[i][j] = 255
    

    找到边缘图像后,得到图像中的所有轮廓:

    cont, hier = cv2.findContours(edge, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    

    对于此图像,您将获得 3 个轮廓,两个对象为 2 个,两个对象组合为 1 个。要消除两个组合对象的轮廓,请使用层次信息。

    # I am taking only those contours which do not have a child contour.
    finalContours = np.asarray([cont[i] for i in range(len(cont)) if hier[0][i][2] == -1])
    

    "finalContours" 将具有两个对象的 2 个轮廓。

    Refer to this link for more information about the parent-child relationship of the contours

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-22
      • 2021-06-08
      • 2012-12-08
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      相关资源
      最近更新 更多