This code implements the One Euro Filter, a smoothing filter designed for real-time applications where noisy signals need to be smoothed while preserving responsiveness to rapid changes. It consists of two main components: the LowPassFilter class and the OneEuroFilter class, along with a helper function get_alpha.
get_alpha Functiondef get_alpha(rate=30, cutoff=1):
tau = 1 / (2 * math.pi * cutoff)
te = 1 / rate
return 1 / (1 + tau / te)
alpha) for a low-pass filter based on the sampling rate (rate) and cutoff frequency (cutoff).rate: The sampling rate (e.g., frames per second). Default is 30.cutoff: The cutoff frequency of the filter. Default is 1.tau: The time constant of the filter, inversely proportional to the cutoff frequency.te: The sampling period, calculated as the reciprocal of the sampling rate.alpha: The smoothing factor, which determines how much weight is given to the current value versus the previous value. A higher alpha gives more weight to the current value.alpha value.LowPassFilter Classclass LowPassFilter:
def __init__(self):
self.x_previous = None
def __call__(self, x, alpha=0.5):
if self.x_previous is None:
self.x_previous = x
return x
x_filtered = alpha * x + (1 - alpha) * self.x_previous
self.x_previous = x_filtered
return x_filtered
x_previous: Stores the previous filtered value.__call__(x, alpha): Applies the low-pass filter to the input x using the smoothing factor alpha.
x_previous is None), the current value is returned as the filtered value.x_previous with the filtered value.OneEuroFilter Classclass OneEuroFilter:
def __init__(self, freq=15, mincutoff=1, beta=0.05, dcutoff=1):
self.freq = freq
self.mincutoff = mincutoff
self.beta = beta
self.dcutoff = dcutoff
self.filter_x = LowPassFilter()
self.filter_dx = LowPassFilter()
self.x_previous = None
self.dx = None
freq: Sampling frequency (e.g., frames per second).mincutoff: Minimum cutoff frequency for the filter.beta: A parameter that controls how much the cutoff frequency adapts to the rate of change.dcutoff: Cutoff frequency for the derivative of the signal.filter_x: A LowPassFilter instance for smoothing the signal.filter_dx: A LowPassFilter instance for smoothing the derivative of the signal.x_previous: Stores the previous input value.dx: Stores the rate of change of the signal.