python - 如何将频谱图数据转换为张量(或多维 numpy 数组)?

标签 python numpy keras scipy tensor

我正在使用keras并且有:

        corrupted_samples, corrupted_sample_rate = sf.read(
            self.corrupted_audio_file_paths[index])

        frequencies, times, spectrogram = scipy.signal.spectrogram(
            corrupted_samples, corrupted_sample_rate)

根据the docs ,这给出:

f (ndarray) - Array of sample frequencies.
t (ndarray) - Array of segment times.
Sxx (ndarray) - Spectrogram of x. By default, the last axis of Sxx corresponds to the segment times.

我假设所有时间都会排队,所以我不关心时间的值(value)(我不认为)。 频率也是如此。所以我实际需要的是每个频率的每个时间的值,它由我的代码中的 Sxx(或频谱图)给出。我不确定如何实际做到这一点。虽然看起来很简单。

最佳答案

基于https://towardsdatascience.com/speech-recognition-analysis-f03ff9ce78e9 ,作者表示频谱图是声音的频谱时间表示,并展示了将 wav 文件转换为频谱图的一些步骤。

其中一个示例如下:

## Check the sampling rate of the WAV file.
audio_file = './siren_mfcc_demo.wav'


import wave
with wave.open(audio_file, "rb") as wave_file:
    sr = wave_file.getframerate()
print(sr)

audio_binary = tf.read_file(audio_file)

# tf.contrib.ffmpeg not supported on Windows, refer to issue
# https://github.com/tensorflow/tensorflow/issues/8271
waveform = tf.contrib.ffmpeg.decode_audio(audio_binary, file_format='wav', samples_per_second=sr, channel_count=1)
print(waveform.numpy().shape)

signals = tf.reshape(waveform, [1, -1])
signals.get_shape()

# Compute a [batch_size, ?, 128] tensor of fixed length, overlapping windows
# where each window overlaps the previous by 75% (frame_length - frame_step
# samples of overlap).
frames = tf.contrib.signal.frame(signals, frame_length=128, frame_step=32)
print(frames.numpy().shape)

# `magnitude_spectrograms` is a [batch_size, ?, 129] tensor of spectrograms. We
# would like to produce overlapping fixed-size spectrogram patches; for example,
# for use in a situation where a fixed size input is needed.
magnitude_spectrograms = tf.abs(tf.contrib.signal.stft(
    signals, frame_length=256, frame_step=64, fft_length=256))

print(magnitude_spectrograms.numpy().shape)

以上方法引用https://colab.research.google.com/drive/1Adcy25HYC4c9uSBDK9q5_glR246m-TSx#scrollTo=QTa1BVSOw1Oe

希望对您有帮助。

关于python - 如何将频谱图数据转换为张量(或多维 numpy 数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60255152/

相关文章:

python - 如何使用 python 将 mbox 文件转换为 .msg 文件格式?

python - Pysys 与 Apama - 在将事件与引用进行比较时如何仅对某些参数进行验证?

python - numpy.extract 和 numpy.any 函数,是否可以使其更简单?

python - 成功安装 NumPy,但无法使用 virtualenv 访问

python - 使用 Keras,如何将 CuDNNLSTM 生成的权重加载到 LSTM 模型中?

tensorflow - Keras 详细训练进度条在每个批处理问题上写一个新行

tensorflow - keras 学习的 LSTM 网络中的前向传递

Python 初学者循环(寻找素数)

python - 根据 groupby 和条件对列求和

python - 如何在 Python shell 中导入 NumPy