OpenCV Mat to ffmpeg AVPicture转换内存泄漏

时间:2015-08-13 11:56:48

标签: c++ opencv memory-leaks ffmpeg opencv3.0

我有下一个代码:

void matToAvPicture(cv::Mat frame, AVPicture *picture)
{
    cv::resize(frame, frame, cv::Size(m_streamWidth, m_streamHeight));
    uint8_t* buf = (uint8_t*)malloc(avpicture_get_size(AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight)); // 3 bytes per pixel
    for(int i = 0; i < m_streamHeight; i++)
    {
        memcpy(&(buf[i * m_streamWidth * 3]), &(frame.data[i * frame.step]), m_streamWidth * 3);
    }
    AVPicture bgrPicture;
    avpicture_alloc(&bgrPicture, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight);
    avpicture_fill(&bgrPicture, buf, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight);
    sws_scale(rgbToYuvContext, (const uint8_t * const *)bgrPicture.data, bgrPicture.linesize, 0, m_streamHeight, picture->data, picture->linesize);
    avpicture_free(&bgrPicture);
//    free(buf);
}

但是avpicture_free(&bgrPicture)的召唤并没有完全释放内存。如果我评论了行avpicture_fill(&bgrPicture, buf, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight);和未评论的行
free(buf)
内存泄漏不会出现。 有什么问题?

1 个答案:

答案 0 :(得分:1)

uint8_t* buf = (uint8_t*)malloc(avpicture_get_size(AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight)); // 3 bytes per pixel
avpicture_alloc(&bgrPicture, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight);
avpicture_fill(&bgrPicture, buf, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight);

两次做同样的事情。 avpicture_alloc使用自分配的缓冲区(使用avpicture_free免费提供)分配和填充图片中的数据数组,avpicture_fill使用您控制的某个缓冲区填充数据结构你自己(在你的情况下:malloc /免费手动)。使用malloc + avpicture_fill +免费,或使用avpicture_alloc + avpicture_free。不要同时使用它们。