简体   繁体   English

Python OpenCV 找到最大轮廓

[英]Python OpenCV finding the biggest contour

I have a problem while looking for biggest contour.我在寻找最大轮廓时遇到问题。 I'm using image after canny edge detection:我在精明边缘检测后使用图像: Canny 边缘检测

Then I'm using然后我正在使用

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

to find contours:寻找轮廓:

轮廓检测

Next step is to find the biggest contour... I've tried:下一步是找到最大的轮廓......我试过了:

contour = max(contours, key = cv2.contourArea)

but this give me something like:但这给了我类似的东西:

在此处输入图像描述

Any ideas how to fix this?任何想法如何解决这一问题? Thanks!谢谢!

Code:代码:

import cv2
image = cv2.imread('TEST_1.png')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

gaussian = cv2.GaussianBlur(gray,(3,3),cv2.BORDER_DEFAULT)
edges = cv2.Canny(gaussian,100,200)

contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contour = max(contours, key = cv2.contourArea)

contourImg = cv2.drawContours(image, contour, -1, (0,255,0), 3)
cv2.imshow("Contours", contourImg)

cv2.waitKey(0)
cv2.destroyAllWindows()

Also, contour area for this dot is 109 and for my biggest contour is 3.5此外,这个点的轮廓面积是 109,我最大的轮廓是 3.5

Apparently it seems like some contours are not closed.显然,有些轮廓似乎没有闭合。 Using length as criterion rather than area in this case worked for me.在这种情况下,使用长度而不是面积作为标准对我有用。

import cv2
image = cv2.imread('TEST_1.png')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

gaussian = cv2.GaussianBlur(gray,(3,3),cv2.BORDER_DEFAULT)
edges = cv2.Canny(gaussian,100,200)

contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
contour = max(contours, key = len)

contourImg = cv2.drawContours(image, contour, -1, (0,255,0), 3)
cv2.imshow("Contours", contourImg)

cv2.waitKey(0)
cv2.destroyAllWindows()

I also changed the method in findContours from cv2.CHAIN_APPROX_SIMPLE to cv2.CHAIN_APPROX_NONE.我还将 findContours 中的方法从 cv2.CHAIN_APPROX_SIMPLE 更改为 cv2.CHAIN_APPROX_NONE。 Alternately, you try fixing the problem by changing the limit values in cv2.Canny() and using cv2.RETR_EXTERNAL.或者,您尝试通过更改 cv2.Canny() 中的限制值并使用 cv2.RETR_EXTERNAL 来解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM