梅尔倒谱系数(MFCC)实现


Posted in Python onJune 19, 2019

本文实例为大家分享了梅尔倒谱系数实现代码,供大家参考,具体内容如下

""" 
@author: zoutai
@file: mymfcc.py 
@time: 2018/03/26 
@description:
"""
from matplotlib.colors import BoundaryNorm
import librosa
import librosa.display
import numpy
import scipy.io.wavfile
from scipy.fftpack import dct
import matplotlib.pyplot as plt
import numpy as np


# 第一步-读取音频,画出时域图(采样率-幅度)
sample_rate, signal = scipy.io.wavfile.read('OSR_us_000_0010_8k.wav') # File assumed to be in the same directory
signal = signal[0:int(3.5 * sample_rate)]
# plot the wave
time = np.arange(0,len(signal))*(1.0 / sample_rate)
# plt.plot(time,signal)
plt.xlabel("Time(s)")
plt.ylabel("Amplitude")
plt.title("Signal in the Time Domain ")
plt.grid('on')#标尺,on:有,off:无。


# 第二步-预加重
# 消除高频信号。因为高频信号往往都是相似的,
# 通过前后时间相减,就可以近乎抹去高频信号,留下低频信号。
# 原理:y(t)=x(t)−αx(t−1)

pre_emphasis = 0.97
emphasized_signal = numpy.append(signal[0], signal[1:] - pre_emphasis * signal[:-1])


time = np.arange(0,len(emphasized_signal))*(1.0 / sample_rate)
# plt.plot(time,emphasized_signal)
# plt.xlabel("Time(s)")
# plt.ylabel("Amplitude")
# plt.title("Signal in the Time Domain after Pre-Emphasis")
# plt.grid('on')#标尺,on:有,off:无。


# 第三步、取帧,用帧表示
frame_size = 0.025 # 帧长
frame_stride = 0.01 # 步长

# frame_length-一帧对应的采样数, frame_step-一个步长对应的采样数
frame_length, frame_step = frame_size * sample_rate, frame_stride * sample_rate # Convert from seconds to samples
signal_length = len(emphasized_signal) # 总的采样数

frame_length = int(round(frame_length))
frame_step = int(round(frame_step))

# 总帧数
num_frames = int(numpy.ceil(float(numpy.abs(signal_length - frame_length)) / frame_step)) # Make sure that we have at least 1 frame

pad_signal_length = num_frames * frame_step + frame_length
z = numpy.zeros((pad_signal_length - signal_length))
pad_signal = numpy.append(emphasized_signal, z) # Pad Signal to make sure that all frames have equal number of samples without truncating any samples from the original signal

# Construct an array by repeating A(200) the number of times given by reps(348).
# 这个写法太妙了。目的:用矩阵来表示帧的次数,348*200,348-总的帧数,200-每一帧的采样数
# 第一帧采样为0、1、2...200;第二帧为80、81、81...280..依次类推
indices = numpy.tile(numpy.arange(0, frame_length), (num_frames, 1)) + numpy.tile(numpy.arange(0, num_frames * frame_step, frame_step), (frame_length, 1)).T
frames = pad_signal[indices.astype(numpy.int32, copy=False)] # Copy of the array indices
# frame:348*200,横坐标348为帧数,即时间;纵坐标200为一帧的200毫秒时间,内部数值代表信号幅度

# plt.matshow(frames, cmap='hot')
# plt.colorbar()
# plt.figure()
# plt.pcolormesh(frames)


# 第四步、加汉明窗
# 傅里叶变换默认操作的时间段内前后端点是连续的,即整个时间段刚好是一个周期,
# 但是,显示却不是这样的。所以,当这种情况出现时,仍然采用FFT操作时,
# 就会将单一频率周期信号认作成多个不同的频率信号的叠加,而不是原始频率,这样就差生了频谱泄漏问题

frames *= numpy.hamming(frame_length) # 相乘,和卷积类似
# # frames *= 0.54 - 0.46 * numpy.cos((2 * numpy.pi * n) / (frame_length - 1)) # Explicit Implementation **

