camshift.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <iostream>
  2. #include <opencv2/imgcodecs.hpp>
  3. #include <opencv2/imgproc.hpp>
  4. #include <opencv2/videoio.hpp>
  5. #include <opencv2/highgui.hpp>
  6. #include <opencv2/video.hpp>
  7. using namespace cv;
  8. using namespace std;
  9. int main(int argc, char **argv)
  10. {
  11. const string about =
  12. "This sample demonstrates the camshift algorithm.\n"
  13. "The example file can be downloaded from:\n"
  14. " https://www.bogotobogo.com/python/OpenCV_Python/images/mean_shift_tracking/slow_traffic_small.mp4";
  15. const string keys =
  16. "{ h help | | print this help message }"
  17. "{ @image |<none>| path to image file }";
  18. CommandLineParser parser(argc, argv, keys);
  19. parser.about(about);
  20. if (parser.has("help"))
  21. {
  22. parser.printMessage();
  23. return 0;
  24. }
  25. string filename = parser.get<string>("@image");
  26. if (!parser.check())
  27. {
  28. parser.printErrors();
  29. return 0;
  30. }
  31. VideoCapture capture(filename);
  32. if (!capture.isOpened()){
  33. //error in opening the video input
  34. cerr << "Unable to open file!" << endl;
  35. return 0;
  36. }
  37. Mat frame, roi, hsv_roi, mask;
  38. // take first frame of the video
  39. capture >> frame;
  40. // setup initial location of window
  41. Rect track_window(300, 200, 100, 50); // simply hardcoded the values
  42. // set up the ROI for tracking
  43. roi = frame(track_window);
  44. cvtColor(roi, hsv_roi, COLOR_BGR2HSV);
  45. inRange(hsv_roi, Scalar(0, 60, 32), Scalar(180, 255, 255), mask);
  46. float range_[] = {0, 180};
  47. const float* range[] = {range_};
  48. Mat roi_hist;
  49. int histSize[] = {180};
  50. int channels[] = {0};
  51. calcHist(&hsv_roi, 1, channels, mask, roi_hist, 1, histSize, range);
  52. normalize(roi_hist, roi_hist, 0, 255, NORM_MINMAX);
  53. // Setup the termination criteria, either 10 iteration or move by atleast 1 pt
  54. TermCriteria term_crit(TermCriteria::EPS | TermCriteria::COUNT, 10, 1);
  55. while(true){
  56. Mat hsv, dst;
  57. capture >> frame;
  58. if (frame.empty())
  59. break;
  60. cvtColor(frame, hsv, COLOR_BGR2HSV);
  61. calcBackProject(&hsv, 1, channels, roi_hist, dst, range);
  62. // apply camshift to get the new location
  63. RotatedRect rot_rect = CamShift(dst, track_window, term_crit);
  64. // Draw it on image
  65. Point2f points[4];
  66. rot_rect.points(points);
  67. for (int i = 0; i < 4; i++)
  68. line(frame, points[i], points[(i+1)%4], 255, 2);
  69. imshow("img2", frame);
  70. int keyboard = waitKey(30);
  71. if (keyboard == 'q' || keyboard == 27)
  72. break;
  73. }
  74. }