Created
September 23, 2017 05:28
-
-
Save garybradski/fabe4ce7ed5c042988b748780393370c to your computer and use it in GitHub Desktop.
Blend one image with another using an alpha mask in python
This file contains hidden or 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) | |
# Multiply the background with ( 1 - alpha ) | |
background = cv2.multiply(1.0 - alpha, background) | |
# Add the masked foreground and background. | |
outImage = cv2.add(foreground, background) | |
# 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
Hi,
Getting the following error for alpha_mask_blend.py. Please help.
error Traceback (most recent call last)
in ()
75
76 image = cv2.imread('E:\Python\Img-Seg\s2.jpg')
---> 77 decode_segmap('E:\Python\Img-Seg\s2.jpg')
in decode_segmap(source, nc)
63
64 # Multiply the foreground with the alpha matte
---> 65 foreground = cv2.multiply(a, foreground)
66
67 # Multiply the background with ( 1 - alpha )
error: OpenCV(3.4.1) C:\Miniconda3\conda-bld\opencv-suite_1533128839831\work\modules\core\src\arithm.cpp:659: error: (-209) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function cv::arithm_op
And for garybradski reply:
ValueError Traceback (most recent call last)
in ()
75
76 image = cv2.imread('E:\Python\Img-Seg\s2.jpg')
---> 77 decode_segmap('E:\Python\Img-Seg\s2.jpg')
in decode_segmap(source, nc)
70 # Add the masked foreground and background
71 #outImage = cv2.add(foreground, background)
---> 72 blended = cv2.convertScaleAbs(foreground * a + background * (1-a))
73 # Return a normalized output image for display
74 return outImage/255
ValueError: operands could not be broadcast together with shapes (256,256,3,3) (256,256,1)