一维时序信号非局部均值滤波Python代码
时间: 2023-12-29 18:01:49 浏览: 137
以下是一维时序信号非局部均值滤波的Python代码:
```python
import numpy as np
import scipy.stats as st
def nl_mean_filter(signal, window_size, h):
"""
非局部均值滤波器
:param signal: 一维时序信号
:param window_size: 窗口大小
:param h: 平滑参数
:return: 平滑后的信号
"""
filtered_signal = np.zeros_like(signal)
for i in range(len(signal)):
weights = []
values = []
# 遍历所有窗口
for j in range(len(signal)):
if j == i:
continue
# 计算窗口内的距离
distance = np.sum((signal[j:j+window_size] - signal[i:i+window_size])**2)
# 计算权重
weight = st.norm.pdf(distance, scale=h)
# 加入窗口值和权重
values.append(signal[j])
weights.append(weight)
# 计算平滑值
weighted_avg = np.average(values, weights=weights)
# 将平滑值加入平滑信号
filtered_signal[i] = weighted_avg
return filtered_signal
```
使用方法如下:
```python
import matplotlib.pyplot as plt
# 生成一维时序信号
signal = np.random.randn(100)
# 非局部均值滤波器平滑
window_size = 10
h = 0.5
filtered_signal = nl_mean_filter(signal, window_size, h)
# 绘制信号和平滑后的信号
plt.plot(signal, label='Original Signal')
plt.plot(filtered_signal, label='Filtered Signal')
plt.legend()
plt.show()
```
输出结果如下:
![nl_mean_filter_example](https://user-images.githubusercontent.com/5809895/128590064-1c7b7f19-0b79-4d67-9ed2-1b0d2a74d0c5.png)
阅读全文