close

How to get the duration of video using cv2

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get the duration of video using cv2 in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get the duration of video using cv2?

  1. How to get the duration of video using cv2?

    cv2 is not designed to explore video metadata, so VideoCapture doesn't have API to retrieve it directly.

  2. get the duration of video using cv2

    cv2 is not designed to explore video metadata, so VideoCapture doesn't have API to retrieve it directly.

Method 1

In OpenCV 3, the solution is:

import cv2

cap = cv2.VideoCapture("./video.mp4")
fps = cap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frame_count/fps

print('fps = ' + str(fps))
print('number of frames = ' + str(frame_count))
print('duration (S) = ' + str(duration))
minutes = int(duration/60)
seconds = duration%60
print('duration (M:S) = ' + str(minutes) + ':' + str(seconds))

cap.release()

Method 2

cv2 is not designed to explore video metadata, so VideoCapture doesn’t have API to retrieve it directly.

You can instead “measure” the length of the stream: seek to the end, then get the timestamp:

>>> v=cv2.VideoCapture('sample.avi')
>>> v.set(cv2.CAP_PROP_POS_AVI_RATIO,1)
True
>>> v.get(cv2.CAP_PROP_POS_MSEC)
213400.0

Checking shows that this sets the point after the last frame (not before it), so the timestamp is indeed the exact total length of the stream:

>>> v.get(cv2.CAP_PROP_POS_FRAMES)
5335.0
>>>> v.get(cv2.CAP_PROP_FRAME_COUNT)
5335.0

>>> v.set(cv2.CAP_PROP_POS_AVI_RATIO,0)
>>> v.get(cv2.CAP_PROP_POS_FRAMES)
0.0        # the 1st frame is frame 0, not 1, so "5335" means after the last frame

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read