1. 读入两幅图像,苹果和橘子
2. 构建苹果和橘子的高斯金字塔(6 层)
3. 根据高斯金字塔计算拉普拉斯金字塔
4. 在拉普拉斯的每一层进行图像融合(苹果的左边与橘子的右边融合)
5. 根据融合后的图像金字塔重建原始图像。
import cv2
import numpy as np
#这里图像必须是2的n次幂
A = cv2.imread(r'D:\python_OpenCV\apple.jpg')
A=cv2.resize(A,(512,512),interpolation=cv2.INTER_CUBIC)
B = cv2.imread(r'D:\python_OpenCV\orange.jpg')
B=cv2.resize(B,(512,512),interpolation=cv2.INTER_CUBIC)
# generate Gaussian pyramid for A
print(f'a size is:{A.size,A.shape}')
print(f'B size is:{B.size,B.shape}')
G = A.copy()
gpA = [G]
#生成7层的高斯金字塔
for i in range(6):
#进行高斯模糊向下采样
G = cv2.pyrDown(G)
print(f'G size is:{G.size, G.shape}')
gpA.append(G)
# print(gpA)
# generate Gaussian pyramid for B
G = B.copy()
gpB = [G]
for i in range(6):
G = cv2.pyrDown(G)
print(f'G size is:{G.size, G.shape}')
gpB.append(G)
# generate Laplacian Pyramid for A
lpA = [gpA[5]]
for i in range(5, 0, -1):
print(f'i is :{i}')
#从顶层开始,不断向上采样
GE = cv2.pyrUp(gpA[i])
print(f'GE size is:{GE.shape,GE.size}')
print(f'gpA{i-1} size is:{gpA[i - 1].shape,gpA[i - 1].size}')
#用下一层的高斯减去上上层高斯的上采样
L = cv2.subtract(gpA[i - 1], GE)
# 结果送给拉普拉斯金字塔
lpA.append(L)
# generate Laplacian Pyramid for B
lpB = [gpB[5]]
for i in range(5, 0, -1):
GE = cv2.pyrUp(gpB[i])
L = cv2.subtract(gpB[i - 1], GE)
lpB.append(L)
# Now add left and right halves of images in each level
# numpy.hstack(tup)
# Take a sequence of arrays and stack them horizontally to make a single array.
LS = []
#zip(lpA, lpB)把两个拉普拉斯金字塔的各层的两个图像组合成一个元祖,然后
#各个元祖构成一个ZIP
#对于各个元祖中的两个图像
for la, lb in zip(lpA, lpB):
#取la,lb的尺寸皆可
rows, cols, dpt = la.shape
#利用np.hstack将这两个图像“一半一半”的拼接起来
#取la的左半边和lb的右半边拼成融合后的图,结果给ls
ls = np.hstack((la[:, 0:cols // 2], lb[:, cols // 2:]))
#两个拉普拉斯金字塔各个层图融合后的结果给LS
LS.append(ls)
# now reconstruct
#用融合后的拉普拉斯金字塔重构最终图像
#初始化ls为融合后拉普拉斯金字塔最高层
#下面就是循环结束后ls就是要求的最终图像
ls_ = LS[0]
for i in range(1, 6):
#每层图像先向上采样,再和当前层的下一层图像相加,结果再赋给ls
ls_ = cv2.pyrUp(ls_)
ls_ = cv2.add(ls_, LS[i])
# image with direct connecting each half
#不用金字塔融合,直接生硬的连接两幅原始图样
real = np.hstack((A[:, :cols // 2], B[:, cols // 2:]))
cv2.imwrite('D:\python_OpenCV\Pyramid_blending2.jpg', ls_)
cv2.imwrite('D:\python_OpenCV\Direct_blending.jpg', real)