cv2.findContours() 行为奇怪吗?

我在图像中找到轮廓。对于我找到的每个轮廓,我打印出它的 bouding rect 和 area,然后将其绘制到图像上。有趣的是,我发现已经绘制了 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

http://img.mukewang.com/611b6f920001fdc603420352.jpghttp://img4.mukewang.com/611b6f9a000158a503360351.jpg

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


慕的地10843
浏览 326回答 1
1回答

撒科打诨

cv2.RETR_TREE是你得到这个的原因。它检索所有轮廓并创建完整的家庭层次结构列表。在轮廓检测中,您应该在黑色背景中使用白色物体。否则,由于层次结构列表,您将获得现在获得的结果。有关更多详细信息,请查看文档。所以一定要在黑色背景中找到白色物体的轮廓。添加cv2.bitwise_not()转换图像的功能。. . .imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.bitwise_not(imgray,imgray). . .输出:4contour 1(76, 118, 58, 2)56.0contour 2(217, 107, 1, 62)0.0contour 3(63, 19, 136, 7)110.5contour 4(248, 1, 66, 45)55.5
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python