-
Notifications
You must be signed in to change notification settings - Fork 25
/
feature_extraction.py
66 lines (53 loc) · 2.02 KB
/
feature_extraction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# -*- coding: utf-8 -*-
"""
@author: Jason Zhang
@github: https://github.com/JasonZhang156/Sound-Recognition-Tutorial
"""
import numpy as np
import librosa
import random
def extract_logmel(y, sr, size=3):
"""
extract log mel spectrogram feature
:param y: the input signal (audio time series)
:param sr: sample rate of 'y'
:param size: the length (seconds) of random crop from original audio, default as 3 seconds
:return: log-mel spectrogram feature
"""
# normalization
y = y.astype(np.float32)
normalization_factor = 1 / np.max(np.abs(y))
y = y * normalization_factor
# random crop
start = random.randint(0, len(y) - size * sr)
y = y[start: start + size * sr]
# extract log mel spectrogram #####
melspectrogram = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=2048, hop_length=1024, n_mels=60)
logmelspec = librosa.power_to_db(melspectrogram)
return logmelspec
def extract_mfcc(y, sr, size=3):
"""
extract MFCC feature
:param y: np.ndarray [shape=(n,)], real-valued the input signal (audio time series)
:param sr: sample rate of 'y'
:param size: the length (seconds) of random crop from original audio, default as 3 seconds
:return: MFCC feature
"""
# normalization
y = y.astype(np.float32)
normalization_factor = 1 / np.max(np.abs(y))
y = y * normalization_factor
# random crop
start = random.randint(0, len(y) - size * sr)
y = y[start: start + size * sr]
# extract log mel spectrogram #####
melspectrogram = librosa.feature.melspectrogram(y=y, sr=sr, n_fft=2048, hop_length=1024)
mfcc = librosa.feature.mfcc(S=librosa.power_to_db(melspectrogram), n_mfcc=20)
mfcc_delta = librosa.feature.delta(mfcc)
mfcc_delta_delta = librosa.feature.delta(mfcc_delta)
mfcc_comb = np.concatenate([mfcc, mfcc_delta, mfcc_delta_delta], axis=0)
return mfcc_comb
if __name__ == '__main__':
# a demo sample
y, sr = librosa.load('./data/esc10/audio/Chainsaw/1-19898-A.ogg')
feat = extract_mfcc(y, sr, size=3)