Opencv Python 简明教程

OpenCV Python - Image Blending with Pyramids

通过使用图像金字塔可以最大程度减少图像的不连续性。这将产生无缝融合的图像。

采取以下步骤来实现最终结果 −

首先加载图像并为两幅图像寻找高斯金字塔。以下是执行此操作的程序 -

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)

从高斯金字塔获取相应的拉普拉斯金字塔。以下是执行此操作的程序 -

# 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)

然后,在金字塔中的每个层中将第一张图像的左半部分与第二张图像的右半部分结合在一起。因此,该程序如下所示 −

# 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)

最后,从这个联合金字塔中重建图像。因此,该程序如下所示 −

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

Output

混合后的结果应如下所示 −

blending pyramids