# plt.pcolormesh(frames)


# 第五步-傅里叶变换频谱和能量谱

# _raw_fft扫窗重叠,将348*200,扩展成348*512
NFFT = 512
mag_frames = numpy.absolute(numpy.fft.rfft(frames, NFFT)) # Magnitude of the FFT
pow_frames = ((1.0 / NFFT) * ((mag_frames) ** 2)) # Power Spectrum


# plt.pcolormesh(mag_frames)
#
# plt.pcolormesh(pow_frames)


# 第六步,Filter Banks滤波器组
# 公式:m=2595*log10(1+f/700);f=700(10^(m/2595)−1)
nfilt = 40 #窗的数目
low_freq_mel = 0
high_freq_mel = (2595 * numpy.log10(1 + (sample_rate / 2) / 700)) # Convert Hz to Mel
mel_points = numpy.linspace(low_freq_mel, high_freq_mel, nfilt + 2) # Equally spaced in Mel scale
hz_points = (700 * (10**(mel_points / 2595) - 1)) # Convert Mel to Hz
bin = numpy.floor((NFFT + 1) * hz_points / sample_rate)

fbank = numpy.zeros((nfilt, int(numpy.floor(NFFT / 2 + 1))))
for m in range(1, nfilt + 1):
 f_m_minus = int(bin[m - 1]) # left
 f_m = int(bin[m])  # center
 f_m_plus = int(bin[m + 1]) # right

 for k in range(f_m_minus, f_m):
 fbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])
 for k in range(f_m, f_m_plus):
 fbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])
filter_banks = numpy.dot(pow_frames, fbank.T)
filter_banks = numpy.where(filter_banks == 0, numpy.finfo(float).eps, filter_banks) # Numerical Stability
filter_banks = 20 * numpy.log10(filter_banks) # dB;348*26

# plt.subplot(111)
# plt.pcolormesh(filter_banks.T)
# plt.grid('on')
# plt.ylabel('Frequency [Hz]')
# plt.xlabel('Time [sec]')
# plt.show()


#
# 第七步,梅尔频谱倒谱系数-MFCCs
num_ceps = 12 #取12个系数
cep_lifter=22 #倒谱的升个数??
mfcc = dct(filter_banks, type=2, axis=1, norm='ortho')[:, 1 : (num_ceps + 1)] # Keep 2-13
(nframes, ncoeff) = mfcc.shape
n = numpy.arange(ncoeff)
lift = 1 + (cep_lifter / 2) * numpy.sin(numpy.pi * n / cep_lifter)
mfcc *= lift #*

# plt.pcolormesh(mfcc.T)
# plt.ylabel('Frequency [Hz]')
# plt.xlabel('Time [sec]')


# 第八步,均值化优化
# to balance the spectrum and improve the Signal-to-Noise (SNR), we can simply subtract the mean of each coefficient from all frames.

filter_banks -= (numpy.mean(filter_banks, axis=0) + 1e-8)
mfcc -= (numpy.mean(mfcc, axis=0) + 1e-8)

# plt.subplot(111)
# plt.pcolormesh(mfcc.T)
# plt.ylabel('Frequency [Hz]')
# plt.xlabel('Time [sec]')
# plt.show()


# 直接频谱分析
# plot the wave
# plt.specgram(signal,Fs = sample_rate, scale_by_freq = True, sides = 'default')
# plt.ylabel('Frequency(Hz)')
# plt.xlabel('Time(s)')
# plt.show()



