如何绘制对象的特定或多个轮廓

时间:2018-12-02 14:46:36

标签: python opencv

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

输入图像:

enter image description here

代码:

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)

输出:

enter image description here

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

1 个答案:

答案 0 :(得分:2)

drawContours中将第三个参数更改为-1(第三个参数是轮廓的索引),这将在图像中绘制所有轮廓:

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

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

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