求助:Matplotlib Specgram与Matlab Spectrogram结果不一致问题排查
Let's break down the key differences between your MATLAB and Python code that are throwing off your results:
1. Window & Overlap Value Data Types
In MATLAB, NWindow = Fs*tWindow gives an integer (8000*64e-3 = 512), which plays nicely with hamming(NWindow). But in Python, this calculation returns a float (512.0), and np.hamming() expects an integer input. While some versions might coerce this silently, it can lead to subtle inconsistencies. Fix this by explicitly casting to integers:
NWindow = int(Fs * tWindow) NOverlap = int(NWindow / 2)
2. Data Type Precision Mismatch
MATLAB’s 1:999 creates a floating-point numeric array, but Python’s range(1,1000) is an integer sequence. mlab.specgram works best with floating-point data to match MATLAB’s precision, so convert your data:
data = np.array(range(1, 1000), dtype=np.float64)
3. Window Scaling Differences
MATLAB’s spectrogram automatically normalizes the window to account for its energy, while mlab.specgram doesn’t apply this scaling by default. To align the two, normalize your Hamming window in Python to match MATLAB’s behavior:
window = np.hamming(NWindow) # Normalize window to match MATLAB's energy scaling window = window / np.sqrt(np.sum(window**2))
4. Spectrogram Output Alignment
MATLAB’s spectrogram returns the complex spectrum with each frame scaled by the window and normalized, while mlab.specgram’s mode='complex' outputs raw windowed FFT values. The normalization step above closes this gap, ensuring the amplitude scaling matches MATLAB’s output.
Corrected Python Code
Putting all these fixes together, your code should now produce results consistent with MATLAB:
import numpy as np from matplotlib import mlab data = np.array(range(1, 1000), dtype=np.float64) Fs = 8000 tWindow = 64e-3 NWindow = int(Fs * tWindow) window = np.hamming(NWindow) window = window / np.sqrt(np.sum(window**2)) # Match MATLAB's window scaling NFFT = 512 NOverlap = int(NWindow / 2) [s, f, t] = mlab.specgram(data, NFFT=NFFT, Fs=Fs, window=window, noverlap=NOverlap, mode='complex')
Test these changes step-by-step—you’ll likely see the results align after adjusting the window scaling and data types!
内容的提问来源于stack exchange,提问作者Rariusz

