填充轮廓的外部OpenCV [英] Fill the outside of contours OpenCV
问题描述
我正在尝试使用openCV和python语言将轮廓的外部区域涂成黑色. 这是我的代码:
I am trying to color in black the outside region of a contours using openCV and python language. Here is my code :
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? `
推荐答案
以下是在一组轮廓之外用黑色填充图像的方法:
Here's how you can fill an image with black color outside of a set of contours:
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)
UPD .:上面的代码利用了一个事实,即bitwise_and
的值为0-s会产生0-s,并且不适用于黑色以外的填充颜色.要填充任意颜色:
UPD.: The code above exploits the fact that bitwise_and
with 0-s produces 0-s, and won't work for fill colors other than black. To fill with an arbitrary color:
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
会用轮廓之外的相同倒置图像填充它:
Can fill with another image as well, for example, using img[sel] = ~img[sel]
instead of img[sel] = fill_color
would fill it with the same inverted image outside of the contours:
这篇关于填充轮廓的外部OpenCV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!