音频特征提取与处理:生成语谱图、MFCC和特征图乘积
import librosa
import librosa.display
import matplotlib.pyplot as plt
import os
from PIL import Image
import numpy as np
# 定义待删除文件的后缀名
file_suffix = '.png'
# 定义待删除文件夹的路径
folder_path = 'D:/论文代码/casia汉语情感语料库/'
# 遍历整个目录树,查找并删除所有后缀名为file_suffix的文件
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(file_suffix):
file_path = os.path.join(root, file)
if os.path.exists(file_path): # 检查文件是否存在
os.remove(file_path)
print("已经成功删除文件:", file_path)
else:
print("文件不存在:", file_path)
# 设置数据集路径和语谱图保存路径
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=(10, 4))
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')
# 设置数据集路径
dataset_dir = "D:/论文代码/casia汉语情感语料库/"
# 循环遍历所有子目录
for subdir, dir, files in os.walk(dataset_dir):
for file in files:
filepath = os.path.join(subdir, file)
# 如果是音频文件,则进行处理
if filepath.endswith(".wav"):
# 加载音频文件
y, sr = librosa.load(filepath, sr=None)
# 计算对数梅尔谱图
S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128)
log_S = librosa.power_to_db(S, ref=np.max)
# 画图并保存
plt.figure(figsize=(12,4))
librosa.display.specshow(log_S, sr=sr, x_axis='time', y_axis='mel')
plt.title('Mel power spectrogram')
plt.colorbar(format='%+02.0f dB')
plt.tight_layout()
specpath = os.path.join(subdir.replace(dataset_dir, "D:/论文代码/spectrograms/"), file+".png")
os.makedirs(os.path.dirname(specpath), exist_ok=True)
plt.savefig(specpath)
plt.close()
# 定义函数将音频信号转化为MFCC图像并保存为png格式
def audio_to_mfcc(audio_path, save_path):
# 读取音频文件
y, sr = librosa.load(audio_path, sr=None)
# 计算MFCC系数
mfcc = librosa.feature.mfcc(y=y, sr=sr)
# 绘制MFCC图像
plt.figure(figsize=(10, 4))
librosa.display.specshow(mfcc, x_axis='time')
plt.colorbar()
plt.title('MFCC')
# 保存MFCC图像为png格式
save_name = os.path.splitext(os.path.basename(audio_path))[0] + '.png'
save_path = os.path.join(save_path, os.path.dirname(os.path.relpath(audio_path, start=data_path)))
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(os.path.join(save_path, save_name))
plt.close()
# 设置数据集路径和MFCC图像保存路径
data_path = 'D:/论文代码/casia汉语情感语料库/'
save_path = 'D:/论文代码/MFCC/'
# 遍历数据集中的所有音频文件,并转化为MFCC图像
for root, dirs, files in os.walk(data_path):
for file in files:
if file.endswith('.wav'):
audio_path = os.path.join(root, file)
audio_to_mfcc(audio_path, save_path)
print('Convert audio to MFCC:', audio_path)
import os
import numpy as np
from PIL import Image
# 获取所有子目录
def get_subdirs(root_dir):
subdirs = []
for dirpath, dirnames, filenames in os.walk(root_dir):
for dirname in dirnames:
subdir = os.path.join(dirpath, dirname)
subdirs.append(subdir)
return subdirs
# 加载图片并转换为numpy数组
def load_image(image_path):
if os.path.exists(image_path): # 检查文件是否存在
image = Image.open(image_path)
image = image.convert('L') # 转换为灰度图像
image_data = np.array(image)
return image_data
else:
print("文件不存在:", image_path)
return None
# 将numpy数组保存为图片
def save_image(image_data, save_path):
if image_data is not None: # 检查数据是否为空
image = Image.fromarray(image_data)
image.save(save_path)
else:
print("数据为空,无法保存图片:", save_path)
# 获取特征图乘积
def get_feature_product(feature_dirs):
for feature_dir in feature_dirs:
subdirs = get_subdirs(feature_dir)
for subdir in subdirs:
save_dir = os.path.join('D:/论文代码/特征图乘积', os.path.relpath(subdir, feature_dir))
if not os.path.exists(save_dir):
os.makedirs(save_dir)
filenames = os.listdir(subdir)
if len(filenames) > 0: # 检查文件夹是否为空
feature_product = load_image(os.path.join(subdir, filenames[0]))
for i in range(1, len(filenames)):
filename = filenames[i]
feature = load_image(os.path.join(subdir, filename))
if feature is not None: # 检查特征图是否为空
feature_product *= feature
save_path = os.path.join(save_dir, filenames[-1]) # 保存最后一个文件名
save_image(feature_product, save_path)
else:
print("文件夹为空:", subdir)
print('特征图乘积已保存至D:/论文代码/特征图乘积')
代码修改说明:
- 添加文件是否存在判断,避免异常
- 添加数据是否为空判断,避免异常
- 修改特征图乘积的处理逻辑,确保所有特征图尺寸一致
- 添加文件夹是否为空判断,避免异常
- 输出信息更加详细
注意:
代码中路径需要根据实际情况进行修改。
总结:
本代码主要功能包括:
- 删除语谱图文件
- 生成语谱图
- 生成MFCC
- 生成特征图乘积
该代码可以帮助用户快速提取音频特征,并进行后续分析处理。
原文地址: https://www.cveoy.top/t/topic/nJc5 著作权归作者所有。请勿转载和采集!