如何在ffmpeg中将cv :: Mat转换为AVFrame

时间:2016-04-21 06:20:23

标签: c++ opencv ffmpeg

  • 我有一个cv :: Mat image.Now我想把这个垫子转换为ffmpeg中的AVFrame。
  • 我有以下代码,

    void matToAVFrame(cv::Mat frame)
    {
        AVFrame *dst, *yuv422_final_frame;
          cv::Size frameSize = frame.size();
          AVCodec *encoder = avcodec_find_encoder(AV_CODEC_ID_H264);
          AVFormatContext* outContainer = avformat_alloc_context();
          AVStream *outStream = avformat_new_stream(outContainer, encoder);
          avcodec_get_context_defaults3(outStream->codec, encoder);
          dst = av_frame_alloc();
          outStream->codec->pix_fmt = AV_PIX_FMT_YUV420P;
          outStream->codec->width = frame.cols;
          outStream->codec->height = frame.rows;
          avpicture_fill((AVPicture*)dst, frame.data, AV_PIX_FMT_BGR24, outStream->codec->width, outStream->codec->height);
          dst->width = frameSize.width;
          dst->height = frameSize.height;
    
    //      av_image_alloc((uint8_t**)frame.data, dst->linesize,dst->width, dst->height,
    //            AV_PIX_FMT_BGR24, 32);
    
          yuv422_final_frame = av_frame_alloc();
          int yuv422_num_bytes = avpicture_get_size( AV_PIX_FMT_YUV420P,  dst->width, dst->height );
          uint8_t* final_frame2_buffer = (uint8_t *)av_malloc(yuv422_num_bytes*sizeof(uint8_t));
    
    
          yuv422_final_frame->width = frameSize.width;
          yuv422_final_frame->height = frameSize.height;
          avpicture_fill((AVPicture*)yuv422_final_frame, (uchar*)dst->data, AV_PIX_FMT_YUV420P,  dst->width, dst->height);
    
         SwsContext *final_sws_ctx = sws_getContext(dst->width , dst->height,
             AV_PIX_FMT_BGR24, dst->width, dst->height,
             AV_PIX_FMT_YUV420P, SWS_FAST_BILINEAR, 0, 0, 0);
    
    //     avpicture_fill((AVPicture*)dst, frame.data, AV_PIX_FMT_RGB24, dst->width, dst->height);
         sws_scale(final_sws_ctx, dst->data,
                 dst->linesize,
                   0, dst->height,
                   yuv422_final_frame->data,
                   yuv422_final_frame->linesize);
    
         Mat cvmImage = cv::Mat( yuv422_final_frame->height, yuv422_final_frame->width, CV_8UC3, yuv422_final_frame->data[2],
                 yuv422_final_frame->linesize[2]);
    
         imwrite("/home/radix/Desktop/OpenCV/cvmImage.png", cvmImage);
    }
    int main()
    {
        av_register_all();
        Mat frame = imread("path to image");
        matToAVFrame(frame);
    }
    

但它给了我一些不好的图像,在某些情况下它没有给出任何图像。 *所以请任何人告诉我我做错了什么。谢谢!!

  • 修改
  • 有时它会给我一些错误,例如[swscaler @ 0x1c9a6e0] bad src image pointers

  • 所以我从上面的代码中得到了这种类型的输出。

  • 输入图片:

InputImage

  • 输出图片

outputImage

0 个答案:

没有答案