Ask Your Question
0

How to copy vector of Mat and write video ?

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

Bensuperpc gravatar image

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

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) {
        video_vect.emplace_back(trame_vid.clone());
}

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())
      break;
    // Copy current image to vector
    video_vect.emplace_back(frame.clone());
    imshow("Frame", frame);

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

  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) {
    video_vect.emplace_back(trame_vid.clone());
  }

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

  for (cv::Mat &trame_vid : video_vect) {
    video.write(trame_vid);
  }
  // Liberation des ressources
  capture.release();

  video.release();
  video_vect.clear();
  video_vect.shrink_to_fit();

  // Closes all the frames
  cv::destroyAllWindows();
edit retag flag offensive close merge delete

Comments

1

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 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
0

answered 2020-01-26 07:18:02 -0600

Bensuperpc gravatar image

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: /

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2020-01-22 11:05:00 -0600

Seen: 1,542 times

Last updated: Jan 22 '20