bg_sub.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * @file bg_sub.cpp
  3. * @brief Background subtraction tutorial sample code
  4. * @author Domenico D. Bloisi
  5. */
  6. #include <iostream>
  7. #include <sstream>
  8. #include <opencv2/imgcodecs.hpp>
  9. #include <opencv2/imgproc.hpp>
  10. #include <opencv2/videoio.hpp>
  11. #include <opencv2/highgui.hpp>
  12. #include <opencv2/video.hpp>
  13. using namespace cv;
  14. using namespace std;
  15. const char* params
  16. = "{ help h | | Print usage }"
  17. "{ input | vtest.avi | Path to a video or a sequence of image }"
  18. "{ algo | MOG2 | Background subtraction method (KNN, MOG2) }";
  19. int main(int argc, char* argv[])
  20. {
  21. CommandLineParser parser(argc, argv, params);
  22. parser.about( "This program shows how to use background subtraction methods provided by "
  23. " OpenCV. You can process both videos and images.\n" );
  24. if (parser.has("help"))
  25. {
  26. //print help information
  27. parser.printMessage();
  28. }
  29. //! [create]
  30. //create Background Subtractor objects
  31. Ptr<BackgroundSubtractor> pBackSub;
  32. if (parser.get<String>("algo") == "MOG2")
  33. pBackSub = createBackgroundSubtractorMOG2();
  34. else
  35. pBackSub = createBackgroundSubtractorKNN();
  36. //! [create]
  37. //! [capture]
  38. VideoCapture capture( samples::findFile( parser.get<String>("input") ) );
  39. if (!capture.isOpened()){
  40. //error in opening the video input
  41. cerr << "Unable to open: " << parser.get<String>("input") << endl;
  42. return 0;
  43. }
  44. //! [capture]
  45. Mat frame, fgMask;
  46. while (true) {
  47. capture >> frame;
  48. if (frame.empty())
  49. break;
  50. //! [apply]
  51. //update the background model
  52. pBackSub->apply(frame, fgMask);
  53. //! [apply]
  54. //! [display_frame_number]
  55. //get the frame number and write it on the current frame
  56. rectangle(frame, cv::Point(10, 2), cv::Point(100,20),
  57. cv::Scalar(255,255,255), -1);
  58. stringstream ss;
  59. ss << capture.get(CAP_PROP_POS_FRAMES);
  60. string frameNumberString = ss.str();
  61. putText(frame, frameNumberString.c_str(), cv::Point(15, 15),
  62. FONT_HERSHEY_SIMPLEX, 0.5 , cv::Scalar(0,0,0));
  63. //! [display_frame_number]
  64. //! [show]
  65. //show the current frame and the fg masks
  66. imshow("Frame", frame);
  67. imshow("FG Mask", fgMask);
  68. //! [show]
  69. //get the input from the keyboard
  70. int keyboard = waitKey(30);
  71. if (keyboard == 'q' || keyboard == 27)
  72. break;
  73. }
  74. return 0;
  75. }