要求
尝试设计巴特沃斯或高斯低通滤波器对下面的图像进行处理,比较不同参数下的结果,并与理想滤波器的结果进行比较。
高斯低通滤波器实现原理
高斯低通滤波器公式如下:
根据不同的sigma值,生成模糊后图像
高斯低通滤波器实现代码
import cv2
from matplotlib import pyplot as plt
import numpy as np
imgGray = cv2.imread(r"D:\Project\PythonProject\GraphicAnalysis\class4\zuoye4.png", flags=0) # flags=0 读取为灰度图像
imgFloat32 = np.float32(imgGray)
dft = cv2.dft(imgFloat32, flags=cv2.DFT_COMPLEX_OUTPUT)
dftShift = np.fft.fftshift(dft)
plt.figure(figsize=(10, 10))
rows, cols = imgGray.shape[:2]
sigma2 = np.arange(0.05, 0.25, 0.05)
for i in range(4):
x, y = np.mgrid[-1:1:2 / rows, -1:1:2 / cols]
z = np.exp(-(x ** 2 + y ** 2) / (2 * sigma2[i]))
# 归一化为 [0,255]
z = np.uint8(cv2.normalize(z, None, 0, 255, cv2.NORM_MINMAX))
maskGauss = np.zeros((rows, cols, 2), np.uint8)
maskGauss[:,:,0] = z
maskGauss[:,:,1] = z
dftTrans = dftShift * maskGauss
ishift = np.fft.ifftshift(dftTrans)
idft = cv2.idft(ishift)
imgRebuild = cv2.magnitude(idft[:,:,0], idft[:,:,1])
plt.subplot(2,4,i+1), plt.title("sigma^2={:.2f}".format(sigma2[i])), plt.axis('off')
plt.imshow(maskGauss[:,:,0], cmap='gray')
plt.subplot(2,4,i+5), plt.title(" "), plt.axis('off')
plt.imshow(imgRebuild, cmap='gray')
plt.tight_layout()
plt.show()
高斯低通滤波器实现效果
与理想低通滤波对比
理想低通滤波实现代码
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("D:/Project/PythonProject/GraphicAnalysis/class4/zuoye4.png")[:,:,0]
#傅里叶变换
dft = cv2.dft(np.float32(img), flags = cv2.DFT_COMPLEX_OUTPUT)
fshift = np.fft.fftshift(dft)
#设置低通滤波器
rows, cols = img.shape
crow,ccol = int(rows/2), int(cols/2) #中心位置
mask = np.zeros((rows, cols, 2), np.uint8)
mask[crow-60:crow+60, ccol-60:ccol+60] = 1
#掩膜图像和频谱图像乘积
f = fshift * mask
print (f.shape, fshift.shape, mask.shape)
#傅里叶逆变换
ishift = np.fft.ifftshift(f)
iimg = cv2.idft(ishift)
res = cv2.magnitude(iimg[:,:,0], iimg[:,:,1])
#显示原始图像和低通滤波处理图像
plt.subplot(131), plt.imshow(img, 'gray'), plt.title('Original Image')
plt.axis('off')
plt.subplot(132), plt.imshow(res, 'gray'), plt.title('Result Image')
plt.axis('off')
plt.subplot(133), plt.imshow(mask[:,:,1], 'gray'), plt.title('Mask')
plt.axis('off')
plt.show()
理想低通滤波实现效果
分析
分析可知,理想低通滤波器有明显的振铃现象,而高斯低通滤波器没有振铃现象,高斯低通滤波器实现效果较好。