gpt4 book ai didi

python - 填充轮廓 OpenCV 的外部

转载 作者:太空狗 更新时间:2023-10-29 22:15:17 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com