Python Frames Video Save Pictures

Keywords: Python OpenCV

Original Address

Go directly to the program, comment instructions

import cv2
import os
from application.processbar.progressbar import bar3 # My own progress bar module, see the reference

# Full path to incoming video, automatically generates a folder with the same name under the video path, and saves the pictures inside
def video2img1(pathv):
    file_name = pathv.split(os.sep)[-1].split('.')[0]  # The path delimiter for the current system of os.sep can also be used with'\\'
    out_floder = pathv.split('.')[0]    # Path full path removes the last suffix and generates a folder with the same name as the video
    # Create a file to store pictures
    if not os.path.exists(out_floder):
        os.makedirs(out_floder, exist_ok=True)
    vc = cv2.VideoCapture(pathv)  # Read Video File
    n_frame = int(vc.get(cv2.CAP_PROP_FRAME_COUNT))     # Total Video Frames

    c = 0   # Frame Index
    rval = vc.isOpened()    # Detects whether VC is successfully initialized, returns True if successful, and opens via vc.open() for initialization

    while rval:  # If initialization is successful, video frames can be read in a loop
        c = c + 1
        rval, frame = vc.read() # Returns two values, first returns a bool value, True if the frame is read correctly, otherwise False. You can check the end of the video by checking the return value. Then returns a value, which is a three-dimensional matrix for each frame of the image
        pic_name = file_name + '_' + str(c).zfill(4) + '.jpg'   # Stitching Picture Name
        if rval:
            save_path = os.path.join(out_floder, pic_name)
            cv2.imwrite(save_path, frame)  # Store as an image, save a folder name _number (the file number). jpg
            bar3(c, n_frame, 40, 'Processing progress:')	# Call my own progressor function, see the reference
            cv2.waitKey(1)
        else:
            break
    vc.release()
    print('\nsave_success')

if __name__ == '__main__':
    pv = r'E:\Test\historyimg.flv'

    video2img1(pv)

My program has a problem with the progress bar. The total number of frames obtained by the program is slightly larger than the total number of pictures actually saved, which prevents the progress bar from reaching 100%. As to what is the reason, I did not go into it.

  • Lose one step

If you want to make bulk changes to all the video files in a file, you can modify the u main_u section

if __name__ == '__main__':
    path = r'E:\Test'	# Folder Path
    filelist = os.listdir(path)		# Get all the files/folders under the folder (current layer, no recursion)
    for fi in filelist:
        if fi.endswith('.mp4'):		# Determine whether video files, if they are all video files, can not do this step
            video2img1(fi)
  • Extract Keyframe

The above method extracts all the frames, which is actually not very good in most cases. In my example, I extract all the frames of a video with a duration of about 1 minute, a frame rate of 25fps (25 frames per second) and a resolution of 1920x1080 for 1400 + pictures, with a total space of 600+M.For frame speed, up to 120 frames (Baidu Encyclopedia), the resolution is now 4K or higher.More importantly, many of the extracted pictures are identical, at least to the naked eye.

To address this issue, I've seen the phrase extracting keyframes, such as CV | Python + OpenCV Extract Keyframes from Video , I understand the practice of this article is to take one per second, the specific operation is to extract the frame frequency, only when the frame pointer%frame frequency==0, save the current frame picture.

Others are more academic. Generally speaking, it is sorted according to the differences between the frame pictures, and saved the frame pictures with big differences before the examination. Similar frames will not be saved (one left), which means Xue Weiwei has some meaning of image recognition, so it is not deep.There is such an article: python for video keyframe extraction (based on inter-frame difference) - You can refer to it

Reference

opencv python takes videos from cameras / files / saves videos

Python Language Implements Batch Video Framing and Saves Video Frames

Python:print progress bar

58 original articles published, 2 praised, 1502 visited
Private letter follow

Posted by ILYAS415 on Fri, 31 Jan 2020 18:46:22 -0800