使用以下代码(我在另一个stackoverflow帖子中找到,并且不是我的),我试图在掩码的帮助下从图像复制多边形区域。我不太熟悉python的numpy数组,并且很难搞清楚如何在这里创建透明蒙版。目前,代码生成黑色(#000000)掩码。我已经尝试过使用Python Wand的一些后期图像处理,但结果是不可取的。
编辑:这是原帖:NumPy/OpenCV 2: how do I crop non-rectangular region?
这是我的python魔杖代码:
from wand.image import Image
from wand.color import Color
from wand.drawing import Drawing
from wand.compat import nested
with Image(filename="image_masked.png") as img:
img.format = "png"
with Color("#000000") as black:
twenty_percent = int(65535*0.2) # Note: percent must be calculated from Quantum
img.transparent_color(black, alpha=0.0, fuzz=twenty_percent)
img.save(filename="transparent.png")
这是原始代码:
import cv2
import numpy as np
# original image
# -1 loads as-is so if it will be 3 or 4 channel as the original
image = cv2.imread('input_image.jpg', -1)
# mask defaulting to black for 3-channel and transparent for 4-channel
# (of course replace corners with yours)
mask = np.zeros(image.shape, dtype=np.uint8)
roi_corners = np.array([[(2320,330), (0,90), (0,450), (0,550)]],dtype=np.int32)
# fill the ROI so it doesn't get wiped out when the mask is applied
channel_count = image.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,)*channel_count
cv2.fillPoly(mask, roi_corners, ignore_mask_color)
# apply the mask
masked_image = cv2.bitwise_and(image, mask)
# save the result
cv2.imwrite('image_masked.png', masked_image)
cv2.imshow('image',masked_image)
cv2.waitKey(0)
cv2.destroyAllWindows()