Record multiple videos in OpenCV C++

I want to record selected frames as multiple videos from webcam. I tried the following code to start recording a video on a key press and stop recording that video with a different key press. I want to record multiple such videos. But the recorded video files are empty. Can you please help me to correct my mistake? Record multiple videos from webcam stream in OpenCV C++ - Stack Overflow

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;

int main(){

  // Create a VideoCapture object and use camera to capture the video
  VideoCapture cap(0); 

  // Check if camera opened successfully
  if(!cap.isOpened()){
    cout << "Error opening video stream" << endl;
        return -1;
  }
  
  // Default resolutions of the frame are obtained.
  int frame_width = cap.get(cv::CAP_PROP_FRAME_WIDTH);
  int frame_height = cap.get(cv::CAP_PROP_FRAME_HEIGHT);

  bool recording = false;
  int videono = 1;

  VideoWriter video("dummy.avi", cv::VideoWriter::fourcc('M','J','P','G'), 10, Size(frame_width,frame_height));
  video.release();

  while(1)
  {

    Mat frame;
   
    // Capture frame-by-frame
    cap >> frame;
 
    // If the frame is empty, break immediately
    if (frame.empty())
      break;
   
    // Display the resulting frame    
    imshow( "Frame", frame );
 
    // Press  ESC on keyboard to  exit
    char c = (char)waitKey(1);
    if( c == 27 ) 
      break;
    
    // Press  s on keyboard to start recording
    if( c == 115 and !recording)
    {
      char path[100];
      sprintf(path, "%d.avi", videono);
      std::cout << "recording started for " << path << "\n";
      videono += 1;
      VideoWriter video(path, cv::VideoWriter::fourcc('M','J','P','G'), 10, Size(frame_width,frame_height));
      recording = true;
    }       

    if( recording )
      video.write(frame);
    
    // Press x on keyboard to stop recording
    if( c == 120)
    {
      std::cout << "recording finished.\n";
      recording = false;
      video.release();
    }
        
  }

  // release the video capture and write object
  cap.release();
  

  // Closes all the frames
  destroyAllWindows();
  return 0;

one problem is here:

you’re creating a local VideoWriter , which is never used.
to overwrite / recreate the global one, use:

video = VideoWriter(path, cv::VideoWriter::fourcc('M','J','P','G'), 10, Size(frame_width,frame_height));
1 Like

thanks @berak, but the complete answer/solution is Record multiple videos from webcam stream in OpenCV C++ - Stack Overflow

you had that answer on SO before you even posted here.

why did you ask here, if you already had the “complete answer”?

@crackwitz first I posted here but my account and question were on hold by OpenCV for staff review. Then I posted it on SO. Before I could get any response from OpenCV, I received answer on SO.