Created
September 29, 2017 14:59
-
-
Save royshil/0b20a7dd08961c83e210024a4a7d841a to your computer and use it in GitHub Desktop.
Laplacian pyramid blending with a mask in OpenCV-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
# adapted from http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_pyramids/py_pyramids.html | |
import cv2 | |
import numpy as np | |
def Laplacian_Pyramid_Blending_with_mask(A, B, m, num_levels = 6): | |
# assume mask is float32 [0,1] | |
# generate Gaussian pyramid for A,B and mask | |
GA = A.copy() | |
GB = B.copy() | |
GM = m.copy() | |
gpA = [GA] | |
gpB = [GB] | |
gpM = [GM] | |
for i in xrange(num_levels): | |
GA = cv2.pyrDown(GA) | |
GB = cv2.pyrDown(GB) | |
GM = cv2.pyrDown(GM) | |
gpA.append(np.float32(GA)) | |
gpB.append(np.float32(GB)) | |
gpM.append(np.float32(GM)) | |
# generate Laplacian Pyramids for A,B and masks | |
lpA = [gpA[num_levels-1]] # the bottom of the Lap-pyr holds the last (smallest) Gauss level | |
lpB = [gpB[num_levels-1]] | |
gpMr = [gpM[num_levels-1]] | |
for i in xrange(num_levels-1,0,-1): | |
# Laplacian: subtarct upscaled version of lower level from current level | |
# to get the high frequencies | |
LA = np.subtract(gpA[i-1], cv2.pyrUp(gpA[i])) | |
LB = np.subtract(gpB[i-1], cv2.pyrUp(gpB[i])) | |
lpA.append(LA) | |
lpB.append(LB) | |
gpMr.append(gpM[i-1]) # also reverse the masks | |
# Now blend images according to mask in each level | |
LS = [] | |
for la,lb,gm in zip(lpA,lpB,gpMr): | |
ls = la * gm + lb * (1.0 - gm) | |
LS.append(ls) | |
# now reconstruct | |
ls_ = LS[0] | |
for i in xrange(1,num_levels): | |
ls_ = cv2.pyrUp(ls_) | |
ls_ = cv2.add(ls_, LS[i]) | |
return ls_ | |
if __name__ == '__main__': | |
A = cv2.imread("input1.png",0) | |
B = cv2.imread("input2.png",0) | |
m = np.zeros_like(A, dtype='float32') | |
m[:,A.shape[1]/2:] = 1 # make the mask half-and-half | |
lpb = Laplacian_Pyramid_Blending_with_mask(A, B, m, 5) | |
cv2.imwrite("lpb.png",lpb) |
@mezher14 you need m[:,int(A.shape[1]/2):]
hello!
It doesn't work for me
it gives an error:
LA = np.subtract(gpA[i-1], cv2.pyrUp(gpA[i]))
ValueError: operands could not be broadcast together with shapes (119,119) (120,120)
could you please help?
thank you
error with subtraction since when it is upscaled I don't get the same size.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
helo ,
It doesn't work for me
in fact it gives an error :
m[:,A.shape[1]/2:] = 1 # make the mask half-and-half
TypeError: slice indices must be integers or None or have an index method
Can u please help ?
thanks