梯形低通滤波器类似上篇巴特沃斯低通滤波,只是其转移函数不同。
梯形低通滤波器的转移函数如下:
式中,D0为截止频率,D1可以任取,但要求D1>D0。两个都不能为负。
D(u,v)也是从频率域的原点到(u,v)的距离,计算公式在理想低通滤波那里介绍过。
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import suanfa as sf
mpl.rcParams['font.sans-serif'] = ['SimHei']
def low_pass_tixing(img, D0, D1):
r,c = img.shape[1], img.shape[0]
u = np.arange(r)
v = np.arange(c)
u,v = np.meshgrid(u,v)
low_pass = np.sqrt( (u-r/2)**2 + (v-c/2)**2 )
idx = low_pass < D0
idx2 = (low_pass >= D0) & (low_pass <= D1)
idx3 = low_pass > D1
low_pass[idx] = 1
low_pass[idx2] = ( low_pass[idx2] - D1 ) / (D0 - D1)
low_pass[idx3] = 0
return low_pass
def ditong(img, D0, D1):
k = low_pass_tixing(img, D0, D1)
result = img.copy() # 复制图片
#result = np.float64(result) # 转换为float64
result_f = np.fft.fft2(result) # 傅里叶变换
result_fshift = np.fft.fftshift(result_f) # 低频移至中心
#dst = np.zeros_like(result_fshift) # 构建目标矩阵,初始化全为0
dst_filter = k*result_fshift # 低通滤波与原图相乘
dst_ifftshit = np.fft.ifftshift(dst_filter) # 反向移动到原来位置
dst_ifft = np.fft.ifft2(dst_ifftshit) # 傅里叶反变换
dst_ifft = np.abs(dst_ifft)
return dst_ifft
img = cv.imread('lena512color.tiff', 0)
img = sf.add_noise(img, 2000)
dst1 = ditong(img, 10, 20)
dst2 = ditong(img, 15, 50)
dst3 = ditong(img, 25, 30)
dst4 = ditong(img, 25, 100)
dst5 = ditong(img, 50, 100)
plt.subplot(231),plt.imshow(img, cmap='gray'),plt.axis('off'),plt.title('原图')
plt.subplot(232),plt.imshow(dst1, cmap='gray'),plt.axis('off'),plt.title('梯形滤波,D0=10, D1=20')
plt.subplot(233),plt.imshow(dst2, cmap='gray'),plt.axis('off'),plt.title('梯形滤波,D0=15, D1=50')
plt.subplot(234),plt.imshow(dst3, cmap='gray'),plt.axis('off'),plt.title('梯形滤波,D0=25, D1=30')
plt.subplot(235),plt.imshow(dst4, cmap='gray'),plt.axis('off'),plt.title('梯形滤波,D0=25, D1=100')
plt.subplot(236),plt.imshow(dst5, cmap='gray'),plt.axis('off'),plt.title('梯形滤波,D0=50, D1=100')
plt.show()
下图中,左图为原图,其余为当D0,D1取不同值时的梯形低通滤波器的结果图。由图可以看出,梯形低通滤波有消除噪声的效果,但图像会模糊,并且会有一定的振铃现象。