如何用Scipy.signal.bu实现带通巴特沃斯滤波器

2024-09-27 09:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

更新:

我在这个问题上找到了一个很好的方法!所以,对于任何感兴趣的人,直接转到:Contents » Signal processing » Butterworth Bandpass


我很难实现最初看起来很简单的一个任务:为一维numpy阵列(时间序列)实现Butterworth带通滤波器。

我必须包括的参数是采样率、截止频率(赫兹)和可能的阶数(其他参数,如衰减、固有频率等,对我来说比较模糊,所以任何“默认”值都可以)。

我现在得到的是这个,它看起来像是高通滤波器,但我不确定我做得是否正确:

def butter_highpass(interval, sampling_rate, cutoff, order=5):
    nyq = sampling_rate * 0.5

    stopfreq = float(cutoff)
    cornerfreq = 0.4 * stopfreq  # (?)

    ws = cornerfreq/nyq
    wp = stopfreq/nyq

    # for bandpass:
    # wp = [0.2, 0.5], ws = [0.1, 0.6]

    N, wn = scipy.signal.buttord(wp, ws, 3, 16)   # (?)

    # for hardcoded order:
    # N = order

    b, a = scipy.signal.butter(N, wn, btype='high')   # should 'high' be here for bandpass?
    sf = scipy.signal.lfilter(b, a, interval)
    return sf

enter image description here

这些文档和示例令人费解且晦涩难懂,但我想实现推荐中标记为“for bandpass”的表单。注释中的问号显示了我只是复制粘贴了一些示例而不了解发生了什么。

我不是电子工程或科学家,只是一个医疗设备设计师需要对肌电信号进行一些相当简单的带通滤波。


Tags: for参数signalwsrateorderscipywp
3条回答

对于带通滤波器,ws是包含上下角频率的元组。它们表示滤波器响应比通带小3db的数字频率。

wp是包含停止带数字频率的元组。它们表示最大衰减开始的位置。

gpass是通带中的最大出席,单位为dB,gstop是阻带中的出席。

例如,您想要设计一个采样率为8000个采样/秒、角频率为300和3100赫兹的滤波器。奈奎斯特频率是采样率除以2,或者在本例中是4000赫兹。等效数字频率为1.0。两个角频率分别为300/4000和3100/4000。

现在让我们假设您希望阻带比拐角频率低30db/-100hz。因此,您的阻带将从200和3200赫兹开始,产生200/4000和3200/4000的数字频率。

要创建过滤器,您可以调用buttord作为

fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
   gpass=0.0, gstop=30.0)

结果滤波器的长度将取决于停止带的深度和响应曲线的陡度,响应曲线的陡度由拐角频率和停止带频率之间的差异决定。

accepted answer中的过滤器设计方法是正确的,但它有一个缺陷。用b,a设计的SciPy带通滤波器是unstable,可能在higher filter orders处产生erroneous filters

相反,使用滤波器设计的sos(二阶部分)输出。

from scipy.signal import butter, sosfilt, sosfreqz

def butter_bandpass(lowcut, highcut, fs, order=5):
        nyq = 0.5 * fs
        low = lowcut / nyq
        high = highcut / nyq
        sos = butter(order, [low, high], analog=False, btype='band', output='sos')
        return sos

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
        sos = butter_bandpass(lowcut, highcut, fs, order=order)
        y = sosfilt(sos, data)
        return y

此外,还可以通过更改

b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)

sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)

您可以跳过button的使用,而只需为过滤器选择一个顺序,看看它是否符合您的过滤条件。要生成带通滤波器的滤波器系数,请将滤波器阶数、截止频率Wn=[low, high](表示为奈奎斯特频率的分数,即采样频率的一半)和频带类型btype="band"

下面是一个脚本,它定义了两个使用巴特沃斯带通滤波器的便利函数。当作为脚本运行时,它生成两个图。其中一个显示了相同采样率和截止频率下几个滤波器阶数的频率响应。另一个图展示了滤波器(阶数为6)对样本时间序列的影响。

from scipy.signal import butter, lfilter


def butter_bandpass(lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a


def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
    b, a = butter_bandpass(lowcut, highcut, fs, order=order)
    y = lfilter(b, a, data)
    return y


if __name__ == "__main__":
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.signal import freqz

    # Sample rate and desired cutoff frequencies (in Hz).
    fs = 5000.0
    lowcut = 500.0
    highcut = 1250.0

    # Plot the frequency response for a few different orders.
    plt.figure(1)
    plt.clf()
    for order in [3, 6, 9]:
        b, a = butter_bandpass(lowcut, highcut, fs, order=order)
        w, h = freqz(b, a, worN=2000)
        plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)

    plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
             '--', label='sqrt(0.5)')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.legend(loc='best')

    # Filter a noisy signal.
    T = 0.05
    nsamples = T * fs
    t = np.linspace(0, T, nsamples, endpoint=False)
    a = 0.02
    f0 = 600.0
    x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
    x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
    x += a * np.cos(2 * np.pi * f0 * t + .11)
    x += 0.03 * np.cos(2 * np.pi * 2000 * t)
    plt.figure(2)
    plt.clf()
    plt.plot(t, x, label='Noisy signal')

    y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
    plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
    plt.xlabel('time (seconds)')
    plt.hlines([-a, a], 0, T, linestyles='--')
    plt.grid(True)
    plt.axis('tight')
    plt.legend(loc='upper left')

    plt.show()

以下是此脚本生成的绘图:

Frequency response for several filter orders

enter image description here

相关问题 更多 >

    热门问题