cv2.findContours() 行为异常?

cv2.findContours() acts strangely?

我正在查找图像中的轮廓。对于我找到的每个轮廓,我打印出它的边界矩形和区域,然后将其绘制到图像上。有趣的是,我发现已经绘制了 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()

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