Saturday, 30 January 2016

Capturing a Video from a File/Webcam

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);

Reading from a File:


//OpenCv C++ Code for reading video from a File
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
  using namespace std;
  using namespace cv;
 
  int main()
  {
       //Capturing the Video
       VideoCapture capture("D:\\MyVideo.avi");

       
       //Check whether video is Opening
       if (!capture.isOpened())
       throw "Error when reading file";

       namedWindow("window", 1);
       
       //Reading frames of Video
       for (;;)
     {
            Mat frame;
            capture >> frame;
            if (frame.empty())
              break;
            imshow("window", frame);
            waitKey(1);
       }
   }  


Reading from a Webcam:


#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
  using namespace std;
  using namespace cv;
 
  int main()
  {
       //Capturing the Video
       VideoCapture capture(0);

       
       //Check whether video is Opening
       if (!capture.isOpened())
       throw "Error when reading file";

       namedWindow("window", 1);
       
       //Reading frames of Video
       for (;;)
     {
            Mat frame;
            capture >> frame;
            if (frame.empty())
              break;
            imshow("window", frame);
            waitKey(1);
       }
   }  

No comments:

Post a Comment