In the process of studying at university, I write down what I generally thought would be useful. I refer to this article. The above article describes methods such as extracting all frames from the video, extracting frames from $ t_1 $ seconds to $ t_2 $ seconds, but in this article I will introduce the method of cutting out every second. I am.
"I want to analyze the video, but it's difficult to handle the video as it is?: Confounded:" "Then, if you cut it out with a frame, you can't get back to the task of the image ?: open_mouth :" From my personal experience, the purpose is to cut out frames from the video every second.
The following directory structure is assumed.
|── sample.ipynb
|
|── video
|    └── video_sample.mp4
|     
└── frame
     └── video_sample
           |── image_0000.jpg
           ︙
           └── image_00030.jpg
If the video (video_sample.mp4) is 30 seconds, it is assumed that 31 images at 0 seconds, 1 second, ..., 30 seconds will be saved under frame / video_sample.
Opencv-python is a good reference for installing OpenCV.
--video_path: The path of the video you want to crop the frame --frame_dir: Where to save the frame
sample.ipynb
import cv2
from os import makedirs
from os.path import splitext, dirname, basename, join
def save_frames(video_path: str, frame_dir: str, 
                name="image", ext="jpg"):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        return
    v_name = splitext(basename(video_path))[0]
    if frame_dir[-1:] == "\\" or frame_dir[-1:] == "/":
        frame_dir = dirname(frame_dir)
    frame_dir_ = join(frame_dir, v_name)
    makedirs(frame_dir_, exist_ok=True)
    base_path = join(frame_dir_, name)
    idx = 0
    while cap.isOpened():
        idx += 1
        ret, frame = cap.read()
        if ret:
            if cap.get(cv2.CAP_PROP_POS_FRAMES) == 1:  #Save 0 second frame
                cv2.imwrite("{}_{}.{}".format(base_path, "0000", ext),
                            frame)
            elif idx < cap.get(cv2.CAP_PROP_FPS):
                continue
            else:  #Save frames 1 second at a time
                second = int(cap.get(cv2.CAP_PROP_POS_FRAMES)/idx)
                filled_second = str(second).zfill(4)
                cv2.imwrite("{}_{}.{}".format(base_path, filled_second, ext),
                            frame)
                idx = 0
        else:
            break
save_frames(".\\video\\video_sample.mp4", ".\\frame")
When executed, it is saved as follows.

It's difficult to handle videos.
Recommended Posts