4

I am trying to count total number of Frames in my video file ('foo.h264').

>>> import numpy as nm
>>> import cv2
>>> cap = cv2.VideoCapture('foo.h264')
>>> cap.get(CV_CAP_PROP_FRAME_COUNT)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'CV_CAP_PROP_FRAME_COUNT' is not defined
>>> cap.get(5)
25.0
>>> cap.get(7)
-192153584101141.0

So I think get(5) is giving frame rate and get(7) gives total number of frames. Obviously get(7) is incorrect in the above case. So to verify I tried to find these values in an .avi file.

>>> cap = cv2.VideoCapture('foo.avi')
>>> cap.get(5)
29.97002997002997
>>> cap.get(7)
256379.0

I can calculate the total number of frames by multiplying FPS by duration of the video, but I'm not sure if the FPS given for .h264 is right or not. Why does it give negative number of total frames? Is this a bug?
P.S: I recorded this video file (.h264) using raspberry pi camera.

Coderaemon
  • 3,619
  • 6
  • 27
  • 50

3 Answers3

5

Another solution is using imageio, which works for some videos.

import imageio
filename="person15_walking_d1_uncomp.avi"
vid = imageio.get_reader(filename,  'ffmpeg')
# number of frames in video
num_frames=vid._meta['nframes']
1

As it turns out OpenCV does not support h.264 format (Link). However, the documentation on Video Capture at Python OpenCV documentation mentions an integer argument for the get command. So, you're right on that count on using 5 and 7 instead of 'CV_CAP_PROP_FRAME_COUNT'. You could try changing the capture format on the raspberry pi to avi.

Community
  • 1
  • 1
optimist
  • 1,018
  • 13
  • 26
  • Yes .h264 is just NAL stream and doesn't contain the information about the framerate. Now when I wrap the video in a container like .mp4 I am able to calculate the total number of frames. But the framerate of the new video is 25fps which is wrong. But from total number of frames and duration I can calculate the real framerate. – Coderaemon Feb 13 '15 at 12:11
1

This worked for me (no opencv used):

import imageio

file="video.mp4" #the path of the video
vid=imageio.get_reader(file,  'ffmpeg')
totalframes = vid.count_frames()

print(totalframes)

It will return the total frames :)

Akascape
  • 219
  • 2
  • 11