ffmpeg-python icon indicating copy to clipboard operation
ffmpeg-python copied to clipboard

how to get the frames number of the whole video ?

Open ucasiggcas opened this issue 5 years ago • 2 comments

hi,dear, Just wanna get the video frame number directly, Could you please help me ?

any advice or suggestion will be appreciated. thx

ucasiggcas avatar Jan 08 '20 02:01 ucasiggcas

Hi,

try:

probe = ffmpeg.probe('file.mp4')
video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)

the dictionary has all the information about the video stream.

Bid

bidspells avatar Mar 10 '20 13:03 bidspells

For me, the following code seems to work reliably, based on the suggestion of @bidspells above:

def num_frames(video_path: str) -> int:
    video_streams = [s for s in ffmpeg.probe(video_path)["streams"] if s["codec_type"] == "video"]
    assert len(video_streams) == 1
    return int(video_streams[0]["nb_frames"])

The corresponding value is directly read from the video header and might (rarely) actually be wrong.

One can also force probe() to actually count the frames, but this requires decoding the complete video (compare this discussion on Stack Overflow):

def num_frames_exact(video_path: str) -> int:
    # `count_frames=None` corresponds to the `ffprobe` command line argument `-count_frames`
    video_streams = [s for s in ffmpeg.probe(video_path, count_frames=None)["streams"] if s["codec_type"] == "video"]
    assert len(video_streams) == 1
    # "nb_read_frames" will only be created with `count_frames=None`
    return int(video_streams[0]["nb_read_frames"])

spezold avatar May 14 '24 15:05 spezold