Skip to content

cv::VideoWriter with CAP_OPENCV_MJPEG api creates broken (or just unfinished) video file. #24171

@alexlyulkov

Description

@alexlyulkov

System Information

OpenCV version: 4.8.0
Windows 11
Microsoft Visual Studio 2022 64bit

Detailed description

If I create a certain video using cv::VideoWriter with CAP_OPENCV_MJPEG api, I can load the video correctly using cv::VideoCapture, but I get an error message during loading.

[mjpeg @ 0000015a20f1df00] error count: 268435456
[mjpeg @ 0000015a20f1df00] error y=0 x=0

Also I can watch the created video using Windows Media Player without any errors.
If I create the same video using CAP_FFMPEG api, I don't get error messages.
The error reproduces only on a certain video content, so I can create a different video with the same size without error messages.

Steps to reproduce

#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>

int w = 16;
int h = 16;
int num_frames = 1;

void saveVideo(std::string filename, cv::VideoCaptureAPIs api, long base_color) {
    cv::VideoWriter writer(filename, api, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 30, cv::Size(w, h), true);
    for (long i = 0; i < num_frames; ++i) {
        cv::Mat frame1(h, w, CV_8UC3);
        for (long x = 0; x < w; x++) {
            for (long y = 0; y < h; y++) {
                frame1.at<cv::Vec3b>(y, x) = cv::Vec3b((base_color * x) % 256, base_color + 2, base_color + 3);
            }
        }
        writer.write(frame1);
    }
    writer.release();
}

void loadVideo(std::string filename) {
    std::cout << "===== loading " << filename << std::endl << std::flush;
    cv::VideoCapture cap(filename, cv::CAP_FFMPEG);
    if (!cap.isOpened()) {
        std::cout << "No video stream detected" << std::endl;
        return;
    }
    cv::Mat frame;
    uint32_t frame_cnt = 0;
    while (true) {
        cap >> frame;
        if (frame.empty()) {
            break;
        }

    }
    cap.release();
    std::cout << "===== loaded " << filename << std::endl << std::flush;
}

int main(int argc, char* argv[]) {
    saveVideo("out1.avi", cv::CAP_FFMPEG, 147);
    saveVideo("out2.avi", cv::CAP_FFMPEG, 146);
    saveVideo("out3.avi", cv::CAP_OPENCV_MJPEG, 147);
    saveVideo("out4.avi", cv::CAP_OPENCV_MJPEG, 146);

    loadVideo("out1.avi");
    loadVideo("out2.avi");
    loadVideo("out3.avi");
    loadVideo("out4.avi"); // prints error message
}

Issue submission checklist

  • I report the issue, it's not a question
  • I checked the problem with documentation, FAQ, open issues, forum.opencv.org, Stack Overflow, etc and have not found any solution
  • I updated to the latest OpenCV version and the issue is still there
  • There is reproducer code and related data files (videos, images, onnx, etc)

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions