如何绘制物体的特定或多个轮廓

Art*_*nov 3 python opencv

我似乎找不到一种方法来绘制多个物体的轮廓。

输入图像:

在此输入图像描述

代码:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

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

Moh*_*ani 6

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

cv2.drawContours(img, contours, -1, (0,0,255), 2)
Run Code Online (Sandbox Code Playgroud)

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

cnt1 = contours[0]
cnt2 = contours[1]
cv2.drawContours(img, [cnt1, cnt2], -1, (0,0,255), 2)
Run Code Online (Sandbox Code Playgroud)