fback.cpp 1.8 KB

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