乐闻世界logo
搜索文章和话题

How to get the duration of video using OpenCV

1个答案

1

When using OpenCV to process videos, it is typically necessary to first load the video and then retrieve its properties, such as frame count and frame rate, to calculate the total duration. Below are the detailed steps and example code demonstrating how to obtain the video duration using Python and OpenCV.

Steps:

  1. Import necessary libraries: First, import the cv2 library.

  2. Load the video: Use the cv2.VideoCapture() function to load the video.

  3. Retrieve video frame rate and frame count: - Use cap.get(cv2.CAP_PROP_FPS) to obtain the frame rate (frames per second). - Use cap.get(cv2.CAP_PROP_FRAME_COUNT) to get the total frame count.

  4. Calculate video duration: - Total duration (seconds) = total frame count / frame rate.

  5. Output the result.

Example Code:

python
import cv2 # Load video video_path = 'video.mp4' cap = cv2.VideoCapture(video_path) if not cap.isOpened(): print("Error: Could not open video.") else: # Get frame rate fps = cap.get(cv2.CAP_PROP_FPS) # Get total frame count frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) # Calculate video duration duration = frame_count / fps print(f"Video frame rate: {fps} FPS") print(f"Total frame count: {frame_count}") print(f"Video duration: {duration} seconds") # Release video resources cap.release()

Explanation:

In this example, we first load a video file using cv2.VideoCapture(). Then, we use the cap.get() method to retrieve the frame rate and total frame count. With these two values, we can simply calculate the total duration in seconds by dividing the total frame count by the frame rate.

This method is very useful for video processing or analysis, such as in video editing or video surveillance. Understanding the video duration can help in performing more precise video analysis and processing.

2024年6月29日 12:07 回复

你的答案