Advertisement
Alior

Untitled

Oct 29th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. // Movement detection.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <opencv2/imgproc/imgproc.hpp>
  6. #include <opencv2/core.hpp>
  7. #include <opencv2/imgcodecs.hpp>
  8. #include <opencv2/highgui.hpp>
  9. #include <iostream>
  10. #include <deque>
  11. #include <opencv2/video/background_segm.hpp>
  12. #include <windows.h>
  13.  
  14. using namespace cv;
  15. using namespace std;
  16. int main(int argc, char** argv)
  17. {
  18.     auto source = "C:\\Users\\alior\\Downloads\\Video.mp4";
  19.     VideoCapture inputVideo(source);
  20.     if (!inputVideo.isOpened())
  21.     {
  22.         cout << "Could not open the input video: " << source << endl;
  23.         return -1;
  24.     }
  25.  
  26.     Mat frame;
  27.     auto substractor = createBackgroundSubtractorMOG2(500, 16, false);
  28.  
  29.     while (inputVideo.read(frame))
  30.     {
  31.         Mat substracted;
  32.  
  33.         substractor->apply(frame, substracted);
  34.  
  35.         auto closingKernel = getStructuringElement(MORPH_ELLIPSE, Size(2, 2));
  36.         auto openingKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
  37.  
  38.         Mat opened;
  39.         morphologyEx(substracted, opened, MORPH_OPEN, openingKernel);
  40.  
  41.         Mat closed;
  42.         morphologyEx(opened, closed, MORPH_CLOSE, closingKernel);
  43.  
  44.  
  45.         Mat dilated;
  46.         dilate(closed, dilated, closingKernel, Point(-1, -1), 2);
  47.  
  48.         vector<vector<Point> > contours;
  49.         vector<Vec4i> hierarchy;
  50.         findContours(dilated, contours, noArray(), CV_RETR_LIST, CV_CHAIN_APPROX_TC89_KCOS);
  51.  
  52.         float areaThreshold = 5;
  53.  
  54.         for (int i = 0; i < contours.size(); i++)
  55.         {
  56.             Scalar color = Scalar(255, 0, 0);
  57.             auto rect = boundingRect(contours[i]);
  58.             if (rect.area() < areaThreshold)
  59.                 continue;
  60.  
  61.             rectangle(frame, rect, color, 1);
  62.  
  63.             //drawContours(frame, contours, i, color, 2, 8, noArray(), 0, Point());
  64.         }
  65.  
  66.         imshow("Opened", opened);
  67.         imshow("Result", dilated);
  68.         imshow("Movement", substracted);
  69.         imshow("Frame", frame);
  70.  
  71.  
  72.         while ((char)waitKey(30) != 'q');
  73.     }
  74.  
  75.     inputVideo.release();
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement