您的位置:首页 > 产品设计 > 产品经理

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

2015-07-13 11:36 686 查看
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,***MEDIA_TYPE_VIDEO,-1,-1,pCodec,0);
早期的版本没有这个函数,可以使用以下方式寻找:
for(i=0;i<pFormatCtx->nb_streams;i++)
{
if(pFormatCtx->streams[i]->codec->codec_type
== ***MEDIA_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((***Picture*)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(***Frame *pFrame,int
width, 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: