Skip to content

Instantly share code, notes, and snippets.

@dalsh
Created November 15, 2017 12:32
Show Gist options
  • Save dalsh/465ef928905dd02072f679e8140949af to your computer and use it in GitHub Desktop.
Save dalsh/465ef928905dd02072f679e8140949af to your computer and use it in GitHub Desktop.
Spectrograms with Scipy and Matplotlib
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
from scipy.io import wavfile
BASEDIR = './'
OUTDIR = BASEDIR + 'spectrograms/'
def save_spectrogram(voice_name):
sample_rate, samples = wavfile.read(BASEDIR + 'samples/' + voice_name + '.wav')
# average all channels
avg = np.add(samples[:,0],samples[:,0])/2
# generate spectrogram
f, t, Sxx = signal.spectrogram(avg, sample_rate)
# make a figure without borders or padding
fig=plt.figure(frameon=False)
fig.set_size_inches(512/32,512/32) # 512 pixels, 32 dpi
mesh = fig.add_subplot(1,1,1)
mesh.pcolormesh(t, f, Sxx,
norm=colors.SymLogNorm(linthresh=0.00001), # magic value threshold set so it looks good
cmap='Greys')
plt.axis('off')
mesh.axes.get_xaxis().set_visible(False)
mesh.axes.get_yaxis().set_visible(False)
fig.subplots_adjust(bottom = 0)
fig.subplots_adjust(top = 1)
fig.subplots_adjust(right = 1)
fig.subplots_adjust(left = 0)
fig.savefig(OUTDIR + voice_name + '.png', transparent=True, dpi = 32)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment