Python - Get STFT Output as 2D NumPy matrix

Viewed 162

I'm using the code below to get Frequency, Time and Power parameters resulting from STFT.

 f,t,Z = signal.stft(x, fr, nperseg=40)

and getting the mesh plot by:

plt.pcolormesh(t, f, np.abs(Z), shading='gouraud')
plt.title('STFT Magnitude')
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.show()

enter image description here

I'm looking for a way to derive that image as a grayscaled 2D NumPy matrix without actually plotting it. Another way would be saving the plot and loading it as a NumPy array and then converting it to a grayscale image, but it would cost a lot of computation time. I'm looking for a neat and effective way of deriving that 2D matrix.

1 Answers

There's no need for other variables but Z which is a 2D NumPy matrix and contains all the required information to construct the plot. However, it is needed to take its absolute, as it contains imaginary values.

Z = np.abs(signal.stft(x,fr, nperseg=200)[2])
plt.imshow(Z)
plt.show()

enter image description here

Related