当我只绘制更大的轮廓对象时,Python Opencv drawContours 失败 [英] Python Opencv drawContours fail when I draw just the bigger contour object

查看:65
本文介绍了当我只绘制更大的轮廓对象时,Python Opencv drawContours 失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制最大物体的轮廓.

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)  

结果如下:

为什么轮廓没有连通?

提前致谢.

推荐答案

看到在你的代码中你通过 -1 参数告诉函数绘制你的所有轮廓,当你真正想要的时候只绘制 best 一个.因此,代替 -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)  

与:

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

或者你仍然可以使用-1,但是你将需要一组点作为参数([]):

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)  

您可以在 OpenCV 文档页面

这篇关于当我只绘制更大的轮廓对象时,Python Opencv drawContours 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