With the following code (which I have found in another stackoverflow post, and isn't mine), I am trying to copy a polygonal region from an image with the help of a mask. I am not very conversant with python's numpy array and having a very hard time figuring out how to create a transparent mask here. Currently, the code generates a black(#000000) mask. I have tried some post image processing with Python Wand something like that but the result is not desirable.
EDIT: here is the original post: NumPy/OpenCV 2: how do I crop non-rectangular region?
Here is my python wand code:
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")
here is the original code:
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()