Bootstrap

避坑ffmpeg直接获取视频fps不准确

最近在做视频相关的任务,调试代码发现一个非常坑的点,就是直接用ffmpeg获取fps是有很大误差的,如下:

# GPT4o generated
import ffmpeg

probe = ffmpeg.probe(video_path, v="error", select_streams="v:0", show_entries="stream=nb_frames,r_frame_rate")
r_frame_rate = probe['streams'][0]['r_frame_rate']
num, denom = map(int, r_frame_rate.split('/'))
fps = num / denom

我的任务里,上述代码给的fps是30,但是用总帧数除以总时长是29.91,误差还是比较大的。正确做法就是自己做除法:

# GPT4o generated
def get_video_info(video_path):
    probe = ffmpeg.probe(video_path)
    video_streams = [
        stream for stream in probe["streams"] if stream["codec_type"] == "video"
    ]
    if not video_streams:
        raise ValueError("No video stream found")
    video_stream = video_streams[0]

    # 获取帧数
    frames = int(video_stream.get("nb_frames", 0))

    # 获取时长
    duration = float(video_stream.get("duration", probe["format"].get("duration", 0.0)))

    # 获取帧率
    # r_frame_rate = video_stream.get('r_frame_rate', '0/1')
    # num, den = map(int, r_frame_rate.split('/'))
    # fps = num / den # inaccurate
    fps = frames / duration

    return frames, duration, fps

真是成也GPT,败也GPT ==

;