pyrlk_optical_flow.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. #include <iostream>
  2. #include <vector>
  3. #include <iomanip>
  4. #include "opencv2/core/utility.hpp"
  5. #include "opencv2/imgcodecs.hpp"
  6. #include "opencv2/videoio.hpp"
  7. #include "opencv2/highgui.hpp"
  8. #include "opencv2/core/ocl.hpp"
  9. #include "opencv2/video/video.hpp"
  10. using namespace std;
  11. using namespace cv;
  12. typedef unsigned char uchar;
  13. #define LOOP_NUM 10
  14. int64 work_begin = 0;
  15. int64 work_end = 0;
  16. static void workBegin()
  17. {
  18. work_begin = getTickCount();
  19. }
  20. static void workEnd()
  21. {
  22. work_end += (getTickCount() - work_begin);
  23. }
  24. static double getTime()
  25. {
  26. return work_end * 1000. / getTickFrequency();
  27. }
  28. static void drawArrows(UMat& _frame, const vector<Point2f>& prevPts, const vector<Point2f>& nextPts, const vector<uchar>& status,
  29. Scalar line_color = Scalar(0, 0, 255))
  30. {
  31. Mat frame = _frame.getMat(ACCESS_WRITE);
  32. for (size_t i = 0; i < prevPts.size(); ++i)
  33. {
  34. if (status[i])
  35. {
  36. int line_thickness = 1;
  37. Point p = prevPts[i];
  38. Point q = nextPts[i];
  39. double angle = atan2((double) p.y - q.y, (double) p.x - q.x);
  40. double hypotenuse = sqrt( (double)(p.y - q.y)*(p.y - q.y) + (double)(p.x - q.x)*(p.x - q.x) );
  41. if (hypotenuse < 1.0)
  42. continue;
  43. // Here we lengthen the arrow by a factor of three.
  44. q.x = (int) (p.x - 3 * hypotenuse * cos(angle));
  45. q.y = (int) (p.y - 3 * hypotenuse * sin(angle));
  46. // Now we draw the main line of the arrow.
  47. line(frame, p, q, line_color, line_thickness);
  48. // Now draw the tips of the arrow. I do some scaling so that the
  49. // tips look proportional to the main line of the arrow.
  50. p.x = (int) (q.x + 9 * cos(angle + CV_PI / 4));
  51. p.y = (int) (q.y + 9 * sin(angle + CV_PI / 4));
  52. line(frame, p, q, line_color, line_thickness);
  53. p.x = (int) (q.x + 9 * cos(angle - CV_PI / 4));
  54. p.y = (int) (q.y + 9 * sin(angle - CV_PI / 4));
  55. line(frame, p, q, line_color, line_thickness);
  56. }
  57. }
  58. }
  59. int main(int argc, const char* argv[])
  60. {
  61. const char* keys =
  62. "{ h help | | print help message }"
  63. "{ l left | | specify left image }"
  64. "{ r right | | specify right image }"
  65. "{ c camera | 0 | enable camera capturing }"
  66. "{ v video | | use video as input }"
  67. "{ o output | pyrlk_output.jpg| specify output save path when input is images }"
  68. "{ points | 1000 | specify points count [GoodFeatureToTrack] }"
  69. "{ min_dist | 0 | specify minimal distance between points [GoodFeatureToTrack] }"
  70. "{ m cpu_mode | false | run without OpenCL }";
  71. CommandLineParser cmd(argc, argv, keys);
  72. if (cmd.has("help"))
  73. {
  74. cout << "Usage: pyrlk_optical_flow [options]" << endl;
  75. cout << "Available options:" << endl;
  76. cmd.printMessage();
  77. return EXIT_SUCCESS;
  78. }
  79. bool defaultPicturesFail = true;
  80. string fname0 = samples::findFile(cmd.get<string>("left"));
  81. string fname1 = samples::findFile(cmd.get<string>("right"));
  82. string vdofile = cmd.get<string>("video");
  83. string outfile = cmd.get<string>("output");
  84. int points = cmd.get<int>("points");
  85. double minDist = cmd.get<double>("min_dist");
  86. int inputName = cmd.get<int>("c");
  87. UMat frame0;
  88. imread(fname0, IMREAD_GRAYSCALE).copyTo(frame0);
  89. UMat frame1;
  90. imread(fname1, IMREAD_GRAYSCALE).copyTo(frame1);
  91. vector<cv::Point2f> pts(points);
  92. vector<cv::Point2f> nextPts(points);
  93. vector<unsigned char> status(points);
  94. vector<float> err;
  95. cout << "Points count : " << points << endl << endl;
  96. if (frame0.empty() || frame1.empty())
  97. {
  98. VideoCapture capture;
  99. UMat frame, frameCopy;
  100. UMat frame0Gray, frame1Gray;
  101. UMat ptr0, ptr1;
  102. if(vdofile.empty())
  103. capture.open( inputName );
  104. else
  105. capture.open(vdofile.c_str());
  106. int c = inputName ;
  107. if(!capture.isOpened())
  108. {
  109. if(vdofile.empty())
  110. cout << "Capture from CAM " << c << " didn't work" << endl;
  111. else
  112. cout << "Capture from file " << vdofile << " failed" <<endl;
  113. if (defaultPicturesFail)
  114. return EXIT_FAILURE;
  115. goto nocamera;
  116. }
  117. cout << "In capture ..." << endl;
  118. for(int i = 0;; i++)
  119. {
  120. if( !capture.read(frame) )
  121. break;
  122. if (i == 0)
  123. {
  124. frame.copyTo( frame0 );
  125. cvtColor(frame0, frame0Gray, COLOR_BGR2GRAY);
  126. }
  127. else
  128. {
  129. if (i%2 == 1)
  130. {
  131. frame.copyTo(frame1);
  132. cvtColor(frame1, frame1Gray, COLOR_BGR2GRAY);
  133. ptr0 = frame0Gray;
  134. ptr1 = frame1Gray;
  135. }
  136. else
  137. {
  138. frame.copyTo(frame0);
  139. cvtColor(frame0, frame0Gray, COLOR_BGR2GRAY);
  140. ptr0 = frame1Gray;
  141. ptr1 = frame0Gray;
  142. }
  143. pts.clear();
  144. goodFeaturesToTrack(ptr0, pts, points, 0.01, 0.0);
  145. if(pts.size() == 0)
  146. continue;
  147. calcOpticalFlowPyrLK(ptr0, ptr1, pts, nextPts, status, err);
  148. if (i%2 == 1)
  149. frame1.copyTo(frameCopy);
  150. else
  151. frame0.copyTo(frameCopy);
  152. drawArrows(frameCopy, pts, nextPts, status, Scalar(255, 0, 0));
  153. imshow("PyrLK [Sparse]", frameCopy);
  154. }
  155. char key = (char)waitKey(10);
  156. if (key == 27)
  157. break;
  158. else if (key == 'm' || key == 'M')
  159. {
  160. ocl::setUseOpenCL(!cv::ocl::useOpenCL());
  161. cout << "Switched to " << (ocl::useOpenCL() ? "OpenCL" : "CPU") << " mode\n";
  162. }
  163. }
  164. capture.release();
  165. }
  166. else
  167. {
  168. nocamera:
  169. if (cmd.has("cpu_mode"))
  170. {
  171. ocl::setUseOpenCL(false);
  172. std::cout << "OpenCL was disabled" << std::endl;
  173. }
  174. for(int i = 0; i <= LOOP_NUM; i ++)
  175. {
  176. cout << "loop" << i << endl;
  177. if (i > 0) workBegin();
  178. goodFeaturesToTrack(frame0, pts, points, 0.01, minDist);
  179. calcOpticalFlowPyrLK(frame0, frame1, pts, nextPts, status, err);
  180. if (i > 0 && i <= LOOP_NUM)
  181. workEnd();
  182. if (i == LOOP_NUM)
  183. {
  184. cout << "average time (noCamera) : ";
  185. cout << getTime() / LOOP_NUM << " ms" << endl;
  186. drawArrows(frame0, pts, nextPts, status, Scalar(255, 0, 0));
  187. imshow("PyrLK [Sparse]", frame0);
  188. imwrite(outfile, frame0);
  189. }
  190. }
  191. }
  192. waitKey();
  193. return EXIT_SUCCESS;
  194. }