通过Python中的Scipy创建带通滤波器?

ntjbwcob  于 2022-11-10  发布在  Python
关注(0)|答案(2)|浏览(195)

有没有办法通过Python 3.6中的scipylibrosa为16 KHz的wav文件创建一个快速的带通滤波器,以过滤300- 3400 Hz的人声频带之外的噪声?下面是一个低频背景噪声的sample wav file
更新:是的,我已经看过/试过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

我做错了什么,或者如何改进这一点,使背景噪音被正确过滤掉。
下面是使用上面的链接对原始文件和过滤后的文件进行的可视化。可视化看起来很合理,但听起来很可怕:(如何修复这个问题?

pkmbmrz7

pkmbmrz71#

显然,当写入未规范化的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)
xlpyo6sf

xlpyo6sf2#

以下代码用于从此处生成带通滤波器: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

相关问题