Python Librosa 语谱图生成:调整图像大小至 (224, 224)
Python Librosa 语谱图生成:调整图像大小至 (224, 224)
本文将介绍如何使用 Python 的 Librosa 库生成语谱图,并调整图像大小为 (224, 224),这对于图像识别模型训练非常有用。
代码示例
# 设置数据集路径和语谱图保存路径
dataset_path = 'D:/论文代码/casia汉语情感语料库/'
spectrogram_path = 'D:/论文代码/语谱图/'
# 遍历数据集中各个子目录,对每个文件夹下的音频文件生成对应的语谱图
for subfolder in os.listdir(dataset_path):
subfolder_path = os.path.join(dataset_path, subfolder)
# 确保当前为子目录而不是文件
if os.path.isdir(subfolder_path):
for audio_file in os.listdir(subfolder_path):
audio_path = os.path.join(subfolder_path, audio_file)
# 判断是否为音频文件,目前仅支持.wav格式的音频
if audio_file.endswith('.wav'):
# 读取音频文件并进行短时傅里叶变换计算得到语谱图
y, sr = librosa.load(audio_path, sr=None)
D = librosa.amplitude_to_db(np.abs(librosa.stft(y)), ref=np.max)
# 创建保存该语谱图的文件夹
spectrogram_folder = os.path.join(spectrogram_path, subfolder)
os.makedirs(spectrogram_folder, exist_ok=True)
# 保存语谱图到对应的文件夹中
spectrogram_path_full = os.path.join(spectrogram_folder, f'{os.path.splitext(audio_file)[0]}.png')
plt.figure(figsize=(224/80, 224/80))
librosa.display.specshow(D, y_axis='linear')
plt.colorbar(format='%+2.0f dB')
plt.savefig(spectrogram_path_full, bbox_inches='tight', pad_inches=0)
plt.clf()
plt.close('all')
关键代码解释
plt.figure(figsize=(224/80, 224/80)): 在生成语谱图前,使用plt.figure函数设置图像大小为 (224/80, 224/80)。librosa.display.specshow(D, y_axis='linear'): 使用librosa.display.specshow函数绘制语谱图,并设置y_axis='linear'以便将频率轴设置为线性刻度。plt.savefig(spectrogram_path_full, bbox_inches='tight', pad_inches=0): 使用plt.savefig函数保存语谱图,并设置bbox_inches='tight'和pad_inches=0以便去除多余的空白。
总结
本文介绍了如何使用 Python 的 Librosa 库生成语谱图,并调整图像大小为 (224, 224),这对于图像识别模型训练非常有用。希望本教程对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/nLcH 著作权归作者所有。请勿转载和采集!