(2)生成代码,实现图像分别添加椒盐噪声与乘性噪声,手写实现3*3窗口均值滤波与中值滤波,并比 较两种方法在不同噪声下的去噪效果。提示:嵌套使用for循环语句
时间: 2024-10-28 07:07:34 浏览: 36
为了手写实现图像的椒盐噪声、乘性噪声的添加,以及3x3窗口的均值滤波和中值滤波,我们可以使用Python的PIL库处理图片,numpy处理数组运算。以下是部分代码示例:
```python
from PIL import Image
import numpy as np
# 加载图像
def load_image(file_path):
return Image.open(file_path).convert('L') # 黑白图像处理
# 添加椒盐噪声
def add_salt_pepper_noise(image, probability=0.05):
noisy = np.array(image)
salt_mask = np.random.rand(*noisy.shape) < probability
pepper_mask = np.invert(salt_mask)
noisy[salt_mask] = 255 # 将随机位置设为最大亮度
noisy[pepper_mask] = 0 # 将随机位置设为最小亮度
return Image.fromarray(noisy)
# 乘性噪声
def add_multiplicative_noise(image, factor=0.5):
noisy = np.array(image)
noisy *= np.random.normal(1, factor, size=noisy.shape) # 随机乘以一个小于1的因子
return Image.fromarray(np.uint8(noisy))
# 3x3窗口均值滤波
def mean_filter(image, kernel_size=3):
padded_img = np.pad(image, pad_width=(kernel_size // 2, kernel_size // 2), mode='edge')
filtered = np.zeros_like(padded_img)
for i in range(kernel_size, len(padded_img) - kernel_size + 1):
for j in range(kernel_size, len(padded_img[0]) - kernel_size + 1):
filtered[i, j] = np.mean(padded_img[i:i+kernel_size, j:j+kernel_size])
return filtered
# 中值滤波
def median_filter(image, kernel_size=3):
padded_img = np.pad(image, pad_width=(kernel_size // 2, kernel_size // 2), mode='edge')
filtered = np.zeros_like(padded_img)
for i in range(kernel_size, len(padded_img) - kernel_size + 1):
for j in range(kernel_size, len(padded_img[0]) - kernel_size + 1):
filtered[i, j] = np.median(padded_img[i:i+kernel_size, j:j+kernel_size])
return filtered
# 使用以上函数对原始图像进行操作并比较结果
original_image = load_image("input.jpg")
salt_and_pepper_noisy = add_salt_pepper_noise(original_image)
multiplicative_noisy = add_multiplicative_noise(original_image)
filtered_mean = mean_filter(salt_and_pepper_noisy)
filtered_median = median_filter(salt_and_pepper_noisy)
# 可能需要将过滤后的图像保存或显示出来,以便对比
mean_filtered_image = Image.fromarray(filtered_mean)
median_filtered_image = Image.fromarray(filtered_median)
# 比较结果
# ...
阅读全文