编写中值滤波程序处理高斯噪声和椒盐噪声的代码
时间: 2024-06-17 13:04:24 浏览: 132
中值滤波是一种非线性滤波,可以有效地去除高斯噪声和椒盐噪声。下面是一份Python代码示例,可以实现中值滤波处理高斯噪声和椒盐噪声。
```
import cv2
import numpy as np
# 读取图片
img = cv2.imread('test.jpg')
# 添加高斯噪声
img_gaussian = cv2.GaussianBlur(img, (5, 5), 0.8)
# 添加椒盐噪声
img_sp = img.copy()
sp_ratio = 0.05
noise_num = int(sp_ratio * img_sp.shape * img_sp.shape)
for i in range(noise_num):
rand_x = np.random.randint(0, img_sp.shape)
rand_y = np.random.randint(0, img_sp.shape)
if np.random.rand() < 0.5:
img_sp[rand_x, rand_y] = 0
else:
img_sp[rand_x, rand_y] = 255
# 中值滤波去除高斯噪声
img_median_gaussian = cv2.medianBlur(img_gaussian, 5)
# 中值滤波去除椒盐噪声
img_median_sp = cv2.medianBlur(img_sp, 5)
# 显示图片
cv2.imshow('Original Image', img)
cv2.imshow('Gaussian Noise Image', img_gaussian)
cv2.imshow('Salt and Pepper Noise Image', img_sp)
cv2.imshow('Median Filtered Gaussian Noise Image', img_median_gaussian)
cv2.imshow('Median Filtered Salt and Pepper Noise Image', img_median_sp)
cv2.waitKey(0)
```
阅读全文