中值滤波算法python实现
时间: 2023-11-02 10:06:04 浏览: 305
中值滤波是一种常用的图像处理算法,可以有效地去除图像中的噪声。下面是中值滤波算法的Python实现:
```python
import numpy as np
import cv2
def median_filter(img, kernel_size):
# 获取图像的行数和列数
rows, cols = img.shape[:2]
# 计算卷积核的半径
radius = kernel_size // 2
# 创建一个新的图像,用于存储中值滤波后的结果
result = np.zeros_like(img)
# 对图像进行遍历
for i in range(rows):
for j in range(cols):
# 获取卷积核对应的像素值
pixels = []
for k in range(-radius, radius+1):
for l in range(-radius, radius+1):
x = i + k
y = j + l
if x >= 0 and x < rows and y >= 0 and y < cols:
pixels.append(img[x, y])
# 对像素值进行排序,并取中间值作为当前像素的值
pixels.sort()
result[i, j] = pixels[len(pixels) // 2]
return result
# 读取图像
img = cv2.imread('lena.png', cv2.IMREAD_GRAYSCALE)
# 对图像进行中值滤波
result = median_filter(img, 3)
# 显示原始图像和中值滤波后的结果
cv2.imshow('Original', img)
cv2.imshow('Median Filter', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文
相关推荐

















