如何将Librosa光谱图图保存为特定大小的图像?

2024-04-18 01:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想把光谱图图像输入到一个卷积神经网络中,试图对各种声音进行分类。我希望每个图像精确到384x128像素。然而,当我实际保存图像时,它只有297x98。这是我的密码:

def save_spectrogram(num):
  dpi = 128
  x_pixels = 384
  y_pixels = 128
  samples, sr = load_wave(num)
  stft = np.absolute(librosa.stft(samples))
  db = librosa.amplitude_to_db(stft, ref=np.max)
  fig = plt.figure(figsize=(x_pixels//dpi, y_pixels//dpi), dpi=dpi, frameon=False)
  ax = fig.add_subplot(111)
  ax.axes.get_xaxis().set_visible(False)
  ax.axes.get_yaxis().set_visible(False)
  ax.set_frame_on(False)
  librosa.display.specshow(db, y_axis='linear')
  plt.savefig(TRAIN_IMG+str(num)+'.jpg', bbox_inches='tight', pad_inches=0, dpi=dpi)

有人对我如何解决这个问题有什么建议吗?我也尝试过不使用子绘图,但当我这样做时,它仍然保存为错误的大小,并且有空白/背景


Tags: 图像falsedbnpfigpltaxnum
1条回答
网友
1楼 · 发布于 2024-04-18 01:35:54

绘图是供人类查看的,包含轴标记、标签等对机器学习不有用的内容。要向模型提供光谱图的“图像”,只需输出数据。这些数据可以以任何格式存储,但如果您想使用标准图像格式,则应使用PNG。JPEG等有损压缩会引入压缩伪影

下面是保存光谱图的工作示例代码。请注意,为了获得固定大小的图像输出,代码提取音频信号的固定长度窗口。将音频流划分为这种固定长度的分析窗口是标准做法

示例代码

import librosa
import numpy
import skimage.io

def scale_minmax(X, min=0.0, max=1.0):
    X_std = (X - X.min()) / (X.max() - X.min())
    X_scaled = X_std * (max - min) + min
    return X_scaled

def spectrogram_image(y, sr, out, hop_length, n_mels):
    # use log-melspectrogram
    mels = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=n_mels,
                                            n_fft=hop_length*2, hop_length=hop_length)
    mels = numpy.log(mels + 1e-9) # add small number to avoid log(0)

    # min-max scale to fit inside 8-bit range
    img = scale_minmax(mels, 0, 255).astype(numpy.uint8)
    img = numpy.flip(img, axis=0) # put low frequencies at the bottom in image
    img = 255-img # invert. make black==more energy

    # save as PNG
    skimage.io.imsave(out, img)


if __name__ == '__main__':
    # settings
    hop_length = 512 # number of samples per time-step in spectrogram
    n_mels = 128 # number of bins in spectrogram. Height of image
    time_steps = 384 # number of time-steps. Width of image

    # load audio. Using example from librosa
    path = librosa.util.example_audio_file()
    y, sr = librosa.load(path, offset=1.0, duration=10.0, sr=22050)
    out = 'out.png'

    # extract a fixed length window
    start_sample = 0 # starting at beginning
    length_samples = time_steps*hop_length
    window = y[start_sample:start_sample+length_samples]
    
    # convert to PNG
    spectrogram_image(window, sr=sr, out=out, hop_length=hop_length, n_mels=n_mels)
    print('wrote file', out)

输出

Spectrogram stored as PNG image

相关问题 更多 >

    热门问题