saving an image sequence from video using opencv2

前端 未结 3 999
青春惊慌失措
青春惊慌失措 2021-01-15 16:48

Newbie question and yes I have spent a lot of time sifting through similar questions and Answers with no luck.

What I am trying to do is save frames from a video fil

3条回答
  •  一整个雨季
    2021-01-15 17:33

    This is my way to do in Python3.0. Have to have CV2 3+ version for it to work. This function saves images with frequency given.

    import cv2
    import os
    print(cv2.__version__)
    
    # Function to extract frames 
    def FrameCapture(path,frame_freq): 
    
        # Path to video file 
        video = cv2.VideoCapture(path) 
        success, image = video.read()
    
        # Number of frames in video
        fps = int(video.get(cv2.CAP_PROP_FPS))
        length = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
    
        print('FPS:', fps)
        print('Extracting every {} frames'.format(frame_freq))
        print('Total Frames:', length)
        print('Number of Frames Saved:', (length // frame_freq) + 1)
    
        # Directory for saved frames
        try:
            frame_dir = path.split('.')[0]
            os.mkdir(frame_dir)
        except FileExistsError:
            print('Directory ({}) already exists'.format(frame_dir))
    
        # Used as counter variable 
        count = 0
    
        # checks whether frames were extracted 
        success = 1
    
        # vidObj object calls read 
        # function extract frames 
    
        while count < length :
            video.set(cv2.CAP_PROP_POS_FRAMES , count)
            success, image = video.read()
            # Saves the frames with frame-count 
            cv2.imwrite(frame_dir + "/frame%d.jpg" % count, image)
            count = count + frame_freq
    

提交回复
热议问题