1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fft,ifft import pandas as pd
# 采样频率 sr=1000 # 采样时间间隔 ts=1/sr # 样本采样点 t=np.arange(0,2,ts) # 原始信号 f_clean=5 freq=10 f_clean+=2*np.sin(2*np.pi*freq*t+3) freq=30 f_clean+=5*np.sin(2*np.pi*freq*t) # 信号噪音 f_noise=f_clean+3*np.random.randn(len(t)) # 绘制信号 # fig,ax=plt.subplots(figsize=(12,3)) # ax.plot(t,f_noise,linewidth=.5,color='c',label='Noisy') # ax.plot(t,f_clean,linewidth=.5,color='r',label='Clean') # ax.set_xlabel('Sampling Time') # ax.set_ylabel('Amplitude') # ax.legend() # plt.show()
X=fft(f_noise) N=len(X) # 采集数据的idx n=np.arange(N) # 总的采样时间 T=N/sr freq=n/T
# fig,ax=plt.subplots(2,1,figsize=(10,8)) # ax[0].stem(freq,np.abs(X),'b',markerfmt=' ',basefmt='-b') # ax[0].set_xlabel('Freq(Hz)') # ax[0].set_ylabel('FFT Amplitude |X(freq)|') # # 实际幅度 # X_norm=X/N*2 # ax[1].stem(freq,np.abs(X_norm),'b',markerfmt=' ',basefmt='-b') # ax[1].set_xlim(-1,40) # ax[1].set_xlabel('Freq(Hz)') # ax[1].set_ylabel('FFT Amplitude |X(freq)|') # ax[1].annotate(r'5(Constant terms)',xy=(0,5),xytext=(+10,50),textcoords='offset points',arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=-.5')) # ax[1].annotate(r'$2\sin(2\pi\cdot 10t+3)$',xy=(10,2),xytext=(+10,30),textcoords='offset points',arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=-.5')) # ax[1].annotate(r'$5\sin(2\pi\cdot 30t)$',xy=(30,4),xytext=(+10,30),textcoords='offset points',arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=-.5')) # plt.show()
# 对DFT结果进行噪音去除,过滤除去低振幅项,并可视化 freq_clean=pd.Series(X).apply(lambda x: x if np.abs(x)>1000 else 0).to_numpy() # fig,ax=plt.subplots(figsize=(10,4)) # ax.stem(freq,np.abs(freq_clean),'b',markerfmt=' ',basefmt='-b') # ax.set_xlim(-1,100) # ax.set_xlabel('Freq(Hz)') # ax.set_ylabel('FFT Amplitude |X(freq)|') # ax.annotate(r'5(Constant terms)',xy=(0,5*N/2),xytext=(+10,50),textcoords='offset points',arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=-.5')) # ax.annotate(r'$2\sin(2\pi\cdot 10t+3)$',xy=(10,2*N/2),xytext=(+10,30),textcoords='offset points',arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=-.5')) # ax.annotate(r'$5\sin(2\pi\cdot 30t)$',xy=(30,4*N/2),xytext=(+10,30),textcoords='offset points',arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=-.5')) # plt.show()
# 将过滤后的信号进行傅里叶逆变换并可视化 ix=ifft(freq_clean) # 绘制信号 fig,ax=plt.subplots(figsize=(12,3)) ax.plot(t,ix,linewidth=.5,color='c',label='IFFT') ax.plot(t,f_clean,linewidth=.5,color='r',linestyle='-.',label='Raw signal',alpha=0.7) ax.set_xlabel('Sampling Time') ax.set_ylabel('Amplitude') ax.legend() plt.show()
|