ffmpeg-python
ffmpeg-python copied to clipboard
how to get the frames number of the whole video ?
hi,dear, Just wanna get the video frame number directly, Could you please help me ?
any advice or suggestion will be appreciated. thx
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
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"])