How to know total number of Frame in a file with cv2 in python How to know total number of Frame in a file with cv2 in python python python

How to know total number of Frame in a file with cv2 in python


With a newer OpenCV version (I use 3.1.0) it works like this:

import cv2cap = cv2.VideoCapture("video.mp4")length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))print( length )

And similar for other video properties cv2.CAP_PROP_*


import cv2cap = cv2.VideoCapture(fn)if not cap.isOpened():     print "could not open :",fn    returnlength = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))width  = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH))height = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))fps    = cap.get(cv2.cv.CV_CAP_PROP_FPS)

see here for more info.

also, all of it with a grain of salt, not all those props are mandatory, some might not be available with your capture / video codec


Here is how it works with Python 3.6.5 (on Anaconda) and OpenCV 3.4.2.[Note]: You need to drop the "CV_" from the "CV_CAP_PROP_xx" for any property as given on the official OpenCV website.

import cv2cap = cv2.VideoCapture("video.mp4")property_id = int(cv2.CAP_PROP_FRAME_COUNT) length = int(cv2.VideoCapture.get(cap, property_id))print( length )