plt.figure(figsize=(10, 4))
mfccs = librosa.feature.melspectrogram(signal,sr=8000,n_fft=512,n_mels=40)
librosa.display.specshow(mfccs, x_axis='time')
plt.colorbar()
plt.title('MFCC')
plt.tight_layout()
plt.show()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python读取excel表格生成erlang数据
Aug 26 Python
教你用Python写安卓游戏外挂
Jan 11 Python
简单实现python数独游戏
Mar 30 Python
Windows下将Python文件打包成.EXE可执行文件的方法
Aug 03 Python
pygame游戏之旅 创建游戏窗口界面
Nov 20 Python
python 遗传算法求函数极值的实现代码
Feb 11 Python
Python3和PyCharm安装与环境配置【图文教程】
Feb 14 Python
Python Scrapy多页数据爬取实现过程解析
Jun 12 Python
Pycharm 解决自动格式化冲突的设置操作
Jan 15 Python
Python实现文本文件拆分写入到多个文本文件的方法
Apr 18 Python
python 使用tkinter与messagebox写界面和弹窗
Mar 20 Python
python运行脚本文件的三种方法实例
Jun 25 Python
python 中的列表生成式、生成器表达式、模块导入
Jun 19 #Python
PyQt5 QTable插入图片并动态更新的实例
Jun 18 #Python
pyqt5 禁止窗口最大化和禁止窗口拉伸的方法
Jun 18 #Python
PyQt5 对图片进行缩放的实例
Jun 18 #Python
梅尔频率倒谱系数(mfcc)及Python实现
Jun 18 #Python
Python生成一个迭代器的实操方法
Jun 18 #Python
利用anaconda保证64位和32位的python共存
Mar 09 #Python
You might like
php+mysql 实现身份验证代码
2010/03/24 PHP
php设计模式  Command(命令模式)
2011/06/17 PHP
php实现redis数据库指定库号迁移的方法
2015/01/14 PHP
PHP MPDF中文乱码的解决方式
2015/12/08 PHP
thinkphp框架下404页面设置 仅三步
2016/05/14 PHP
javascript针对DOM的应用实例(一)
2012/04/15 Javascript
ScrollDown的基本操作示例
2013/06/09 Javascript
js中cookie的添加、取值、删除示例代码
2013/10/21 Javascript
javascript中的if语句使用介绍
2013/11/20 Javascript
js导入导出excel(实例代码)
2013/11/25 Javascript
《JavaScript函数式编程》读后感
2015/08/07 Javascript
javascript学习笔记整理(概述、变量、数据类型简介)
2015/10/25 Javascript
jQuery如何封装输入框插件
2016/08/19 Javascript
微信小程序 支付简单实例及注意事项
2017/01/06 Javascript
js模仿微信朋友圈计算时间显示几天/几小时/几分钟/几秒之前
2017/04/27 Javascript
jquery append与appendTo方法比较
2017/05/24 jQuery
vue项目中应用ueditor自定义上传按钮功能
2018/04/27 Javascript
JS实现方形抽奖效果
2018/08/27 Javascript
如何利用python制作时间戳转换工具详解
2018/09/12 Python
用Python中的turtle模块画图两只小羊方法
2019/04/09 Python
Linux下远程连接Jupyter+pyspark部署教程
2019/06/21 Python
python网络编程socket实现服务端、客户端操作详解
2020/03/24 Python
HTML+CSS3 模仿Windows7 桌面效果
2010/06/17 HTML / CSS
SmartBuyGlasses美国官网:太阳眼镜和眼镜
2017/08/20 全球购物
德国药房apodiscounter中文官网:德国排名前三的网上药店
2019/06/03 全球购物
北美最大的零售退货翻新商:VIP Outlet
2019/11/21 全球购物
PyQt QMainWindow的使用示例
2021/03/24 Python
应届生船舶驾驶求职信
2013/10/19 职场文书
办公室副主任岗位职责
2013/11/25 职场文书
计算机求职自荐信范文
2014/04/19 职场文书
销售行政专员岗位职责
2014/06/10 职场文书
公司人事专员岗位职责
2014/08/11 职场文书
大学生创业事迹材料
2014/12/30 职场文书
2015年信访工作总结
2015/04/07 职场文书
军训新闻稿范文
2015/07/17 职场文书
《詹天佑》教学反思
2016/02/20 职场文书