将频谱图存储为Python中的图像 [英] Store the Spectrogram as Image in Python

查看:214
本文介绍了将频谱图存储为Python中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将音频的STFT频谱图存储为图像.下面的代码向我显示了一个频谱图,但是当另存为图像时,我得到了另一幅图像.

I want to store the STFT spectrogram of the audio as image. The code below shows a spectrogram to me as output, but when saved as image I get a different image.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

audio_name = '---.au'
hop_length = 512
window_size = 1024

import librosa
y, sr = librosa.load(audio_name)
window = np.hanning(window_size)
out  = librosa.core.spectrum.stft(y, n_fft = window_size, hop_length = hop_length, 
       window=window)
out = 2 * np.abs(out) / np.sum(window)

import librosa.display
librosa.display.specshow(librosa.amplitude_to_db(out,ref=np.max),
               y_axis='log', x_axis='time')

from PIL import Image
img = Image.fromarray(out)    
if img.mode != 'RGBA':
    img = img.convert('RGBA')
img.save('output.png')

但是当我保存它时,输出文件是黑色图像.

But when I save it the output file is a black image.

我要保存光谱仪的确切图像.

I want to save the exact image of the spectogrm.

推荐答案

如果您确切想要librosa.display.spectrogram()将会显示的内容,请使用matplotlib将图保存到文件中:

If you want exactly what librosa.display.spectrogram() will show, then use matplotlib to save the plot to a file:

import matplotlib.pyplot as plt
import librosa.display

import numpy as np
import pandas as pd
import librosa


filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)
y = y[:100000] # shorten audio a bit for speed

window_size = 1024
window = np.hanning(window_size)
stft  = librosa.core.spectrum.stft(y, n_fft=window_size, hop_length=512, window=window)
out = 2 * np.abs(stft) / np.sum(window)

# For plotting headlessly
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

fig = plt.Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
p = librosa.display.specshow(librosa.amplitude_to_db(out, ref=np.max), ax=ax, y_axis='log', x_axis='time')
fig.savefig('spec.png')

spec.png:

这篇关于将频谱图存储为Python中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