1. 程式人生 > >python+opencv影象金字塔融合

python+opencv影象金字塔融合

本文參考《OpenCV-Python 中文教程》上的影象融合內容,在測試程式碼時執行有兩種錯誤,

第一個問題:應該是python版本問題

第二個問題:教程上的程式碼是做六層高斯金子塔,然後根據高斯金子塔在做拉普拉斯金字塔,在這過程中有圖片在某一層不能被二整除,導致維度不一致,出現錯誤。所以在做融合時圖片在每一層都能被二整除

我的解決方案:

1.通過改變程式碼,使程式碼能夠在python3.5上執行。

2.通過改變程式碼,使被融合的圖片不必每層都要被2整除

程式碼如下:

import cv2
import numpy as np,sys

A = cv2.imread('./data/apple.jpg')
B = cv2.imread('./data/orange.jpg')
print(type(A))
# generate Gaussian pyramid for A
G = A.copy()
print(G)
gpA = [G]
for i in range(6):
    G = cv2.pyrDown(G)
    gpA.append(G)
G = B.copy()
gpB = [G]
for i in range(6):
    G = cv2.pyrDown(G)
    gpB.append(G)
lpA = [gpA[5]]
for i in range(6,0,-1):
    print(i)
    GE = cv2.pyrUp(gpA[i])
    GE=cv2.resize(GE,gpA[i - 1].shape[-2::-1])
    L = cv2.subtract(gpA[i-1],GE)
    print(L.shape)
    lpA.append(L)
# generate Laplacian Pyramid for B
lpB = [gpB[5]]
for i in range(6,0,-1):
    print(i)
    GE = cv2.pyrUp(gpB[i])
    GE = cv2.resize(GE, gpB[i - 1].shape[-2::-1])
    L = cv2.subtract(gpB[i-1],GE)
    print(L.shape)
    lpB.append(L)
# Now add left and right halves of images in each level
LS = []
lpAc=[]
for i in range(len(lpA)):
    b=cv2.resize(lpA[i],lpB[i].shape[-2::-1])
    print(b.shape)
    lpAc.append(b)
print(len(lpAc))
print(len(lpB))
j=0
for i in zip(lpAc,lpB):
    print(i)
    print('ss')
    la,lb=i
    print(la)
    print(lb)
    rows,cols,dpt = la.shape
    ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))
    j=j+1
    print(j)
    LS.append(ls)
ls_ = LS[0]
for i in range(1,6):
    ls_ = cv2.pyrUp(ls_)
    ls_= cv2.resize(ls_, LS[i].shape[-2::-1])
    ls_ = cv2.add(ls_, LS[i])
# image with direct connecting each half
B= cv2.resize(B, A.shape[-2::-1])
real = np.hstack((A[:,:cols//2],B[:,cols//2:]))
cv2.imwrite('Pyramid_blending2.jpg',ls_)
cv2.imwrite('Direct_blending.jpg',real)

被融合圖片:

直接融合後結果:

影象金子塔融合後的結果: