python绘制频谱图DTFT,DFT
《数字信号处理》——(一).DTFT、DFT(python实现)
python绘制频谱图:序列的傅里叶变换(DTFT),离散傅里叶变换(DFT)
《数字信号处理》、python学习记录
涉及知识
(之前用matlab来画图,深感matlab打开、运行较慢,就学习了一下python,初学者,错误之处欢迎指正)
- DTFT原理;
- DFT原理;
- python matplotlib库
DTFT、DFT原理
一.DTFT
X ( e j ω ) = ∑ n = − ∞ ∞ x ( n ) e − j ω n X\left(e^{j \omega}\right)=\sum_{n=-\infty}^{\infty} x(n) e^{-j \omega n} X(ejω)=∑n=−∞∞x(n)e−jωn (式1-1)
x ( n ) = 1 2 π ∫ − π π X ( e j ω ) e j ω n d ω x(n)=\frac{1}{2 \pi} \int_{-\pi}^{\pi} X\left(e^{j \omega}\right) e^{j \omega n} d \omega x(n)=2π1∫−ππX(ejω)ejωndω (式1-2)
二.DFT
X ( k ) = ∑ n = 0 N − 1 x ( n ) e − j 2 π N n k X(k)=\sum_{n=0}^{N-1} x(n) e^{-j \frac{2 \pi}{N} n k} X(k)=∑n=0N−1x(n)e−jN2πnk (式2-1)
x ( n ) = 1 N ∑ k = 0 N − 1 X ( k ) e j 2 π N n k x(n)=\frac{1}{N} \sum_{k=0}^{N-1} X(k) e^{j \frac{2 \pi}{N} n k} x(n)=N1∑k=0N−1X(k)ejN2πnk (式2-2)
三.DFT与DTFT关系
X ( k ) = ∑ n = 0 N − 1 x ( n ) e − j 2 π N n k X(k)=\sum_{n=0}^{N-1} x(n) e^{-j \frac{2 \pi}{N} n k} X(k)=∑n=0N−1x(n)e−jN2πnk = X ( e j ω ) ∣ ω = 2 π N k =\left.X\left(e^{j \omega}\right)\right|_{\omega=\frac{2 \pi}{N} k} =X(ejω)∣∣ω=N2πk (式3-1)
python代码实现
实现类dtft、dft,由(式3-1)dft类可继承类dtft,简化程序(不太会用csdn编辑器,代码缩进使用时可能需要调整)
DTFT.py
import math
import numpy as np
class dtft():
#xvalues:输入序列
def __init__(self,xvalues=[]):
self.yvalues = []
self.xvalues = xvalues
#fre:频率坐标
def xjw(self,fre = []):
#(式1-1)实现yvalues为X(jw)频谱值
for f in fre:
p = 0;
for x in self.xvalues:
p = math.e**(-1j*f*x) + p
self.yvalues.append(p)
DFT.py
from DTFT import dtft
import math
class dft(dtft):
#Num:dft点数,self.Num序列值,self.K 序列横坐标,self.xk:存放dft计算结果,
#self.Xk():式(3-1)计算dft
def __init__(self,Num,xvalues):
super().__init__(xvalues)
self.Num = Num
self.xk = []
self.K = list(range(0,self.Num,1))
self.Xk()
def Xk(self):
W = []
for x in self.K:
W.append(x*2*math.pi/len(self.K))
self.xjw(W)
for x in self.yvalues:
self.xk.append(abs(x))
举例绘制一个门函数频谱 x ( n ) = R 4 ( n ) x(n)=R_{4}(n) x(n)=R4(n)
一.DTFT
import matplotlib.pyplot as plt
import math
import numpy as np
from DTFT import dtft
#dtft数据产生
xvalues = list(range(0,4,1))
#画图
DTFT = dtft(xvalues)
W = np.arange(0,10,0.01)
DTFT.xjw(W)
xjw = []
for x in DTFT.yvalues:
xjw.append(x)、
plt.plot(W,xjw, linewidth = 5)
plt.title('DTFT',fontsize = 14)
plt.xlabel("w",fontsize = 14)
plt.ylabel("abs(dtft(xjw))",fontsize = 14)
plt.tick_params(axis = 'both',labelsize = 14)
二.DFT(32点)
import matplotlib.pyplot as plt
import math
import numpy as np
from DTFT import dtft
from DFT import dft
#dtft数据产生
xvalues = list(range(0,4,1))
N1 = 32
DFT1 = dft(N1,xvalues)
X,Y,Z = plt.stem(DFT1.K,DFT1.xk,markerfmt = "o",linefmt = "-.",basefmt = "--")
plt.setp(X,color = 'k')
plt.setp(Y,color = 'r')
plt.setp(Z,color = 'b')
plt.title('DFT',fontsize = 14)
plt.xlabel("w",fontsize = 14)
plt.ylabel("abs(dft(xjw))",fontsize = 14)
plt.tick_params(axis = 'both',labelsize = 14,which = 'major')
plt.show()
总结
初学python,通过python这里的使用加深了对数字信号处理相关知识和python的认识,在复习dsp过程增添了些许乐趣。