Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@royshil
Created September 29, 2017 14:59
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save royshil/0b20a7dd08961c83e210024a4a7d841a to your computer and use it in GitHub Desktop.
Save royshil/0b20a7dd08961c83e210024a4a7d841a to your computer and use it in GitHub Desktop.
Laplacian pyramid blending with a mask in OpenCV-Python
# 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
Copy link

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

@linksyncjameshwartlopez

@mezher14 you need m[:,int(A.shape[1]/2):]

@ChoWonmin
Copy link

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

@bowdawn
Copy link

bowdawn commented Apr 17, 2019

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