I managed to generate a mask from a PNG transparent image and to use it in order to generate a transparent area on another photo.
This is the image that I use for generating the mask (is a frame with transparent area):
After some resize to match the size of the picture the mask is:
This is almost perfect because I have the original picture and the area covered by the masked became transparent but I need to have just the corners transparent without the border.
I want to trim/crop a rectangular based on transparent pixel and in the end to obtain this:
The result should be the equivalent of Photoshop function Image -> Trim, Based on transparent pixels, trim away top, bottom, left, right:
How I can accomplish this using my code? The masks will have many shapes and sizes.
Here is my python with opencv code:
import cv2
import numpy as np
#load image with alpha channel. use IMREAD_UNCHANGED to ensure loading of alpha channel
image = cv2.imread('rama1.png', cv2.IMREAD_UNCHANGED)
poza = cv2.imread("poza1.jpg")
#make images of same size
image = cv2.resize(image, poza.shape[1::-1])
#make mask of where the transparent bits are
trans_mask = image[:,:,3] != 0
#replace areas of transparency with white and not transparent
image[trans_mask] = [0, 0, 0,0]
#new image without alpha channel...
new_img = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
thresh, image_black = cv2.threshold(new_img, 200, 255, cv2.THRESH_BINARY)
image_black = cv2.cvtColor(image_black, cv2.COLOR_BGR2GRAY)
final = cv2.bitwise_and(poza,poza, mask= image_black)
cv2.imwrite('result before.png', final)
final = cv2.cvtColor(final, cv2.COLOR_BGR2BGRA)
final[:,:,3] = image_black #Set mask as alpha channel
cv2.imwrite('result.png', final)
cv2.imshow('image.jpeg', final)
cv2.waitKey(0)