How to capture video from other cameras in OpenCV using C++?

OpenCVC++Server Side ProgrammingProgramming

In this topic, we will determine how to use OpenCV to capture videos from the other cameras. The accessing of cameras other than the default camera is similar to accessing the default camera. There is only one difference that is instead of using 'VideoCapture cap(0)', we have to assign the camera number. The camera number is as per the sequence of a USB port. If the camera is connected to the third USB port, then the number of the camera is 3.

The following program access the third camera and show the real-time video stream taken from the camera.

Example

#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//
#include<iostream>
using namespace std;
using namespace cv;
int main() {
   Mat myImage;//Declaring a matrix to load the frames//
   namedWindow("Video Player");//Declaring the video to show the video//
   VideoCapture cap(3);//Declaring an object to capture stream of frames from third camera//
   if (!cap.isOpened()){ //This section prompt an error message if no video stream is found//
      cout << "No video stream detected" << endl;
      system("pause");
      return-1;
   }
   while (true){ //Taking an everlasting loop to show the video//
      cap >> myImage;
      if (myImage.empty()){ //Breaking the loop if no video frame is detected//
         break;
      }
      imshow("Video Player", myImage);//Showing the video//
      char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition//
      if (c == 27){ //If 'Esc' is entered break the loop//
         break;
      }
      imshow("Video Player", myImage);//Showing the video//
      char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition//
      if (c == 27){ //If 'Esc' is entered break the loop//
         break;
      }
   }
   cap.release();//Releasing the buffer memory//
   return 0;
}

Output

raja
Published on 10-Mar-2021 08:25:28
Advertisements