前言
上一章讲了均值滤波,实现比较容易。今天我们开始中值滤波,难度升级。
一、中值滤波
中值滤波的原理就是在以下3x3窗口里面选出9个像素的中值,一种方法是先选择使用排序算法,对9个像素排序,然后选出中值。另外一种方法是使用并行3步中值法,我们在Python以及FPGA中都采用3步中值法,方便实现。
二、增加噪音
还是采用椒盐增噪。
img = plt.imread("lenna.png")
img = img * 255#图像是[0-1]--->[0-255]
img = img.astype(np.uint8)
prob = 0.92#生成盐噪生的概率为1-0.92=0.08
noise = np.random.choice((0, 255), size=img.shape, p=[prob, 1 - prob])#产生和图像维度一样的噪音矩阵
noise_img = np.where(noise == 0, img, 255).astype(np.uint8)#生成噪音图像,椒(0黑色)盐噪声的盐(255白色)
plt.imsave("noise.png", noise_img)#保存噪音图像,用于FPGA去噪
fig = plt.figure(figsize=(10, 6))
ax = plt.subplot(1, 2, 1)
ax.set_title("raw image")
ax.set_xlabel("width")
ax.set_ylabel("height")
plt.imshow(img)
ax = plt.subplot(1, 2, 2)
ax.set_title("salt image")
ax.set_xlabel("width")
ax.set_ylabel("height")
plt.imshow(noise_img)
三、Python实现中值滤波
def image_gray(image):
gray = np.dot(image[:, :, ...], [0.299, 0.587, 0.114])#等同0.299 * image[:, :, 0] + 0.587 * image[:, :, 1] + 0.114 * image[:, :, 2]
return gray.astype(np.uint8)
def median_filter(image, n):
h, w = image.shape
filtered_image = np.zeros((h, w))
m = int((n - 1) / 2)
for i in range(m, h - m):
for j in range(m, w - m):
kernel = image[i - m: i + m