Reputation: 784
I can only get the number of frames CAP_PROP_FRAME_COUNT
using OpenCV.
However, I cannot find the parameter to get the duration of the video using OpenCV.
How to do that?
Thank you very much.
Upvotes: 38
Views: 78146
Reputation: 5412
First calculate frame per second like this
import cv2 as cv
# cap = cv.VideoCapture...
fps = cap.get(cv.CAP_PROP_FPS)
Then duration can be calculated as (number of frames) / (frames per second)
duration = float(num_frames) / float(fps) # in seconds
Upvotes: 5
Reputation: 984
I noticed a weird phenomenon that many video DO NOT HAVE as much frames as the vid.get(cv.CAP_PROP_FRAME_COUNT)
gets.
I suppose that the video duration should be the divided value of TOTAL FRAMES by FPS, but it always mismatch. The video duration would be longer than we calculated. Considering what FFMPEG does, the original video might has some empty frames.
Hope this help.
Upvotes: 1
Reputation: 41
In my personal experience I've been using the OpenCV method. Try this code:
import cv2 as cv
def get_dur(filename):
video = cv.VideoCapture(filename)
fps = video.get(cv.CAP_PROP_FPS)
frame_count = video.get(cv.CAP_PROP_FRAME_COUNT)
seconds = frame_count / fps
minutes = int(seconds / 60)
rem_sec = int(seconds % 60)
return f"{minutes}:{rem_sec}"
print(get_dur("dafuck.mp4"))
Upvotes: 2
Reputation: 562
Capture the video and output the duration is seconds
import cv2 as cv
vidcapture = cv.VideoCapture('myvideo.mp4')
fps = vidcapture.get(cv.CAP_PROP_FPS)
totalNoFrames = vidcapture.get(cv.CAP_PROP_FRAME_COUNT)
durationInSeconds = totalNoFrames / fps
print("durationInSeconds:", durationInSeconds, "s")
Upvotes: 8
Reputation: 35986
OpenCV 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:
>>> import cv2 as cv
>>> v = cv.VideoCapture('sample.avi')
>>> v.set(cv.CAP_PROP_POS_AVI_RATIO, 1)
True
>>> v.get(cv.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(cv.CAP_PROP_POS_FRAMES)
5335.0
>>>> v.get(cv.CAP_PROP_FRAME_COUNT)
5335.0
>>> v.set(cv.CAP_PROP_POS_AVI_RATIO, 0)
>>> v.get(cv.CAP_PROP_POS_FRAMES)
0.0 # the 1st frame is frame 0, not 1, so "5335" means after the last frame
Upvotes: 38
Reputation: 3314
In OpenCV 3, the solution is:
import cv2 as cv
cap = cv.VideoCapture("./video.mp4")
fps = cap.get(cv.CAP_PROP_FPS) # OpenCV v2.x used "CV_CAP_PROP_FPS"
frame_count = int(cap.get(cv.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()
Upvotes: 64