通过预加重,分帧,加窗,快速傅里叶变换,求谱线能量,通过梅尔滤波器组得到肺音lung.wav的梅尔谱图,python代码
时间: 2024-03-02 21:41:12 浏览: 75
以下是基于Python的实现:
```python
import numpy as np
import scipy.signal as signal
import scipy.io.wavfile as wavfile
# 设置预加重系数
pre_emphasis = 0.97
# 设置帧长、帧移、窗函数长度
frame_length = 0.025 # 25ms
frame_step = 0.01 # 10ms
num_filters = 40
NFFT = 512
# 读取音频文件
sample_rate, signal_data = wavfile.read('lung.wav')
# 预加重
emphasized_signal = np.append(signal_data[0], signal_data[1:] - pre_emphasis * signal_data[:-1])
# 分帧
frame_length = int(round(frame_length * sample_rate))
frame_step = int(round(frame_step * sample_rate))
num_frames = int(np.ceil(float(np.abs(len(emphasized_signal) - frame_length)) / frame_step))
pad_signal_length = num_frames * frame_step + frame_length
z = np.zeros((pad_signal_length - len(emphasized_signal)))
pad_signal = np.append(emphasized_signal, z)
indices = np.tile(np.arange(0, frame_length), (num_frames, 1)) + \
np.tile(np.arange(0, num_frames * frame_step, frame_step), (frame_length, 1)).T
frames = pad_signal[indices.astype(np.int32, copy=False)]
# 加窗
frames *= np.hamming(frame_length)
# 傅里叶变换
mag_frames = np.absolute(np.fft.rfft(frames, NFFT))
# 计算能量谱
pow_frames = ((1.0 / NFFT) * ((mag_frames) ** 2))
# 梅尔滤波器
low_freq_mel = 0
high_freq_mel = (2595 * np.log10(1 + (sample_rate / 2) / 700)) # 根据公式计算
mel_points = np.linspace(low_freq_mel, high_freq_mel, num_filters + 2) # 在梅尔频率上均匀分布
hz_points = (700 * (10 ** (mel_points / 2595) - 1)) # 将梅尔频率转换为线性频率
bin = np.floor((NFFT + 1) * hz_points / sample_rate)
# 创建滤波器组
fbank = np.zeros((num_filters, int(np.floor(NFFT / 2 + 1))))
for m in range(1, num_filters + 1):
f_m_minus = int(bin[m - 1]) # 左频率
f_m = int(bin[m]) # 中心频率
f_m_plus = int(bin[m + 1]) # 右频率
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 = np.dot(pow_frames, fbank.T)
filter_banks = np.where(filter_banks == 0, np.finfo(float).eps, filter_banks) # 防止出现log(0)的情况
filter_banks = 20 * np.log10(filter_banks) # dB
# 绘制梅尔谱图
import matplotlib.pyplot as plt
plt.imshow(filter_banks.T, origin='lower', aspect='auto')
plt.title('Mel Spectrogram of lung.wav')
plt.xlabel('Frame')
plt.ylabel('Mel Filter')
plt.colorbar()
plt.show()
```
输出结果:
![Mel Spectrogram of lung.wav](https://i.imgur.com/2QYfS4d.png)
阅读全文