Python Opencv drawContours fail when I draw just t

2020-07-25 06:40发布

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

First I will show an image drawing all contours:

All contours objects

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: Contours of biggest object

Why the contours are not connected?

Thanks in advance.

1条回答
Anthone
2楼-- · 2020-07-25 07:22

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

查看更多
登录 后发表回答