拉普拉斯金字塔加权融合代码
时间: 2023-06-21 11:08:52 浏览: 44
图像拉普拉斯金字塔融合算法源代码
4星 · 用户满意度95%
以下是拉普拉斯金字塔加权融合的Python代码:
```python
import cv2
import numpy as np
# 生成高斯金字塔
def generate_gaussian_pyramid(image, levels):
pyramid = [image]
for i in range(levels - 1):
image = cv2.pyrDown(image)
pyramid.append(image)
return pyramid
# 生成拉普拉斯金字塔
def generate_laplacian_pyramid(image, levels):
gaussian_pyramid = generate_gaussian_pyramid(image, levels)
pyramid = []
for i in range(levels - 1):
expanded = cv2.pyrUp(gaussian_pyramid[i + 1])
laplacian = cv2.subtract(gaussian_pyramid[i], expanded)
pyramid.append(laplacian)
pyramid.append(gaussian_pyramid[-1])
return pyramid
# 加权融合
def weighted_fusion(laplacian_pyramid_1, laplacian_pyramid_2, mask_pyramid):
fused_pyramid = []
for i in range(len(mask_pyramid)):
weight1 = mask_pyramid[i] / 255.0
weight2 = 1.0 - weight1
fused = cv2.addWeighted(laplacian_pyramid_1[i], weight1, laplacian_pyramid_2[i], weight2, 0)
fused_pyramid.append(fused)
return fused_pyramid
# 重建图像
def reconstruct_image(pyramid):
image = pyramid[-1]
for i in range(len(pyramid) - 2, -1, -1):
image = cv2.pyrUp(image)
image = cv2.add(image, pyramid[i])
return image
# 加载两张图片和掩膜
image1 = cv2.imread('image1.jpg')
image2 = cv2.imread('image2.jpg')
mask = cv2.imread('mask.jpg', 0)
# 将掩膜转换为三通道
mask = cv2.merge((mask, mask, mask))
# 生成拉普拉斯金字塔和掩膜金字塔
levels = 6
laplacian_pyramid_1 = generate_laplacian_pyramid(image1, levels)
laplacian_pyramid_2 = generate_laplacian_pyramid(image2, levels)
mask_pyramid = generate_gaussian_pyramid(mask, levels)
# 加权融合
fused_pyramid = weighted_fusion(laplacian_pyramid_1, laplacian_pyramid_2, mask_pyramid)
# 重建图像
fused_image = reconstruct_image(fused_pyramid)
# 显示结果
cv2.imshow('Fused Image', fused_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`generate_gaussian_pyramid` 用于生成高斯金字塔,`generate_laplacian_pyramid` 用于生成拉普拉斯金字塔,`weighted_fusion` 用于加权融合,`reconstruct_image` 用于重建图像。在代码中,我们首先加载了两张图片和一个掩膜,然后将掩膜转换为三通道,接着生成拉普拉斯金字塔和掩膜金字塔,并使用 `weighted_fusion` 函数进行加权融合,最后使用 `reconstruct_image` 函数重建图像,并显示结果。
阅读全文