Skip to content

Instantly share code, notes, and snippets.

@royshil royshil/
Created Sep 29, 2017

What would you like to do?
Laplacian pyramid blending with a mask in OpenCV-Python
# adapted from
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)
# 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]))
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)
# 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)

This comment has been minimized.

Copy link

mezher14 commented Apr 18, 2018

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 ?


This comment has been minimized.

Copy link

linksyncjameshwartlopez commented Apr 30, 2018

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


This comment has been minimized.

Copy link

ChoWonmin commented Oct 2, 2018


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


This comment has been minimized.

Copy link

BogdanKOleinikov 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
You can’t perform that action at this time.