ffmepg 找关键帧_yuan1988219_新浪博客

本文介绍了一个使用FFmpeg库实现的C++程序,该程序能够从指定路径的视频文件中提取关键帧并记录其编号。首先打开视频文件并获取视频流信息,然后查找合适的解码器并初始化解码上下文,最后遍历所有数据包以找到关键帧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

void GetKeyFrame(const char* first_path)
{
int nFrameCount = 0;
m_vecKeyFrame.clear();
AVFormatContext *pFormatCtx = avformat_alloc_context();;
if(avformat_open_input(&pFormatCtx, first_path, NULL,NULL)!=0)   
{
return;
}
  
if(avformat_find_stream_info(pFormatCtx,NULL)<0)   
return; 
   
int videoStream=-1;   
for(int i=0; inb_streams; i++)   
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)   
{   
videoStream=i;   
break;   
}   
if(videoStream==-1)   
printf("error!\n");// Didn't find a video stream   
  
// 得到视频流编码上下文的指针   
AVCodecContext *pCodecCtx=pFormatCtx->streams[videoStream]->codec;  

AVCodec *pCodec;     
//  寻找视频流的解码器   
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);   
if(pCodec==NULL)   
printf("error!\n");// 找不到解码器    
// 打开解码器  avcodec_open2 
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)   
printf("error!\n"); // 打不开解码器  

AVPacket packet={0};
AVFrame *frame = av_frame_alloc();
int got_picture=0;
while(av_read_frame(pFormatCtx,&packet) >= 0)
{
if (packet.stream_index == videoStream)
{
nFrameCount ++;
avcodec_decode_video2(pCodecCtx,frame,&got_picture,&packet);
if (got_picture)
{
if (frame->key_frame == 1)
{
m_vecKeyFrame.push_back(nFrameCount);
}
}
}
av_free_packet(&packet);   

}
av_free(frame);  
avcodec_close(pCodecCtx); 
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值