goturnTracker.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright 2018 Satya Mallick (LearnOpenCV.com)
  3. */
  4. #include <opencv2/opencv.hpp>
  5. #include <opencv2/tracking.hpp>
  6. using namespace cv;
  7. using namespace std;
  8. #define SSTR( x ) static_cast< std::ostringstream & >( \
  9. ( std::ostringstream() << std::dec << x ) ).str()
  10. int main(int argc, char **argv)
  11. {
  12. // Create tracker
  13. Ptr<Tracker> tracker = TrackerGOTURN::create();
  14. // Read video
  15. VideoCapture video("chaplin.mp4");
  16. // Exit if video is not opened
  17. if(!video.isOpened())
  18. {
  19. cout << "Could not read video file" << endl;
  20. return EXIT_FAILURE;
  21. }
  22. // Read first frame
  23. Mat frame;
  24. if (!video.read(frame))
  25. {
  26. cout << "Cannot read video file" << endl;
  27. return EXIT_FAILURE;
  28. }
  29. // Define initial boundibg box
  30. Rect2d bbox(287, 23, 86, 320);
  31. // Uncomment the line below to select a different bounding box
  32. //bbox = selectROI(frame, false);
  33. // Initialize tracker with first frame and bounding box
  34. tracker->init(frame, bbox);
  35. while(video.read(frame))
  36. {
  37. // Start timer
  38. double timer = (double)getTickCount();
  39. // Update the tracking result
  40. bool ok = tracker->update(frame, bbox);
  41. // Calculate Frames per second (FPS)
  42. float fps = getTickFrequency() / ((double)getTickCount() - timer);
  43. if (ok)
  44. {
  45. // Tracking success : Draw the tracked object
  46. rectangle(frame, bbox, Scalar( 255, 0, 0 ), 2, 1 );
  47. }
  48. else
  49. {
  50. // Tracking failure detected.
  51. putText(frame, "Tracking failure detected", Point(100,80), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0,0,255),2);
  52. }
  53. // Display tracker type on frame
  54. putText(frame, "GOTURN Tracker", Point(100,20), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(50,170,50),2);
  55. // Display FPS on frame
  56. putText(frame, "FPS : " + SSTR(int(fps)), Point(100,50), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(50,170,50), 2);
  57. // Display frame.
  58. imshow("Tracking", frame);
  59. // Exit if ESC pressed.
  60. if(waitKey(1) == 27) break;
  61. }
  62. return EXIT_SUCCESS;
  63. }