Get video duration using Python - OpenCV
Determining a video’s total duration is a key step in video processing. With OpenCV in Python, we can retrieve the total frame count and frame rate (FPS) to calculate the duration and use the datetime module to present it in a human-readable format (hours, minutes, seconds).
Prerequisites:
Installation
You can install OpenCV using pip:
pip install opencv-python
Approach
To get the duration of a video, the following steps has to be followed:
- Import Modules : Use cv2 for video processing and datetime.timedelta for formatting.
- Load Video : Create a cv2.VideoCapture("path/to/video.mp4") object.
- Get Properties : Extract total frames (CAP_PROP_FRAME_COUNT) and FPS (CAP_PROP_FPS).
- Calculate Duration : Duration = total frames ÷ FPS, then format using datetime.timedelta.
Implementation
import cv2
import datetime
video = cv2.VideoCapture('C:/Users/Asus/Documents/videoDuration.mp4')
frames = video.get(cv2.CAP_PROP_FRAME_COUNT)
fps = video.get(cv2.CAP_PROP_FPS)
seconds = round(frames / fps)
video_time = datetime.timedelta(seconds=seconds)
print(f"Frames: {frames}")
print(f"FPS: {fps}")
print(f"Duration in seconds: {seconds}")
print(f"Video time (HH:MM:SS): {video_time}")
Output:
Frames: 840.0
FPS: 30.0
Duration in seconds: 28
Video time (HH:MM:SS): 0:00:28
Explanation:
- cv2.VideoCapture('path') creates a capture object for the video file.
- video.get(cv2.CAP_PROP_FRAME_COUNT) retrieves the total number of frames.
- video.get(cv2.CAP_PROP_FPS) fetches the frame rate (frames per second).
- round(frames / fps) computes the total duration in seconds.
- datetime.timedelta(seconds=seconds) converts seconds into HH:MM:SS format.