在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()
函数构建拉普拉斯金字塔。最后显示金字塔的每一层。