加权中值滤波 python
时间: 2023-10-21 18:04:46 浏览: 126
加权中值滤波函数,需要配合opencv
3星 · 编辑精心推荐
加权中值滤波是一种在中值滤波基础上进行改进的滤波方法。相比于传统中值滤波,加权中值滤波在选择中值时引入了权重,使得更接近中心像素的像素值对中值的计算有更大的贡献。
下面是一个使用Python实现加权中值滤波的示例代码:
```python
from PIL import Image
import numpy as np
from scipy.ndimage import generic_filter
def weighted_median(data, weights):
sorted_data = np.sort(data)
cum_weights = np.cumsum(weights[np.argsort(data)])
median_idx = np.searchsorted(cum_weights, np.sum(weights) / 2.0)
return sorted_data[median_idx]
def weighted_median_filter(image_path, window_size):
image = Image.open(image_path).convert('L')
data = np.array(image)
weights = np.ones(window_size**2)
filtered_data = generic_filter(data, weighted_median, size=window_size, extra_arguments=(weights,))
filtered_image = Image.fromarray(filtered_data)
return filtered_image
image_path = "path_to_image.jpg"
window_size = 3
filtered_image = weighted_median_filter(image_path, window_size)
filtered_image.show()
```
阅读全文