gpt4 book ai didi

python-3.x - 将频谱图存储为Python中的图像

转载 作者:行者123 更新时间:2023-12-02 22:45:05 26 4
gpt4 key购买 nike

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

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

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

但是,当我保存它时,输出文件是黑色图像。 enter image description here

我想保存spectogrm的确切图像。

最佳答案

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

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:

spec.png

关于python-3.x - 将频谱图存储为Python中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52432731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com