1 #include "opencv2/video/tracking.hpp" 2 #include "opencv2/imgproc/imgproc.hpp" 3 #include "opencv2/videoio/videoio.hpp" 4 #include "opencv2/highgui/highgui.hpp" 5 6 #include <iostream> 7 8 using namespace cv; 9 using namespace std; 10 11 static void help() 12 { 13 cout << 14 "\nThis program demonstrates dense optical flow algorithm by Gunnar Farneback\n" 15 "Mainly the function: calcOpticalFlowFarneback()\n" 16 "Call:\n" 17 "./fback\n" 18 "This reads from video camera 0\n" << endl; 19 } 20 static void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step, 21 double, const Scalar& color) 22 { 23 for(int y = 0; y < cflowmap.rows; y += step) 24 for(int x = 0; x < cflowmap.cols; x += step) 25 { 26 const Point2f& fxy = flow.at<Point2f>(y, x); 27 line(cflowmap, Point(x,y), Point(cvRound(x+fxy.x), cvRound(y+fxy.y)), 28 color); 29 circle(cflowmap, Point(x,y), 2, color, -1); 30 } 31 } 32 33 int main(int, char**) 34 { 35 VideoCapture cap(0); 36 help(); 37 if( !cap.isOpened() ) 38 return -1; 39 40 Mat flow, cflow, frame; 41 UMat gray, prevgray, uflow; 42 namedWindow("flow", 1); 43 44 for(;;) 45 { 46 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 imshow("flow", cflow); 56 } 57 if(waitKey(30)>=0) 58 break; 59 std::swap(prevgray, gray); 60 } 61 return 0; 62 } 63