小波变换批量图像融合python代码
时间: 2023-06-12 14:06:37 浏览: 185
以下是基于PyWavelets库实现的小波变换批量图像融合Python代码:
```python
import os
import numpy as np
import cv2
import pywt
# 小波变换融合函数
def wavelet_fusion(img1, img2, method='max', level=1, wavelet='haar'):
# 将图像转换为灰度图
img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 将图像进行小波分解
coeffs1 = pywt.wavedec2(img1_gray, wavelet, mode='symmetric', level=level)
coeffs2 = pywt.wavedec2(img2_gray, wavelet, mode='symmetric', level=level)
# 将第一幅图像的低频系数与第二幅图像的高频系数进行合并
fused_coeffs = []
for i in range(len(coeffs1)):
if i == 0:
fused_coeffs.append(coeffs1[0])
else:
if method == 'max':
fused_coeffs.append(np.maximum(coeffs1[i], coeffs2[i]))
elif method == 'min':
fused_coeffs.append(np.minimum(coeffs1[i], coeffs2[i]))
elif method == 'mean':
fused_coeffs.append((coeffs1[i] + coeffs2[i]) / 2)
# 将合并后的系数进行小波重构
fused_img = pywt.waverec2(fused_coeffs, wavelet)
# 将图像进行归一化
fused_img = cv2.normalize(fused_img, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
return fused_img
# 批量图像融合函数
def batch_fusion(img_dir, method='max', level=1, wavelet='haar'):
# 读取所有图像
img_names = os.listdir(img_dir)
img_names.sort()
imgs = []
for img_name in img_names:
img_path = os.path.join(img_dir, img_name)
img = cv2.imread(img_path)
imgs.append(img)
# 进行图像融合
fused_img = imgs[0]
for img in imgs[1:]:
fused_img = wavelet_fusion(fused_img, img, method, level, wavelet)
return fused_img
# 测试函数
if __name__ == '__main__':
img_dir = 'image_folder'
fused_img = batch_fusion(img_dir, method='max', level=1, wavelet='haar')
cv2.imshow('Fused Image', fused_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`wavelet_fusion`函数实现了单幅图像的小波变换融合,`batch_fusion`函数实现了批量图像融合,`method`参数指定了融合方式(最大值、最小值或平均值),`level`参数指定了小波变换的层数,`wavelet`参数指定了小波基函数。在测试函数中,将融合后的图像显示出来。
阅读全文