用python代码实现自适应中值滤波器去除灰度图像的椒盐噪声,不调用openCV库
时间: 2024-05-14 19:14:33 浏览: 75
以下是使用python代码实现自适应中值滤波器去除灰度图像的椒盐噪声:
```python
import numpy as np
from PIL import Image
# 定义自适应中值滤波器函数
def adaptive_median_filter(img, kernel_size):
# 获取图像的宽度和高度
width, height = img.shape
# 计算kernel_size的一半
half_kernel_size = kernel_size // 2
# 创建一个与原始图像相同大小的结果图像
result_img = np.zeros_like(img)
# 遍历图像的每个像素
for i in range(width):
for j in range(height):
# 获取kernel_size内的像素值
pixel_values = []
for m in range(-half_kernel_size, half_kernel_size + 1):
for n in range(-half_kernel_size, half_kernel_size + 1):
# 判断像素是否在图像边界内
if i + m >= 0 and i + m < width and j + n >= 0 and j + n < height:
pixel_values.append(img[i + m][j + n])
# 对像素值进行排序
pixel_values.sort()
# 获取中值
median_value = pixel_values[len(pixel_values) // 2]
# 获取最大和最小的像素值
z_min = pixel_values[0]
z_max = pixel_values[-1]
# 获取中心像素值
z_med = img[i][j]
# 判断z_med是否在[z_min, z_max]之间
if z_min < z_med < z_max:
result_img[i][j] = z_med
else:
# 增加kernel_size的大小
kernel_size += 2
half_kernel_size = kernel_size // 2
# 如果kernel_size大于图像的大小,就返回原始像素值
if kernel_size > min(width, height):
result_img[i][j] = z_med
else:
# 递归调用自适应中值滤波器
return adaptive_median_filter(img, kernel_size)
return result_img
# 读取图像
img = Image.open('lena.jpg').convert('L')
img = np.array(img)
# 添加椒盐噪声
salt_vs_pepper_ratio = 0.05 # 盐和椒的比例
noise_img = np.copy(img)
salt_vs_pepper_amount = int(salt_vs_pepper_ratio * img.shape[0] * img.shape[1])
salt_coords = [np.random.randint(0, i - 1, salt_vs_pepper_amount) for i in img.shape]
pepper_coords = [np.random.randint(0, i - 1, salt_vs_pepper_amount) for i in img.shape]
noise_img[salt_coords] = 255
noise_img[pepper_coords] = 0
# 使用自适应中值滤波器去除椒盐噪声
filtered_img = adaptive_median_filter(noise_img, 3)
# 显示图像
Image.fromarray(img).show()
Image.fromarray(noise_img).show()
Image.fromarray(filtered_img).show()
```
这段代码首先读取一张灰度图像,然后添加椒盐噪声。接下来,它使用自适应中值滤波器去除椒盐噪声,并将结果图像显示出来。