Skip to content

Instantly share code, notes, and snippets.

@asmwarrior
Created April 26, 2023 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asmwarrior/f60c891e76361091f509db1f65c9ddff to your computer and use it in GitHub Desktop.
Save asmwarrior/f60c891e76361091f509db1f65c9ddff to your computer and use it in GitHub Desktop.
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
int width = 640;
int height = 480;
int fps = 30;
int num_frames = 100;
Scalar black(0, 0, 0);
Scalar white(255, 255, 255);
int font = FONT_HERSHEY_SIMPLEX;
double font_scale = 1.0;
int thickness = 2;
VideoWriter writer("output.mp4", VideoWriter::fourcc('M', 'P', '4', 'V'), fps, Size(width, height));
for (int i = 0; i < num_frames; i++) {
Mat frame = Mat::zeros(height, width, CV_8UC3);
putText(frame, std::to_string(i), Point(width / 2 - 50, height / 2), font, font_scale, white, thickness);
writer.write(frame);
}
writer.release();
return 0;
}
@asmwarrior
Copy link
Author

Here is the code to read back the mp4 file, and save the images with the file name as the index. You can see the for "00.jpg", it shows "0" in the image, so it works correctly.

#include <opencv2/opencv.hpp>
#include <string>

using namespace cv;

int main() {
    std::string video_path = "output.mp4";
    VideoCapture cap(video_path);

    if (!cap.isOpened()) {
        std::cerr << "Error opening video file" << std::endl;
        return -1;
    }

    int i = 0;
    Mat frame;
    while (cap.read(frame)) {
        std::string file_path = std::to_string(i);
        file_path = std::string(2 - file_path.length(), '0') + file_path + ".jpg";
        imwrite(file_path, frame);
        i++;
    }

    cap.release();

    return 0;
}

There is a warning when I save the mp4 file, the warning is below:

OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 12 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment