How To apply a filter to a signal in python

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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.

回答1:

Yes! There are two:

scipy.signal.filtfilt scipy.signal.lfilter 

There are also methods for convolution (convolve and fftconvolve), but these are probably not appropriate for your application because it involves IIR filters.

Full code sample:

b, a = scipy.signal.butter(N, Wn, 'low') output_signal = scipy.signal.filtfilt(b, a, input_signal) 

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.

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.

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!