Can anyone please help with my below code.
I want to track the moving object
int main (int argc,char** argv ){
IplImage *frame = 0;
cvNamedWindow("src",1);
cvNamedWindow("gray",1);
CvCapture* capture =cvCaptureFromAVI("c:/dev/projects/opencv_test/kalman.avi");
CvKalman *kalman = cvCreateKalman( 4, 2, 0 );
CvRandState rng;
cvRandInit( &rng, 0, 1, -1, CV_RAND_UNI );
CvMat *x_k = cvCreateMat( 3, 1, CV_16UC1 );
cvRandSetRange( &rng, 0, 0.1, 0 );
rng.disttype = CV_RAND_NORMAL;
cvRand( &rng, x_k );
const float F[] = { 1, 0, 1, 0,
0, 1, 0, 1,
0, 0, 1, 0,
0, 0, 0, 1};
memcpy( kalman->transition_matrix->data.fl, F, sizeof(F));
const float H[] = { 1, 0, 0, 0,
0, 1, 0, 0};
memcpy( kalman->measurement_matrix->data.fl, H, sizeof(H));
const float Q[] = { 0.0005, 0, 0, 0,
0, 0.0005, 0, 0,
0, 0, 0.0005, 0,
0, 0, 0, 0.0005 };
memcpy( kalman->process_noise_cov->data.fl, Q, sizeof(Q));
const float R[] = { 0.1, 0,
0, 0.1,};
memcpy( kalman->measurement_noise_cov->data.fl, R,sizeof(R));
const float V[] = { 0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0 };
memcpy( kalman->error_cov_post->data.fl, V, sizeof(V));
cvRand( &rng, kalman->state_post );
CvMat* w_k = cvCreateMat( 2, 1, CV_16UC1 );
CvMat* z_k = cvCreateMat( 2, 1, CV_32FC1 );
cvZero( z_k );
IplImage* imgwhite = NULL;
while(cvGrabFrame(capture))
{
frame=cvRetrieveFrame(capture);
int imgWidth=frame->width;
int imgHeight=frame->height;
IplImage *gray = cvCreateImage(cvSize(imgWidth,imgHeight),8,1);
cvCvtColor(frame,gray,CV_BGR2GRAY);
cvThreshold(gray,gray,150,255,CV_THRESH_BINARY);
cvSmooth( gray, gray, CV_GAUSSIAN, 9, 9 );
if(!frame)
break;
if(imgwhite== NULL)
{
imgwhite = cvCreateImage(cvGetSize(frame), 8, 3);
}
CvMoments *moments = (CvMoments*)malloc(sizeof(CvMoments));
cvMoments(gray, moments, 1);
double moment10 = cvGetSpatialMoment(moments, 1, 0);
double moment01 = cvGetSpatialMoment(moments, 0, 1);
double area = cvGetCentralMoment(moments, 0, 0);
static int posX ;
static int posY ;
int lastX = posX;
int lastY = posY;
posX = moment10/area;
posY = moment01/area;
if(lastX>0 && lastY>0 && posX>0 && posY>0)
{
printf("position (%d,%d)\n", posX, posY);
int pt1=posX;
int pt2=posY;
int measurement[]={pt1,pt2};
memcpy( z_k->data.fl, measurement,sizeof(measurement));
cvKalmanCorrect( kalman, z_k );
float measured_x = z_k->data.fl[0];
float measured_y = z_k->data.fl[1];
printf ("z_k: %f, %f", measured_x, measured_y);
const CvMat* y_k = cvKalmanPredict( kalman, 0 );
float predicted_x = y_k->data.fl[0];
float predicted_y = y_k->data.fl[1];
cvLine(imgwhite, cvPoint(posX, posY), cvPoint(lastX, lastY), cvScalar(0,255,0), 2);
cvLine(frame,cvPoint(predicted_x,predicted_y), cvPoint(pt1,pt2), CV_RGB(0,255,255),2);
}
cvAdd(frame, imgwhite, frame);
cvShowImage("src" ,frame);
cvShowImage("gray",gray);
if(cvWaitKey(100) == 27){
break;
}
}
cvDestroyAllWindows();
}