How to store video on your computer in OpenCV using C++?

OpenCVC++Server Side ProgrammingProgramming

When we want to store a video, we have to define the location we want to store. Then we need to specify FourCC, FourCC stands for 'Four Character Code'. It is a sequence of 4-byte characters that identifies data formats. We also need to declare the FPS to store a video and frame size is also necessary for this storing process. The following program takes real-time video stream from the default camera and stores the video in C directory.

The following program demonstrates how to store video in your computer in OpenCV using C++.


#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class and VideoWriter//
using namespace std;
using namespace cv;
int main() {
   Mat myImage;//Declaring a matrix to store the frames//
   VideoCapture cap(0);//Taking an object of VideoCapture Class to capture video from default camera//
   namedWindow("Video Player");//Declaring the video to show the video//
   if(!cap.isOpened()){ //This section prompt an error message if no video stream is found//
      cout << "Failed to access the camera" << endl;
   int frame_width = cap.get(CAP_PROP_FRAME_WIDTH);//Getting the frame height//
   int frame_height = cap.get(CAP_PROP_FRAME_HEIGHT);//Getting the frame width//
   VideoWriter video("video1.mp4",10,17,Size(frame_width, frame_height));//Declaring an object of VideoWriter class//
   while (true){ //Taking an everlasting loop to show the video//
      cap >> myImage;
      if (myImage.empty()){ //Breaking the loop if no video frame is detected//
      video.write(myImage);//Write the video//
      imshow("Video Player", myImage);//Showing the video//
      char c= (char)waitKey(25);
   cap.release();//Releasing the buffer memory//
   return 0;

This program will store the video in the defined directory as a defined name in the defined format.

Published on 10-Mar-2021 08:31:13