samples/cpp/videowriter.cpp#

An example using VideoCapture and VideoWriter class

  1/**
  2  @file videowriter.cpp
  3  @brief A sample for VideoWriter and VideoCapture with options to specify video codec, fps and resolution
  4  @date April 05, 2024
  5*/
  6
  7
  8#include <opencv2/core.hpp>
  9#include <opencv2/videoio.hpp>
 10#include <opencv2/highgui.hpp>
 11#include <opencv2/imgproc.hpp>
 12#include <iostream>
 13#include <map>
 14
 15using namespace cv;
 16using namespace std;
 17
 18inline map<string, int> fourccByCodec() {
 19    map<string, int> res;
 20    res["h264"] = VideoWriter::fourcc('H', '2', '6', '4');
 21    res["h265"] = VideoWriter::fourcc('H', 'E', 'V', 'C');
 22    res["mpeg2"] = VideoWriter::fourcc('M', 'P', 'E', 'G');
 23    res["mpeg4"] = VideoWriter::fourcc('M', 'P', '4', '2');
 24    res["mjpeg"] = VideoWriter::fourcc('M', 'J', 'P', 'G');
 25    res["vp8"] = VideoWriter::fourcc('V', 'P', '8', '0');
 26    return res;
 27}
 28
 29// Function to parse resolution string "WxH"
 30static Size parseResolution(const string& resolution) {
 31    stringstream ss(resolution);
 32    int width, height;
 33    char delimiter;
 34
 35    ss >> width >> delimiter >> height;
 36
 37    if (ss.fail() || delimiter != 'x') {
 38        throw runtime_error("Invalid resolution format. Please provide in WxH format.");
 39    }
 40
 41    return Size(width, height);
 42}
 43
 44
 45int main(int argc, char** argv) {
 46    const String keys =
 47        "{help h usage ? |      | Print help message   }"
 48        "{fps           |30    | fix frame per second for encoding (supported: fps > 0)   }"
 49        "{codec         |mjpeg | Supported codecs depend on OpenCV Configuration. Try one of 'h264', 'h265', 'mpeg2', 'mpeg4', 'mjpeg', 'vp8' }"
 50        "{resolution    |1280x720 | Video resolution in WxH format, (e.g., '1920x1080') }"
 51        "{output_filepath    | output.avi | Path to the output video file}";
 52
 53    CommandLineParser parser(argc, argv, keys);
 54    parser.about("Video Capture and Write with codec and resolution options");
 55
 56    if (parser.has("help")) {
 57        parser.printMessage();
 58        return 0;
 59    }
 60
 61    double fps = parser.get<double>("fps");
 62    string codecStr = parser.get<string>("codec");
 63    string resolutionStr = parser.get<string>("resolution");
 64    string outputFilepath = parser.get<string>("output_filepath");
 65
 66    auto codecMap = fourccByCodec();
 67
 68    if (codecMap.find(codecStr) == codecMap.end()) {
 69        cerr << "Invalid codec" << endl;
 70        return -1;
 71    }
 72
 73    int codec = codecMap[codecStr];
 74    Size resolution = parseResolution(resolutionStr);
 75
 76    // Video Capture
 77    VideoCapture cap(0);
 78    if (!cap.isOpened()) {
 79        cerr << "ERROR! Unable to open camera\n";
 80        return -1;
 81    }
 82
 83    cout << "Selected FPS: " << fps << endl;
 84    cout << "Selected Codec: " << codecStr << endl;
 85    cout << "Selected Resolution: " << resolutionStr << " (" << resolution.width << "x" << resolution.height << ")" << endl;
 86
 87    // Set up VideoWriter
 88    VideoWriter writer(outputFilepath, codec, fps, resolution, true); // Assuming color video
 89    if (!writer.isOpened()) {
 90        cerr << "Could not open the output video file for write\n";
 91        return -1;
 92    }
 93
 94    cout << "Writing video file: " << outputFilepath << endl
 95         << "Press any key to terminate" << endl;
 96
 97    Mat frame, resizedFrame;
 98    for (;;) {
 99        // Capture frame
100        if (!cap.read(frame) || frame.empty()) {
101            break;
102        }
103
104        // Resize frame to desired resolution
105        resize(frame, resizedFrame, resolution);
106
107        // Write resized frame to video
108        writer.write(resizedFrame);
109
110        // Show live
111        imshow("Live", resizedFrame);
112        if (waitKey(5) >= 0) break;
113    }
114
115    // VideoWriter and VideoCapture are automatically closed by their destructors
116
117    return 0;
118}