A Beginner Guide to Python Get Video Duration with OpenCV – Python Tutorial

By | September 11, 2019

OpenCV is a nice python library for us to process video and image, which is widely used in deep learning. In this tutorial, we will introduce how to get video duration with this library. You can learn how to do.

Install OpenCV

pip install opencv-python

Import libraries

import cv2
import datetime

Create a VideoCapture object with video file

cap = cv2.VideoCapture(video)
if not cap.isOpened():

Get video fps, frame count, width and height

frame_number = cap.get(cv2.CAP_PROP_FRAME_COUNT)
h  = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
w  = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
fps = int(cap.get(cv2.CAP_PROP_FPS))
size = (w,h)

The basic information of this video is:

(1280, 772)

Compute video duration with video frame count and fps

seconds = int(frame_number / fps)

video_time = str(datetime.timedelta(seconds = seconds))

The duration is:


Compare the real duration of this video, we find this duration value is wrong.

The real duration is: 14: 16, however, the result of computing is 15: 51.

python video duration example

Check the basic information of video

Check the basic information got by opencv, we find:

the width, height and fps is right, but the frame count is wrong.

Video frame count is got by cap.get(cv2.CAP_PROP_FRAME_COUNT), which reads the head information of this video file, which may can not refect the real frame count of video.

Compute the video frame count frame by frame

total_frame = 0
while True:
    ret, frame = cap.read()
    if ret is False:
    total_frame += 1
print("total_frame = " + str(total_frame))

The total frame also is: 8567, which is wrong. It means there are some wrong frames in this vidoe, which cause us to compute wrong video duration.

How to get video correct duration?

We can use movepy library, you can read this tutoral.

Best Practice to Python Get Video Duration with MoviePy – Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *