在OpenCV中,可以使用cv2.pyrDown()
和cv2.pyrUp()
函數來構建圖像金字塔。
import cv2
# 讀取圖像
image = cv2.imread('image.jpg')
# 構建高斯金字塔
layer = image.copy()
gaussian_pyramid = [layer]
for i in range(6):
layer = cv2.pyrDown(layer)
gaussian_pyramid.append(layer)
# 顯示高斯金字塔
for i in range(6):
cv2.imshow('Gaussian Pyramid Layer '+str(i), gaussian_pyramid[i])
cv2.waitKey(0)
# 構建拉普拉斯金字塔
laplacian_pyramid = [gaussian_pyramid[5]]
for i in range(5, 0, -1):
size = (gaussian_pyramid[i - 1].shape[1], gaussian_pyramid[i - 1].shape[0])
laplacian = cv2.subtract(gaussian_pyramid[i - 1], cv2.pyrUp(gaussian_pyramid[i], dstsize=size))
laplacian_pyramid.append(laplacian)
# 顯示拉普拉斯金字塔
for i in range(6):
cv2.imshow('Laplacian Pyramid Layer '+str(i), laplacian_pyramid[i])
cv2.waitKey(0)
cv2.destroyAllWindows()
這段代碼首先讀取圖像,然后使用cv2.pyrDown()
函數構建高斯金字塔,接著通過減法和cv2.pyrUp()
函數構建拉普拉斯金字塔。最后顯示金字塔的每一層。