0

I am trying to plot a spectrogram using custom width and height but when I run the followding code it throws me the following error, but when i remove the custom width and height it works fine but it creates the spectrogram in a 515x389

Code:

 filename = path
x, sr = librosa.load(filename, mono=True)
widthHeight = (432, 288)
plt.figure(figsize=widthHeight)
plt.specgram(x, NFFT=2048, Fs=2, Fc=0, noverlap=128, cmap='inferno', sides='default', mode='default', scale='dB')
plt.axis('off')
plt.savefig("spec.png", bbox_inches='tight', transparent=True)
plt.clf()

Error

_tkinter.TclError: not enough free memory for image buffer
Blacky_99
  • 155
  • 4
  • 20
  • 1
    Width and height are the figure size in inches. You are making a figure that is 10 m x 8 m and overfilling your memory. – Jody Klymak Mar 11 '21 at 05:38
  • @JodyKlymak what would be the conversion rate then if i would want to convert it to 432 pixels bv 288 ? – Blacky_99 Mar 11 '21 at 05:40
  • default 72 pixels per inch – JohanC Mar 11 '21 at 05:56
  • @JodyKlymak thanks for doing the math. That is pretty funny – joostblack Mar 11 '21 at 06:37
  • inches to pixels is set by dpi (dots per inch). Default is usually 100. But you can specify this in `plt.savefig(..., dpi=200)`. If you want to specify figures with a certain number of pixels, you just need to know the dpi you will save with. May as well, use the default, so `widthHeight=(4.32, 2.88)` should get you a figure that is 432x288 pixels. Note, however, the axes is not 432x288 pixels, the whole figure is. – Jody Klymak Mar 11 '21 at 17:14

2 Answers2

1

Width and height are the figure size in inches. I was making a figure that was 10 m x 8 m and overfilling your memory

filename = path
x, sr = librosa.load(filename, mono=True)
widthHeight = (5.32, 3.49)
plt.figure(figsize=widthHeight)
plt.specgram(x, NFFT=2048, Fs=2, Fc=0, noverlap=128, cmap='inferno', sides='default', mode='default', scale='dB')
plt.axis('off')
plt.savefig("spec.png", bbox_inches='tight', transparent=True)
plt.clf()
Blacky_99
  • 155
  • 4
  • 20
0

If you are looking to save just the spectrogram data as image, see How can I save a Librosa spectrogram plot as a specific sized image?

If you want to have the plot but use librosa to compute spectrograms instead of matplotlib, see this answer. This allows using mel-spectrograms etc, common and better performing for Machine Learning etc.

Jon Nordby
  • 5,494
  • 1
  • 21
  • 50