dis_opticalflow.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "opencv2/core/utility.hpp"
  2. #include "opencv2/highgui.hpp"
  3. #include "opencv2/imgproc.hpp"
  4. #include "opencv2/videoio.hpp"
  5. #include "opencv2/video.hpp"
  6. using namespace std;
  7. using namespace cv;
  8. int main(int argc, char **argv)
  9. {
  10. CommandLineParser parser(argc, argv, "{ @video | vtest.avi | use video as input }");
  11. string filename = samples::findFileOrKeep(parser.get<string>("@video"));
  12. VideoCapture cap;
  13. cap.open(filename);
  14. if(!cap.isOpened())
  15. {
  16. printf("ERROR: Cannot open file %s\n", filename.c_str());
  17. parser.printMessage();
  18. return -1;
  19. }
  20. Mat prevgray, gray, rgb, frame;
  21. Mat flow, flow_uv[2];
  22. Mat mag, ang;
  23. Mat hsv_split[3], hsv;
  24. char ret;
  25. Ptr<DenseOpticalFlow> algorithm = DISOpticalFlow::create(DISOpticalFlow::PRESET_MEDIUM);
  26. while(true)
  27. {
  28. cap >> frame;
  29. if (frame.empty())
  30. break;
  31. cvtColor(frame, gray, COLOR_BGR2GRAY);
  32. if (!prevgray.empty())
  33. {
  34. algorithm->calc(prevgray, gray, flow);
  35. split(flow, flow_uv);
  36. multiply(flow_uv[1], -1, flow_uv[1]);
  37. cartToPolar(flow_uv[0], flow_uv[1], mag, ang, true);
  38. normalize(mag, mag, 0, 1, NORM_MINMAX);
  39. hsv_split[0] = ang;
  40. hsv_split[1] = mag;
  41. hsv_split[2] = Mat::ones(ang.size(), ang.type());
  42. merge(hsv_split, 3, hsv);
  43. cvtColor(hsv, rgb, COLOR_HSV2BGR);
  44. imshow("flow", rgb);
  45. imshow("orig", frame);
  46. }
  47. if ((ret = (char)waitKey(20)) > 0)
  48. break;
  49. std::swap(prevgray, gray);
  50. }
  51. return 0;
  52. }