使用 OpenCV 从轮廓中获取掩码

get mask from contour with OpenCV

我想从轮廓中得到一个图像蒙版(它只存在 1 个轮廓)我已经计算了感谢 cv.findContours。

然而,虽然我的轮廓变量不为空,但我无法使用 cv.drawContours 检索图像遮罩,我的目标图像始终为空。

这是我的代码:

img = mosaicImage[:,:,0].astype('uint8')
contours, _ = cv.findContours(img.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
mask = np.zeros(img.shape, np.uint8)
cv.drawContours(mask, contours, -1, (0,255,0),1)

希望对你有所帮助!

谢谢

您正在为蒙版设置颜色 (0,255,0),但蒙版是单通道的,因此您使用颜色 0 绘制轮廓。

尝试

 cv.drawContours(mask, contours, -1, (255),1)

 cv.drawContours(mask, contours, -1, (255,255,255),1)