Thursday 4 June 2015

Capturing a video form a file or webcam in opencv using VideoCapture()


This tutorial is about capturing a video form a file or webcam and storing it:

Video is a series of images displayed sequentially in quick succession.
Thus in other words we can say that a video is a continuous frame of images.Here by continuous we mean that each image frame is played in a rapid succession such that it appears continuous frames to our eyes.
(Due to persistence of vision)

Thus processing a video is analogous to processing each frame of still images.
There are two ways to process a video:
1. Load it from a file
2. Capture it from a webcam i.e real time recording of video.

Thus if we need to capture a video from a webcam we need to just replace the line of the code by
VideoCapture capture(0);
where the parameter 0 indicates that we are using the default camera for capturing the video.

Thus if attach external camera other than the one which we have with our laptop we need to give that index as our parameter.

e.g VideoCapture capture(1);

Opencv Code for Loading a video from a file:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
  using namespace std;
  using namespace cv;

  int main()
  {
       VideoCapture capture("D:\\MyVideo.avi");
            if (!capture.isOpened())
            throw "Error when reading file";
       namedWindow("window", 1);
       for (;;)
     {
            Mat frame;
            capture >> frame;
            if (frame.empty())
              break;
            imshow("window", frame);
            waitKey(1);
       }
   }  

 Opencv Code for Loading a video from a webcam:
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <iostream>  
  using namespace std;  
  using namespace cv;  
  
  int main()
  {  
       VideoCapture capture(0);  
            if (!capture.isOpened())  
            throw "Error when reading file";  
       namedWindow("window", 1);  
       for (;;)
     { 
            Mat frame; 
            capture >> frame;  
            if (frame.empty())  
              break;  
            imshow("window", frame);  
            waitKey(1);  
       }  
   }  

By changing the parameter of the waitKey we can change the speed of the video.
Here is the link of the code to capture video from a webcam using opencv:

No comments:

Post a Comment