从文件夹读入图像1,将图像1转成灰度图像2。给灰度图像2人为地加上椒盐噪声得到带噪声的图像3,用中值滤波法对图像3进行去噪得到图像4。在同一个界面上分别显示图像1,图像2,图像3和图像4。
时间: 2024-10-10 17:14:03 浏览: 56
在Python中,你可以使用PIL(Pillow库)和OpenCV这两个常用的图像处理库来完成这个任务。以下是步骤:
1. 首先,你需要安装Pillow和OpenCV,可以使用pip安装:
```
pip install pillow opencv-python
```
2. 读取图像1:
```python
from PIL import Image
img1 = Image.open('image1.jpg') # 替换为实际文件路径
```
3. 转换为灰度图像2:
```python
img2 = img1.convert('L')
```
4. 添加椒盐噪声到图像2:
```python
import numpy as np
salt_vs_pepper = 0.1 # 指定椒盐噪声的比例
noisy_img3 = np.array(img2)
row, col = noisy_img3.shape
s_vs_p = salt_vs_pepper * 255
amount = s_vs_p / 2
out = np.copy(noisy_img3)
# 创建椒盐噪声矩阵
num_salt = np.ceil(amount * img2.size * np.random.rand())
num_pepper = np.ceil(amount * img2.size * np.random.rand())
coords = [np.random.randint(0, i - 1, int(num_salt)) for i in noisy_img3.shape]
out[coords] = 255
coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in noisy_img3.shape]
out[coords] = 0
noisy_img3 = out.astype(np.uint8)
noisy_img3 = Image.fromarray(noisy_img3)
```
5. 对图像3应用中值滤波:
```python
from scipy.ndimage import median_filter
img4 = median_filter(noisy_img3, size=(3, 3)) # 可以调整滤波器大小
```
6. 显示所有四张图像:
```python
from matplotlib import pyplot as plt
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(10, 10))
axs[0, 0].imshow(img1, cmap='gray')
axs[0, 0].set_title('Original Image')
axs[0, 1].imshow(img2, cmap='gray')
axs[0, 1].set_title('Grayscale Image')
axs[1, 0].imshow(noisy_img3, cmap='gray')
axs[1, 0].set_title('Noisy Image')
axs[1, 1].imshow(img4, cmap='gray')
axs[1, 1].set_title('De-noised Image')
for ax in axs.flat:
ax.set(xticks=[], yticks=[])
plt.tight_layout()
plt.show()
```
这将在同一窗口中展示原始图像、灰度图像、添加了噪声的图像以及经过中值滤波后的清晰图像。
阅读全文