How to copy vector of Mat and write video ?

asked 2020-01-22 11:06:24 -0500

Bensuperpc gravatar image

updated 2020-01-22 11:18:04 -0500

I would like to duplicate the images of a video via a vector, There are the right number of frames in vector but when copying, they are empty when writing the file, so the file only has the first copy of the frames but not the rest.

I think the problem comes from this loop but I do not know why it does not work :

for (cv::Mat &trame_vid : video_vect) {

Clone makes a copy and it is sent to the vector via emplace_back(), if I understand correctly ?

the entire code :

 std::string filename = "chaplin.mp4";
  cv::VideoCapture capture(filename);

  if (!capture.isOpened())
    throw "Error when reading chaplin.mp4";
  double fps = capture.get(cv::CAP_PROP_FPS);
  int frame_width = capture.get(cv::CAP_PROP_FRAME_WIDTH);
  int frame_height = capture.get(cv::CAP_PROP_FRAME_HEIGHT);

  cv::Mat frame;
  std::vector<cv::Mat> video_vect;
  video_vect.reserve(capture.get(cv::CAP_PROP_FRAME_COUNT) * 2);
  while (1) {

    // Capture frame-by-frame
    capture >> frame;
    // If the frame is empty, break immediately
    if (frame.empty())
    // Copy current image to vector
    imshow("Frame", frame);

    // ESC to stop
    char c = (char)cv::waitKey(20);
    if (c == 27)

  int codec = cv::VideoWriter::fourcc('X', '2', '6', '4');
  cv::VideoWriter video("out.avi", codec, (int)fps,
                        cv::Size(frame_width, frame_height), true);

  std::cout << video_vect.size() << std::endl;
  //Copy Mat
  for (cv::Mat &trame_vid : video_vect) {

  std::cout << video_vect.size() << std::endl;

  for (cv::Mat &trame_vid : video_vect) {
  // Liberation des ressources


  // Closes all the frames
edit retag flag offensive close merge delete



can you explain, why you're doing all of this ?

(e.g. why you need to save images in a vector, or why you're duplicating all of it ?)

berak gravatar imageberak ( 2020-01-22 11:54:07 -0500 )edit

It's only to test and learn how OpenCV works, I have to use it soon in a school project, I can't understand why it doesn't work: /

Bensuperpc gravatar imageBensuperpc ( 2020-01-26 07:18:02 -0500 )edit