对bmp图片进行中值滤波和均值滤波并保存
时间: 2024-05-08 17:15:32 浏览: 182
中值滤波和均值滤波是常用的图像处理方法,可以从图像中去除噪声和平滑图像。下面是对bmp图片进行中值滤波和均值滤波的Python代码,并保存处理后的图片。
首先,需要安装Pillow库,可以使用以下命令安装:
```python
!pip install Pillow
```
然后,读取bmp图片并转换为灰度图像:
```python
from PIL import Image
# 读取bmp图片并转换为灰度图像
img = Image.open("lena.bmp").convert("L")
```
接下来,定义中值滤波和均值滤波函数:
```python
import numpy as np
def median_filter(img, kernel_size):
"""
中值滤波
img: PIL.Image对象,灰度图像
kernel_size: int,卷积核大小
"""
w, h = img.size
img_array = np.array(img)
# 边缘填充
pad_size = kernel_size // 2
img_pad = np.pad(img_array, pad_size, mode="edge")
# 滤波
img_filt = np.zeros((w, h), dtype=np.uint8)
for i in range(w):
for j in range(h):
roi = img_pad[i:i+kernel_size, j:j+kernel_size]
img_filt[i, j] = np.median(roi)
# 返回PIL.Image对象
return Image.fromarray(img_filt)
def mean_filter(img, kernel_size):
"""
均值滤波
img: PIL.Image对象,灰度图像
kernel_size: int,卷积核大小
"""
w, h = img.size
img_array = np.array(img)
# 边缘填充
pad_size = kernel_size // 2
img_pad = np.pad(img_array, pad_size, mode="edge")
# 滤波
img_filt = np.zeros((w, h), dtype=np.uint8)
for i in range(w):
for j in range(h):
roi = img_pad[i:i+kernel_size, j:j+kernel_size]
img_filt[i, j] = np.mean(roi)
# 返回PIL.Image对象
return Image.fromarray(img_filt)
```
最后,调用中值滤波和均值滤波函数,并保存处理后的图片:
```python
# 中值滤波
img_median = median_filter(img, 5)
img_median.save("lena_median.bmp")
# 均值滤波
img_mean = mean_filter(img, 5)
img_mean.save("lena_mean.bmp")
```
完整代码如下:
```python
from PIL import Image
import numpy as np
def median_filter(img, kernel_size):
"""
中值滤波
img: PIL.Image对象,灰度图像
kernel_size: int,卷积核大小
"""
w, h = img.size
img_array = np.array(img)
# 边缘填充
pad_size = kernel_size // 2
img_pad = np.pad(img_array, pad_size, mode="edge")
# 滤波
img_filt = np.zeros((w, h), dtype=np.uint8)
for i in range(w):
for j in range(h):
roi = img_pad[i:i+kernel_size, j:j+kernel_size]
img_filt[i, j] = np.median(roi)
# 返回PIL.Image对象
return Image.fromarray(img_filt)
def mean_filter(img, kernel_size):
"""
均值滤波
img: PIL.Image对象,灰度图像
kernel_size: int,卷积核大小
"""
w, h = img.size
img_array = np.array(img)
# 边缘填充
pad_size = kernel_size // 2
img_pad = np.pad(img_array, pad_size, mode="edge")
# 滤波
img_filt = np.zeros((w, h), dtype=np.uint8)
for i in range(w):
for j in range(h):
roi = img_pad[i:i+kernel_size, j:j+kernel_size]
img_filt[i, j] = np.mean(roi)
# 返回PIL.Image对象
return Image.fromarray(img_filt)
# 读取bmp图片并转换为灰度图像
img = Image.open("lena.bmp").convert("L")
# 中值滤波
img_median = median_filter(img, 5)
img_median.save("lena_median.bmp")
# 均值滤波
img_mean = mean_filter(img, 5)
img_mean.save("lena_mean.bmp")
```
阅读全文