python - 填充轮廓 OpenCV 的外部

标签 python image python-2.7 opencv contour

我正在尝试使用 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? `

最佳答案

以下是如何在一组轮廓之外用黑色填充图像:

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)

enter image description here enter image description here

UPD.: 上面的代码利用了 bitwise_and 与 0-s 产生 0-s 的事实,并且不适用于黑色以外的填充颜色。填充任意颜色:

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)

enter image description here

也可以用另一个图像填充,例如,使用 img[sel] = ~img[sel] 而不是 img[sel] = fill_color 会填充它在轮廓外具有相同的倒置图像:

enter image description here

关于python - 填充轮廓 OpenCV 的外部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37912928/

相关文章:

image - 在 MATLAB 中标记图形上的特定点

python - Python 列表的问题

python - 使用格式运算符 % 将 RGB 值的 numpy 数组转换为十六进制

WPF DataGrid 图标和 bool 值

python - setuptools - 从相对路径从框架 bundle

java - 如何为swing应用程序设置图标图像?

Python - 如何添加初始 MP3 属性

python 2.7 : decode error output not utf-8 on a simple string

python - Django 后端中立的 DictCursor

python 带有可选参数的假设检验