-
-
Save Nerdyvedi/1d3a1f90ef4ee6ed484f641caea4139c to your computer and use it in GitHub Desktop.
Blend one image with another using an alpha mask in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
# Read the images | |
foreground = cv2.imread("puppets.png") | |
background = cv2.imread("ocean.png") | |
alpha = cv2.imread("puppets_alpha.png") | |
# Convert uint8 to float | |
foreground = foreground.astype(float) | |
background = background.astype(float) | |
# Normalize the alpha mask to keep intensity between 0 and 1 | |
alpha = alpha.astype(float)/255 | |
# Multiply the foreground with the alpha matte | |
foreground = cv2.multiply(alpha, foreground) | |
width = background.shape[0] | |
height = background.shape[1] | |
alpha_full = cv2.getStructuringElement(cv2.MORPH_RECT,(height,width)) | |
alpha_full = 1.0 - alpha_full | |
foreground_full = alpha_full | |
alpha_full[:alpha_w,:alpha_h] = alpha[:,:,0] | |
#Multiply the background with (1-alpha) | |
for i in range(3): | |
background[:,:,i] = cv2.multiply(1.0 - alpha_full, background[:,:,i]) | |
# Add the masked foreground and background. | |
outImage = background | |
for i in range(3): | |
foreground_full[:alpha_w,:alpha_h] = foreground[:,:,i] | |
outImage[:,:,i] = cv2.add(foreground_full, background[:,:,i]) | |
# Display image | |
cv2.imshow("outImg", outImage/255) | |
cv2.waitKey(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment