SciPy Lfilter 问题

信息处理 过滤器 Python scipy
2022-02-10 13:57:16

对于我的一个 DSP 项目,我决定使用 python 来执行信号处理。虽然我是 python 新手,但我知道它是一种非常强大且用途广泛的语言。对于我的处理,我选择使用 Scipy 的信号库来执行信号处理,在那里我设计了一个模拟的巴特沃斯低通滤波器。当应用过滤器时,使用“signal.lfilter”命令,我收到以下错误:

"Traceback (most recent call last):
  File "C:\Users\bessi\Desktop\crying.py", line 39, in <module>
    f = signal.lfilter(b, a, data, axis = 0)
  File "C:\Users\bessi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\signal\signaltools.py", line 1397, in lfilter
    return sigtools._linear_filter(b, a, x, axis)
ValueError: selected axis is out of range"

与滤波器的设计和应用相关的代码行如下,第一行是创建低通滤波器的行,而第二行是 lfilter 命令,是发生错误的地方(第 39 行) )

b, a = signal.butter(4, 21980, 'low', analog = True, output='ba') 

f = signal.lfilter(b, a, data)

(数据是输入的采样信号。)

这个值错误让我整个晚上都感到困惑,因为它说我的轴参数无效。更让我困惑的是,函数的轴输入参数的默认值是“-1”,我最初并没有篡改。我尝试调整轴值,甚至尝试硬编码值,但是,同样的错误不断出现。希望有人可以提供一些建议/帮助。

lfilter 命令的链接:https ://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html#scipy.signal.lfilter

scipy 过滤器创建链接:https ://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.butter.html#scipy.signal.butter

1个回答

你的形状是data什么?应该是空的。试试print(data.shape)它是否是一个 Numpy 数组。

另一句话,将lfilter解释为离散时间传递函数的系数,因此您不能将其与模拟巴特沃斯滤波器系数一起使用。ba

axis如果您的输入数据是多维的,您只需要担心参数。

例如:

#!/usr/bin/env python3

import matplotlib.pyplot as plt
from numpy import random, log10, angle, pi, transpose, arange, unwrap
from scipy.signal import butter, lfilter, freqz

f_s = 96000 # sample frequency
f_c = 21980 # cut-off frequency

b, a = butter(4, 2 * f_c / f_s)            # Design digital Butterworth filter

if True:
    x = random.randn(1000, 1)              # Generate Gaussian noise (column)
    y = lfilter(b, a, x, axis=1)           # Filter the signal
    plt.plot(x, label='Noise')
    plt.plot(y, label='Filtered')
    print(x.shape)
else:
    x = random.randn(1, 1000)              # Generate Gaussian noise (row)
    y = lfilter(b, a, x, axis=0)           # Filter the signal
    plt.plot(transpose(x), label='Noise')
    plt.plot(transpose(y), label='Filtered')
    print(x.shape)

plt.legend()
plt.show()

# Calculate the frequency response
w, h = freqz(b, a, worN=4096)
w *= f_s / (2 * pi)                        # Convert from rad/sample to Hz

# Plot the amplitude response
plt.subplot(2, 1, 1)
plt.suptitle('Bode Plot')
plt.plot(w, 20 * log10(abs(h)))            # Convert modulus to dB
plt.ylabel('Magnitude [dB]')
plt.xlim(0, f_s / 2)
plt.ylim(-60, 10)
plt.axvline(f_c, color='red')
plt.axhline(-3.01, linewidth=0.8, color='black', linestyle=':')

# Plot the phase response
plt.subplot(2, 1, 2)
plt.plot(w, 180 * unwrap(angle(h)) / pi)   # Convert argument to degrees
plt.xlabel('Frequency [Hz]')
plt.ylabel('Phase [°]')
plt.xlim(0, f_s / 2)
plt.ylim(-360, 0)
plt.yticks(arange(-360, 45, 90))
plt.axvline(f_c, color='red')

plt.show()