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(): exit(0)
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)) print(fps) print(frame_number) size = (w,h) print(size)
The basic information of this video is:
9 8567.0 (1280, 772)
Compute video duration with video frame count and fps
seconds = int(frame_number / fps) print(seconds) video_time = str(datetime.timedelta(seconds = seconds)) print(video_time)
The duration is:
951 0:15:51
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.
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: break 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