如何将过滤器应用于python中的信号 [英] How To apply a filter to a signal in python
问题描述
python 中是否有任何准备好的函数可以将滤波器(例如巴特沃斯滤波器)应用于给定信号?我在 'scipy.signal' 中寻找这样的函数,但我没有找到比过滤器设计更有用的函数.实际上我希望这个函数用信号对滤波器进行卷积.
is there any prepared function in python to apply a filter (for example Butterworth filter) to a given signal? I looking for such a function in 'scipy.signal' but I haven't find any useful functions more than filter design ones. actually I want this function to convolve a filter with the signal.
推荐答案
是的!有两个:
scipy.signal.filtfilt
scipy.signal.lfilter
也有卷积方法(convolve
和 fftconvolve
),但这些可能不适合您的应用,因为它涉及 IIR 滤波器.
There are also methods for convolution (convolve
and fftconvolve
), but these are probably not appropriate for your application because it involves IIR filters.
完整代码示例:
b, a = scipy.signal.butter(N, Wn, 'low')
output_signal = scipy.signal.filtfilt(b, a, input_signal)
您可以在文档中阅读有关参数和用法的更多信息.一个问题是 Wn
是奈奎斯特频率的一小部分(采样频率的一半).因此,如果采样率为 1000Hz 并且您希望截止频率为 250Hz,则应使用 Wn=0.5
.
You can read more about the arguments and usage in the documentation. One gotcha is that Wn
is a fraction of the Nyquist frequency (half the sampling frequency). So if the sampling rate is 1000Hz and you want a cutoff of 250Hz, you should use Wn=0.5
.
顺便说一句,对于大多数应用程序,我强烈建议使用 filtfilt
而不是 lfilter
(在 Matlab 中仅称为 filter
).正如文档所述:
By the way, I highly recommend the use of filtfilt
over lfilter
(which is called just filter
in Matlab) for most applications. As the documentation states:
此函数应用线性过滤器两次,一次向前,一次向后.组合滤波器具有线性相位.
This function applies a linear filter twice, once forward and once backwards. The combined filter has linear phase.
这意味着输出的每个值都是输入中过去"和未来"点的函数.因此它不会滞后于输入.
What this means is that each value of the output is a function of both "past" and "future" points in the input equally. Therefore it will not lag the input.
相反,lfilter
仅使用输入的过去"值.这不可避免地引入了时间延迟,这将取决于频率.当然有一些应用程序需要这样做(特别是实时过滤),但大多数用户使用 filtfilt
效果更好.
In contrast, lfilter
uses only "past" values of the input. This inevitably introduces a time lag, which will be frequency-dependent. There are of course a few applications for which this is desirable (notably real-time filtering), but most users are far better off with filtfilt
.
这篇关于如何将过滤器应用于python中的信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!