使用 LIBAVCODEC 将原始图像缓冲区转换为 JPEG

标签 c encoding compression ffmpeg libavcodec

我有一个从相机捕获的原始图像缓冲区(在内存中),我想将其转换为 JPEG(以减小尺寸)。问题是将这些图像保存为 .pgm 格式会导致巨大的文件大小,由于内存限制和保存这种大小的大文件所涉及的延迟(我正在处理的应用程序中的限制),我无法承受.

我想知道如何使用 LIBAVCODEC 将图像缓冲区压缩/编码为 .jpg 格式?我的图像捕获代码在 C 中。

最佳答案

此代码适用于 YUV 原始图像。我在尝试对 RGB 原始图像进行编码时遇到段错误。但您可以使用 swscale() 将 RGB 转换为 YUV

int main()
{
    int ret;
    AVFrame *frame;
    AVPacket pkt;

    av_register_all();

    AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG);
    if (!codec)
    {
        printf("Codec not found\n");
        exit(1);
    }

    AVCodecContext* c = avcodec_alloc_context3(codec);
    if (!c)
    {
        printf("Could not allocate video codec context\n");
        exit(1);
    }

    c->bit_rate = 400000;
    c->width = 320;
    c->height = 200;
    c->time_base= (AVRational){1,25};
    c->pix_fmt = AV_PIX_FMT_YUVJ420P;

    if (avcodec_open2(c, codec, NULL) < 0)
    {
        printf("Could not open codec\n");
        exit(1);
    }

    frame = avcodec_alloc_frame();
    if (!frame)
    {
        printf("Could not allocate video frame\n");
        exit(1);
    }
    frame->format = c->pix_fmt;
    frame->width  = c->width;
    frame->height = c->height;

    ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height, c->pix_fmt, 32);
    if (ret < 0)
    {
        printf("Could not allocate raw picture buffer\n");
        exit(1);
    }

    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;

    /* prepare a dummy image */
    /* Y */
    for(int y=0;y<c->height;y++) {
        for(int x=0;x<c->width;x++) {
            frame->data[0][y * frame->linesize[0] + x] = x + y;
        }
    }

    /* Cb and Cr */
    for(int y=0;y<c->height/2;y++) {
        for(int x=0;x<c->width/2;x++) {
            frame->data[1][y * frame->linesize[1] + x] = 128 + y;
            frame->data[2][y * frame->linesize[2] + x] = 64 + x;
        }
    }


    frame->pts = 1;

    int got_output = 0;
    ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
    if (ret < 0)
    {
        printf("Error encoding frame\n");
        exit(1);
    }

    if (got_output)
    {
        printf("got frame\n");
        FILE* f = fopen("x.jpg", "wb");
        fwrite(pkt.data, 1, pkt.size, f);
        av_free_packet(&pkt);
    }

    avcodec_close(c);
    av_free(c);
    av_freep(&frame->data[0]);
    avcodec_free_frame(&frame);
    printf("\n");

    return 0;
}

关于使用 LIBAVCODEC 将原始图像缓冲区转换为 JPEG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9364693/

相关文章:

c - 拆分文件中的字符串并将值保存在数组中会打印错误的输出

c - 使用 Cygwin 的 MPICH2 编译问题

c - 杀死 SDL 2 线程 (C)

perl - 这个 Perl 字符串是用什么编码的?

compression - 不推荐使用 GNU GZIP 环境变量,如何通过 tar 控制 ZLIB 压缩?

c - else if 语句错误,我如何转到嵌套 for 循环中的下一个语句

python - 奇怪的网站编码。是否有可能使用 python 获取它?

c# - 使用元音字符读取 Xml 文件

c# - GZipStream.Write 方法

compression - pdftk 压缩选项