denysowova
denysowova

Reputation: 111

Can't extract frames from video using C++ with OpenCV

I want to extract all frames from a short .mp4 video and save them as images to folder. But when I call a function cv::VideoCapture::read() it fails to extract a frame. What is the problem with my code?

#include <iostream>
#include <string>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/videoio.hpp>

int main(int argc, const char * argv[]) {
     cv::VideoCapture cap("test.mp4");

     if (!cap.isOpened()) {
         std::cout << "Cannot open the video file.\n";
         return -1;
     }

     for (int frame_count = 0; frame_count < cap.get(cv::CAP_PROP_FRAME_COUNT); frame_count++) {
          cap.set(cv::CAP_PROP_POS_FRAMES, frame_count);
          cv::Mat frame;

          if (!cap.read(frame)) {
              std::cout << "Failed to extract a frame.\n";
              return -1;
          }

          std::string image_path = "frames/" + std::to_string(frame_count) + ".jpg"; 
          cv::imwrite(image_path, frame);
    }

    return 0;
}

My output is always "Failed to extract a frame.".

Upvotes: 1

Views: 2769

Answers (1)

Bhoke
Bhoke

Reputation: 519

On the tutorial you provided above, there is an instruction:

Uncheck WITH_FFMPEG

ffmpeg library contains mp4 codecs, you need to check WITH_FFMPEG and USE_FFMPEG in order to read .mp4 and many other formats.

Upvotes: 1

Related Questions