本模板供Python环境使用。另外,你也可以选择用MATLAB完成,或用C++与Opencv完成。
# 对'rice.tif'添加椒盐噪声,再做中值滤波。使用Python+skimage实现
%matplotlib inline
from skimage import io, util, filters
from skimage.morphology import disk
import skimage.filters.rank as sfr
import matplotlib.pyplot as plt
import numpy as np
# 原图片
im = io.imread("book-cover.tif")
plt.figure(figsize=(12,4))
plt.subplot(131), io.imshow(im), plt.axis('off'), plt.title('original image')
# 添加了椒盐噪声
im1 = util.random_noise(im, mode='s&p')
plt.figure(figsize=(12,4))
plt.subplot(132), io.imshow(im1), plt.axis('off'), plt.title('salt & pepper')
# 中值滤波器
im2 = filters.median(im1,np.ones((3, 3)))
plt.figure(figsize=(12,4))
plt.subplot(133), io.imshow(im2), plt.axis('off'), plt.title('median filter')
# 最大值滤波器
im3 = sfr.maximum(im1, disk(5))
plt.figure(figsize=(12,4))
plt.subplot(121), io.imshow(im3), plt.axis('off'), plt.title('maximum filter')
# 最小值滤波器
im4 =sfr.minimum(im1, disk(5))
plt.figure(figsize=(12,4))
plt.subplot(122), io.imshow(im4), plt.axis('off'), plt.title('minimum filter')
def modified_alpha_mean(image, kernel, d=0):
height, width = image.shape[:2]
m, n = kernel.shape[:2]
padding_h = int((m -1)/2)
padding_w = int((n -1)/2)
# 这样的填充方式,可以奇数核或者偶数核都能正确填充
image_pad = np.pad(image, ((padding_h, m - 1 - padding_h), \
(padding_w, n - 1 - padding_w)), mode="edge")
img_result = np.zeros(image.shape)
for i in range(height):
for j in range(width):
temp = np.sum(image_pad[i:i + m, j:j + n] * 1)
img_result[i, j] = temp / (m * n - d)
return img_result
kernel = np.ones([5, 5])
im5 = modified_alpha_mean(im1, kernel=kernel, d=1)
plt.figure(figsize=(12,12))
plt.subplot(236), plt.imshow(im5, 'gray'), plt.title('Modified alpha mean d=6'), plt.xticks([]),plt.yticks([])
plt.show()