Cut out frames from video by 1 second with Python + OpenCV

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.

Purpose

"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.

Premise

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.

Execution environment

Opencv-python is a good reference for installing OpenCV.

Implementation

Argument description

--video_path: The path of the video you want to crop the frame --frame_dir: Where to save the frame

code

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. image.png

Conclusion

It's difficult to handle videos.

Recommended Posts

Cut out frames from video by 1 second with Python + OpenCV
Cut out face with Python + OpenCV
Save video frame by frame with Python OpenCV
Cut out an image with python
Face detection from multiple image files with openCV, cut out and save
Make OpenCV3 available from python3 installed with pyenv
Read line by line from a file with Python
Binarization with OpenCV / Python
JPEG image generation by specifying quality with Python + OpenCV
Display USB camera video with Python OpenCV with Raspberry Pi
Make thumbnails easily with opencv from the erotic video folder
"Apple processing" with OpenCV3 + Python3
Real-time face recognition with video acquired by getUserMedia [HTML5, openCV]
Add fake tilt shift effect to video with OpenCV + Python
Image editing with python OpenCV
Camera capture with Python + OpenCV
YouTube video management with Python 3
[Python] Using OpenCV with Python (Basic)
Loop video loading with opencv
I tried face recognition from the video (OpenCV: python version)
Create a simple video analysis tool with python wxpython + openCV
Cut out JPEG for time lapse from Theta S video
Convert video to black and white with ffmpeg + python + opencv
With skype, notify with skype from python!
Using OpenCV with Python @Mac
Object extraction in images by pattern matching using OpenCV with Python
I tried to cut out a still image from the video
Pass a list by reference from Python to C ++ with pybind11
[Python] Try to recognize characters from images with OpenCV and pyocr
Shining life with Python and OpenCV
Call C from Python with DragonFFI
[Python] Using OpenCV with Python (Image Filtering)
Neural network with OpenCV 3 and Python 3
Using Rstan from Python with PypeR
[Python] Using OpenCV with Python (Image transformation)
Install Python from source with Ansible
Create folders from '01' to '12' with python
[Python] Using OpenCV with Python (Edge Detection)
Easy Python + OpenCV programming with Canopy
Run Aprili from Python with Orange
Try face recognition with python + OpenCV
Face recognition with camera with opencv3 + python2.7
Load gif images with Python + OpenCV
Call python from nim with Nimpy
Find image similarity with Python + OpenCV
Use OpenCV with Python 3 in Window
Draw an illustration with Python + OpenCV
Read fbx from python with cinema4d
Track baseball balls with Python + OpenCV
Object recognition with openCV by traincascade
Draw arrows (vectors) with opencv / python
Basic study of OpenCV with Python
Put OpenCV in OS X with Homebrew and input / output video with python
[Implementation example] Read the file line by line with Cython (Python) from the last line
Collecting information from Twitter with Python (Twitter API)
Play video with sound with python !! (tkinter / imageio)
Get property information by scraping with python
Receive textual data from mysql with python
Get html from element with Python selenium
[Note] Get data from PostgreSQL with Python
[Python] Face detection by OpenCV (Haar Cascade)