How to load video from your computer in OpenCV using C++?


In this topic, we will know how to load a video file and play it using OpenCV, and we have to use a similar method that we have learned in the previous topic. The only difference is instead of putting the number as arguments of the object of 'VideoCapture' class, and we have to put the path of the video.

The following program demonstrates how to load the video from your computer in OpenCV using C++.

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("video.mp4");//Declaring an object to capture stream of frames from default 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;
      }
   }
   cap.release();//Releasing the buffer memory//
   return 0;
}

Output

Updated on: 10-Mar-2021

566 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements