使用Python的fft2()函数进行图像的低通滤波处理
发布时间:2023-12-28 14:42:35
在Python中,图像的低通滤波处理可以使用fft2()函数来实现。fft2()函数是numpy库中的一个函数,用于对二维数组进行二维离散傅里叶变换。
下面是一个使用fft2()函数对图像进行低通滤波处理的示例:
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
# 读取图像
img = Image.open('input.jpg')
# 将图像转换为灰度图
gray_img = img.convert('L')
# 将灰度图转换为numpy数组
np_img = np.array(gray_img)
# 进行二维离散傅里叶变换
fft_img = np.fft.fft2(np_img)
# 将频谱中心移动到图片中心
fft_img = np.fft.fftshift(fft_img)
# 设置低通滤波器掩码
rows, cols = np_img.shape
crow, ccol = rows // 2, cols // 2
mask = np.zeros((rows, cols), np.uint8)
mask[crow - 30:crow + 30, ccol - 30:ccol + 30] = 1
# 将频谱与低通滤波器掩码相乘
fft_img = fft_img * mask
# 将频谱中心移动回原位
fft_img = np.fft.ifftshift(fft_img)
# 进行二维离散傅里叶逆变换
filtered_img = np.fft.ifft2(fft_img).real
# 幅度谱归一化
filtered_img = filtered_img / np.max(filtered_img) * 255
# 将numpy数组转换为图像
filtered_img = Image.fromarray(filtered_img.astype('uint8'))
# 显示处理结果
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.title('Original Image')
plt.subplot(1, 2, 2)
plt.imshow(filtered_img, cmap='gray')
plt.title('Filtered Image')
plt.show()
# 保存处理结果
filtered_img.save('output.jpg')
上述代码中,首先通过Image.open()函数读取输入图像,并通过convert()函数将图像转换为灰度图。然后,使用np.array()函数将灰度图转换为numpy数组。
接下来,使用np.fft.fft2()函数对numpy数组进行二维离散傅里叶变换,得到图像的频谱。为了使频谱中心对齐到图像中心,使用np.fft.fftshift()函数。
然后,创建一个与图像大小相同的掩码,将掩码内的值设为1,其余位置设为0。掩码定义了低通滤波器的形状。
将频谱与低通滤波器掩码相乘,然后使用np.fft.ifftshift()函数将频谱中心移回原位。
最后,使用np.fft.ifft2()函数进行二维离散傅里叶逆变换,得到经过低通滤波处理后的图像。为了将幅度谱归一化,将图像值除以最大值并乘以255。
最后,使用Image.fromarray()函数将numpy数组转换为图像,并使用Matplotlib库来显示原始图像和经过低通滤波处理后的图像。使用save()函数将处理结果保存为输出图像。
通过修改掩码的形状和大小,可以实现不同形状和大小的低通滤波器效果。
在实际应用中,可能需要对图像进行频谱修复以去除噪声、增强图像细节等。fft2()函数提供了一种方便的方式来处理图像频谱。需要注意的是,频谱修复处理可能会导致一些损失,因此在使用之前应该对图像进行备份。
