天天看點

運動跟蹤(五):Kalman濾波

class CV_EXPORTS_W KalmanFilter
{
public:
    //! the default constructor
    CV_WRAP KalmanFilter();
    //! the full constructor taking the dimensionality of the state, of the measurement and of the control vector
    CV_WRAP KalmanFilter(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);
    //! re-initializes Kalman filter. The previous content is destroyed.
    void init(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);

    //! computes predicted state
    CV_WRAP const Mat& predict(const Mat& control=Mat());
    //! updates the predicted state from the measurement
    CV_WRAP const Mat& correct(const Mat& measurement);

    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)

    // temporary matrices
    Mat temp1;
    Mat temp2;
    Mat temp3;
    Mat temp4;
    Mat temp5;
};
           

(1)KalmanFilter示例

// KalmanFilter.cpp : 定義控制台應用程式的入口點。
//

#include "stdafx.h"

#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;
}
           

(2)測試效果

運動跟蹤(五):Kalman濾波

下面的内容是轉載:

原文:https://blog.csdn.net/onezeros/article/details/6318944

在機器視覺中追蹤時常會用到預測算法,kalman是你一定知道的。它可以用來預測各種狀态,比如說位置,速度等。關于它的理論有很多很好的文獻可以參考。opencv給出了kalman filter的一個實作,而且有範例,但估計不少人對它的使用并不清楚,因為我也是其中一個。本文的應用是對二維坐标進行預測和平滑

使用方法:

1、初始化

const int stateNum=4;//狀态數,包括(x,y,dx,dy)坐标及速度(每次移動的距離)

const int measureNum=2;//觀測量,能看到的是坐标值,當然也可以自己計算速度,但沒必要

Kalman* kalman = cvCreateKalman( stateNum, measureNum, 0 );//state(x,y,detaX,detaY)

轉移矩陣或者說增益矩陣的值好像有點莫名其妙

[cpp]  view plain  copy

  1. float A[stateNum][stateNum] ={//transition matrix  
  2.         1,0,1,0,  
  3.         0,1,0,1,  
  4.         0,0,1,0,  
  5.         0,0,0,1  
  6.     };  

看下圖就清楚了

運動跟蹤(五):Kalman濾波

X1=X+dx,依次類推

是以這個矩陣還是很容易卻确定的,可以根據自己的實際情況定制轉移矩陣

同樣的方法,三維坐标的轉移矩陣可以如下

[cpp]  view plain  copy

  1. float A[stateNum][stateNum] ={//transition matrix  
  2.         1,0,0,1,0,0,  
  3.         0,1,0,0,1,0,  
  4.         0,0,1,0,0,1,  
  5.         0,0,0,1,0,0,  
  6.         0,0,0,0,1,0,  
  7.         0,0,0,0,0,1  
  8.     };  

當然并不一定得是1和0

2.預測cvKalmanPredict,然後讀出自己需要的值

3.更新觀測矩陣 

4.更新CvKalman

 隻有第一步麻煩些。上述這幾步跟代碼中的序号對應

 如果你在做tracking,下面的例子或許更有用些。

[cpp]  view plain  copy

  1. #include <cv.h>  
  2. #include <cxcore.h>  
  3. #include <highgui.h>  
  4. #include <cmath>  
  5. #include <vector>  
  6. #include <iostream>  
  7. using namespace std;  
  8. const int winHeight=600;  
  9. const int winWidth=800;  
  10. CvPoint mousePosition=cvPoint(winWidth>>1,winHeight>>1);  
  11. //mouse event callback  
  12. void mouseEvent(int event, int x, int y, int flags, void *param )  
  13. {  
  14.     if (event==CV_EVENT_MOUSEMOVE) {  
  15.         mousePosition=cvPoint(x,y);  
  16.     }  
  17. }  
  18. int main (void)  
  19. {  
  20.     //1.kalman filter setup  
  21.     const int stateNum=4;  
  22.     const int measureNum=2;  
  23.     CvKalman* kalman = cvCreateKalman( stateNum, measureNum, 0 );//state(x,y,detaX,detaY)  
  24.     CvMat* process_noise = cvCreateMat( stateNum, 1, CV_32FC1 );  
  25.     CvMat* measurement = cvCreateMat( measureNum, 1, CV_32FC1 );//measurement(x,y)  
  26.     CvRNG rng = cvRNG(-1);  
  27.     float A[stateNum][stateNum] ={//transition matrix  
  28.         1,0,1,0,  
  29.         0,1,0,1,  
  30.         0,0,1,0,  
  31.         0,0,0,1  
  32.     };  
  33.     memcpy( kalman->transition_matrix->data.fl,A,sizeof(A));  
  34.     cvSetIdentity(kalman->measurement_matrix,cvRealScalar(1) );  
  35.     cvSetIdentity(kalman->process_noise_cov,cvRealScalar(1e-5));  
  36.     cvSetIdentity(kalman->measurement_noise_cov,cvRealScalar(1e-1));  
  37.     cvSetIdentity(kalman->error_cov_post,cvRealScalar(1));  
  38.     //initialize post state of kalman filter at random  
  39.     cvRandArr(&rng,kalman->state_post,CV_RAND_UNI,cvRealScalar(0),cvRealScalar(winHeight>winWidth?winWidth:winHeight));  
  40.     CvFont font;  
  41.     cvInitFont(&font,CV_FONT_HERSHEY_SCRIPT_COMPLEX,1,1);  
  42.     cvNamedWindow("kalman");  
  43.     cvSetMouseCallback("kalman",mouseEvent);  
  44.     IplImage* img=cvCreateImage(cvSize(winWidth,winHeight),8,3);  
  45.     while (1){  
  46.         //2.kalman prediction  
  47.         const CvMat* prediction=cvKalmanPredict(kalman,0);  
  48.         CvPoint predict_pt=cvPoint((int)prediction->data.fl[0],(int)prediction->data.fl[1]);  
  49.         //3.update measurement  
  50.         measurement->data.fl[0]=(float)mousePosition.x;  
  51.         measurement->data.fl[1]=(float)mousePosition.y;  
  52.         //4.update  
  53.         cvKalmanCorrect( kalman, measurement );       
  54.         //draw   
  55.         cvSet(img,cvScalar(255,255,255,0));  
  56.         cvCircle(img,predict_pt,5,CV_RGB(0,255,0),3);//predicted point with green  
  57.         cvCircle(img,mousePosition,5,CV_RGB(255,0,0),3);//current position with red  
  58.         char buf[256];  
  59.         sprintf_s(buf,256,"predicted position:(%3d,%3d)",predict_pt.x,predict_pt.y);  
  60.         cvPutText(img,buf,cvPoint(10,30),&font,CV_RGB(0,0,0));  
  61.         sprintf_s(buf,256,"current position :(%3d,%3d)",mousePosition.x,mousePosition.y);  
  62.         cvPutText(img,buf,cvPoint(10,60),&font,CV_RGB(0,0,0));  
  63.         cvShowImage("kalman", img);  
  64.         int key=cvWaitKey(3);  
  65.         if (key==27){//esc     
  66.             break;     
  67.         }  
  68.     }        
  69.     cvReleaseImage(&img);  
  70.     cvReleaseKalman(&kalman);  
  71.     return 0;  
  72. }  

kalman filter 視訊示範:

http://v.youku.com/v_show/id_XMjU4MzEyODky.html

demo snapshot:

運動跟蹤(五):Kalman濾波