Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To apply a filter to a signal in python

Tags:

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.

like image 318
Navid Khairdast Avatar asked Dec 06 '12 09:12

Navid Khairdast


People also ask

How do filters work in signals?

When the signal frequency is within the filter's pass band, the filter passes the signal. As the signal moves out of the pass band, the filter begins to attenuate the signal. Note that the transition from the pass band to the stop band is a gradual process, where the filter's response decreases continuously.


1 Answers

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.

like image 117
cxrodgers Avatar answered Oct 11 '22 01:10

cxrodgers