巴特沃斯低通滤波器python
时间: 2023-06-22 21:39:20 浏览: 86
巴特沃斯低通滤波器是一种常用的信号处理方法,可以用于去除信号中的高频噪声。在Python中,可以使用scipy库中的butter函数来设计和实现巴特沃斯低通滤波器。以下是一个示例代码:
```python
import numpy as np
from scipy.signal import butter, filtfilt
# 设计低通滤波器
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
# 应用滤波器
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = filtfilt(b, a, data)
return y
# 示例数据
data = np.random.randn(1000)
# 设计并应用低通滤波器
cutoff = 100 # 截止频率
fs = 1000 # 采样率
order = 6 # 阶数
filtered_data = butter_lowpass_filter(data, cutoff, fs, order)
# 绘制原始数据和滤波后的数据
import matplotlib.pyplot as plt
t = np.arange(len(data)) / fs
plt.plot(t, data, 'r-', label='raw data')
plt.plot(t, filtered_data, 'b-', linewidth=2, label='filtered data')
plt.legend()
plt.xlabel('Time (seconds)')
plt.ylabel('Amplitude')
plt.show()
```
在上面的示例代码中,我们先定义了两个函数:butter_lowpass和butter_lowpass_filter。其中,butter_lowpass用于根据指定的截止频率、采样率和阶数,设计出一个巴特沃斯低通滤波器;而butter_lowpass_filter则是用于将输入数据应用到这个滤波器上,得到滤波后的输出数据。最后,我们使用随机生成的数据并绘制了原始数据和滤波后的数据。