我有一个视频,每秒23.98帧,这可以从命令行中的Quicktime和ffmpeg中看到。OpenCV错误地认为它有23帧/秒。我感兴趣的是找到一种从ffmpeg中找到视频fps的编程方法。
使用FFMPEG-C++获取视频每秒帧数(fps)值
/* find first stream */
for(int i=0; i<pAVFormatContext->nb_streams ;i++ )
{
if( pAVFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO )
/* if video stream found then get the index */
{
VideoStreamIndx = i;
break;
}
}
/* if video stream not availabe */
if((VideoStreamIndx) == -1)
{
std::cout<<"video streams not found"<<std::endl;
return -1;
}
/* get video fps */
double videoFPS = av_q2d(ptrAVFormatContext->streams[VideoStreamIndx]->r_frame_rate);
std::cout<<"fps :"<<videoFPS<<std::endl;
快速查看OpenCV源代码显示以下内容:
double CvCapture_FFMPEG::get_fps()
{
double fps = r2d(ic->streams[video_stream]->r_frame_rate);
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
if (fps < eps_zero)
{
fps = r2d(ic->streams[video_stream]->avg_frame_rate);
}
#endif
if (fps < eps_zero)
{
fps = 1.0 / r2d(ic->streams[video_stream]->codec->time_base);
}
return fps;
}
所以看起来很对。也许通过这个部分运行调试会话来验证此时的值?AVStream的avg_frame_rate
是AVRational
,因此它应该能够保持精确的值。也许,如果您的代码由于较旧的ffmpeg版本而使用第二个if块,则time_base
设置不正确?
编辑
如果您进行调试,请查看r_frame_rate
和avg_frame_rate
是否不同,因为至少根据这一点,它们往往会根据所使用的编解码器而不同。由于您没有提到视频格式,因此很难猜测,但似乎至少对于H264,您应该直接使用avg_ frame_rate
,并且从r_frame_rate
获得的值可能会把事情搞砸。
2013年03月29日发布的libavformat
版本55.1.100
中增加了av_guess_frame_rate()
。
/**
* Guess the frame rate, based on both the container and codec information.
*
* @param ctx the format context which the stream is part of
* @param stream the stream which the frame is part of
* @param frame the frame for which the frame rate should be determined, may be NULL
* @return the guessed (valid) frame rate, 0/1 if no idea
*/
AVRational av_guess_frame_rate(AVFormatContext *ctx, AVStream *stream, AVFrame *frame);