# 作者:喵酱
# 开发时间:2022/4/17 10:11
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
from scipy import ndimage
plt.rcParams['font.sans-serif'] = ['FangSong'] # 设置字体以便正确显示中文
def add_salt_noise(img, P):
"""添加椒盐噪声"""
img_ = img.copy()
h, w = img.shape
mask = np.random.choice((0, 1, 2), size=(h, w), p=P)
img_[mask == 1] = 255
img_[mask == 2] = 0
return img_
def mean_filtering(img):
"""均值滤波"""
kernel = 1/9 * np.asarray([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
img_out = ndimage.convolve(img, kernel)
return img_out
def gaussian_filtering(img):
"""高斯滤波"""
kernel = 1/16 * np.asarray([[1, 2, 1], [2, 4, 2], [1, 2, 1]])
img_out = ndimage.convolve(img, kernel)
return img_out
def abort_filtering(img):
"""中值滤波"""
h, w = img.shape
img_ = img.copy()
for i in np.arange(1, h):
for j in np.arange(1, w):
mat = img[i-1:i+1, j-1:j+1]
img_[i][j] = np.median(mat)
return img_
img = np.asarray(Image.open('la.tif')) # 读入原始图像
img_noise = add_salt_noise(img, [0.9, 0.05, 0.05]) # 添加椒盐噪声
img_noise_mean = mean_filtering(img_noise) # 均值滤波
img_noise_gaussian = gaussian_filtering(img_noise) # 高斯滤波
img_noise_abort = abort_filtering(img_noise) # 中值滤波
plt.figure(1)
plt.subplot(121)
plt.imshow(img, cmap='gray')
plt.title('原始图像')
plt.subplot(122)
plt.imshow(img_noise, cmap='gray')
plt.title('添加椒盐噪声图像')
plt.figure(2)
plt.subplot(131)
plt.imshow(img_noise_mean, cmap='gray')
plt.title('均值滤波图像')
plt.subplot(132)
plt.imshow(img_noise_gaussian, cmap='gray')
plt.title('高斯滤波图像')
plt.subplot(133)
plt.imshow(img_noise_abort, cmap='gray')
plt.title('中值滤波图像')
plt.show()