kalman滤波--运动跟踪

kalman滤波大家都很熟悉,其基本思想就是先不考虑输入信号和观测噪声的影响,得到状态变量和输出信号的估计值,再用输出信号的估计误差加权后校正状态变量的估计值,使状态变量估计误差的均方差最小。具体它的原理和实现,我想也不用我在这里费口舌,但这个理论基础必须的有,必须得知道想用kalman滤波做跟踪,必须得先建立运动模型和观察模型,不是想用就能用的。如果不能建立运动模型,也就意味着你所要面对的问题不能用kalman滤波解决。

我结合一下OpenCV自带的kalman.cpp这个例程来介绍一下如何在OpenCV中使用kalman滤波吧,OpenCV已经把Kalman滤波封装到一个类KalmanFilter中了。使用起来非常方便,但那繁多的各种矩阵还是容易让人摸不着头脑。这里要知道的一点是,想要用kalman滤波,要知道前一时刻的状态估计值x,当前的观测值y,还得建立状态方程和量测方程。有了这些就可以运用kalman滤波了。

OpenCV自带了例程里面是对一个1维点的运动跟踪,虽然这个点是在2维平面中运动,但由于它是在一个圆弧上运动,只有一个自由度,角度,所以还是1维的。还是一个匀速运动,建立匀速运动模型,

设定状态变量  x = [ x1, x2 ] = [ 角度,角速度 ],

则运动模型为:

x1(k+1) = x1(k)+x2(k)*T

x2(k+1)= x2(k)

则状态转移方程为:

x* = Ax + w

这里设计的噪声是高斯随机噪声,则量测方程为:

z = Cx + v

看了代码,对应上以上各项:

状态估计值x --> state

当前观测值z --> measurement

KalmanFilter类内成员变量transitionMatrix就是状态转移方程中的矩阵A

KalmanFilter类内成员变量measurementMatrix就是量测方程中矩阵C

    Mat statePre;           //!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k)
    Mat statePost;          //!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
    Mat transitionMatrix;   //!< state transition matrix (A)
    Mat controlMatrix;      //!< control matrix (B) (not used if there is no control)
    Mat measurementMatrix;  //!< measurement matrix (H)
    Mat processNoiseCov;    //!< process noise covariance matrix (Q)
    Mat measurementNoiseCov;//!< measurement noise covariance matrix (R)
    Mat errorCovPre;        //!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/
    Mat gain;               //!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)
    Mat errorCovPost;       //!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k)

使用的时候,除了初始化我刚刚初始化过的transitionMatrix和measurementMatrix外,还需要初始化processNoiseCov,measurementNoiseCov和errorCovPost

把它们初始化好之后,接下来的动作就很简单了,分两步走,第一步调用成员函数predict得到当前状态变量的估计值,第二步调用成员函数correct用观测值校正状态变量。再更新状态变量做下一次估计。

下面是OpenCV自带 samples\cpp\kalman.cpp中的源码:

#include "opencv2/video/tracking.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <stdio.h>

using namespace cv;

static inline Point calcPoint(Point2f center, double R, double angle)
{
    return center + Point2f((float)cos(angle), (float)-sin(angle))*(float)R;
}

static void help()
{
    printf( "\nExamle of c calls to OpenCV's Kalman filter.\n"
"   Tracking of rotating point.\n"
"   Rotation speed is constant.\n"
"   Both state and measurements vectors are 1D (a point angle),\n"
"   Measurement is the real point angle + gaussian noise.\n"
"   The real and the estimated points are connected with yellow line segment,\n"
"   the real and the measured points are connected with red line segment.\n"
"   (if Kalman filter works correctly,\n"
"    the yellow segment should be shorter than the red one).\n"
            "\n"
"   Pressing any key (except ESC) will reset the tracking with a different speed.\n"
"   Pressing ESC will stop the program.\n"
            );
}

