fback.cpp 1.8 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);
        }
}

ValeryTyumen's avatar
ValeryTyumen committed
33
int main(int argc, char** argv)
34
{
ValeryTyumen's avatar
ValeryTyumen committed
35 36 37 38 39 40
    cv::CommandLineParser parser(argc, argv, "{help h||}");
    if (parser.has("help"))
    {
        help();
        return 0;
    }
41
    VideoCapture cap(0);
Gary Bradski's avatar
Gary Bradski committed
42
    help();
43 44
    if( !cap.isOpened() )
        return -1;
45

46 47
    Mat flow, cflow, frame;
    UMat gray, prevgray, uflow;
48
    namedWindow("flow", 1);
49

50 51 52
    for(;;)
    {
        cap >> frame;
53
        cvtColor(frame, gray, COLOR_BGR2GRAY);
54

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