Python Opencv drawContours fail when I draw just the bigger contour object

≯℡__Kan透↙ 提交于 2019-12-06 12:00:28

问题


I'm trying to draw the contour of the biggest object.

First I will show an image drawing all contours:

To find the biggest object I used this code:

maxsize = 0  
best = 0  
count = 0  
for cnt in contours:  
    if cv2.contourArea(cnt) > maxsize:  
        maxsize = cv2.contourArea(cnt)  
        best = count  
    count += 1  

cv2.drawContours(img_rgb, contours[best], -1, (0,0,255), 2)  

And the result is the next:

Why the contours are not connected?

Thanks in advance.


回答1:


See that on your code you are telling by the -1 parameter to the function draw all of your contours, when you actually wants to draw only the best one. So, instead of the -1 (all) you can simply ask for the function to draw the contour that you desire.

You can fix this problem replacing the line:

cv2.drawContours(img_rgb, contours[best], -1, (0,0,255), 2)  

with:

cv2.drawContours(img_rgb, contours, best, (0,0,255), 2)

or you can still use the -1, but then you are going to need as parameter a set of points ([]):

cv2.drawContours(img_rgb, [contours[best]], -1, (0,0,255), 2)  

You can have more information about this theme in the OpenCV Docs page



来源:https://stackoverflow.com/questions/27647664/python-opencv-drawcontours-fail-when-i-draw-just-the-bigger-contour-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!