利用图像金字塔进行图像混合,即实现实现自然过渡,又避免损失清晰度,加载两张要处理的图像,注意n层金字塔,要求图像大小是2的n次方的整数
img1 = cv.imread('./opencv_dataset/cv_01.jpg',3) # 灰色图像
A = img1[:448,:448,:] ## 注意图像尺寸的大小要能被64整除,因为我们要做6层
img2 = cv.imread('./opencv_dataset/cv_02.jpg',3) # 灰色图像
B = img2[:448,:448,:]
print(A.shape)
print(B.shape)
'''
(448, 448, 3)
(448, 448, 3)
'''
plt.subplot(1,2,1),plt.imshow(cv.cvtColor(A, cv.COLOR_BGR2RGB))
plt.title('A'), plt.xticks([]), plt.yticks([])
plt.subplot(1,2,2),plt.imshow(cv.cvtColor(B, cv.COLOR_BGR2RGB))
plt.title('B'), plt.xticks([]), plt.yticks([])
plt.show()
G = A.copy()
gpA = [G]
plt.subplot(2,3,1),plt.imshow(cv.cvtColor(gpA[0], cv.COLOR_BGR2RGB))
for i in range(5): # i=[0,6)
# print(i)
G = cv.pyrDown(G)
gpA.append(G)
plt.subplot(2,3,i+2),plt.imshow(cv.cvtColor(gpA[i+1], cv.COLOR_BGR2RGB))
plt.show()
len(gpA)#6
G = B.copy()
gpB = [G]
plt.subplot(2,3,1),plt.imshow(cv.cvtColor(gpB[0], cv.COLOR_BGR2RGB))
for i in range(5): # i=[0,6)
# print(i)
G = cv.pyrDown(G)
gpB.append(G)
plt.subplot(2,3,i+2),plt.imshow(cv.cvtColor(gpB[i+1], cv.COLOR_BGR2RGB))
plt.show()
len(gpB)#6
lpA = [gpA[5]]
plt.subplot(2,3,1),plt.imshow(cv.cvtColor(lpA[0], cv.COLOR_BGR2RGB))
for i in range(5,0,-1):
GE = cv.pyrUp(gpA[i])
L = cv.subtract(gpA[i-1],GE)
lpA.append(L)
plt.subplot(2,3,6-i+1),plt.imshow(cv.cvtColor(L, cv.COLOR_BGR2RGB))
plt.show()
lpB = [gpB[5]]
plt.subplot(2,3,1),plt.imshow(cv.cvtColor(lpB[0], cv.COLOR_BGR2RGB))
for i in range(5,0,-1):
GE = cv.pyrUp(gpB[i])
L = cv.subtract(gpB[i-1],GE)
lpB.append(L)
plt.subplot(2,3,6-i+1),plt.imshow(cv.cvtColor(L, cv.COLOR_BGR2RGB))
plt.show()
LS = []
i = 1
for la,lb in zip(lpA,lpB):
rows,cols,dpt = la.shape
ls = np.hstack((la[:,0:int(cols/2)], lb[:,int(cols/2):]))
LS.append(ls)
plt.subplot(2,3,i),plt.imshow(cv.cvtColor(ls, cv.COLOR_BGR2RGB))
i += 1
plt.show()
ls_ = LS[0] # ls_是最模糊的那张图像
plt.subplot(2,3,1),plt.imshow(cv.cvtColor(ls_, cv.COLOR_BGR2RGB))
for i in range(1,6):
ls_ = cv.pyrUp(ls_) # 加零,高斯模糊
ls_ = cv.add(ls_, LS[i]) # 加差值,提高分辨率
plt.subplot(2,3,i+1),plt.imshow(cv.cvtColor(ls_, cv.COLOR_BGR2RGB))
plt.show()
real = np.hstack((A[:,:int(cols/2)],B[:,int(cols/2):]))
# 对比两种处理的效果
plt.subplot(1,2,1),plt.imshow(cv.cvtColor(real, cv.COLOR_BGR2RGB))
plt.subplot(1,2,2),plt.imshow(cv.cvtColor(ls_, cv.COLOR_BGR2RGB))
plt.show()