fback.cpp 1.47 KB
Newer Older
1 2 3
#include <opencv2/video/tracking.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
4

Gary Bradski's avatar
Gary Bradski committed
5 6
#include <iostream>

7
using namespace cv;
Gary Bradski's avatar
Gary Bradski committed
8
using namespace std;
9

Gary Bradski's avatar
Gary Bradski committed
10 11 12 13 14 15 16 17 18
void help()
{
	cout <<
			"\nThis program demonstrates dense, Farnback, optical flow\n"
			"Mainly the function: calcOpticalFlowFarneback()\n"
			"Call:\n"
			"./fback\n"
			"This reads from video camera 0\n" << endl;
}
19
void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step,
20
                    double, const Scalar& color)
21 22 23 24 25 26 27 28 29 30 31
{
    for(int y = 0; y < cflowmap.rows; y += step)
        for(int x = 0; x < cflowmap.cols; x += step)
        {
            const Point2f& fxy = flow.at<Point2f>(y, x);
            line(cflowmap, Point(x,y), Point(cvRound(x+fxy.x), cvRound(y+fxy.y)),
                 color);
            circle(cflowmap, Point(x,y), 2, color, -1);
        }
}

32
int main(int, char**)
33 34
{
    VideoCapture cap(0);
Gary Bradski's avatar
Gary Bradski committed
35
    help();
36 37 38 39 40 41 42 43 44 45 46 47 48
    if( !cap.isOpened() )
        return -1;
    
    Mat prevgray, gray, flow, cflow, frame;
    namedWindow("flow", 1);
    
    for(;;)
    {
        cap >> frame;
        cvtColor(frame, gray, CV_BGR2GRAY);
        
        if( prevgray.data )
        {
Gary Bradski's avatar
Gary Bradski committed
49
            (prevgray, gray, flow, 0.5, 3, 15, 3, 5, 1.2, 0);
50 51 52 53 54 55 56 57 58 59
            cvtColor(prevgray, cflow, CV_GRAY2BGR);
            drawOptFlowMap(flow, cflow, 16, 1.5, CV_RGB(0, 255, 0));
            imshow("flow", cflow);
        }
        if(waitKey(30)>=0)
            break;
        std::swap(prevgray, gray);
    }
    return 0;
}