Motion tracking (1): calcOpticalFlowFarneback(), dense optical flow method

The demo about the Pyramid LK optical flow has been explained in the previous blog, address: https://blog.csdn.net/liangchunjiang/article/details/79869830

Test the effect of OpenCV's function calcOpticalFlowFarneback()

void cv::calcOpticalFlowFarneback( InputArray _prev0, InputArray _next0,
                               OutputArray _flow0, double pyr_scale, int levels, int winsize,
                               int iterations, int poly_n, double poly_sigma, int flags )
// The parameter description is as follows:
// _prev0: input the previous frame image
// _next0: Input the next frame of image
// _flow0: output optical flow
// pyr_scale: The scale relationship between the upper and lower layers of the pyramid
// levels: the number of pyramid levels
// winsize: the average window size, the larger the better the denoise and the ability to detect fast moving targets, but it will cause blurred motion areas
// iterations: the number of iterations
// poly_n: pixel field size, generally 5, 7, etc.
// poly_sigma: Gaussian label difference, generally 1-1.5
// flags: calculation method. Mainly include OPTFLOW_USE_INITIAL_FLOW and OPTFLOW_FARNEBACK_GAUSSIAN

(1)OpenCV Demo

#include "stdafx.h"
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/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);
			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, char**)
{
	VideoCapture cap(0);
	help();
	if( !cap.isOpened() )
		return -1;

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

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

		if( prevgray.data )
		{
			calcOpticalFlowFarneback(prevgray, gray, flow, 0.5, 3, 15, 3, 5, 1.2, 0);
			cvtColor(prevgray, cflow, COLOR_GRAY2BGR);
			drawOptFlowMap(flow, cflow, 16, 1.5, Scalar(0, 255, 0));
			imshow("flow", cflow);
		}
		if(waitKey(30)>=0)
			break;
		std::swap(prevgray, gray);
	}
	return 0;
}
(2) Test effect



refer to:

https://blog.csdn.net/yzhang6_10/article/details/51225545



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325419640&siteId=291194637