How To Create a Webcam Video Capture Using OpenCV [C++]

In this short Tutorial we will see briefly how to create a live video capture from a laptop webcam using OpenCV (Open Computer Vision) which is similar to a Hello World program in the Field of image processing. So let's start coding :D !

How To Create a Webcam Video Capture Using OpenCV [C++]

Photo by Cottonbro on Pexels 


Step 1 : Importing HPP files (Headers):

#include <opencv2\opencv.hpp>

Step 2 : Creating namespaces :

using namespace cv;

using namespace std;

Using namespaces will let us save some time and effort. For instance, we don't need to write certain terms like cv every time before calling an OpenCV function.

Example : namedWindow("trackbar"); instead of cv::namedWindow("trackbar"); 

Step 3 : Writing the main function :

int main() {

// Code Here

return 0 ;

}

If you don't know what a main function is, it's simply a function that presents the start or in other words the entry point of the program that we are going to run.

Step 4 : Declaring the necessary variables :

Mat image ;

We are here creating an empty matrix where we are going to store webcam frames.

Step 5 : Creating a display window :

namedWindow("Display window");

Display window will be the window name.

Step 6 : Opening the webcam :

VideoCapture cap(0);

if (!cap.isOpened())

{

cout << "cannot open camera";

}
  • 0 is the index of the Webcam. If you get an error, try changing that index to -1 or 1, 2 ... etc until you find the right index.
  • We used an if statement to verify if a video device has been successfully initialized or not.

Step 7 : Writing an infinite while loop inside the main function:

int main() {

while (true)

{

//code here

}

return 0 ;

}

We need an infinite loop to be able to show the video repeatedly frame by frame. 

Step 8 : Inserting the webcam frame inside the image matrix :

cap >> image;

image = cap ; will give you back an error. So pay attention about the >>

Step 9 : Displaying the image matrix inside the window

imshow("Display window", image);

Step 10 : Setting up display time of the webcam frames

waitKey(25);

The value inside waitKey() will affect how fast webcam frames will be displayed. If this value is

too low, the video will looks very fast. If it's too high, the video will looks very slow and laggy.

25 milliseconds will be OK in normal cases and avoid choosing 0 ms, it will display the same

frame infinitely until you press any key(it is suitable for image display not for video display).

Code [C++] :

#include <opencv2\opencv.hpp>

using namespace cv;

using namespace std;

int main() {

Mat image;

namedWindow("Display window");

VideoCapture cap(0);

if (!cap.isOpened()) {

cout << "cannot open camera";

}

while (true) {

cap >> image;

imshow("Display window", image);

waitKey(25);

}

return 0;

}