改进自适应中值滤波python代码
时间: 2023-08-06 15:16:53 浏览: 172
以下是改进后的自适应中值滤波 Python 代码:
``` python
import cv2
import numpy as np
def adaptive_median_filter(img, max_window_size):
img_out = np.zeros_like(img)
img_pad = np.pad(img, max_window_size // 2, mode='reflect')
for i in range(img.shape[0]):
for j in range(img.shape[1]):
window_size = 3 # initial window size
while window_size <= max_window_size:
window = img_pad[i:i+window_size, j:j+window_size]
window_flat = window.flatten()
median = np.median(window_flat)
min_val, max_val = np.min(window_flat), np.max(window_flat)
if min_val < median < max_val:
img_out[i, j] = median
break
else:
window_size += 2 # increase window size by 2
if window_size > max_window_size:
img_out[i, j] = median
return img_out
```
这个算法的改进主要是在增加了初始窗口大小,这样可以更快地找到合适的窗口大小,从而提高滤波效率。同时,我们使用 `np.pad()` 函数对图像进行边缘填充,避免了对边缘像素的特殊处理。另外,我们使用了 `numpy` 库中的 `flatten()` 函数,将窗口中的像素展开成一维数组,方便进行统计计算。
阅读全文