#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <cxcore.h>
#include <math.h>
#include <ctype.h>
#include <stdio.h>
IplImage *image = 0, *grey = 0, *prev_grey = 0, *pyramid = 0, *prev_pyramid = 0, *swap_temp;
int win_size = 10;
const int MAX_COUNT = 500;
CvPoint2D32f* points[2] = {0,0}, *swap_points;
char* status = 0;
int count = 0;
int need_to_init = 0;
int night_mode = 0;
int flags = 0;
int add_remove_pt = 0;
CvPoint pt;
int main()
{
int scale = 5;
cvNamedWindow("vel", 1);
cvNamedWindow("image1", 1);
cvNamedWindow("image2", 1);
CvSize isize = cvSize(80,80);
CvSize vsize = cvSize(isize.width * scale, isize.height * scale);
IplImage *image1 = cvCreateImage(isize, 8, 1 );
IplImage *image2 = cvCreateImage(isize, 8, 1 );
IplImage *velx = cvCreateImage(isize, IPL_DEPTH_32F, 1);
IplImage *vely = cvCreateImage(isize, IPL_DEPTH_32F, 1);
IplImage *vel = cvCreateImage(vsize, 8, 3);
IplImage *flow = cvCreateImage(isize, IPL_DEPTH_32F, 2);
int sim = 0;
for (;;)
{
if (sim * 4 > isize.width*3 /4)
sim = 0;
CvPoint pts1 = {sim * 1, 30};
CvPoint pts2 = {pts1.x + 4, pts1.y + 4};
cvZero(image1);
cvRectangle(image1, pts1, pts2, CV_RGB(255, 255, 255), -1);
pts1.x += 1;
pts2.x += 1;
cvZero(image2);
cvRectangle(image2, pts1, pts2, CV_RGB(255, 255, 255), -1);
sim++;
#if 0
cvCalcOpticalFlowLK(image1, image2, cvSize(5,5), velx, vely);
#else
#if 1
cv::Mat im1 = cv::cvarrToMat(image1), im2 = cv::cvarrToMat(image2);
cv::Mat _flow = cv::cvarrToMat(flow);
cv::calcOpticalFlowFarneback( im1, im2, _flow, 0.5, 2, 5, 2, 7, 1.5, cv::OPTFLOW_FARNEBACK_GAUSSIAN);
#else
//cvCalcOpticalFlowFarneback(image1, image2, flow, 0.5, 1, 5, 2, 7, 1.5, 0);
icvCalcOpticalFlowBBW( im1, im2, _flow, 1, 1, 1, 0 );
#endif
{
for( int y = 0; y < flow->height; y++ )
{
float* vx = (float*)(velx->imageData + velx->widthStep*y);
float* vy = (float*)(vely->imageData + vely->widthStep*y);
const float* f = (const float*)(flow->imageData + flow->widthStep*y);
for( int x = 0; x < flow->width; x++ )
{
vx[x] = f[2*x];
vy[x] = f[2*x+1];
}
}
}
#endif
CvPoint2D64f ave = {0,0};
cvZero(vel);
pts1.x *= scale;
pts1.y *= scale;
pts2.x *= scale;
pts2.y *= scale;
cvRectangle(vel, pts1, pts2, CV_RGB(255, 255, 255), 1);
for (int y = 0; y < image1->height; y++)
for (int x = 0; x < image1->width; x++)
{
double dx = cvGetReal2D(velx, y, x);
double dy = cvGetReal2D(vely, y, x);
CvPoint p = cvPoint(x * scale, y * scale);
cvLine(vel, p, p, cvScalar(170,170,170));
ave.x += dx;
ave.y += dy;
double l = sqrt(dx*dx + dy*dy);
if (l > 0)
{
CvPoint p2 = cvPoint(p.x + (int)(dx * 10 + .5), p.y + (int)(dy * 10 + .5));
cvLine(vel, p, p2, CV_RGB(0,255,0), 1, 8);
}
}
cvShowImage("vel", vel);
cvShowImage("image1", image1);
cvShowImage("image2", image2);
printf("ave=(%.2f,%.2f)\n", ave.x, ave.y);
if( cvWaitKey(300) == 'q' )
break;
}
return 0;
}