编写一个使用拉普拉斯金字塔实现图像融合的代码
时间: 2023-11-28 22:47:29 浏览: 42
好的,以下是一个使用拉普拉斯金字塔实现图像融合的 Python 代码示例:
``` python
import cv2
import numpy as np
# 定义生成拉普拉斯金字塔的函数
def laplacian_pyramid(image, levels):
pyramid = [image]
for i in range(levels):
# 缩小图像
image = cv2.pyrDown(image)
# 扩大图像
expanded_image = cv2.pyrUp(image)
# 计算差值
laplacian = cv2.subtract(image, expanded_image[:image.shape[0], :image.shape[1]])
pyramid.append(laplacian)
return pyramid
# 定义图像融合函数
def image_blend(image1, image2, levels):
# 生成拉普拉斯金字塔
image1_pyramid = laplacian_pyramid(image1, levels)
image2_pyramid = laplacian_pyramid(image2, levels)
blended_pyramid = []
# 融合每一层图像
for i in range(levels+1):
blended = cv2.addWeighted(image1_pyramid[i], 0.5, image2_pyramid[i], 0.5, 0)
blended_pyramid.append(blended)
# 重建图像
blended_image = blended_pyramid[levels]
for i in range(levels-1, -1, -1):
blended_image = cv2.pyrUp(blended_image)
blended_image = cv2.add(blended_pyramid[i][:blended_image.shape[0], :blended_image.shape[1]], blended_image)
return blended_image
# 读取两张图像
image1 = cv2.imread('image1.jpg')
image2 = cv2.imread('image2.jpg')
# 设置金字塔层数
levels = 5
# 融合图像
blended_image = image_blend(image1, image2, levels)
# 显示结果
cv2.imshow('Image 1', image1)
cv2.imshow('Image 2', image2)
cv2.imshow('Blended Image', blended_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
使用时,只需要将需要融合的两张图像以及金字塔层数传入 `image_blend` 函数即可。