Ask Your Question

Revision history [back]

Farneback optical flow in box/ROI

I'm detecting the optical flow by the Farneback method, but I need to delimit the area of the video that will be detected. I researched ROI, but I did not succeed. Any suggestions on how I can with the mouse create a box and the algorithm only run in that region?

#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;

static void help()
{
    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;
}
static void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step,
    double, const Scalar& color)
{
    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)*5;
            line(cflowmap, Point(x, y), Point(cvRound(x + fxy.x), cvRound(y + fxy.y)),
                color);
            circle(cflowmap, Point(x, y), 2, color, -1);
        }
}

int main(int argc, char** argv)
{
    CommandLineParser parser(argc, argv, "{help h||}");
    if (parser.has("help")){
    help();
    return 0;
    }
    VideoCapture cap("completo.MPG");
    help();
    if (!cap.isOpened())
    return -1;

    Mat flow, cflow, frame;
    UMat gray, prevgray, uflow;
    namedWindow("flow", 1);

    for (;;) {
    cap >> frame;
    cvtColor(frame, gray, COLOR_BGR2GRAY);

    if (!prevgray.empty()){
    calcOpticalFlowFarneback(prevgray, gray, uflow, 0.5, 3, 15, 3, 5, 1.2, 0);
    cvtColor(prevgray, cflow, COLOR_GRAY2BGR);
    uflow.copyTo(flow);
    drawOptFlowMap(flow, cflow, 30, 1.5, Scalar(0, 255, 0));
    imshow("flow", cflow);

    VideoWriter(gray);
    }
    if (waitKey(30) >= 0)
    break;
    std::swap(prevgray, gray);
    }

    return 0;
}