在 Python 中通过 Scipy 创建一个带通滤波器?

Create a band-pass filter via Scipy in Python?

有没有一种方法可以通过 scipylibrosa 在 Python 3.6 中为 16KHz wav 文件创建快速带通滤波器,以过滤 300- 人类语音频带之外的噪声3400赫兹?这是一个 sample wav file 的低频背景噪音。

更新: 是的,我已经 seen/tried How to implement band-pass Butterworth filter with Scipy.signal.butter 了。不幸的是,过滤后的声音严重变形。本质上,整个代码都是这样做的:

lo,hi=300,3400
sr,y=wavfile.read(wav_file)
b,a=butter(N=6, Wn=[2*lo/sr, 2*hi/sr], btype='band')
x = lfilter(b,a,y)
sounddevice.play(x, sr)  # playback

我做错了什么或者如何改进才能正确过滤掉背景噪音。

这是使用上面的 link 对原始文件和过滤后的文件进行的可视化。可视化看起来很合理,但听起来很糟糕 :( 如何解决这个问题?

以下代码用于从此处生成带通滤波器:https://scipy.github.io/old-wiki/pages/Cookbook/ButterworthBandpass

     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() 

看看这是否有助于您的事业。 您可以在此处指定所需的频率:

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

显然问题发生在写入非规范化的 64 位浮点数据时。通过将 x 转换为 16 位或 32 位整数,或者通过将 x 标准化为范围 [-1, 1] 并转换为 32 浮点数,我得到一个听起来合理的输出文件。

我没有使用 sounddevice;相反,我将过滤后的数据保存到一个新的 WAV 文件中并播放它。以下是对我有用的变体:

# Convert to 16 integers
wavfile.write('off_plus_noise_filtered.wav', sr, x.astype(np.int16))

或...

# Convert to 32 bit integers
wavfile.write('off_plus_noise_filtered.wav', sr, x.astype(np.int32))

或...

# Convert to normalized 32 bit floating point
normalized_x = x / np.abs(x).max()
wavfile.write('off_plus_noise_filtered.wav', sr, normalized_x.astype(np.float32))

输出整数时,您可以按比例放大值,以最大限度地减少因截断浮点值而导致的精度损失:

x16 = (normalized_x * (2**15-1)).astype(np.int16)
wavfile.write('off_plus_noise_filtered.wav', sr, x16)