#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
void drawOpticalFlow(const Mat& flowImage, Mat& flowImageGray)
{
int stepSize = 16;
Scalar color = Scalar(0, 255, 0);
for(int y = 0; y < flowImageGray.rows; y += stepSize)
{
for(int x = 0; x < flowImageGray.cols; x += stepSize)
{
int radius = 2;
int thickness = -1;
circle(flowImageGray, Point(x,y), radius, color, thickness);
Point2f pt = flowImage.at<Point2f>(y, x);
line(flowImageGray, Point(x,y), Point(cvRound(x+pt.x), cvRound(y+pt.y)), color);
}
}
}
int main(int, char** argv)
{
VideoCapture cap(0);
if(!cap.isOpened())
{
cerr << "Unable to open the webcam. Exiting!" << endl;
return -1;
}
char ch;
Mat curGray, prevGray, flowImage, flowImageGray, frame;
string windowName = "Optical Flow";
namedWindow(windowName, 1);
float scalingFactor = 0.75;
while(true)
{
cap >> frame;
if(frame.empty())
break;
resize(frame, frame, Size(), scalingFactor, scalingFactor, INTER_AREA);
cvtColor(frame, curGray, COLOR_BGR2GRAY);
if(prevGray.data)
{
float pyrScale = 0.5;
int numLevels = 3;
int windowSize = 15;
int numIterations = 3;
int neighborhoodSize = 5;
float stdDeviation = 1.2;
calcOpticalFlowFarneback(prevGray, curGray, flowImage, pyrScale, numLevels, windowSize, numIterations, neighborhoodSize, stdDeviation, OPTFLOW_USE_INITIAL_FLOW);
cvtColor(prevGray, flowImageGray, COLOR_GRAY2BGR);
drawOpticalFlow(flowImage, flowImageGray);
imshow(windowName, flowImageGray);
}
ch = waitKey(10);
if(ch == 27)
break;
std::swap(prevGray, curGray);
}
return 0;
}