Get video duration using OpenCV Python

OpenCV is an Open Source Computer Vision Library in Python that provides numerous functions for image and video processing operations. The library uses NumPy to represent video frames and images as ndarray objects.

In this article, we will explore different methods to get video duration using OpenCV Python by leveraging the VideoCapture.get() method with specific property flags.

Understanding VideoCapture Properties

The OpenCV VideoCapture.get() method retrieves specified properties of a video by passing property identifier flags ?

Syntax

VideoCapture.get(propId)

Key property identifiers for duration calculation ?

  • CAP_PROP_FRAME_COUNT: Total number of frames in the video file
  • CAP_PROP_FPS: Frame rate (frames per second)
  • CAP_PROP_POS_MSEC: Current position in milliseconds
  • CAP_PROP_FRAME_WIDTH: Width of video frames
  • CAP_PROP_FRAME_HEIGHT: Height of video frames

Duration Calculation Approach

To calculate video duration, we use this formula: Duration = Total Frames รท FPS

The process involves ?

  • Load video using cv2.VideoCapture()
  • Get FPS using cv2.CAP_PROP_FPS
  • Get total frames using cv2.CAP_PROP_FRAME_COUNT
  • Calculate duration by dividing total frames by FPS
  • Format the result as needed

Method 1: Duration in Seconds

Calculate the basic video duration in seconds ?

import cv2

# Create a sample video file path (replace with your video)
video_path = 'sample_video.mp4'

# Create video capture object
cap = cv2.VideoCapture(video_path)

# Get video properties
fps = cap.get(cv2.CAP_PROP_FPS)
total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)

# Calculate duration in seconds
duration_seconds = total_frames / fps

print(f"Video Duration: {duration_seconds:.2f} seconds")
print(f"Total Frames: {total_frames}")
print(f"FPS: {fps}")

# Release the video capture object
cap.release()
Video Duration: 65.00 seconds
Total Frames: 1625.0
FPS: 25.0

Method 2: Duration in Minutes and Seconds

Format duration as minutes and seconds for better readability ?

import cv2

def get_video_duration(filename):
    video = cv2.VideoCapture(filename)
    fps = video.get(cv2.CAP_PROP_FPS)
    frame_count = video.get(cv2.CAP_PROP_FRAME_COUNT)
    
    # Calculate total seconds
    total_seconds = frame_count / fps
    
    # Convert to minutes and seconds
    minutes = int(total_seconds // 60)
    seconds = int(total_seconds % 60)
    
    video.release()
    return f"{minutes}:{seconds:02d}"

# Example usage
video_path = 'sample_video.mp4'
duration = get_video_duration(video_path)
print(f"Video Duration: {duration}")
Video Duration: 1:05

Method 3: Using datetime Module

Use Python's datetime module for precise time formatting ?

import cv2
import datetime

def get_formatted_duration(filename):
    video = cv2.VideoCapture(filename)
    fps = video.get(cv2.CAP_PROP_FPS)
    frame_count = video.get(cv2.CAP_PROP_FRAME_COUNT)
    
    # Calculate duration in seconds
    total_seconds = frame_count / fps
    
    # Create timedelta object
    video_duration = datetime.timedelta(seconds=total_seconds)
    
    video.release()
    return str(video_duration)

# Example usage
video_path = 'sample_video.mp4'
formatted_duration = get_formatted_duration(video_path)
print(f"Video Duration: {formatted_duration}")
Video Duration: 0:01:05

Complete Example with Error Handling

A robust function that handles potential errors ?

import cv2
import datetime

def get_video_info(video_path):
    """Get comprehensive video duration information"""
    try:
        cap = cv2.VideoCapture(video_path)
        
        # Check if video opened successfully
        if not cap.isOpened():
            return "Error: Could not open video file"
        
        # Get video properties
        fps = cap.get(cv2.CAP_PROP_FPS)
        frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
        width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
        height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
        
        # Calculate duration
        duration_seconds = frame_count / fps if fps > 0 else 0
        duration_formatted = str(datetime.timedelta(seconds=duration_seconds))
        
        cap.release()
        
        return {
            'duration_seconds': round(duration_seconds, 2),
            'duration_formatted': duration_formatted,
            'total_frames': frame_count,
            'fps': fps,
            'resolution': f"{int(width)}x{int(height)}"
        }
        
    except Exception as e:
        return f"Error: {str(e)}"

# Example usage
video_info = get_video_info('sample_video.mp4')
print("Video Information:")
for key, value in video_info.items():
    print(f"{key}: {value}")
Video Information:
duration_seconds: 65.0
duration_formatted: 0:01:05
total_frames: 1625.0
fps: 25.0
resolution: 1920x1080

Conclusion

OpenCV provides a straightforward way to calculate video duration using frame count and FPS properties. The datetime.timedelta approach offers the most flexible formatting options for displaying duration in a user-friendly format.

---
Updated on: 2026-03-27T06:55:57+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements