Capture Webcam Video in C++ using OpenCV

In this tutorial, we are going to explore how to capture webcam video using OpenCV in C++. This guide covers everything from initialization of webcam to display video feed in a window.

 

Introduction to OpenCV

OpenCV is an Open-Source Computer Vision Library of programming functions specially aimed at real-time computer vision. It’s widely used in tasks such as image processing, face detection and video capture.
Capturing video from a webcam is a very common task in OpenCV.  This makes it easier for developers to interface with camera hardware.

Setting Up the Environment

Before entering into the code itself, you must ensure that:

  1. OpenCV should be installed on your machine.
  2. A C++ compiler such as g++.
  3.  A connected webcam for video capturing.

To install OpenCV and g++, refer the installation guide found in the official OpenCV and G++ documentation for your OS.

Capturing Webcam Video

The steps for capturing webcam video in OpenCV are straightforward:

  1. Initialize a cv::VideoCapture object to access the webcam.
  2. Capture video frames in a loop.
  3. Display the frames in a window.

Example:

#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

int main() {
    // Creating object to access the webcam
    VideoCapture V(0); // 0 for the default webcam
    
    if (!V.isOpened()) { // Check if the webcam is opened
        cerr << "Error: Webcam not detected!" << endl;
        return -1;
    }

    cout << "Press 'q' to quit the video capture." << endl;

    Mat frames; // Variable to store frames captured
    while (true) {
        V >> frames; // Capture the current frame
        
        if (frames.empty()) { // Check if the frame is empty
            cerr << "Error: Captured frame is empty!" << endl;
            break;
        }
        
        imshow("Webcam Video", frames);  // Display the frame in a window
        
        if (waitKey(30) == 'q') {  // Exit the loop when 'q' is pressed
            break;
        }
    }
    
    V.release();  // Release the webcam and close the window
    destroyAllWindows();
    return 0;
}

 

Explanation:

  1. Initializing webcam: VideoCapture V(0) , ‘0‘ refers to the default webcam.
  2. Capturing Frames: V>>frames; statement captures each frame from webcam.
  3.  Displaying frames using the imshow(“Webcam Video”, frames); statement.
  4. Exiting: When we press q , the loop breaks and the program ends.

Conclusion:

In this tutorial, we have learned to capture webcam using C++ with OpenCV library.
Try experimenting with the code to build exciting projects using your webcam.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top