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

OpenCVC++Server Side ProgrammingProgramming

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++.


#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//
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;
   while (true){ //Taking an everlasting loop to show the video//
      cap >> myImage;
      if (myImage.empty()){ //Breaking the loop if no video frame is detected//
      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//
   cap.release();//Releasing the buffer memory//
   return 0;


Published on 10-Mar-2021 12:58:54