通过预加重,分帧,加窗,快速傅里叶变换,求谱线能量,通过梅尔滤波器组得到肺音lung.wav的梅尔谱图,横坐标为lung.wav的时间,纵坐标为频率,python代码
时间: 2024-05-10 20:19:43 浏览: 108
课程作业基于python实现梅尔频谱的信号分类和识别源码.zip
以下是基于Python的肺音梅尔谱图提取代码:
```python
import numpy as np
import scipy.signal as signal
import scipy.io.wavfile as wavfile
# 定义预处理参数
pre_emphasis = 0.97
frame_size = 0.025
frame_stride = 0.01
NFFT = 512
nfilt = 40
# 定义梅尔滤波器组参数
low_freq_mel = 0
high_freq_mel = (2595 * np.log10(1 + (wavfile.read('lung.wav')[0] / 2) / 700)) # 根据Nyquist频率计算高频
mel_points = np.linspace(low_freq_mel, high_freq_mel, nfilt + 2) # 均匀分布梅尔刻度
hz_points = (700 * (10 ** (mel_points / 2595) - 1)) # 将梅尔刻度转换为赫兹刻度
bin = np.floor((NFFT + 1) * hz_points / wavfile.read('lung.wav')[0])
# 定义加窗函数
hamming = np.hamming
# 加载音频文件
signal, sr = wavfile.read('lung.wav')
# 预加重
emphasized_signal = np.append(signal[0], signal[1:] - pre_emphasis * signal[:-1])
# 分帧
frame_length, frame_step = frame_size * sr, frame_stride * sr
signal_length = len(emphasized_signal)
frame_length = int(round(frame_length))
frame_step = int(round(frame_step))
num_frames = int(np.ceil(float(np.abs(signal_length - frame_length)) / frame_step))
pad_signal_length = num_frames * frame_step + frame_length
z = np.zeros((pad_signal_length - signal_length))
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 *= hamming(frame_length)
# 快速傅里叶变换
mag_frames = np.absolute(np.fft.rfft(frames, NFFT)) # Magnitude of the FFT
pow_frames = ((1.0 / NFFT) * ((mag_frames) ** 2)) # Power Spectrum
# 建立梅尔滤波器组
f_bank = np.zeros((nfilt, int(np.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):
f_bank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])
for k in range(f_m, f_m_plus):
f_bank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])
# 应用梅尔滤波器组
filter_banks = np.dot(pow_frames, f_bank.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, cmap="hot", origin="lower")
plt.xlabel("Time")
plt.ylabel("Frequency")
plt.title("Mel Spectrogram")
plt.colorbar()
plt.show()
```
运行以上代码后将会生成肺音lung.wav的梅尔谱图。
阅读全文