Capturing live stream from camera is very easy task with the help of OpenCV library. To capture camera video stream we have to to do following steps:

  1. Create a VideoCapture object.
  2. capture frame-by-frame.
  3. Release the capture frame at the end and destroy the window.

To use VideoCapture interface we have to include   #include “opencv2/opencv.hpp”

The VideoCapture object can be declared as below:VideoCapture cap(0); // open the default camera

The argument 0 is passed for default camera. if you have another camera attached with your system and if capture fails then you can pass 1 as argument. This is simply an index of the camera device.

Sometimes if there is problem due to hardware or driver issues then capture fails this type of error can be checked with following code.
if(!cap.isOpened())  // check if we succeeded
        return -1;

Now we can read video stream frame by frame and display in opencv window. for this we use infinite for loop. Here is simple example of code written in C/C++ which will read your video steam from camera and show you in opencv window.

//g++ camera.cpp `pkg-config --cflags --libs opencv` -o demo

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;


        Mat video;
        if( )// get a new frame from camera
        imshow("mycamera", video);
        if(waitKey(30) >= 0) break;
    // release memory
    return 0;

waitKey(int) function wait for user key event. if we press key the window will be closed.

How to compile on Linux/Ubuntu

g++ camera.cpp `pkg-config --cflags --libs opencv` -o demo

Related Contents to follow