Python实战:5步搞定MFCC语音特征提取(附完整代码)
Python实战5步搞定MFCC语音特征提取附完整代码语音识别技术正以前所未有的速度渗透到智能家居、车载系统和虚拟助手等场景中。作为这项技术的核心梅尔频率倒谱系数MFCC因其对人耳听觉特性的高度模拟成为最常用的语音特征提取方法之一。本文将用Python带你完整实现MFCC特征提取流程从理论到代码实现每个步骤都配有可运行的示例。1. 环境准备与音频预处理在开始提取MFCC特征前我们需要搭建合适的工作环境并准备好待处理的音频数据。核心工具包安装pip install numpy scipy matplotlib python_speech_features音频信号预处理是MFCC提取的第一步主要包括以下关键操作import numpy as np import matplotlib.pyplot as plt from scipy.io import wavfile # 读取音频文件 sample_rate, signal wavfile.read(speech.wav) signal signal[:int(3.5*sample_rate)] # 截取前3.5秒 # 信号归一化 signal signal / np.max(np.abs(signal)) # 预加重处理 pre_emphasis 0.97 emphasized_signal np.append(signal[0], signal[1:] - pre_emphasis * signal[:-1]) # 可视化对比 plt.figure(figsize(12,4)) plt.subplot(211) plt.plot(signal) plt.title(原始信号) plt.subplot(212) plt.plot(emphasized_signal) plt.title(预加重后信号) plt.tight_layout() plt.show()注意预加重系数通常取值0.95-0.97用于增强高频分量补偿语音信号在发声过程中被抑制的高频部分。2. 分帧与加窗处理语音信号是准平稳信号需要在短时窗口内进行处理。典型的分帧参数设置如下参数推荐值说明帧长25ms对应400个采样点(16kHz采样率)帧移10ms相邻帧重叠15ms窗函数汉明窗减少频谱泄漏实现分帧加窗的Python代码def framesig(sig, frame_len, frame_step, winfuncnp.hamming): slen len(sig) frame_len int(round(frame_len)) frame_step int(round(frame_step)) num_frames int(np.ceil(float(slen - frame_len) / frame_step)) padlen num_frames * frame_step frame_len zeros np.zeros((padlen - slen,)) padsignal np.concatenate((sig, zeros)) indices np.tile(np.arange(0, frame_len), (num_frames, 1)) \ np.tile(np.arange(0, num_frames * frame_step, frame_step), (frame_len, 1)).T frames padsignal[indices.astype(np.int32, copyFalse)] frames * winfunc(frame_len) return frames frame_size 0.025 # 25ms frame_stride 0.01 # 10ms frames framesig(emphasized_signal, frame_size*sample_rate, frame_stride*sample_rate)3. 频域分析与梅尔滤波器组将时域信号转换到频域后我们需要构建符合人耳听觉特性的梅尔尺度滤波器组def mel2hz(mel): return 700 * (10**(mel/2595.0) - 1) def hz2mel(hz): return 2595 * np.log10(1 hz/700.0) def get_filterbanks(nfilt26, nfft512, samplerate16000): lowmel hz2mel(0) highmel hz2mel(samplerate/2) melpoints np.linspace(lowmel, highmel, nfilt2) hzpoints mel2hz(melpoints) bin np.floor((nfft1)*hzpoints/samplerate) fbank np.zeros((nfilt, int(nfft/21))) for j in range(1, nfilt1): for i in range(int(bin[j-1]), int(bin[j])): fbank[j-1,i] (i - bin[j-1]) / (bin[j]-bin[j-1]) for i in range(int(bin[j]), int(bin[j1])): fbank[j-1,i] (bin[j1]-i) / (bin[j1]-bin[j]) return fbank # 计算功率谱 NFFT 512 mag_frames np.absolute(np.fft.rfft(frames, NFFT)) pow_frames (1.0/NFFT) * (mag_frames**2) # 创建梅尔滤波器组 filter_banks get_filterbanks(nfilt26, nfftNFFT, sampleratesample_rate) # 应用滤波器组 filter_banks np.dot(pow_frames, filter_banks.T) filter_banks np.where(filter_banks 0, np.finfo(float).eps, filter_banks) filter_banks 20 * np.log10(filter_banks) # 转换为dB尺度 # 可视化滤波器组 plt.figure(figsize(10,4)) plt.imshow(filter_banks.T, aspectauto, originlower) plt.colorbar() plt.title(梅尔滤波器组能量) plt.show()4. 离散余弦变换与MFCC系数对滤波器组输出进行DCT变换得到最终的MFCC系数from scipy.fftpack import dct def mfcc(filter_banks, num_ceps12): mfcc dct(filter_banks, type2, axis1, normortho)[:, 1:(num_ceps1)] # 倒谱提升 (nframes, ncoeff) mfcc.shape n np.arange(ncoeff) cep_lifter 22 lift 1 (cep_lifter/2) * np.sin(np.pi * n / cep_lifter) mfcc * lift # 均值归一化 mfcc - (np.mean(mfcc, axis0) 1e-8) return mfcc mfcc_features mfcc(filter_banks) # 可视化MFCC特征 plt.figure(figsize(12,4)) plt.imshow(mfcc_features.T, aspectauto, originlower, cmapjet) plt.colorbar() plt.title(MFCC特征) plt.ylabel(MFCC系数) plt.xlabel(帧) plt.show()5. 完整实现与进阶优化将上述步骤整合为完整的MFCC提取流程并添加一些实用优化技巧def extract_mfcc(audio_path, n_mfcc13, n_fft512, win_length0.025, hop_length0.01, n_mels26): # 1. 读取并预处理音频 sample_rate, signal wavfile.read(audio_path) signal signal[:int(3.5*sample_rate)] signal signal / np.max(np.abs(signal)) # 2. 预加重 pre_emphasis 0.97 emphasized_signal np.append(signal[0], signal[1:] - pre_emphasis * signal[:-1]) # 3. 分帧加窗 frame_length int(win_length * sample_rate) frame_step int(hop_length * sample_rate) frames framesig(emphasized_signal, frame_length, frame_step) # 4. 计算功率谱 mag_frames np.absolute(np.fft.rfft(frames, n_fft)) pow_frames (1.0/n_fft) * (mag_frames**2) # 5. 梅尔滤波器组 filter_banks get_filterbanks(nfiltn_mels, nfftn_fft, sampleratesample_rate) filter_banks np.dot(pow_frames, filter_banks.T) filter_banks np.where(filter_banks 0, np.finfo(float).eps, filter_banks) filter_banks 20 * np.log10(filter_banks) # 6. DCT变换得到MFCC mfcc_features dct(filter_banks, type2, axis1, normortho)[:, 1:(n_mfcc1)] # 7. 倒谱提升 (nframes, ncoeff) mfcc_features.shape n np.arange(ncoeff) cep_lifter 22 lift 1 (cep_lifter/2) * np.sin(np.pi * n / cep_lifter) mfcc_features * lift # 8. 均值归一化 mfcc_features - (np.mean(mfcc_features, axis0) 1e-8) return mfcc_features, sample_rate # 使用示例 mfcc_features, sr extract_mfcc(speech.wav) # 添加动态特征(一阶和二阶差分) def add_deltas(mfcc_features): delta np.zeros_like(mfcc_features) for i in range(1, len(mfcc_features)-1): delta[i] (mfcc_features[i1] - mfcc_features[i-1]) / 2 delta_delta np.zeros_like(delta) for i in range(1, len(delta)-1): delta_delta[i] (delta[i1] - delta[i-1]) / 2 return np.hstack((mfcc_features, delta, delta_delta)) full_features add_deltas(mfcc_features)实际项目中MFCC特征通常会配合以下优化策略能量特征将每帧的能量作为额外特征差分系数计算一阶和二阶差分表征动态特征归一化对特征进行CMVN(倒谱均值方差归一化)处理降维使用PCA或LDA对高维特征进行降维# 计算帧能量 def compute_energy(frames): return np.sum(frames**2, axis1) energy compute_energy(frames) energy np.log(energy 1e-8) # 对数能量 energy energy.reshape(-1, 1) # 转为列向量 # 合并MFCC和能量特征 mfcc_with_energy np.hstack((mfcc_features, energy)) # CMVN归一化 def cmvn(features): mean np.mean(features, axis0) std np.std(features, axis0) return (features - mean) / (std 1e-8) normalized_features cmvn(mfcc_with_energy)通过这五个步骤我们完成了从原始语音信号到MFCC特征的完整提取流程。在实际语音识别系统中这些特征将被输入到声学模型中进行进一步处理。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2448363.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!