2016-10-12 23:50:00 +02:00
|
|
|
from __future__ import print_function
|
|
|
|
import numpy as np
|
2016-10-14 07:27:45 +02:00
|
|
|
import config
|
2016-11-08 02:41:26 +01:00
|
|
|
import melbank
|
2016-10-12 23:50:00 +02:00
|
|
|
|
2016-10-23 06:55:22 +02:00
|
|
|
|
2016-11-08 02:41:26 +01:00
|
|
|
class ExpFilter:
|
2016-10-23 06:55:22 +02:00
|
|
|
"""Simple exponential smoothing filter"""
|
|
|
|
def __init__(self, val=0.0, alpha_decay=0.5, alpha_rise=0.5):
|
|
|
|
"""Small rise / decay factors = more smoothing"""
|
|
|
|
assert 0.0 < alpha_decay < 1.0, 'Invalid decay smoothing factor'
|
|
|
|
assert 0.0 < alpha_rise < 1.0, 'Invalid rise smoothing factor'
|
|
|
|
self.alpha_decay = alpha_decay
|
|
|
|
self.alpha_rise = alpha_rise
|
|
|
|
self.value = val
|
|
|
|
|
|
|
|
def update(self, value):
|
2016-12-27 10:13:02 +01:00
|
|
|
if isinstance(self.value, (list, np.ndarray, tuple)):
|
2016-10-23 06:55:22 +02:00
|
|
|
alpha = value - self.value
|
|
|
|
alpha[alpha > 0.0] = self.alpha_rise
|
|
|
|
alpha[alpha <= 0.0] = self.alpha_decay
|
|
|
|
else:
|
|
|
|
alpha = self.alpha_rise if value > self.value else self.alpha_decay
|
|
|
|
self.value = alpha * value + (1.0 - alpha) * self.value
|
|
|
|
return self.value
|
|
|
|
|
|
|
|
|
|
|
|
def rfft(data, window=None):
|
2016-10-25 01:42:03 +02:00
|
|
|
window = 1.0 if window is None else window(len(data))
|
2016-11-08 02:41:26 +01:00
|
|
|
ys = np.abs(np.fft.rfft(data * window))
|
2016-10-23 06:55:22 +02:00
|
|
|
xs = np.fft.rfftfreq(len(data), 1.0 / config.MIC_RATE)
|
2016-10-12 23:50:00 +02:00
|
|
|
return xs, ys
|
|
|
|
|
|
|
|
|
2016-10-23 06:55:22 +02:00
|
|
|
def fft(data, window=None):
|
2016-10-25 01:42:03 +02:00
|
|
|
window = 1.0 if window is None else window(len(data))
|
2016-11-08 02:41:26 +01:00
|
|
|
ys = np.fft.fft(data * window)
|
2016-10-23 06:55:22 +02:00
|
|
|
xs = np.fft.fftfreq(len(data), 1.0 / config.MIC_RATE)
|
|
|
|
return xs, ys
|
2016-10-14 07:27:45 +02:00
|
|
|
|
|
|
|
|
2017-01-04 01:09:39 +01:00
|
|
|
samples = int(config.MIC_RATE * config.N_ROLLING_HISTORY / (2.0 * config.FPS))
|
2016-11-22 05:11:16 +01:00
|
|
|
mel_y, (_, mel_x) = melbank.compute_melmat(num_mel_bands=config.N_FFT_BINS,
|
2016-11-08 02:41:26 +01:00
|
|
|
freq_min=config.MIN_FREQUENCY,
|
|
|
|
freq_max=config.MAX_FREQUENCY,
|
|
|
|
num_fft_bands=samples,
|
2016-11-12 00:52:00 +01:00
|
|
|
sample_rate=config.MIC_RATE)
|
|
|
|
|
2016-12-25 06:54:43 +01:00
|
|
|
|
2016-11-12 00:52:00 +01:00
|
|
|
def create_mel_bank(n_history):
|
|
|
|
global samples, mel_y, mel_x
|
|
|
|
config.N_ROLLING_HISTORY = n_history
|
2017-01-04 01:09:39 +01:00
|
|
|
samples = int(config.MIC_RATE * config.N_ROLLING_HISTORY / (2.0 * config.FPS))
|
2016-11-22 05:11:16 +01:00
|
|
|
mel_y, (_, mel_x) = melbank.compute_melmat(num_mel_bands=config.N_FFT_BINS,
|
2016-11-12 00:52:00 +01:00
|
|
|
freq_min=config.MIN_FREQUENCY,
|
|
|
|
freq_max=config.MAX_FREQUENCY,
|
|
|
|
num_fft_bands=samples,
|
|
|
|
sample_rate=config.MIC_RATE)
|