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:
- OpenCV should be installed on your machine.
- A C++ compiler such as g++.
- 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:
- Initialize a cv::VideoCapture object to access the webcam.
- Capture video frames in a loop.
- 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:
- Initializing webcam: VideoCapture V(0) , ‘0‘ refers to the default webcam.
- Capturing Frames: V>>frames; statement captures each frame from webcam.
- Displaying frames using the imshow(“Webcam Video”, frames); statement.
- 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.