20hz-20000hz Butterworth filtering exploding

我的未来我决定 提交于 2019-12-08 05:58:13

问题


I want to filter out everything outside 20 Hz - 20000 Hz. I'm using a Butterworth filter:

from scipy.io import wavfile
from scipy import signal
import numpy

sr, x = wavfile.read('sweep.wav')
nyq = 0.5 * sr
b, a = signal.butter(5, [20.0 / nyq, 20000.0 / nyq], btype='band')

x = signal.lfilter(b, a, x)
x = numpy.float32(x)
x /= numpy.max(numpy.abs(x))
wavfile.write('b.wav', sr, x)

I've noticed that it works with a 44.1 khz file, but not with a 96 khz WAV file (demo file here) (it's not an audio I/O problem): the output is either blank (silence) or exploding (with some other input wav files).

1) Is there something that makes that the Butterworth filters don't work with a bandpass [b1, b2] where b2 < 0.5 ?

2) More generally, how would you do a filtering to keep only 20 - 20000Hz with Python / scipy? (no other external library)


回答1:


scipy.signal.butter is generating an unstable filter:

In [17]: z, p, k = signal.tf2zpk(b, a)

In [18]: np.max(np.abs(p))
Out[18]: 1.0005162676670694

For a stable filter, that maximum must be less than 1. Unfortunately, the code doesn't warn you about this.

I suspect the problem is b1, not b2. In the normalized units, you are trying to create a lower cutoff of 2.1e-4, which is pretty small. If, for example, the lower cutoff is 200.0/nyq, the filter is stable:

In [13]: b, a = signal.butter(5, [200.0 / nyq, 20000.0 / nyq], btype='band')

In [14]: z, p, k = signal.tf2zpk(b, a)

In [15]: np.max(np.abs(p))
Out[15]: 0.99601892668982284

Instead of using the (b, a) format for the filter, you can use the more robust sos (second order sections) format, which was added to scipy version 0.16. To use it, change these two lines

b, a = signal.butter(5, [20.0 / nyq, 20000.0 / nyq], btype='band')
x = signal.lfilter(b, a, x)

to

sos = signal.butter(5, [20.0 / nyq, 20000.0 / nyq], btype='band', output='sos')
x = signal.sosfilt(sos, x)

That SOS filter does not suffer from the instability problem.



来源:https://stackoverflow.com/questions/41371915/20hz-20000hz-butterworth-filtering-exploding

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