将FFMPEG帧写入png / jpeg文件

问题描述 投票:1回答:1

我有AV_PIX_FMT_YUV420P AVFrame,并且我想将其写为PNG或JPEG文件,无论里面是什么格式(BGR,BGRA,RGB或RGBA)都没有关系。我尝试将其另存为AV_PIX_FMT_YUV420P,但我将3张图片合而为一,因此我需要先将其转换为RGB24。我通过:

        int destW = decCtx->width;
        int destH = decCtx->height;

        AVFrame * resFrame = av_frame_alloc();
        resFrame->linesize[0] = destW * 3;
        resFrame->data[0] = (uint8_t*)malloc(resFrame->linesize[0] * destH);

        SwsContext * ctx = sws_getContext(decCtx->width,
                                          decCtx->height,
                                          AV_PIX_FMT_YUV420P,
                                          decCtx->width,
                                          decCtx->height,
                                          AV_PIX_FMT_RGB24,
                                          SWS_FAST_BILINEAR, 0, 0, 0);
        sws_scale(ctx, frame->data, frame->linesize, 0,
                  decCtx->height, resFrame->data, resFrame->linesize);
        sws_freeContext(ctx);
        int64_t pts = frame->pts;

        resFrame->format = AV_PIX_FMT_RGB24;
        resFrame->pts = pts;

看起来我的转换帧正确,但是现在编码器向我返回了一个大小为86的数据包,因此我的图像实际上是空白或接近它。我通过以下方式进行编码:

    encCodec = avcodec_find_encoder(AV_CODEC_ID_PNG);

    if (!encCodec) {
        return false;
    }

    encCtx = avcodec_alloc_context3(encCodec);
    if (!encCtx) {
        return false;
    }

    encCtx->bit_rate = decCtx->bit_rate;
    encCtx->codec_type = AVMEDIA_TYPE_VIDEO;
    encCtx->thread_count = 1;
    encCtx->width = decCtx->width;
    encCtx->height = decCtx->height;

    int fps = fmtc->streams[iVideoStream]->r_frame_rate.num / fmtc->streams[iVideoStream]->r_frame_rate.den;
    encCtx->time_base = (AVRational){1, fps};
    encCtx->framerate = (AVRational){fps, 1};

    encCtx->gop_size = decCtx->gop_size;
    encCtx->max_b_frames = decCtx->max_b_frames;
    encCtx->pix_fmt = AV_PIX_FMT_RGB24;

    int ret = avcodec_parameters_from_context(fmtc->streams[iVideoStream]->codecpar, encCtx);
    if (ret < 0) {
        return false;
    }

    ret = avcodec_open2(encCtx, encCodec,  nullptr);
    if (ret < 0) {
        return false;
    }

    ret = avcodec_send_frame(encCtx, source);
    if (ret < 0) {
        return false;
    }

    av_packet_unref(pkt);
    av_init_packet(pkt);

    ret = avcodec_receive_packet(encCtx, pkt);
    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
        return false;
    else if (ret < 0) {
        return false;
    }

    if (ret >= 0)
    {
        FILE * outPng = fopen("./sample.png", "wb");
        fwrite(pkt->data, pkt->size, 1, outPng);
        fclose(outPng);
    }

将图像转换为RGB24或对其进行编码时,我做错了什么?

c++ c ffmpeg
1个回答
0
投票

@ parthlr在上面的讨论中提供了可接受的解决方案。但是,您也可以在他的介词下阅读我的评论。

© www.soinside.com 2019 - 2024. All rights reserved.