一维非局部均值滤波Python代码
时间: 2023-11-21 14:19:42 浏览: 61
非局部均值滤波代码
5星 · 资源好评率100%
以下是一维非局部均值滤波的Python代码:
```python
import numpy as np
from scipy import signal
def nlmeans_1d(signal, h, search_area):
"""
One-dimensional non-local means filter.
Parameters:
signal (array-like): 1D signal to be filtered.
h (float): Smoothing parameter.
search_area (int): Size of the search area. Determines the maximum distance between patches to be compared.
Returns:
filtered_signal (ndarray): Filtered signal.
"""
# Padding signal to prevent boundary issues
signal_padded = np.pad(signal, (search_area, search_area), mode="reflect")
# Precompute weights
weights = np.zeros(signal.shape)
for i in range(search_area, len(signal_padded) - search_area):
for j in range(i - search_area, i + search_area + 1):
patch1 = signal_padded[i - search_area:i + search_area + 1]
patch2 = signal_padded[j - search_area:j + search_area + 1]
diff = patch1 - patch2
weights[i - search_area] += np.exp(-np.sum(diff ** 2) / (h ** 2))
# Normalize weights
weights /= np.sum(weights)
# Convolve weights with signal
filtered_signal = signal.convolve(signal_padded, weights, mode="valid")
return filtered_signal
```
使用该函数的示例:
```python
import matplotlib.pyplot as plt
# Generate noisy signal
np.random.seed(0)
signal = np.sin(2 * np.pi * np.linspace(0, 1, 200)) + np.random.normal(0, 0.1, 200)
# Apply non-local means filter
filtered_signal = nlmeans_1d(signal, h=0.1, search_area=10)
# Plot results
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].plot(signal)
ax[0].set_title("Original signal")
ax[1].plot(filtered_signal)
ax[1].set_title("Filtered signal")
plt.show()
```
输出结果如下图所示:
![nlmeans_1d_example.png](https://i.loli.net/2021/02/05/UWCiqTfS7kDz1X8.png)
阅读全文