该图像有椒盐噪声,写一个中值滤波进行降噪的代码
时间: 2024-10-14 09:09:00 浏览: 28
中值滤波是一种非线性的图像去噪技术,它通过计算像素周围邻域内像素值的中位数来替换当前像素值,能有效去除椒盐噪声。下面是一个简单的Python代码示例,使用OpenCV库来实现二维中值滤波:
```python
import cv2
import numpy as np
def median_filter(image, kernel_size):
# 将图像转换为灰度,如果已经是灰度图则无需这一步
if len(image.shape) == 3 and image.shape[2] == 3:
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
gray_image = image
# 应用中值滤波
filtered_image = cv2.medianBlur(gray_image, kernel_size)
return filtered_image
# 使用示例
noisy_image = ... # 输入含有椒盐噪声的图像
kernel_size = 3 # 过滤核大小,通常选择奇数
denoised_image = median_filter(noisy_image, kernel_size)
# 显示原图和处理后的图片
cv2.imshow("Original Image", noisy_image)
cv2.imshow("Median Filtered Image", denoised_image)
cv2.waitKey(0) # 等待用户按键,按任意键关闭窗口
阅读全文