python中图像添加高斯噪声并且使用三种不同尺寸进行均值滤波降噪
时间: 2024-11-30 12:13:55 浏览: 54
在Python中,我们可以使用PIL(Python Imaging Library)或其后续库Pillow处理图像,并利用NumPy进行数值计算,包括添加高斯噪声和进行均值滤波。这里是一个简单的步骤:
1. **添加高斯噪声**:
- 加载图像:`img = Image.open('image.jpg')`
- 将图像转换为灰度图或彩色通道分别处理,如果是彩色图像:`gray_img = img.convert('L')`
- 使用`numpy.random.normal()`生成高斯噪声,然后与原像素值相加:`noisy_img = np.array(gray_img) + np.random.normal(0, sigma, gray_img.shape)`
- 将结果转换回图像格式:`noisy_pil = Image.fromarray(np.uint8(noisy_img))`
2. **不同尺寸的均值滤波**:
- 使用`ImageFilter.BLUR`、`ImageFilter.GaussianBlur` 或者自定义大小的`ImageFilter.KERNEL_SIZE`进行均值滤波,如:
```python
filtered_img_3x3 = noisy_pil.filter(ImageFilter.BLUR)
filtered_img_5x5 = noisy_pil.filter(ImageFilter.GaussianBlur(radius=2))
custom_filter = ImageFilter.Kernel((7, 7), [1/49]*49)
custom_filtered_img = noisy_pil.filter(custom_filter)
```
3. **保存处理后的图像**:
- 对于每个滤波版本,可以分别保存到文件:`filtered_img_3x3.save('3x3_blur.jpg')`, ...等。
阅读全文
相关推荐


















