MATLAB和Python之间的不同谱图

时间:2015-06-28 16:18:48

标签: python matlab matplotlib signal-processing spectrogram

我在MATLAB中有一个程序,我希望移植到Python。问题在于我使用了内置的spectrogram函数,尽管matplotlib specgram函数看起来相同,但是当我运行它们时,我得到的结果会有所不同。

这些是我一直在运行的代码。

MATLAB:

data = 1:999; %Dummy data. Just for testing.

Fs = 8000; % All the songs we'll be working on will be sampled at an 8KHz rate

tWindow = 64e-3; % The window must be long enough to get 64ms of the signal
NWindow = Fs*tWindow; % Number of elements the window must have
window = hamming(NWindow); % Window used in the spectrogram

NFFT = 512;
NOverlap = NWindow/2; % We want a 50% overlap

[S, F, T] = spectrogram(data, window, NOverlap, NFFT, Fs);

的Python:

import numpy as np
from matplotlib import mlab

data = range(1,1000) #Dummy data. Just for testing

Fs = 8000
tWindow = 64e-3
NWindow = Fs*tWindow
window = np.hamming(NWindow)

NFFT = 512
NOverlap = NWindow/2

[s, f, t] = mlab.specgram(data, NFFT = NFFT, Fs = Fs, window = window, noverlap = NOverlap)

这是我在两次执行中得到的结果:

http://i.imgur.com/QSPvYsC.png

(两个程序中的F和T变量完全相同)

很明显他们是不同的;事实上,Python执行甚至不会返回复数。可能是什么问题呢?有没有办法解决它或我应该使用另一个频谱图功能?

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

matplotlib中,specgram默认返回功率谱密度(mode='PSD')。在MATLAB中,spectrogram默认返回短时傅里叶变换,除非nargout==4,在这种情况下它还会计算PSD。要使matplotlib行为与MATLAB行为相匹配,请设置mode='complex'