ffmpeg: 从视频里提取视频帧,并保存为图片文件

  1. 用ffmpeg处理视频时,有时需要从视频里提取某个时间的一帧视频数据,这时需要用到ffmpeg的一个关键函数,av_seek_frame。
    av_seek_frame原型如下:
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags){}
参数1: s操作上下文;
参数2: stream_index 流索引,当流索引为-1时,会选择一个默认流,时间戳会从以AV_TIME_BASE为单位
参数3: timestamp将要定位处的时间戳
参数4: flags功能flag 
AVSEEK_FLAG_BACKWARD  seek到请求的时间戳之前最近的关键帧
AVSEEK_FLAG_BYTE      基于字节位置的查找 
AVSEEK_FLAG_ANY       是可以seek到任意帧,注意不一定是关键帧,因此使用时可能会导致花屏    
AVSEEK_FLAG_FRAME     是基于帧数量快进 
  1. 示例很简单,工程代码如下:
    保存文件可以为调试代码用,函数如下
int saveAsJPEG(AVFrame* pFrame, int width, int height, int index)
{
    char out_file[256] = {0};
    sprintf_s(out_file, sizeof(out_file), "%s%d.jpg", "", index);
    AVFormatContext* pFormatCtx = avformat_alloc_context();
    pFormatCtx->oformat = av_guess_format("mjpeg", nullptr, nullptr);
    if( avio_open(&pFormatCtx->pb, out_file, AVIO_FLAG_READ_WRITE) < 0)
    {
        printf("Couldn't open output file.");
        return -1;
    }
    AVStream* pAVStream = avformat_new_stream(pFormatCtx, 0);
    if( pAVStream == nullptr )
    {
        return -1;
    }
    AVCodecContext* pCodecCtx = pAVStream->codec;
    pCodecCtx->codec_id   = pFormatCtx->oformat->video_codec;
    pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
    pCodecCtx->pix_fmt    = AV_PIX_FMT_YUVJ420P;
    pCodecCtx->width      = width;
    pCodecCtx->height     = height;
    pCodecCtx->time_base.num = 1;
    pCodecCtx->time_base.den = 25;
    //打印输出相关信息
    av_dump_format(pFormatCtx, 0, out_file, 1);
    //================================== 查找编码器 ==================================//
    AVCodec* pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
    if( !pCodec )
    {
        printf("Codec not found.");
        return -1;
    }
    if( avcodec_open2(pCodecCtx, pCodec, nullptr) < 0 )
    {
        printf("Could not open codec.");
        return -1;
    }
    //================================Write Header ===============================//
    avformat_write_header(pFormatCtx, nullptr);
    int y_size = pCodecCtx->width * pCodecCtx->height;
    AVPacket pkt;
    av_new_packet(&pkt, y_size * 3);

    //
    int got_picture = 0;
    int ret = avcodec_encode_video2(pCodecCtx, &pkt, pFrame, &got_picture);
    if( ret < 0 )
    {
        printf("Encode Error.\n");
        return -1;
    }
    if( got_picture == 1 )
    {
        pkt.stream_index = pAVStream->index;
        ret = av_write_frame(pFormatCtx, &pkt);
    }
    av_free_packet(&pkt);
    av_write_trailer(pFormatCtx);
    if( pAVStream )
    {
        avcodec_close(pAVStream->codec);
    }
    avio_close(pFormatCtx->pb);
    avformat_free_context(pFormatCtx);
    return 0;
}

main函数如下:

int main()
{
    //std::cout << "Hello World!" << std::endl;
    AVFormatContext *pFormatCtx = avformat_alloc_context();
    int res;
    res = avformat_open_input(&pFormatCtx, "test.mp4", nullptr, nullptr);
    if (res) {
        return 0;
    }
    avformat_find_stream_info(pFormatCtx, nullptr);
    int videoStream = -1;
    for(int i=0; i<pFormatCtx->nb_streams; i++) {
        if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoStream=i;
            break;
        }
    }
    if(videoStream == -1) {
        return 0;
    }
    AVCodecContext *pCodecCtxOrig = nullptr;
    // Get a pointer to the codec context for the video stream
    pCodecCtxOrig = pFormatCtx->streams[videoStream]->codec;
    AVCodec *pCodec = nullptr;
    // Find the decoder for the video stream
    pCodec = avcodec_find_decoder(pCodecCtxOrig->codec_id);
    if(pCodec == nullptr) {
        fprintf(stderr, "Unsupported codec!\n");
        return 0; // Codec not found
    }
    AVCodecContext *pCodecCtx = nullptr;
    // Copy context
    pCodecCtx = avcodec_alloc_context3(pCodec);
    if(avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) {
        fprintf(stderr, "Couldn't copy codec context");
        return 0; // Error copying codec context
    }
    // Open codec
    if(avcodec_open2(pCodecCtx, pCodec, nullptr)<0) {
        return 0;// Could not open codec
    }
    AVFrame *pFrameRGB = nullptr;
    pFrameRGB = av_frame_alloc();
    res = av_seek_frame(pFormatCtx, -1, 10 * AV_TIME_BASE, AVSEEK_FLAG_BACKWARD);//10(second)
    if (res<0) {
        return 0;
    }
    AVPacket packet;
    while(1) {
        av_read_frame(pFormatCtx, &packet);
        if(packet.stream_index == videoStream) {
            res = avcodec_send_packet(pCodecCtx, &packet);
            int gotPicture = avcodec_receive_frame(pCodecCtx, pFrameRGB); //gotPicture = 0 success, a frame was returned
            if(gotPicture == 0) {
                SwsContext* swsContext = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_RGB24,
                                          SWS_BICUBIC, nullptr, nullptr, nullptr);
                AVFrame* frameRGB = av_frame_alloc();
                avpicture_alloc((AVPicture*)frameRGB, AV_PIX_FMT_RGB24, pCodecCtx->width, pCodecCtx->height);
                sws_scale(swsContext, pFrameRGB->data, pFrameRGB->linesize, 0, pCodecCtx->height, frameRGB->data, frameRGB->linesize);
                saveAsJPEG(pFrameRGB, pCodecCtx->width, pCodecCtx->height, 10);
                avformat_close_input(&pFormatCtx);
                return 0;
            }
        }
    }
    return 0;
}

如果在Qt工程里使用,则可以很简单的用QImage来保存数据,具体讲SaveAsJPEG()这一行代码替换为:

QImage image(frameRGB->data[0], pCodecCtx->width, pCodecCtx->height, frameRGB->linesize[0], QImage::Format_RGB888);
image.save("10.jpg");

需要包含头文件

extern "C" {
#include 
#include 
#include 
#include 
#include "libswresample/swresample.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include 
}

你可能感兴趣的:(ffmpeg)