为了账号安全,请及时绑定邮箱和手机立即绑定

cv2.findContours() 行为奇怪吗?

cv2.findContours() 行为奇怪吗?

慕的地10843 2021-08-17 16:12:42
我在图像中找到轮廓。对于我找到的每个轮廓,我打印出它的 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.5import cv2 import numpy as npimg = 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()
查看完整描述

1 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

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

所以一定要在黑色背景中找到白色物体的轮廓。添加cv2.bitwise_not()转换图像的功能。

. . .

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

. . .

输出:

//img1.sycdn.imooc.com//611b6fbb0001c48f03280339.jpg//img1.sycdn.imooc.com//611b6fc10001d71f03270342.jpg

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


查看完整回答
反对 回复 2021-08-17
  • 1 回答
  • 0 关注
  • 325 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号