如何绘制对象的特定或多个轮廓 [英] How to draw particular or multiple contours of objects

查看:88
本文介绍了如何绘制对象的特定或多个轮廓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎找不到一种绘制多个对象轮廓的方法.

I can't seem to find a way to draw more than one contour of objects.

输入图像:

代码:

import cv2
import numpy as np

#import image
img = cv2.imread('img.png', 0)

#Thresh
ret, thresh = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)

#Finding the contours in the image
_, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

#Convert img to RGB and draw contour
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
cv2.drawContours(img, contours, 0, (0,0,255), 2)

#save output img
cv2.imwrite('output_img.png', img)

输出:

仅绘制较大的对象轮廓.我将如何绘制两个轮廓?

Only the larger object contour is drawn. How would I draw both contours?

推荐答案

在您的

Change the third parameter to -1(third argument is index of contours) in your drawContours which will draw all contours in your image:

cv2.drawContours(img, contours, -1, (0,0,255), 2)

如果只想绘制两个轮廓并且前两个轮廓是白色对象,请使用:

If you want to draw only two contours and the first two contours are of the white objects use:

cnt1 = contours[0]
cnt2 = contours[1]
cv2.drawContours(img, [cnt1, cnt2], -1, (0,0,255), 2)

这篇关于如何绘制对象的特定或多个轮廓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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