我如何为 OpenCV 的 VideoWriter 动态 select 一个可用的编解码器?

How do I dynamically select an available codec for OpenCV's VideoWriter?

我正在编写一个图像处理应用程序来对齐一组图像,我希望有将这些图像写入视频的功能。图像处理部分在 OpenCV 3.2.0 (C++) 中完成,目前输出未拼接在一起的静止图像。

我已经成功地将 VideoWriter 与我的机器可用的编解码器之一一起使用,将输出图像写入 .avi,但据我所知,不能保证任何编解码器都可以在不同的平台上使用。因为我希望能够共享此应用程序,所以这是一个问题。

如果重要的话,GUI 内置于 wxWidgets 3.1.0 中,所以如果有什么东西可以帮助我,但我没有找到,我很想知道。

我的假设是,如果不以某种方式随应用程序一起提供编解码器,就无法保证视频成功,但是有没有办法在 运行 时间浏览可用的编解码器?

我知道在某些平台上,以下内容会弹出一个附加编解码器的对话框,如果我能自动解释它就完美了:

cv::Size outputSize = myImage.size();
cv::VideoWriter("output.avi", -1, 30, outputSize);

但这也不适用于所有平台。那么有没有什么方法可以在 运行 时间从机器上清除可用的编解码器,或者我是否必须以某种方式提供编解码器才能跨平台编写视频?

OpenCV 中没有这样的函数来列出所有可用的编解码器。然而,如果你的机器上有 ffmpeg 或 LibAV——你应该有 building/installing OpenCV——那么你可以使用 ffmpeg/LibAV 列出所有可用的编解码器。以下是执行此操作的代码:

#include <iostream>

extern "C" {
    #include <libavcodec/avcodec.h>
}

int main(int argc, char **argv)
{
    /* initialize libavcodec, and register all codecs and formats */
    avcodec_register_all();

    // struct to hold the codecs
    AVCodec* current_codec = NULL;

    // initialize the AVCodec* object with first codec
    current_codec = av_codec_next(current_codec);

    std::cout<<"List of codecs:"<<std::endl;

    // loop over all codecs
    while (current_codec != NULL)
    {

        if(av_codec_is_encoder(current_codec) | av_codec_is_decoder(current_codec))
        {
            std::cout<<current_codec->name<<std::endl;
        }
        current_codec = av_codec_next(current_codec);
    }
}

编译:

g++ listcodecs.cpp -o listcodecs `pkg-config libavcodec --cflags --libs`