在python3的scipy ndimage模块提供了一个名为percentile_filter()的函数,它是中值滤波器的一个通用版本。
脉冲噪声图
代码语言:javascript复制from skimage.io import imread
import matplotlib.pylab as pylab
import numpy as np
pylab.rcParams['font.sans-serif'] = ['KaiTi']
pylab.rcParams['axes.unicode_minus'] = False
def plot_image(image, title=''):
pylab.title(title, size=15)
pylab.imshow(image)
pylab.axis('off')
lena = imread(r'D:image_processingimage4f.jpg')
noise = np.random.random(lena.shape)
lena[noise > 0.9] = 255
lena[noise < 0.1] = 0
plot_image(lena, '噪声图')
pylab.show()
中值滤波器
代码语言:javascript复制from skimage.io import imread
import matplotlib.pylab as pylab
import numpy as np
from scipy import signal, misc, ndimage
pylab.rcParams['font.sans-serif'] = ['KaiTi']
pylab.rcParams['axes.unicode_minus'] = False
def plot_image(image, title=''):
pylab.title(title, size=15)
pylab.imshow(image)
pylab.axis('off')
lena = imread(r'D:image_processingimage4f.jpg')
noise = np.random.random(lena.shape)
lena[noise > 0.9] = 255
lena[noise < 0.1] = 0
plot_image(lena, '噪声图')
pylab.show()
fig = pylab.figure(figsize=(20, 15))
i = 1
for p in range(25, 100, 25):
for k in range(5, 25, 5):
pylab.subplot(3, 4, i)
filtered = ndimage.percentile_filter(lena, percentile=p, size=(k, k, 1))
plot_image(filtered, str(p) ' 核尺寸为, ' str(k) 'x' str(k))
i = 1
pylab.show()
运行上面的代码后,我们可以看到,在所有百分位滤波器中,核尺寸较小的中值滤波器(对应于第50百分位)在去除脉冲噪声方面的效果最好,而同时丢失的图像细节也极少。