注意
转到末尾 下载完整的示例代码。
基于FFT的图像去噪¶
通过实现基于FFT的模糊处理来去除图像 (../../../../data/moonlanding.png
) 的噪声。
通过FFT实现以下卷积
读取并绘制图像¶
import numpy as np
import matplotlib.pyplot as plt
im = plt.imread("../../../../data/moonlanding.png").astype(float)
plt.figure()
plt.imshow(im, "gray")
plt.title("Original image")
Text(0.5, 1.0, 'Original image')
计算输入图像的二维FFT¶
import scipy as sp
im_fft = sp.fft.fft2(im)
# Show the results
def plot_spectrum(im_fft):
from matplotlib.colors import LogNorm
# A logarithmic colormap
plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5))
plt.colorbar()
plt.figure()
plot_spectrum(im_fft)
plt.title("Fourier transform")
Text(0.5, 1.0, 'Fourier transform')
在FFT中进行滤波¶
# In the lines following, we'll make a copy of the original spectrum and
# truncate coefficients.
# Define the fraction of coefficients (in each direction) we keep
keep_fraction = 0.1
# Call ff a copy of the original transform. NumPy arrays have a copy
# method for this purpose.
im_fft2 = im_fft.copy()
# Set r and c to be the number of rows and columns of the array.
r, c = im_fft2.shape
# Set to zero all rows with indices between r*keep_fraction and
# r*(1-keep_fraction):
im_fft2[int(r * keep_fraction) : int(r * (1 - keep_fraction))] = 0
# Similarly with the columns:
im_fft2[:, int(c * keep_fraction) : int(c * (1 - keep_fraction))] = 0
plt.figure()
plot_spectrum(im_fft2)
plt.title("Filtered Spectrum")
Text(0.5, 1.0, 'Filtered Spectrum')
重建最终图像¶
# Reconstruct the denoised image from the filtered spectrum, keep only the
# real part for display.
im_new = sp.fft.ifft2(im_fft2).real
plt.figure()
plt.imshow(im_new, "gray")
plt.title("Reconstructed Image")
Text(0.5, 1.0, 'Reconstructed Image')
更简单、更好的方法: scipy.ndimage.gaussian_filter()
¶
直接使用FFT实现滤波既复杂又耗时。我们可以使用
scipy.ndimage
中的高斯滤波器。
im_blur = sp.ndimage.gaussian_filter(im, 4)
plt.figure()
plt.imshow(im_blur, "gray")
plt.title("Blurred image")
plt.show()
脚本总运行时间:(0分钟0.765秒)