Save an image (only content, without axes or anything else) to a file using Matloptlib
Asked Answered
M

2

5

I'd like to obtain a spectrogram out of a wav file and then save it to a png, but I need just the content of the image (not axes or anything else). I came across these questions
Matplotlib plots: removing axis, legends and white spaces
scipy: savefig without frames, axes, only content
I've also read the Matplotlib documentation but it seems useless and so either answers to questions above are outdated or I'm doing something wrong because simple

plt.savefig('out.png', bbox_inches='tight', pad_inches=0)

does not do what I want to achieve. Initially I tried to follow this guide but the code crashes. Then I tried this approach, but since it's outdated I modified it a little:

import matplotlib.pyplot as plt
from scipy.io import wavfile
import numpy as np

def graph_spectrogram(wav_file):
    rate, data = wavfile.read(wav_file)
    pxx, freqs, bins, im = plt.specgram(x=data, Fs=rate, noverlap=384, NFFT=512)
    plt.axis('off')
    plt.savefig('sp_xyz.png', bbox_inches='tight', dpi=300, frameon='false')

if __name__ == '__main__': # Main function
    graph_spectrogram('...')

This is what I got:
enter image description here Maybe it's not visible, but there's a white border around the content (from the biggest to the smallest): left, bottom, top, right. I want the same image but just the content without anything else. How can I achieve that? I use python 3.6 and Matplotlib 2.0.2.

Monocoque answered 6/11, 2017 at 22:49 Comment(5)
Try pad_inches=0.0 as parameter in plt.savefig(...)Kirkwall
No, unfortunately. I've seen this in comments to the linked questions and I've tried it earlier but it changes nothing.Monocoque
I've just seen you can give a negative value to pad_inches in this answer comment, have you tried that?Blackboard
I've seen that question too, but I didn't tried that, wait a secMonocoque
No, it's not that.Monocoque
D
9

I think you want subplots_adjust:

fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
ax.axis('tight')
ax.axis('off')

In this case:

import matplotlib.pyplot as plt
from scipy.io import wavfile
import numpy as np

def graph_spectrogram(wav_file):
    rate, data = wavfile.read(wav_file)
    fig,ax = plt.subplots(1)
    fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
    ax.axis('off')
    pxx, freqs, bins, im = ax.specgram(x=data, Fs=rate, noverlap=384, NFFT=512)
    ax.axis('off')
    fig.savefig('sp_xyz.png', dpi=300, frameon='false')

if __name__ == '__main__': # Main function
    graph_spectrogram('...')
Dews answered 6/11, 2017 at 23:8 Comment(2)
Now I don't have any content at all, although the image is 1920 x 1440 pxMonocoque
The thing was that I used plt.specgram instead of ax.specgram. ThanksMonocoque
L
2

May be helpful for someone who use librosa latest versions.

You can add transparent=True to the plt.savefig() function to set transparent background. But the problem is still x and y axis information are visible. Hens, you need to remove axis details using ax.set_axis_off()

You can remove right side color-bar by commenting out plt.colorbar()

plt.figure(figsize=(12, 4))
ax = plt.axes()
ax.set_axis_off()
plt.set_cmap('hot')
librosa.display.specshow(librosa.amplitude_to_db(S_full[:, idx], ref=np.max), y_axis='log', x_axis='time',sr=sr)
plt.colorbar()
plt.savefig(f'{args["output"]}/{name}_{i}.png', bbox_inches='tight', transparent=True, pad_inches=0.0 )

Please click images to check differences

When nothing is changed(Default) save image without changing anything

When the axis informations are off Using ax.set_axis_off()

Here, this image doesn't have axis info but white background is there. When axis off

When enabling transparent using transparent= True

Here, this image doesn't have white background but axis info is there. enter image description here

With axis info are off and enabling transparent

This image doesn't have either white background or axis info Axis info is off and enable transparent

You may not see the exact differences since images might be changed when uploading.

Lobo answered 30/9, 2018 at 7:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.