一维时序信号非局部均值滤波的完整Python代码
时间: 2023-12-29 10:01:45 浏览: 70
非局部均值滤波代码
5星 · 资源好评率100%
以下是一维时序信号非局部均值滤波的完整Python代码:
```python
import numpy as np
from scipy import signal
def nl_means_filter(signal, window_size, sigma, h):
# Compute the half window size
half_window = window_size // 2
# Compute the padded signal
padded_signal = np.pad(signal, half_window, mode='reflect')
# Compute the distance weights
weights = np.zeros_like(signal)
for i in range(signal.size):
for j in range(signal.size):
# Compute the distance between the patches
patch1 = padded_signal[i:i+window_size]
patch2 = padded_signal[j:j+window_size]
distance = np.sum((patch1 - patch2) ** 2) / (window_size * sigma ** 2)
# Compute the weight
weights[i, j] = np.exp(-distance)
# Normalize the weights
norm_weights = weights.sum(axis=1)
for i in range(signal.size):
weights[i, :] /= norm_weights[i]
# Compute the filtered signal
filtered_signal = np.zeros_like(signal)
for i in range(signal.size):
weights_i = weights[i, :]
window = padded_signal[i:i+window_size]
filtered_signal[i] = np.sum(weights_i * window) / np.sum(weights_i)
# Apply the hard thresholding
filtered_signal = signal - filtered_signal
filtered_signal = np.where(filtered_signal < -h, -h, filtered_signal)
filtered_signal = np.where(filtered_signal > h, h, filtered_signal)
filtered_signal = signal - filtered_signal
return filtered_signal
# Example usage
signal = np.sin(np.linspace(0, 2*np.pi, 100))
noisy_signal = signal + np.random.normal(0, 0.1, 100)
filtered_signal = nl_means_filter(noisy_signal, window_size=5, sigma=0.1, h=0.1)
import matplotlib.pyplot as plt
plt.plot(signal, label='Original signal')
plt.plot(noisy_signal, label='Noisy signal')
plt.plot(filtered_signal, label='Filtered signal')
plt.legend()
plt.show()
```
该代码使用了NumPy和SciPy库,实现了一维时序信号非局部均值滤波算法。其中,`nl_means_filter`函数接受一个输入信号,以及窗口大小、标准差和硬阈值等参数,返回经过滤波后的信号。在例子中,我们使用了正弦波作为原始信号,加入了高斯噪声,并对噪声进行了非局部均值滤波。最后,我们使用Matplotlib库将原始信号、噪声信号和滤波后的信号进行了可视化。
阅读全文