写一个基于小波变换的图像融合代码,并附带评价指标结果
时间: 2024-10-25 09:03:03 浏览: 14
【信号隐藏】基于奇异值分解svd和小波变换算法求解水印嵌入提取附Matlab代码.zip
小波变换是一种处理信号和图像的强大工具,常用于图像融合中的去噪、特征提取等步骤。下面是一个简单的Python示例,使用PyWavelets库实现二维离散小波变换(DWT)并将两个图像融合:
```python
import numpy as np
from scipy.signal import wavedec2
from PIL import Image
# 加载图片
img1 = Image.open('image1.jpg').convert('L')
img2 = Image.open('image2.jpg').convert('L')
# 将图片转换为灰度数组
arr1 = np.array(img1)
arr2 = np.array(img2)
# 定义小波级数分解次数
level = 4
# 对两个图像分别进行小波分解
coeffs1 = wavedec2(arr1, level=level)
coeffs2 = wavedec2(arr2, level=level)
# 设定阈值,这里简单地采用平均值作为参考
threshold = (coeffs1[level-1].std() + coeffs2[level-1].std()) / 2
# 合并系数:将较大的幅值选择为合并后的系数
merged_coeffs = [np.where(np.abs(coeffs1[l]) > np.abs(coeffs2[l]), coeffs1[l], coeffs2[l])
for l in range(level)]
# 进行重构得到融合后的图像
reconstructed_img = np.abs(wavedec22id(merged_coeffs, shape=arr1.shape))
# 融合图像转回PIL格式
fused_image = Image.fromarray(reconstructed_img.astype('uint8'))
# 显示原图和融合后的图像
fused_image.show()
# 评价指标:
# PSNR (Peak Signal-to-Noise Ratio) - 可计算两个图像的对比度
psnr = compare_psnr(arr1, reconstructed_img)
print(f"PSNR: {psnr} dB")
# SSIM (Structural Similarity Index) - 测量结构相似性
ssim = compare_ssim(arr1, reconstructed_img)
print(f"SSIM: {ssim}")
def compare_psnr(image1, image2):
mse = np.mean((image1 - image2) ** 2)
if mse == 0:
return float("inf")
else:
return 20 * np.log10(255.0 / np.sqrt(mse))
def compare_ssim(image1, image2):
from skimage.measure import compare_ssim as sk_compare_ssim
return sk_compare_ssim(image1, image2, multichannel=True)
阅读全文