Python:谈谈常规滤波器(带通、低通、高通、带阻)的用法
在Python中,常规滤波器可以使用scipy.signal
模块来实现。以下是实现带通、低通、高通和带阻滤波器的示例代码:
import numpy as np
from scipy.signal import butter, lfilter, bpf, lfilter, hpf, bpfdb
# 设计低通滤波器
def lowpass_filter(data, fs, cutoff, order=5):
b, a = butter(order, cutoff/(fs/2), btype='low')
return lfilter(b, a, data)
# 设计高通滤波器
def highpass_filter(data, fs, cutoff, order=5):
b, a = butter(order, cutoff/(fs/2), btype='high')
return hpf(data, cutoff, fs, order=order)
# 设计带通滤波器
def bandpass_filter(data, fs, cutoff_low, cutoff_high, order=5):
b, a = butter(order, [cutoff_low/(fs/2), cutoff_high/(fs/2)], btype='band')
return bpf(data, b, a)
# 设计带阻滤波器
def bandstop_filter(data, fs, cutoff_low, cutoff_high, order=5, width=1):
b, a = butter(order, [cutoff_low/(fs/2), cutoff_high/(fs/2)], btype='bandstop')
return bpfdb(data, b, a, width=width)
# 示例使用
data = np.random.randn(1000) # 示例数据
fs = 1000 # 采样频率
cutoff_low = 100 # 低频截止频率
cutoff_high = 2000 # 高频截止频率
order = 6 # 滤波器阶数
width = 1.5 # 带阻宽度
# 应用滤波器
low_data = lowpass_filter(data, fs, cutoff_low, order)
high_data = highpass_filter(data, fs, cutoff_high, order)
band_data = bandpass_filter(data, fs, cutoff_low, cutoff_high, order)
bandstop_data = bandstop_filter(data, fs, cutoff_low, cutoff_high, order, width)
在这个例子中,我们定义了设计低通、高通、带通和带阻滤波器的函数,并使用scipy.signal
模块中的butter
函数来设计滤波器的系数,然后使用lfilter
、hpf
、bpf
和bpfdb
来应用滤波器。
注意:bpfdb
函数在scipy
的较新版本中已被弃用,在代码中仅为示例。在实际应用中,请根据你的scipy
版本选择正确的函数。
评论已关闭