繁体   English   中英

python中的卡尔曼二维滤波器

[英]kalman 2d filter in python

我的输入是跟踪器软件在屏幕上移动的点的 2d (x,y) 时间序列。 它有一些我想使用卡尔曼滤波器去除的噪音。 有人可以指出我的卡尔曼二维滤波器的python代码吗? 在 scipy 食谱中,我只找到了一个 1d 示例: http : //www.scipy.org/Cookbook/KalmanFiltering我看到 OpenCV 中有卡尔曼滤波器的实现,但找不到代码示例。 谢谢!

这是我根据wikipedia给出方程实现的卡尔曼滤波器。 请注意,我对卡尔曼滤波器的理解非常初级,因此最有可能改进此代码的方法。 (例如,它受到这里讨论的数值不稳定问题的困扰。据我了解,这只会在运动噪声Q非常小时影响数值稳定性。在现实生活中,噪声通常不小,所以幸运的是(至少对于我的实现)在实践中没有出现数值不稳定性。)

在下面的示例中, kalman_xy假设状态向量是一个 4 元组:2 个数字表示位置,2 个数字表示速度。 FH矩阵专门为此状态向量定义:如果x是 4 元组状态,则

new_x = F * x
position = H * x

然后调用kalman ,这是广义卡尔曼滤波器。 从某种意义上说,如果您希望定义不同的状态向量(可能是表示位置、速度和加速度的 6 元组),它仍然很有用。 您只需要通过提供适当的FH来定义运动方程。

import numpy as np
import matplotlib.pyplot as plt

def kalman_xy(x, P, measurement, R,
              motion = np.matrix('0. 0. 0. 0.').T,
              Q = np.matrix(np.eye(4))):
    """
    Parameters:    
    x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot)
    P: initial uncertainty convariance matrix
    measurement: observed position
    R: measurement noise 
    motion: external motion added to state vector x
    Q: motion noise (same shape as P)
    """
    return kalman(x, P, measurement, R, motion, Q,
                  F = np.matrix('''
                      1. 0. 1. 0.;
                      0. 1. 0. 1.;
                      0. 0. 1. 0.;
                      0. 0. 0. 1.
                      '''),
                  H = np.matrix('''
                      1. 0. 0. 0.;
                      0. 1. 0. 0.'''))

def kalman(x, P, measurement, R, motion, Q, F, H):
    '''
    Parameters:
    x: initial state
    P: initial uncertainty convariance matrix
    measurement: observed position (same shape as H*x)
    R: measurement noise (same shape as H)
    motion: external motion added to state vector x
    Q: motion noise (same shape as P)
    F: next state function: x_prime = F*x
    H: measurement function: position = H*x

    Return: the updated and predicted new values for (x, P)

    See also http://en.wikipedia.org/wiki/Kalman_filter

    This version of kalman can be applied to many different situations by
    appropriately defining F and H 
    '''
    # UPDATE x, P based on measurement m    
    # distance between measured and current position-belief
    y = np.matrix(measurement).T - H * x
    S = H * P * H.T + R  # residual convariance
    K = P * H.T * S.I    # Kalman gain
    x = x + K*y
    I = np.matrix(np.eye(F.shape[0])) # identity matrix
    P = (I - K*H)*P

    # PREDICT x, P based on motion
    x = F*x + motion
    P = F*P*F.T + Q

    return x, P

def demo_kalman_xy():
    x = np.matrix('0. 0. 0. 0.').T 
    P = np.matrix(np.eye(4))*1000 # initial uncertainty

    N = 20
    true_x = np.linspace(0.0, 10.0, N)
    true_y = true_x**2
    observed_x = true_x + 0.05*np.random.random(N)*true_x
    observed_y = true_y + 0.05*np.random.random(N)*true_y
    plt.plot(observed_x, observed_y, 'ro')
    result = []
    R = 0.01**2
    for meas in zip(observed_x, observed_y):
        x, P = kalman_xy(x, P, meas, R)
        result.append((x[:2]).tolist())
    kalman_x, kalman_y = zip(*result)
    plt.plot(kalman_x, kalman_y, 'g-')
    plt.show()

demo_kalman_xy()

在此处输入图片说明

红点显示噪声位置测量值,绿线显示卡尔曼预测位置。

对于我的一个项目,我需要为时间序列建模创建间隔,并且为了使程序更高效,我创建了tsmoothie :一个用于以矢量化方式进行时间序列平滑和异常值检测的 Python 库。

它提供了不同的平滑算法以及计算间隔的可能性。

KalmanSmoother的情况下,您可以对曲线进行平滑处理,将不同的组件组合在一起:水平、趋势、季节性、长季节性

import numpy as np
import matplotlib.pyplot as plt
from tsmoothie.smoother import *
from tsmoothie.utils_func import sim_randomwalk

# generate 3 randomwalks timeseries of lenght 100
np.random.seed(123)
data = sim_randomwalk(n_series=3, timesteps=100, 
                      process_noise=10, measure_noise=30)

# operate smoothing
smoother = KalmanSmoother(component='level_trend', 
                          component_noise={'level':0.1, 'trend':0.1})
smoother.smooth(data)

# generate intervals
low, up = smoother.get_intervals('kalman_interval', confidence=0.05)

# plot the first smoothed timeseries with intervals
plt.figure(figsize=(11,6))
plt.plot(smoother.smooth_data[0], linewidth=3, color='blue')
plt.plot(smoother.data[0], '.k')
plt.fill_between(range(len(smoother.data[0])), low[0], up[0], alpha=0.3)

在此处输入图片说明

我还指出,tsmoothie 可以以矢量化的方式对多个时间序列进行平滑处理

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM