10

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? `
4

1 に答える 1

28

一連の輪郭の外側を黒色で画像を塗りつぶす方法は次のとおりです。

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_andwith 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)

ここに画像の説明を入力

別の画像で塗りつぶすこともできます。たとえば、img[sel] = ~img[sel]代わりにを使用img[sel] = fill_colorすると、輪郭の外側の同じ反転画像で塗りつぶされます。

ここに画像の説明を入力

于 2016-06-20T03:12:55.653 に答える