Skip to content

Instantly share code, notes, and snippets.

@pbnsilva
Last active April 13, 2020 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbnsilva/724f090423ef77b17e9e03917ddc93c7 to your computer and use it in GitHub Desktop.
Save pbnsilva/724f090423ef77b17e9e03917ddc93c7 to your computer and use it in GitHub Desktop.
from scipy import signal
def spectrogram(data, fs=300, nperseg=64, noverlap=32):
f, t, Sxx = signal.spectrogram(data, fs=fs, nperseg=nperseg, noverlap=noverlap)
Sxx = np.transpose(Sxx, [0, 2, 1])
Sxx = np.abs(Sxx)
mask = Sxx > 0
Sxx[mask] = np.log(Sxx[mask])
return f, t, Sxx
_, t, Sxx = spectrogram(np.expand_dims(data, axis=0))
plt.figure(figsize=(15, 5))
xticks_array = np.arange(0, Sxx[0].shape[0], 100)
xticks_labels = [round(t[label]) for label in xticks_array]
plt.xticks(xticks_array, labels=xticks_labels)
plt.xlabel('Time (s)', fontsize=25)
plt.ylabel('Frequency (Hz)', fontsize=25)
plt.imshow(np.transpose(Sxx[0]), aspect='auto', cmap='jet')
plt.gca().invert_yaxis()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment