我正在尝试应用巴特沃斯过滤器,如这个伟大的回复 How to implement band-pass Butterworth filter with Scipy.signal.butter 所示。 。但是,当我使用那里的函数时,结果似乎是错误的(x(-1)):
FIGURE: applied Butterworth filter
出了什么问题? (我认为这是错误的?)
from scipy.signal import butter, lfilter
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = lfilter(b, a, data)
return y
x=np.array(range(100))
y1=np.array([math.sin(2*3.14*xx/3) for xx in x])
y2=np.array([2*math.sin(2*3.14*xx/30) for xx in x])
y0=x*0.05
y=y1+y2+y0
lowcut=1./10000000.
highcut=1./20.
plt.figure(3)
plt.clf()
plt.plot(x, y, label='Noisy signal',lw=2.5,color='blue')
plt.plot(x,y0,ls='--',color='blue')
plt.plot(x,y1,ls='--',color='blue')
plt.plot(x,y2,ls='--',color='blue')
ysm = butter_bandpass_filter(y, lowcut, highcut, fs, order=6)
plt.plot(x, ysm, label='Filtered signal',lw=2.5,color='red')
plt.grid(True)
plt.axis('tight')
plt.legend(loc='upper left')
plt.show()
最佳答案
没有什么问题。您看到的是 IIR 滤波器产生的正常相移。
如果相移 Not Acceptable ,一种选择是更改此行:
y = lfilter(b, a, data)
至
y = filtfilt(b, a, data)
并将 filtfilt
添加到从 scipy.signal
导入的名称中。 filtfilt
应用相同的滤波器两次,一次向前,一次向后,因此相移“取消”。如果您使用 filtfilt
,则可以降低滤波器的阶数,因为您要应用两次。
另一种选择是使用 FIR 滤波器而不是 IIR 滤波器。有关过滤器行为的问题最好在 dsp.stackexchange.com 上询问。
关于python - 巴特沃斯滤波器 - 输出 x (-1)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33769281/