You can use pillow
and putalpha
to add grayscale image (L
) to RGB image as alpha
channel - so it will have transparent background. But both images have to be the same size.
from PIL import Image
# load images
img_org = Image.open('temple.jpg')
img_mask = Image.open('heart.jpg')
# convert images
#img_org = img_org.convert('RGB') # or 'RGBA'
img_mask = img_mask.convert('L') # grayscale
# the same size
img_org = img_org.resize((400,400))
img_mask = img_mask.resize((400,400))
# add alpha channel
img_org.putalpha(img_mask)
# save as png which keeps alpha channel
img_org.save('output-pillow.png')
BTW:
You can use other functions in pillow
to resize only mask and keep original proportions of heart.
Black color give full transparent, white color keep original color, but you can also gray colors to make pixel half-transparent.
EDIT:
The same with cv2
import cv2
# load images
img_org = cv2.imread('temple.jpg')
img_mask = cv2.imread('heart.jpg')
# convert colors
#img_org = cv2.cvtColor(img_org, ???)
img_mask = cv2.cvtColor(img_mask, cv2.COLOR_BGR2GRAY)
# the same size
img_org = cv2.resize(img_org, (400,400))
img_mask = cv2.resize(img_mask, (400,400))
# add alpha channel
b, g, r = cv2.split(img_org)
img_output = cv2.merge([b, g, r, img_mask], 4)
# write as png which keeps alpha channel
cv2.imwrite('output-cv2.png', img_output)
BTW: cv2
uses BGR
instead og RGB
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…