轮廓外部填充OpenCV

15

我正在尝试使用openCV和Python语言将轮廓外部区域着色为黑色。以下是我的代码:

contours, hierarchy = cv2.findContours(copy.deepcopy(img_copy),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt=contours[max_index]
# how to fill of black the outside of the contours cnt please? `
1个回答

36

以下是如何在一组轮廓之外填充黑色颜色的图像的方法:

import cv2
import numpy
img = cv2.imread("zebra.jpg")
stencil = numpy.zeros(img.shape).astype(img.dtype)
contours = [numpy.array([[100, 180], [200, 280], [200, 180]]), numpy.array([[280, 70], [12, 20], [80, 150]])]
color = [255, 255, 255]
cv2.fillPoly(stencil, contours, color)
result = cv2.bitwise_and(img, stencil)
cv2.imwrite("result.jpg", result)

图片描述在此 图片描述在此

更新:上面的代码利用了bitwise_and与0相结合会产生0这一事实,对于除黑色填充颜色以外的颜色不起作用。要使用任意颜色进行填充:

import cv2
import numpy

img = cv2.imread("zebra.jpg")

fill_color = [127, 256, 32] # any BGR color value to fill with
mask_value = 255            # 1 channel white (can be any non-zero uint8 value)

# contours to fill outside of
contours = [ numpy.array([ [100, 180], [200, 280], [200, 180] ]), 
             numpy.array([ [280, 70], [12, 20], [80, 150]])
           ]

# our stencil - some `mask_value` contours on black (zeros) background, 
# the image has same height and width as `img`, but only 1 color channel
stencil  = numpy.zeros(img.shape[:-1]).astype(numpy.uint8)
cv2.fillPoly(stencil, contours, mask_value)

sel      = stencil != mask_value # select everything that is not mask_value
img[sel] = fill_color            # and fill it with fill_color

cv2.imwrite("result.jpg", img)

在此输入图片描述

也可以使用另一张图片填充,例如,使用img [sel] = ~ img [sel] 而不是 img [sel] = fill_color 将使用相同的反转图像填充轮廓外部:

在此输入图片描述


1
谢谢兄弟,我很感激。无论何时你在丹佛,联系我,我会帮你的。 - Bill
@Bill 如果这个回答解决了你的问题,请接受/点赞。不需要客气 ;D - Miki
2
@Miki,别碰我的喜好,当你得到它们时请拒绝! :) - Headcrab
1
@Headcrab 我真的很抱歉... 无论何时你在米兰,都联系我。我会帮你一个忙 ;D - Miki
如果您使用cv2.imread()函数加载普通的jpeg图像,白色的颜色值可能是[255, 255, 255]。或者对于单通道图像,仅为255 - Headcrab
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接