且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中实现FIR高通滤波器?

更新时间:2022-03-16 21:21:06

firwin pass_zero 参数更改为 False .该参数必须是布尔值(即True或False).通过将其设置为False,可以将滤波器的行为选择为高通滤波器(即,该滤波器不会通过信号的0频率).

Change the pass_zero argument of firwin to False. That argument must be a boolean (i.e. True or False). By setting it to False, you are selecting the behavior of the filter to be a high-pass filter (i.e. the filter does not pass the 0 frequency of the signal).

这是您脚本的一种变体.我添加了水平虚线,显示了根据您选择的 ripple_db 确定的阻带(青色)中的所需衰减和通带(红色)中的所需纹波边界.我还绘制了垂直虚线(绿色)以指示从阻带到通带的过渡区域.

Here's a variation of your script. I've added horizontal dashed lines that show the desired attenuation in the stop band (cyan) and desired ripple bounds in the pass band (red) as determined by your choice of ripple_db. I also plot vertical dashed lines (green) to indicate the region of the transition from the stop band to the pass band.

import numpy as np
from scipy.signal import kaiserord, lfilter, firwin, freqz, firwin2
import matplotlib.pyplot as plt

# Nyquist rate.
nyq_rate = 48000 / 2

# Width of the roll-off region.
width = 500 / nyq_rate

# Attenuation in the stop band.
ripple_db = 12.0

num_of_taps, beta = kaiserord(ripple_db, width)
if num_of_taps % 2 == 0:
    num_of_taps = num_of_taps + 1

# Cut-off frequency.
cutoff_hz = 5000.0

# Estimate the filter coefficients.
taps = firwin(num_of_taps, cutoff_hz/nyq_rate, window=('kaiser', beta), pass_zero=False)

w, h = freqz(taps, worN=4000)

plt.plot((w/np.pi)*nyq_rate, 20*np.log10(np.abs(h)), linewidth=2)

plt.axvline(cutoff_hz + width*nyq_rate, linestyle='--', linewidth=1, color='g')
plt.axvline(cutoff_hz - width*nyq_rate, linestyle='--', linewidth=1, color='g')
plt.axhline(-ripple_db, linestyle='--', linewidth=1, color='c')
delta = 10**(-ripple_db/20)
plt.axhline(20*np.log10(1 + delta), linestyle='--', linewidth=1, color='r')
plt.axhline(20*np.log10(1 - delta), linestyle='--', linewidth=1, color='r')

plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain (dB)')
plt.title('Frequency Response')
plt.ylim(-40, 5)
plt.grid(True)
plt.show()

这是它生成的图.如果仔细观察,您会发现频率响应靠近定义滤波器所需性能的区域的拐角处.

Here is the plot that it generates. If you look closely, you'll see that the frequency response is close to the corners of the region that defines the desired behavior of the filter.

这是 ripple_db 更改为21时的图:

Here's the plot when ripple_db is changed to 21: