使用python和numpy,scipy做FIR带通滤波实验
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal
Fs=8000
Ts=1.0/Fs
Ns=512
t=np.arange(0,Ts*(Ns-1),Ts)
f1=500
f2=1800
f3=2000
f4=3200
x1=np.sin(2*np.pi*f1*t)
x2=np.sin(2*np.pi*f2*t)
x3=np.sin(2*np.pi*f3*t)
x4=np.sin(2*np.pi*f4*t)
x=x1+x2+x3+x4
xo=x2+x3
b=np.array([0.0051,0,-0.0294,0,0.1107,0,-0.2193,0,0.271,0,-0.2193,0,0.1107,0,-0.0294,0,0.0051])
y=signal.convolve(x,b)
fftmag=np.abs(np.fft.fft(x,Ns))
fftmagh=fftmag[1:len(fftmag)/2]
f=np.arange(1,len(fftmagh)+1)*Fs/Ns
Npts=200
fig = plt.figure(1)
ax = fig.add_subplot(311)
ax.set_title('input signal')
ax.plot(t[1:Npts],x[1:Npts])
ax = fig.add_subplot(312)
ax.set_title('expected signal')
ax.plot(t[1:Npts],xo[1:Npts])
ax = fig.add_subplot(313)
ax.set_title('filtered signal')
ax.plot(t[1:Npts],y[1:Npts])
w,h = signal.freqz(b,1)
hdb = 20 * np.log10(np.abs(h))
hphs = np.unwrap(np.arctan2(np.imag(h),np.real(h)))
fig2=plt.figure(2)
ax2 = fig2.add_subplot(211)
ax2.set_title('frequency response')
ax2.plot(w/max(w),hdb)
ax2 = fig2.add_subplot(212)
ax2.set_title('phase response')
ax2.plot(w/max(w),hphs)
plt.show()