int main(int, char**)
{
    help();
    Mat img(500, 500, CV_8UC3);
    KalmanFilter KF(2, 1, 0);
    Mat state(2, 1, CV_32F); /* (phi, delta_phi) */
    Mat processNoise(2, 1, CV_32F);
    Mat measurement = Mat::zeros(1, 1, CV_32F);
    char code = (char)-1;

    for(;;)
    {
        randn( state, Scalar::all(0), Scalar::all(0.1) );
        KF.transitionMatrix = *(Mat_<float>(2, 2) << 1, 1, 0, 1);

        setIdentity(KF.measurementMatrix);
        setIdentity(KF.processNoiseCov, Scalar::all(1e-5));
        setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));
        setIdentity(KF.errorCovPost, Scalar::all(1));

        randn(KF.statePost, Scalar::all(0), Scalar::all(0.1));

        for(;;)
        {
            Point2f center(img.cols*0.5f, img.rows*0.5f);
            float R = img.cols/3.f;
            double stateAngle = state.at<float>(0);
            Point statePt = calcPoint(center, R, stateAngle);

            Mat prediction = KF.predict();
            double predictAngle = prediction.at<float>(0);
            Point predictPt = calcPoint(center, R, predictAngle);

            randn( measurement, Scalar::all(0), Scalar::all(KF.measurementNoiseCov.at<float>(0)));

            // generate measurement
            measurement += KF.measurementMatrix*state;

            double measAngle = measurement.at<float>(0);
            Point measPt = calcPoint(center, R, measAngle);

            // plot points
            #define drawCross( center, color, d )                                 \
                line( img, Point( center.x - d, center.y - d ),                \
                             Point( center.x + d, center.y + d ), color, 1, CV_AA, 0); \
                line( img, Point( center.x + d, center.y - d ),                \
                             Point( center.x - d, center.y + d ), color, 1, CV_AA, 0 )

            img = Scalar::all(0);
            drawCross( statePt, Scalar(255,255,255), 3 );
            drawCross( measPt, Scalar(0,0,255), 3 );
            drawCross( predictPt, Scalar(0,255,0), 3 );
            line( img, statePt, measPt, Scalar(0,0,255), 3, CV_AA, 0 );
            line( img, statePt, predictPt, Scalar(0,255,255), 3, CV_AA, 0 );

            if(theRNG().uniform(0,4) != 0)
                KF.correct(measurement);

            randn( processNoise, Scalar(0), Scalar::all(sqrt(KF.processNoiseCov.at<float>(0, 0))));
            state = KF.transitionMatrix*state + processNoise;

            imshow( "Kalman", img );
            code = (char)waitKey(100);

            if( code > 0 )
                break;
        }
        if( code == 27 || code == 'q' || code == 'Q' )
            break;
    }

    return 0;
}



这里给出一个二维点跟踪的示例:

//#include "stdafx.h"
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <cmath>
#include <vector>
#include <iostream>
using namespace std;
const int winHeight=600;
const int winWidth=800;
CvPoint mousePosition=cvPoint(winWidth>>1,winHeight>>1);
//mouse event callback
void mouseEvent(int event, int x, int y, int flags, void *param )
{
       if (event==CV_EVENT_MOUSEMOVE) {
              mousePosition=cvPoint(x,y);
       }
}
int main (void)
{
       //1.kalman filter setup
       const int stateNum=4;
       const int measureNum=2;
       CvKalman* kalman = cvCreateKalman( stateNum, measureNum, 0 );//state(x,y,detaX,detaY)
       CvMat* process_noise = cvCreateMat( stateNum, 1, CV_32FC1 );
       CvMat* measurement = cvCreateMat( measureNum, 1, CV_32FC1 );//measurement(x,y)
       CvRNG rng = cvRNG(-1);
       float A[stateNum][stateNum] ={//transition matrix
              1,0,1,0,
              0,1,0,1,
              0,0,1,0,
              0,0,0,1
       };
       memcpy( kalman->transition_matrix->data.fl,A,sizeof(A));
       cvSetIdentity(kalman->measurement_matrix,cvRealScalar(1) );
       cvSetIdentity(kalman->process_noise_cov,cvRealScalar(1e-5));
       cvSetIdentity(kalman->measurement_noise_cov,cvRealScalar(1e-1));
       cvSetIdentity(kalman->error_cov_post,cvRealScalar(1));
       //initialize post state of kalman filter at random
       cvRandArr(&rng,kalman->state_post,CV_RAND_UNI,cvRealScalar(0),cvRealScalar(winHeight>winWidth?winWidth:winHeight));
       CvFont font;
       cvInitFont(&font,CV_FONT_HERSHEY_SCRIPT_COMPLEX,1,1);
       cvNamedWindow("kalman");
       cvSetMouseCallback("kalman",mouseEvent);
       IplImage* img=cvCreateImage(cvSize(winWidth,winHeight),8,3);
       while (1){
              //2.kalman prediction
              const CvMat* prediction=cvKalmanPredict(kalman,0);
              CvPoint predict_pt=cvPoint((int)prediction->data.fl[0],(int)prediction->data.fl[1]);
              //3.update measurement
              measurement->data.fl[0]=(float)mousePosition.x;
              measurement->data.fl[1]=(float)mousePosition.y;
              //4.update
              cvKalmanCorrect( kalman, measurement );          
              //draw
              cvSet(img,cvScalar(255,255,255,0));
              cvCircle(img,predict_pt,5,CV_RGB(0,255,0),3);//predicted point with green
              cvCircle(img,mousePosition,5,CV_RGB(255,0,0),3);//current position with red
              char buf[256];
              sprintf_s(buf,256,"predicted position:(%3d,%3d)",predict_pt.x,predict_pt.y);
              cvPutText(img,buf,cvPoint(10,30),&font,CV_RGB(0,0,0));
              sprintf_s(buf,256,"current position :(%3d,%3d)",mousePosition.x,mousePosition.y);
              cvPutText(img,buf,cvPoint(10,60),&font,CV_RGB(0,0,0));
             
              cvShowImage("kalman", img);
              int key=cvWaitKey(3);
              if (key==27){//esc  
                     break;  
              }
       }     
       cvReleaseImage(&img);
       cvReleaseKalman(&kalman);
       return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值