【问题标题】:cv2.findContours() acts strangely?cv2.findContours() 行为奇怪?
【发布时间】:2018-11-14 08:31:36
【问题描述】:

我正在寻找图像中的轮廓。对于我找到的每个轮廓,我打印出它的边界矩形和区域,然后将其绘制到图像上。有趣的是,我发现已经绘制了 5 个轮廓,而只打印了 4 个轮廓。有谁知道这里发生了什么?

>>contour 1
>>(0, 0, 314, 326)
>>101538.5
>>contour 2
>>(75, 117, 60, 4)
>>172.0
>>contour 3
>>(216, 106, 3, 64)
>>124.0
>>contour 4
>>(62, 18, 138, 9)
>>383.5

import cv2 
import numpy as np

img = cv2.imread('1.png')

imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)

_, contours, hier = cv2.findContours(thresh, cv2.RETR_TREE, 
cv2.CHAIN_APPROX_SIMPLE)

for i,c in enumerate(contours):
    rect = cv2.boundingRect(c)
    area = cv2.contourArea(c)
    print("contour " + str(i+1))
    print(rect)
    print(area)

cv2.drawContours(img, contours, -1, (0,255,0), 1)

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

【问题讨论】:

    标签: python opencv contour


    【解决方案1】:

    cv2.RETR_TREE 是你得到这个的原因。它检索所有轮廓并创建完整的家庭层次结构列表。在轮廓检测中,您应该在黑色背景中使用白色物体。否则,由于层次结构列表,您会得到现在得到的结果。更多详情请查看documentation

    因此,请确保您找到黑色背景中的白色物体的轮廓。添加cv2.bitwise_not()函数转换图片。

    。 . .

    imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    cv2.bitwise_not(imgray,imgray)
    

    。 . .

    输出:

    4
    contour 1
    (76, 118, 58, 2)
    56.0
    contour 2
    (217, 107, 1, 62)
    0.0
    contour 3
    (63, 19, 136, 7)
    110.5
    contour 4
    (248, 1, 66, 45)
    55.5
    

    【讨论】:

    • 感谢您的回答。但我仍然想知道为什么它会绘制线条的轮廓但不打印出来。
    • 在您的情况下,也只有 4 个轮廓。 Top right contour 附加到图像的边界。所以它被认为是与边界一起的单个轮廓。
    猜你喜欢
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2015-11-21
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多