在python中的巴特沃斯过滤器

时间:2014-11-05 12:30:32

标签: python scipy signal-processing

我正在尝试使用Python中的Butterworth过滤器,如this thread中所述,具有以下功能:

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

我的数据的FFT输出而不应用过滤器给出了以下图表:

enter image description here

但是,在应用上面的过滤器后:

lowcut = 1.0
highcut = 50.0
x2_Vtcr = butter_bandpass_filter(x_Vtcr, lowcut, highcut, fs, order=4)

其中fs是采样频率(在我的情况下是1000)我得到FFT:

enter image description here

看起来滤波器将频率向左移动,我没有得到应有的峰值。 知道为什么会这样吗?

以防我放在data file (second column)的位置。 DC很强,因此在FFT之后第一个元素不应该包含在图中。

谢谢!

1 个答案:

答案 0 :(得分:1)

上面的两个函数似乎在这里工作正常。这是一个在fs=250采样的白噪声信号的示例,并使用您提到的two functions进行过滤,其频率介于1Hz和50 Hz之间:

from numpy import random, arange
from numpy.fft import rfft, rfftfreq

fs = 250.
t = arange(0., 30., 1 / fs)
x_Vtcr = random.randn(len(t))

hat_x_Vtcr = rfft(x_Vtcr)
freqs = rfftfreq(x_Vtcr.size, 1 / fs)
plt.plot(freqs, abs(hat_x_Vtcr), 'b')

lowcut, highcut = 1.0, 50.0
x2_Vtcr = butter_bandpass_filter(x_Vtcr, lowcut, highcut, fs, order=4)

hat_x2_Vtcr = rfft(x2_Vtcr)
plt.plot(freqs, abs(hat_x2_Vtcr), 'r')

由此产生的PSD对我很好(红色是过滤的): enter image description here

我猜你的错误是在其他地方?请将您的代码与上述代码段进行比较。您可能还想在下次阅读THIS

编辑:回复评论。

它确实也适用于您的数据。我做了:

datafile=loadtxt('V.dat')
x_Vtcr=datafile[:,1]
x_Vtcr-=x_Vtcr.mean()

然后我运行了上面的脚本,当然没有生成x_Vtcr数据的行。生成的过滤输出如下: enter image description here