OpenCV2 method of getting a frame from the camera and writing a video file

  • 2020-12-09 00:55:44
  • OfStack

1 block of OpenCV2 based code.

Gets a frame from the camera and writes the frame to the specified video file.

Note that the path to the video file needs to exist, such as D: / images / 1.avi. Images this directory needs to exist. When the member function open of the VideoWrite class object is called, the codec mode parameter is set to -1. When the code is running, a dialog box pops up and the codec mode is manually selected.


#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<opencv2\core\core.hpp>

int main()
{
 // Turn on the camera 
 cv::VideoCapture captrue(0);
 // Video write object 
 cv::VideoWriter write;
 // Write the video file name 
 std::string outFlie = "D:/1.avi";
 // Gets the width and height of the frame 
 int w = static_cast<int>(captrue.get(CV_CAP_PROP_FRAME_WIDTH));
 int h = static_cast<int>(captrue.get(CV_CAP_PROP_FRAME_HEIGHT));
 cv::Size S(w, h);
 // Get the frame rate 
 double r = captrue.get(CV_CAP_PROP_FPS);
 // Open the video file and prepare to write 
 write.open(outFlie, -1, r, S, true);

 // Open the failure 
 if (!captrue.isOpened())
 {
  return 1;
 }
 bool stop = false;
 cv::Mat frame;
 // cycle 
 while (!stop)
 {
  // Reading frame 
  if (!captrue.read(frame))
   break;
  cv::imshow("Video", frame);
  // Written to the file 
  write.write(frame);
  if (cv::waitKey(10) > 0)
  {
   stop = true;
  }
 }
 // Release object 
 captrue.release();
 write.release();
}

Related articles: