fback.cpp 1.66 KB
Newer Older
1 2
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
3
#include "opencv2/videoio/videoio.hpp"
4
#include "opencv2/highgui/highgui.hpp"
5

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

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

11
static void help()
Gary Bradski's avatar
Gary Bradski committed
12
{
13 14 15 16 17 18
    cout <<
            "\nThis program demonstrates dense optical flow algorithm by Gunnar Farneback\n"
            "Mainly the function: calcOpticalFlowFarneback()\n"
            "Call:\n"
            "./fback\n"
            "This reads from video camera 0\n" << endl;
Gary Bradski's avatar
Gary Bradski committed
19
}
20
static void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step,
21
                    double, const Scalar& color)
22 23 24 25 26 27 28 29 30 31 32
{
    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);
        }
}

33
int main(int, char**)
34 35
{
    VideoCapture cap(0);
Gary Bradski's avatar
Gary Bradski committed
36
    help();
37 38
    if( !cap.isOpened() )
        return -1;
39

40 41
    Mat flow, cflow, frame;
    UMat gray, prevgray, uflow;
42
    namedWindow("flow", 1);
43

44 45 46
    for(;;)
    {
        cap >> frame;
47
        cvtColor(frame, gray, COLOR_BGR2GRAY);
48

49
        if( !prevgray.empty() )
50
        {
51
            calcOpticalFlowFarneback(prevgray, gray, uflow, 0.5, 3, 15, 3, 5, 1.2, 0);
52
            cvtColor(prevgray, cflow, COLOR_GRAY2BGR);
53
            uflow.copyTo(flow);
54
            drawOptFlowMap(flow, cflow, 16, 1.5, Scalar(0, 255, 0));
55 56 57 58 59 60 61 62
            imshow("flow", cflow);
        }
        if(waitKey(30)>=0)
            break;
        std::swap(prevgray, gray);
    }
    return 0;
}