How to get the duration of video using cv2

前端 未结 5 1955
北恋
北恋 2021-01-03 19:24

I can only get the number of frames CAP_PROP_FRAME_COUNT using CV2.

However, I cannot find the parameter to get the duration of the video using cv2.

5条回答
  •  佛祖请我去吃肉
    2021-01-03 20:17

    cv2 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:

    >>> v=cv2.VideoCapture('sample.avi')
    >>> v.set(cv2.CAP_PROP_POS_AVI_RATIO,1)
    True
    >>> v.get(cv2.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(cv2.CAP_PROP_POS_FRAMES)
    5335.0
    >>>> v.get(cv2.CAP_PROP_FRAME_COUNT)
    5335.0
    
    >>> v.set(cv2.CAP_PROP_POS_AVI_RATIO,0)
    >>> v.get(cv2.CAP_PROP_POS_FRAMES)
    0.0        # the 1st frame is frame 0, not 1, so "5335" means after the last frame
    

提交回复
热议问题