OpenCV VideoWriter 不起作用

OpenCV VideoWriter doesn't work

本文关键字:不起作用 VideoWriter OpenCV      更新时间:2023-10-16

我正在尝试使用opencv videoWriter来获取视频文件。但是我遇到以下问题:

>[libx264 @ 0x132b680] broken ffmpeg default settings detected
>[libx264 @ 0x132b680] use an encoding preset (e.g. -vpre medium)
>[libx264 @ 0x132b680] preset usage: -vpre <speed> -vpre <profile>
>[libx264 @ 0x132b680] speed presets are listed in x264 --help
>[libx264 @ 0x132b680] profile is optional; x264 defaults to high
>Could not open codec 'libx264': Unspecified error!!! Output video could not be opened

我的系统中确实有libx264,所以我想最后一行只是一个副作用

我尝试运行的代码是取自 如何在OpenCV 2.4.3中编写视频文件的示例 .

int main (int argc, char *argv[]){
// Load input video
VideoCapture input_cap("testi.mp4");
if (!input_cap.isOpened())
{
        std::cout << "!!! Input video could not be opened" << std::endl;
        return -1;
}
// Setup output video
cv::VideoWriter output_cap("testo.mp4", 
               input_cap.get(CV_CAP_PROP_FOURCC),
               input_cap.get(CV_CAP_PROP_FPS),
               cv::Size(input_cap.get(CV_CAP_PROP_FRAME_WIDTH),
               input_cap.get(CV_CAP_PROP_FRAME_HEIGHT)));
if (!output_cap.isOpened())
{
        std::cout << "!!! Output video could not be opened" << std::endl;
        return -1;
}

// Loop to read from input and write to output
cv::Mat frame;
while (true)
{       
    if (!input_cap.read(frame))             
        break;
    output_cap.write(frame);
}
input_cap.release();
output_cap.release();
return 0;
}

我发现了一个有类似问题的帖子 如何从 ffmpeg 中打开的文件获取流信息? 但还没有人回答正确。
我发现人们被告知检查opencv是否使用旧的fmmpeg而不是libav,但事实并非如此,因为它是一个新的版本,而我的ubuntu没有ffmpeg。

Dimazavr的回答并不完全正确。首先,您需要将输出视频文件扩展名从 .mp4更改为 .avi .然后,如果运行代码,将获得以下错误信息:

OpenCV Error: Unsupported format or combination of formats (Gstreamer Opencv backend does not support this codec.) in CvVideoWriter_GStreamer::open, file /home/rwduzhao/store/opencv-2.4.13/modules/highgui/src/cap_gstreamer.cpp, line 1372
terminate called after throwing an instance of 'cv::Exception'
  what():  /home/rwduzhao/store/opencv-2.4.13/modules/highgui/src/cap_gstreamer.cpp:1372: error: (-210) Gstreamer Opencv backend does not support this codec. in function CvVideoWriter_GStreamer::open
Aborted (core dumped)

这意味着opencv2.4中的cv::VideoWriter不支持libx264格式avi或者扩展名与libx264格式不兼容。我建议不要使用libx264编解码器。您可以尝试以下CV_FOURCC支持的编解码器格式列表:

CV_FOURCC('P','I','M','1')    = MPEG-1 codec
CV_FOURCC('M','J','P','G')    = motion-jpeg codec
CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
CV_FOURCC('U', '2', '6', '3') = H263 codec
CV_FOURCC('I', '2', '6', '3') = H263I codec
CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec

根据我的经验,CV_FOURCC('D', 'I', 'V', 'X')的质量很好。此外,如果cv_fourcc设置为-1,则可以在GUI窗口中选择系统中支持的编解码器格式之一。您可以在这里见证运行过程。

VideoWriter不支持.mp4扩展名。请改用.avi