欢迎访问宙启技术站
智能推送

利用Python的fft2()函数对图像进行频域滤波处理

发布时间:2023-12-28 14:43:45

频域滤波是一种常用的图像处理方法,它将图像从空域转换为频域,通过在频域对图像进行滤波操作来改变图像的频谱分布,从而实现对图像的增强、去噪、锐化等处理。

Python中的fft2()函数可以用于对图像进行二维离散傅里叶变换(Discrete Fourier Transform,DFT)。DFT是一种数学变换,它将图像从空域转换为频域,通过计算图像在不同频率下的幅度和相位信息,可以得到图像的频谱。

下面是一个利用Python的fft2()函数对图像进行频域滤波处理的示例代码:

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

# 读取图像并转为灰度图像
image = Image.open('image.jpg')
gray_image = image.convert('L')

# 将灰度图像转为数组
image_array = np.array(gray_image)

# 进行二维离散傅里叶变换
fft_image = np.fft.fft2(image_array)

# 将频谱中心移到图像的中心
fft_shift = np.fft.fftshift(fft_image)

# 绘制频谱图
plt.imshow(np.log(1 + np.abs(fft_shift)), cmap='gray')
plt.title('Frequency Spectrum')
plt.show()

# 定义低通滤波器
def low_pass_filter(image_fft, cutoff_freq):
    rows, cols = image_fft.shape
    crow, ccol = rows // 2, cols // 2

    # 构建低通滤波器
    low_pass_mask = np.zeros((rows, cols))
    low_pass_mask[int(crow) - int(crow) * cutoff_freq : int(crow) + int(crow) * cutoff_freq, 
                  int(ccol) - int(ccol) * cutoff_freq : int(ccol) + int(ccol) * cutoff_freq] = 1

    # 将滤波器与频谱相乘
    filtered_fft = image_fft * low_pass_mask

    return filtered_fft

# 设置截止频率并应用低通滤波器
cutoff_frequency = 0.1
filtered_fft = low_pass_filter(fft_shift, cutoff_frequency)

# 将频谱中心移回初始位置
filtered_fft_shift = np.fft.ifftshift(filtered_fft)

# 进行逆变换,得到滤波后的图像
filtered_image = np.fft.ifft2(filtered_fft_shift)

# 取实部并转为图像对象
filtered_image_real = np.real(filtered_image)
filtered_image_obj = Image.fromarray(filtered_image_real.astype(np.uint8))

# 显示原图和滤波后的图像
plt.subplot(1, 2, 1)
plt.imshow(image_array, cmap='gray')
plt.title('Original Image')
plt.subplot(1, 2, 2)
plt.imshow(filtered_image_obj, cmap='gray')
plt.title('Filtered Image')
plt.show()

在上述示例代码中,首先我们利用Image模块读取图像,并将图像转为灰度图像。然后,我们使用np.array()将灰度图像转为数组形式。接着,我们使用np.fft.fft2()对图像数组进行二维离散傅里叶变换。为了方便观察频谱,我们将频谱中心移到图像中心。然后,我们定义了一个低通滤波器函数low_pass_filter(),该函数根据设定的截止频率生成一个滤波器,并将滤波器与频谱相乘。接下来,我们将滤波后的频谱变换回空域,并取实部得到滤波后的图像。最后,我们使用plt.imshow()将原图和滤波后的图像显示出来。

通过上述示例代码,我们可以利用Python的fft2()函数对图像进行频域滤波处理,实现图像处理的目的。需要注意的是,滤波操作需要针对具体的图像及处理目的进行调整,不同的截止频率和滤波器设计会产生不同的效果,这需要根据具体的应用需求进行调整。