同态滤波器怎么同时处理一个文件夹里的所有图片
时间: 2024-03-09 17:49:39 浏览: 19
要同时处理一个文件夹里的所有图片,可以使用Python中的Pillow库来读取和写入图像,并将同态滤波器应用于每个图像。以下是一个基本的Python代码示例,演示如何使用Pillow和OpenCV库来读取和写入图像,以及如何应用同态滤波器:
```python
from PIL import Image
import cv2
import numpy as np
import os
# 定义同态滤波器函数
def homomorphic_filter(image, gamma_l, gamma_h, c):
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 对数变换
gray_log = np.log1p(gray)
# 傅里叶变换
img_fft = np.fft.fft2(gray_log)
# 中心化
img_fft_shift = np.fft.fftshift(img_fft)
# 构建滤波器
rows, cols = gray.shape
crow, ccol = int(rows/2), int(cols/2)
# 构建高斯滤波器
gauss = np.zeros((rows, cols))
for i in range(rows):
for j in range(cols):
gauss[i,j] = np.exp(-c*((i-crow)**2 + (j-ccol)**2)/(2*gamma_l**2))
# 构建带阻滤波器
H = (gamma_h - gamma_l)*(1-np.exp(-c*((np.arange(rows).reshape(-1,1)-crow)**2 + (np.arange(cols)-ccol)**2)/(2*gamma_h**2))) + gamma_l
# 滤波
img_fft_shift_filter = img_fft_shift * gauss * H
# 中心化逆变换
img_ifft_shift = np.fft.ifftshift(img_fft_shift_filter)
# 逆傅里叶变换
img_ifft = np.fft.ifft2(img_ifft_shift)
# 反对数变换
img_ifft_exp = np.expm1(np.real(img_ifft))
# 转换为0-255之间的整数
img_output = np.uint8(img_ifft_exp)
return img_output
# 定义文件夹路径
folder_path = '/path/to/folder'
# 遍历文件夹里的所有图片
for filename in os.listdir(folder_path):
# 检查文件类型
if filename.endswith('.jpg') or filename.endswith('.png') or filename.endswith('.jpeg'):
# 读取图像
img = cv2.imread(os.path.join(folder_path, filename))
# 处理图像
img_output = homomorphic_filter(img, gamma_l=0.1, gamma_h=1.5, c=1)
# 保存图像
Image.fromarray(img_output).save(os.path.join(folder_path, filename))
```
在这个脚本中,`homomorphic_filter`函数是一个自定义的同态滤波器函数,可以根据需要调整参数。`folder_path`变量是文件夹的路径,可以根据需要修改。脚本将遍历文件夹中的所有图像文件,应用同态滤波器,并将处理后的图像保存回原文件夹。