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

戏子无情 提交于 2019-12-03 09:02:57
4Oh4

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('...')

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)

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 enabling transparent using transparent= True

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

With axis info are off and enabling transparent

This image doesn't have either white background or axis info

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!