OpenCV/Python: read specific frame using VideoCapture

后端 未结 5 983
温柔的废话
温柔的废话 2021-01-30 16:34

Is there a way to get a specific frame using VideoCapture() method?

My current code is:

import numpy as np
import cv2

cap = cv2.VideoCaptur         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 16:56

    Set a specific frame

    From the documentation of the VideoCaptureProperties (docs) is possible to see that the way to set the frame in the VideoCapture is:

    frame = 30
    cap.set(cv2.CAP_PROP_POS_FRAMES, frame)
    

    Notice that you don't have to pass to the function frame - 1 because, as the documentation says, the flag CAP_PROP_POS_FRAMES rapresent the "0-based index of the frame to be decoded/captured next".

    Concluding a full example where i want to read a frame at each second is:

    import cv2
    
    cap = cv2.VideoCapture('video.avi')
    
    # Get the frames per second
    fps = cap.get(cv2.CAP_PROP_FPS) 
    
    # Get the total numer of frames in the video.
    frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    
    frame_number = 0
    cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number) # optional
    success, image = cap.read()
    
    while success and frame_number <= frame_count:
    
        # do stuff
    
        frame_number += fps
        cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
        success, image = cap.read()
    

    Set a specific time

    In the documentation linked above is possible to see that the way to set a specific time in the VideoCapture is:

    milliseconds = 1000
    cap.set(cv2.CAP_PROP_POS_MSEC, milliseconds)
    

    And like before a full example that read a frame each second che be achieved in this way:

    import cv2
    
    cap = cv2.VideoCapture('video.avi')
    
    # Get the frames per second
    fps = cap.get(cv2.CAP_PROP_FPS) 
    
    # Get the total numer of frames in the video.
    frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    
    # Calculate the duration of the video in seconds
    duration = frame_count / fps
    
    second = 0
    cap.set(cv2.CAP_PROP_POS_MSEC, second * 1000) # optional
    success, image = cap.read()
    
    while success and second <= duration:
    
        # do stuff
    
        second += 1
        cap.set(cv2.CAP_PROP_POS_MSEC, second * 1000)
        success, image = cap.read()
    

提交回复
热议问题