OpenCV Python 使用Pyramid进行图像混合
通过使用图像Pyramid,可以最小化图像的不连续性,从而得到一个无缝融合的图像。
实现最终结果需要以下步骤:
首先加载图像并为两个图像找到高斯Pyramid。程序如下所示:
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)
从高斯Pyramid中获取相应的拉普拉斯Pyramid。程序如下-
# 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)
然后,将Pyramid每一层中第一张图像的左半部分与第二张图像的右半部分进行拼接。相应的程序如下:
# 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)
最后,从这个联合Pyramid中重建图像。以下是相同的程序-
ls_ = LS[0]
for i in range(1,6):
ls_ = cv2.pyrUp(ls_)
ls_ = cv2.add(ls_, LS[i])
cv2.imshow('RESULT',ls_)
输出
混合结果应如下: