Matplotlib Specgram 得到与在 Matlab 中相同的结果

Matplotlib Specgram get the same results as in Matlab

我在matlab中有代码:

data = 1:999;
Fs = 8000;
tWindow = 64e-3;
NWindow = Fs*tWindow;
window = hamming(NWindow);

NFFT = 512;
NOverlap = NWindow/2;

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

并在 python

import numpy as np
from matplotlib import mlab
data = range(1,1000)

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, mode  = 'complex')

以上代码基于我在互联网上找到的示例。问题是我无法从 python 和 MatLab 获得相同的结果。哪里有问题?

结果比较:

我相信你比较了错误的结果参数,即Ss

MATLAB spectrogram 文档说(根据您的示例更改了变量名称)。

S = spectrogram(data) returns the short-time Fourier transform of the input signal, data. Each column of S contains an estimate of the short-term, time-localized frequency content of data.

进一步

[___,P] = spectrogram(___) also returns a matrix, P, containing an estimate of the power spectral density (PSD) or the power spectrum of each segment.

为了比较,matplotlib.mlab.specgram 文档说

Returns s: array_like 2-D array, columns are the periodograms of successive segments.

意思是MATLAB spectrogram return值Pmatplotlib.mlab.specgramreturn值s包含功率谱密度值和 是要比较的参数。请注意,您必须在 mlab.specgram.

中使用 mode=psd 作为 kwarg

所以 MATLAB:

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

>> P(1:10, :)

ans =

   1.0e+04 *

   0.308534266716801   1.231732513971400
   0.151013695839005   0.487744349480272
   0.000300936865940   0.000301512606065
   0.000011558094657   0.000011638920865
   0.000032287898006   0.000032310876043
   0.000031582990508   0.000031591963531
   0.000026545275922   0.000026549494058
   0.000021658792166   0.000021661034379
   0.000017687762496   0.000017689063802
   0.000014586747930   0.000014587554750

mlab.specgram

>>> [s, f, t] = mlab.specgram(data, NFFT=NFFT, Fs=Fs, window=window,
                      noverlap=NOverlap, mode='psd')
>>> s[0:9]
array([[3.08534267e+03, 1.23173251e+04],
       [1.51013696e+03, 4.87744349e+03],
       [3.00936866e+00, 3.01512606e+00],
       [1.15580947e-01, 1.16389209e-01],
       [3.22878980e-01, 3.23108760e-01],
       [3.15829905e-01, 3.15919635e-01],
       [2.65452759e-01, 2.65494941e-01],
       [2.16587922e-01, 2.16610344e-01],
       [1.76877625e-01, 1.76890638e-01]])

相等。