English 中文(简体)
OpenCV Python - Image Blending
  • 时间:2024-09-17

OpenCV Python - Image Blending with Pyramids


Previous Page Next Page  

The discontinuity of images can be minimised by the use of image pyramids. This results in a seamless blended image.

Following steps are taken to achieve the final result −

First load the images and find Gaussian pyramids for both. The program for the same is as follows −


import cv2
import numpy as np,sys

kalam = cv2.imread( kalam.jpg )
einst = cv2.imread( einstein.jpg )
### generate Gaussian pyramid for first
G = kalam.copy()
gpk = [G]
for i in range(6):
   G = cv2.pyrDown(G)
   gpk.append(G)
# generate Gaussian pyramid for second
G = einst.copy()
gpe = [G]
for i in range(6):
   G = cv2.pyrDown(G)
   gpe.append(G)

From the Gaussian pyramids, obtain the respective Laplacian Pyramids. The program for the same is as follows −


# generate Laplacian Pyramid for first
lpk = [gpk[5]]
for i in range(5,0,-1):
   GE = cv2.pyrUp(gpk[i])
   L = cv2.subtract(gpk[i-1],GE)
   lpk.append(L)

# generate Laplacian Pyramid for second
lpe = [gpe[5]]
for i in range(5,0,-1):
   GE = cv2.pyrUp(gpe[i])
   L = cv2.subtract(gpe[i-1],GE)
   lpe.append(L)

Then, join the left half of the first image with the right half of second in each level of pyramids. The program for the same is as follows −


# Now add left and right halves of images in each level
LS = []
for la,lb in zip(lpk,lpe):
   rows,cols,dpt = la.shape
   ls = np.hstack((la[:,0:int(cols/2)], lb[:,int(cols/2):]))
   LS.append(ls)

Finally, reconstruct the image from this joint pyramid. The program for the same is given below −


ls_ = LS[0]
for i in range(1,6):
   ls_ = cv2.pyrUp(ls_)
   ls_ = cv2.add(ls_, LS[i])
   cv2.imshow( RESULT ,ls_)

Output

The blended result should be as follows −

Blending Pyramids Advertisements