栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

傅里叶变换(python)(2)例题

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

傅里叶变换(python)(2)例题

目的:去除噪音。时间和信号的关系是:gaussNoisy(t) (g(t))

noiseAmp:控制噪音的大小。noiseAmp为0时图像会变成光滑的信号。

import numpy as np

def gaussNoisy(t, noiseAmp):
    noise = noiseAmp*(np.random.randn(len(t)))
    return np.exp(-0.5*t*t) * (1.0+noise)

N = 256
t = np.linspace(-4.0, 4.0, N)
g = gaussNoisy(t, 0.1)

(閾値は試行錯誤により決定しなさい:范围根据错误决定,我试了好多次xlim和ylim找噪音)

以下为解决方法的程序:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack as scifft
plt.close('all')
def gaussNoisy(t, noiseAmp):
    noise = noiseAmp*(np.random.randn(len(t)))
    return np.exp(-0.5*t*t) * (1.0+noise)

N = 256
t = np.linspace(-4.0, 4.0, N)
g = gaussNoisy(t, 0.1)


fig1, ax1 = plt.subplots(2, 1, figsize=(9, 7))
ax1[0].plot(t,g, color='red') 
ax1[0].set_xlim(-4, 4) 
ax1[0].set_ylim(0,1.3) 
ax1[0].set_xlabel('t') 
ax1[0].set_ylabel('g(t)')


num_data =len(t)
freq = scifft.fftfreq(num_data, d=0.03125)  
freq = scifft.fftshift(freq)

f_hat = scifft.fft(g,n=num_data)
f_hat = scifft.fftshift(f_hat) 
f_spect = f_hat * np.conj(f_hat)/num_data
fig1, ax2 = plt.subplots(4, 1, figsize=(9, 7))
ax2[0].plot(freq, np.real(f_hat), color='blue')
ax2[0].set_xlim(-128,128)
ax2[0].set_ylim(-1.2, 1.2) 
ax2[0].set_xlabel('freq (Hz)') 
ax2[0].set_ylabel('Re[f_hat]') 

# f_hat(f)作图(虚部imag)
ax2[1].plot(freq, np.imag(f_hat), color='blue')
ax2[1].set_xlim(-128,128) 
ax2[1].set_ylim(-1.2, 1.2) 
ax2[1].set_xlabel('freq (Hz)') 
ax2[1].set_ylabel('Im[f_hat]')
 
# f_hat的spect作图
ax2[2].plot(freq,f_spect, color='blue',label="before filtering") #傅里叶变换:可以看出有噪音
ax2[2].set_xlim(-128,128) 
ax2[2].set_ylim(-0.01, 0.01) 
ax2[2].set_xlabel('freq (Hz)') 
ax2[2].set_ylabel('f_spect') 
ax2[2].legend()

indices = f_spect>0.05 
#print("indices=", indices)
 

f_spect_filtered = f_spect * indices
f_hat_filtered = f_hat * indices
 
ax2[3].plot(freq,f_spect_filtered, color='red',label="after filtering")
ax2[3].set_xlim(-128,128)
ax2[3].set_ylim(-0.05, 0.05) 
ax2[3].set_xlabel('freq (Hz)') 
ax2[3].set_ylabel('f_spect(freq)') 
ax2[3].legend()
 
#逆傅里叶变换准备:要用fftshift
f_hat_filtered = scifft.fftshift(f_hat_filtered)
f_filterd = scifft.ifft(f_hat_filtered,n=num_data)
 
ax1[1].set_xlim(-4, 4) 
ax1[1].set_ylim(0,1.3) 
ax1[1].plot(t, np.real(f_filterd), color='blue') 
ax1[1].set_xlabel('time (sec)') 
ax1[1].set_ylabel('f_filtered(t)') 
 
plt.show()
plt.tight_layout()

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/740052.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号