'How to directly save spectrogram image to specific pixel size

I am generating spectrograms and casting them to images for use in a CNN. How can I directly specify the pixel size of the spectrogram. This is what I have so far:

import matplotlib.pyplot as plt
import librosa
import librosa.display


filename = (r'G:pt5GAL_TCL_mono.wav')

y, sr = librosa.load(filename)

fig, ax = plt.subplots(figsize=(5, 5))
ax.set_axis_off()
ax.specgram(y, Fs=2);
fig.savefig(f'test1.png', bbox_inches='tight', pad_inches=0)

Whith this approach, I have to save the file, then recall it to save it as a 244x244 image.

img = Image.open(f'test1.png')
il = img.resize((224, 224))
imageio.imwrite(f'test1.png', il)

How can I do this directly? That is, save the spectrogram data directly as a 244x244 image with no white border?

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source