音频信号特征提取和图像生成:语谱图、梅尔谱图和MFCC
import librosa
import librosa.display
import matplotlib.pyplot as plt
import os
from PIL import Image
import numpy as np
# 设置数据集路径和语谱图保存路径
dataset_path = 'D:/论文代码/casia汉语情感语料库/'
spectrogram_path = 'D:/论文代码/语谱图/'
# 设置生成的图像大小
img_height = 256
img_width = 256
# 遍历数据集中各个子目录,对每个文件夹下的音频文件生成对应的语谱图
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=(img_width/100, img_height/100)) # 设置图像大小
librosa.display.specshow(D, y_axis='linear')
plt.colorbar(format='%+2.0f dB')
plt.savefig(spectrogram_path_full, bbox_inches='tight', pad_inches=0, dpi=100) # 设置图像分辨率
plt.clf()
plt.close('all')
# 设置数据集路径
dataset_dir = 'D:/论文代码/casia汉语情感语料库/'
# 设置生成的图像大小
img_height = 256
img_width = 256
# 循环遍历所有子目录
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=(img_width/100, img_height/100)) # 设置图像大小
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, bbox_inches='tight', pad_inches=0, dpi=100) # 设置图像分辨率
plt.close()
import os
import librosa
import librosa.display
import numpy as np
import matplotlib.pyplot as plt
# 定义函数将音频信号转化为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=(img_width/100, img_height/100)) # 设置图像大小
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), bbox_inches='tight', pad_inches=0, dpi=100) # 设置图像分辨率
plt.close()
# 设置数据集路径和MFCC图像保存路径
data_path = 'D:/论文代码/casia汉语情感语料库/'
save_path = 'D:/论文代码/MFCC/'
# 设置生成的图像大小
img_height = 256
img_width = 256
# 遍历数据集中的所有音频文件,并转化为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):
image = Image.open(image_path)
image = image.convert('L') # 转换为灰度图像
image_data = np.array(image)
return image_data
# 将numpy数组保存为图片
def save_image(image_data, save_path):
image = Image.fromarray(np.uint8(image_data))
image.save(save_path)
# 获取特征图乘积
def get_feature_product(feature_dirs):
feature_product = None
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)
for i in range(len(filenames)):
filename = filenames[i]
if i == 0:
feature_product = load_image(os.path.join(subdir, filename))
else:
feature = load_image(os.path.join(subdir, filename))
feature_product *= feature
save_path = os.path.join(save_dir, filename)
save_image(feature_product, save_path)
print('特征图乘积已保存至D:/论文代码/特征图乘积')
# 设置生成的图像大小
img_height = 256
img_width = 256
# 对应的特征图进行特征图相乘
if __name__ == '__main__':
feature_dirs = ['D:/论文代码/spectrograms', 'D:/论文代码/语谱图', 'D:/论文代码/MFCC']
get_feature_product(feature_dirs)
报错解决方法:
operands could not be broadcast together with shapes (211,306) (205,306) (211,306) 这个错误通常是由于numpy数组的尺寸不匹配所致。可以检查代码中涉及到的numpy数组的尺寸并确认它们是否一致。如果不一致,可以考虑对数组进行重塑或者插值等处理,使它们的尺寸一致。具体方法需要根据具体情况进行调整。
例如:
在get_feature_product函数中,feature_product *= feature 这行代码可能会出现错误,因为feature_product和feature的形状可能不一致。为了解决这个问题,可以将feature数组的形状调整为与feature_product一致,然后进行乘积运算。例如:
feature = load_image(os.path.join(subdir, filename))
feature = np.resize(feature, feature_product.shape)
feature_product *= feature
其他可能的原因:
- 代码中可能存在逻辑错误,导致生成的特征图尺寸不一致。需要仔细检查代码逻辑,确保所有特征图的尺寸一致。
- 音频文件本身可能存在问题,导致提取的特征图尺寸不一致。需要检查音频文件,确保它们都是有效的音频文件。
建议:
- 使用调试工具,逐步检查代码执行过程,查看各个变量的尺寸和值,以便找出错误原因。
- 打印输出相关变量的尺寸,帮助定位问题。
- 仔细阅读librosa库的官方文档,了解各个函数的参数和返回值,确保正确使用函数。
- 如果问题依然存在,可以将代码和相关信息提供给技术论坛或开发者社区寻求帮助。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/nLfb 著作权归作者所有。请勿转载和采集!