7

You would think this would be such a simple operation, but there is nothing in the documentation about how to get the number of frames in a video clip. The only way I can think of is to use iter_frames() and just count the frames out one by one, but for some reason it takes almost a full second to iterate through 15 frames of video, even if i'm not performing any action on them.

Maurdekye
  • 3,597
  • 5
  • 26
  • 43
  • Do you need to do it using `moviepy` or will OpenCV work? – Abdul Fatir Jun 03 '16 at 20:13
  • 2
    I really don't want to import an entire package for a simple feature that should be, and is probably a part of this one already. – Maurdekye Jun 03 '16 at 20:18
  • 3
    In the [moviepy source code](https://github.com/Zulko/moviepy/blob/master/moviepy/Clip.py), you can see how `iter_frames()` is implemented - the line of interest is this: `for t in np.arange(0, self.duration, 1.0/fps):`. So, it's simply getting each frame at time `t`. Thus, you just have to derive the number of frames from the duration and framerate as they're doing. Seems kind of silly, though. Especially because there are variable frame rate videos out there. – Random Davis Jun 03 '16 at 20:19

4 Answers4

19

As it turns out moviepy doesn't save individual frame data, so it doesn't store the exact frame count. Here is the best way I found to get an approximation:

frames = int(clip.fps * clip.duration)
Maurdekye
  • 3,597
  • 5
  • 26
  • 43
16

Okay So I have recently stumbled upon the problem described above. It turns out that currently there is a way of getting the total frames in a clip by simply accessing clip.reader.nframes

So overall the code for accessing the number of frames would look like:

clip = VideoFileClip('video.mp4')
n_frames = clip.reader.nframes
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Kaszanas
  • 446
  • 4
  • 18
  • I meet a case that VideoFileClip('corruptedvideo.mp4') will stop at 67%. and then I use with VideoFileClip('corruptedvideo.mp4') as clip: and do some iteration but then it does not show the progress bar. I want to estimate the progress before whole VideoFileClip complete to show a custom made progress bar but I dont know how to get the number of frame before VideoFileClip finish. – Raii May 30 '22 at 23:53
  • 1
    --- 10 mins later --- oh , you saved me, after with VideoFileClip(file) as clip, and before a for loop, I can use clip.reader.nframes to get 212684. You saved me. – Raii May 31 '22 at 00:08
7

Pretty fast for me using this code:

clip = VideoFileClip('test.mp4')
n_frames = sum(1 for x in clip.iter_frames())
print n_frames
feqwix
  • 1,362
  • 14
  • 16
  • But what if I wanted to know which clip number is being display. I am trying to tag as they are being displayed. – kevbuntu Dec 28 '16 at 14:01
2

This might be a little faster.

clip = VideoFileClip('video.mp4')
num_frames = len(list(clip.iter_frames()))
print(num_frames)
Tong Niu
  • 91
  • 1
  • 4