ffmpeg将视频每帧画面保存为PPM格式图片,使用最新的ffmpeg官网15-7-2日更新的版本

来源:互联网 发布:js 隐藏元素 编辑:程序博客网 时间:2024/05/10 23:28

1、注册所有文件格式和解码器

av_register_all();

2、读取输入文件头,设置null自动检测格式

avformat_open_input(&pFormatCtx,argv[1],NULL,NULL) ;

3、获取流信息

avformat_find_stream_info(pFormatCtx,NULL);

4、寻找第一条视频流

videoStream =av_find_best_stream(pFormatCtx,AVMEDIA_TYPE_VIDEO,-1,-1,pCodec,0);

早期的版本没有这个函数,可以使用以下方式寻找:

for(i=0;i<pFormatCtx->nb_streams;i++)

         {

                   if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)

                   {

                            videoStream =i;

                            break;

                   }

         }

5、寻找第一条视频流相应的解码器及寻找实际的解码器

pCodecCtx=pFormatCtx->streams[videoStream]->codec;

pCodec=avcodec_find_decoder(pCodecCtx->codec_id);

6、打开解码器

avcodec_open2(pCodecCtx,pCodec,NULL);

7、图像存储方面,设置原始图片及目标图片相关尺寸格式等

pFrame=av_frame_alloc();

pFrameRGB=av_frame_alloc();

numBytes=avpicture_get_size(PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height);

buffer=(uint8_t*)av_malloc(numBytes*sizeof(uint8_t));

avpicture_fill((AVPicture*)pFrameRGB,buffer,PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height);

sws_ctx=sws_getContext(pCodecCtx->width,pCodecCtx->height,

                   pCodecCtx->pix_fmt,pCodecCtx->width,pCodecCtx->height,

                   PIX_FMT_RGB24,SWS_BILINEAR,NULL,NULL,NULL);

8、视频图像读取

while(av_read_frame(pFormatCtx,&packet)>=0)

         {

                   if(packet.stream_index==videoStream)

                   {

                            avcodec_decode_video2(pCodecCtx,pFrame, &frameFinished,&packet);

                            if(frameFinished)

                            {

                                     sws_scale(sws_ctx,(uint8_tconst *const *)pFrame->data,

                                               pFrame->linesize,0,pCodecCtx->height,

                                               pFrameRGB->data,pFrameRGB->linesize);

                                     if(++i<=100)

                                     {

                                               SavePPM(pFrameRGB,pCodecCtx->width,pCodecCtx->height,i);

                                     }

                            }

                            av_free_packet(&packet);

                   }

         }

9、PPM图像存储函数

void SavePPM(AVFrame *pFrame,intwidth, int height,intiFrame)

{

         FILE *pFile;

         char szFilename[32];

         int y;

         sprintf(szFilename,"frame%d.ppm",iFrame);

         pFile=fopen(szFilename,"wb");

         if(pFile==NULL)

                   return;

         fprintf(pFile,"P6\n%d%d\n255\n",width,height);

         for(y=0;y<height;y++)

                   fwrite(pFrame->data[0]+y*pFrame->linesize[0],1,width*3,pFile);

         fclose(pFile);

}


完整程序下载http://download.csdn.net/detail/shusexiaoniao/8894245

0 0
原创粉丝点击