在python3的scipy ndimage模塊提供了一個名為percentile_filter()的函數,它是中值濾波器的一個通用版本。
脈沖噪聲圖
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_processing\image4\f.jpg')
noise = np.random.random(lena.shape)
lena[noise > 0.9] = 255
lena[noise < 0.1] = 0
plot_image(lena, '噪聲圖')
pylab.show()
中值濾波器
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_processing\image4\f.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百分比特)在去除脈沖噪聲方面的效果最好,而同時丟失的圖像細節也極少。