background_subtr_opencv.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <iostream>
  2. #include <sstream>
  3. #include <opencv2/bgsegm.hpp>
  4. #include <opencv2/imgcodecs.hpp>
  5. #include <opencv2/imgproc.hpp>
  6. #include <opencv2/videoio.hpp>
  7. #include <opencv2/highgui.hpp>
  8. #include <opencv2/video.hpp>
  9. using namespace cv;
  10. using namespace std;
  11. using namespace cv::bgsegm;
  12. const char* input_params = "{ input | space_traffic.mp4 | Define the full input video path }";
  13. void get_opencv_result(String video_to_process) {
  14. // create VideoCapture object for further video processing
  15. VideoCapture capture(samples::findFile(video_to_process));
  16. if (!capture.isOpened()) {
  17. //error in opening the video input
  18. cerr << "Unable to open: " << video_to_process << endl;
  19. return;
  20. }
  21. // instantiate background subtraction model
  22. Ptr<BackgroundSubtractorGSOC> background_subtr_method = createBackgroundSubtractorGSOC();
  23. Mat frame, fgMask, background;
  24. while (true) {
  25. capture >> frame;
  26. // check whether the frames have been grabbed
  27. if (frame.empty())
  28. break;
  29. // resize video frames
  30. resize(frame, frame, Size(640, 360));
  31. // pass the frame to the background subtractor
  32. background_subtr_method->apply(frame, fgMask);
  33. // obtain the background without foreground mask
  34. background_subtr_method->getBackgroundImage(background);
  35. // show the current frame, foreground mask, subtracted result
  36. imshow("Initial Frames", frame);
  37. imshow("Foreground Masks", fgMask);
  38. imshow("Subtraction Result", background);
  39. int keyboard = waitKey(10);
  40. if (keyboard == 27)
  41. break;
  42. }
  43. }
  44. int main(int argc, char* argv[])
  45. {
  46. CommandLineParser parser(argc, argv, input_params);
  47. // start BS-pipeline
  48. get_opencv_result(parser.get<String>("input"));
  49. return 0;
  50. }