c++ - 使用opencv mat处理AVFrame导致编码错误

标签 c++ opencv ffmpeg encode mat

我正在尝试使用 ffmpeg 解码视频文件,获取 AVFrame 对象,将其转换为 opencv mat 对象,进行一些处理,然后将其转换回 AVFrame 对象并将其编码回视频文件。

好吧,程序可以运行,但是产生了不好的结果。

我不断收到诸如“7 19 请求的帧内模式无法使用顶部 block ”、“解码 MB 7 19、字节流 358 时出错”、“在 P 帧中隐藏 294 DC、294AC、294 MV 错误”等错误。

结果视频到处都是闪闪发光的东西。像这样, enter image description here

我猜这是因为我的 AVFrame 到 Mat 和 Mat 到 AVFrame 方法,它们在这里

//unspecified function
temp_rgb_frame = avcodec_alloc_frame(); 
int numBytes = avpicture_get_size(PIX_FMT_RGB24, width, height); 
uint8_t * frame2_buffer = (uint8_t *)av_malloc(numBytes * sizeof(uint8_t)); 
avpicture_fill((AVPicture*)temp_rgb_frame, frame2_buffer, PIX_FMT_RGB24, width, height);

void CoreProcessor::Mat2AVFrame(cv::Mat **input, AVFrame *output)
{
    //create a AVPicture frame from the opencv Mat input image
    avpicture_fill((AVPicture *)temp_rgb_frame,
        (uint8_t *)(*input)->data,
        AV_PIX_FMT_RGB24,
        (*input)->cols,
        (*input)->rows);

    //convert the frame to the color space and pixel format specified in the sws context

    sws_scale(
        rgb_to_yuv_context, 
        temp_rgb_frame->data,
        temp_rgb_frame->linesize,
        0, height, 
        ((AVPicture *)output)->data, 
        ((AVPicture *)output)->linesize);

    (*input)->release();

}

void CoreProcessor::AVFrame2Mat(AVFrame *pFrame, cv::Mat **mat)
{
    sws_scale(
        yuv_to_rgb_context, 
        ((AVPicture*)pFrame)->data, 
        ((AVPicture*)pFrame)->linesize, 
        0, height, 
        ((AVPicture *)temp_rgb_frame)->data,
        ((AVPicture *)temp_rgb_frame)->linesize);

    *mat = new cv::Mat(pFrame->height, pFrame->width, CV_8UC3, temp_rgb_frame->data[0]);
}

void CoreProcessor::process_frame(AVFrame *pFrame)
{
    cv::Mat *mat = NULL;
    AVFrame2Mat(pFrame, &mat);
    Mat2AVFrame(&mat, pFrame);
}

我是不是内存有问题?因为如果我去掉处理部分,只解码然后编码帧,结果是正确的。

最佳答案

好吧,原来我在temp_rgb_frame的初始化时出错了,如果应该是这样的话,

temp_rgb_frame = avcodec_alloc_frame();
int numBytes = avpicture_get_size(PIX_FMT_RGB24, width, height);
uint8_t * frame2_buffer = (uint8_t *)av_malloc(numBytes * sizeof(uint8_t));
avpicture_fill((AVPicture*)temp_rgb_frame, frame2_buffer, PIX_FMT_RGB24, width, height);

关于c++ - 使用opencv mat处理AVFrame导致编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26910524/

相关文章:

c++ - Opencv train cascade 卡住,命中率为 1,误报率为 0

python - SIFT 或 SURF - 提供关键点并检索描述符

c++ - 如何在 C++ 中将调色板生成器和调色板使用过滤器与 FFmpeg 一起使用?

video - 来自 png 图像不均匀序列的 ffmpeg 视频

c++ - 从单元测试用例运行线程是一个好习惯吗?

c++ - forloop、迭代器和 vector 不配合我

c++ - QML Timer - 如何提高准确性?

c++ - 使用模板和基类实现灵活的数组成员

c++ - opencv神经网络,不正确的预测

nginx - FFMPEG SRT 多个调用者进入一个听众?