[Python] Smasher tried to make the video loading process a function using a generator

The beginning of things

There was a request, so I decided to machine learn about 10 hours of game videos. I made a module to read the video while outputting the progress status to the console.

Ordinary program

import cv2
import sys

fpath = 'data/videos/sample_video.mp4'

video = cv2.VideoCapture(fpath)
can_read, first = video.read()

if not can_read:
    sys.exit()

progress_step = 60    #Show progress once every 60 frames
count = 0
max = int(video.get(cv2.CAP_PROP_FRAME_COUNT))

while video.isOpened():
    if(count % progress_step == 0):
        print(f'Progress rate: {count}/{max}')

    ok, frame = video.read()
    if ok:
        #What you want to do
    else:
        break

video.release()

Execution result

Progress rate: 0/2700
Progress rate: 60/2700
Progress rate: 120/2700
Progress rate: 180/2700
...

Impressions

Although the purpose has been achieved, other programs also have video loading processing, and I want to reuse it there, so I decided to make it a function that can be called from anywhere.

Functionalization Ver

function

reader.py


def video_read(input):
    """
    Parameters
    ----------
    input: str
        Input video path

    Returns
    ------
    Iterator[np.ndarray]
        Generator of video frame
    """

    # video capture start
    video = cv2.VideoCapture(input)
    can_read, first = video.read()

    if not can_read:
        print('Cannot read video file')
        return

    max = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
    yield first

    progress_step = 60    #Show progress once every 60 frames
    count = 0
    while video.isOpened():
        if(count % progress_step == 0):
            print(f'Progress rate: {count}/{max}')

        ok, frame = video.read()
        if ok:
            count += 1
            yield frame
        else:
            break
    video.release()

Caller

import reader

it = reader.video_read('data/videos/sample_video.mp4')
try:
    first = next(it)
except StopIteration:
    sys.exit()

for image in it:
    #What you want to do

Summary

The caller was very refreshing. I think that the video loading process and the main process you want to do have been separated and clarified. I feel like I made good use of the Python generator. I'm sorry for this article, regardless of the smasher ...

Recommended Posts

[Python] Smasher tried to make the video loading process a function using a generator
[Python] Make the function a lambda function
I tried to make a stopwatch using tkinter in python
I tried to make a regular expression of "amount" using Python
I tried to make a regular expression of "time" using Python
I tried to make a regular expression of "date" using Python
I tried to make a periodical process with Selenium and Python
I also tried to imitate the function monad and State monad with a generator in Python
I tried to make a todo application using bottle with python
[Python] I tried to make a simple program that works on the command line using argparse.
Python: I tried to make a flat / flat_map just right with a generator
How to divide and process a data frame using the groupby function
I tried to make a ○ ✕ game using TensorFlow
A super introduction to Django by Python beginners! Part 3 I tried using the template file inheritance function
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
[Python] I tried to get the type name as a string from the type function
I tried to approximate the sin function using chainer
How to make a Python package using VS Code
[Python] Make sure the received function is a user-defined function
How to unit test a function containing the current time using freezegun in python
I tried to make a function to retrieve data from database column by column using sql with sqlite3 of python [sqlite3, sql, pandas]
To return char * in a callback function using ctypes in Python
I tried to implement the mail sending function in Python
I tried to approximate the sin function using chainer (re-challenge)
I tried to make a simple text editor using PyQt
A super introduction to Django by Python beginners! Part 6 I tried to implement the login function
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
I tried to make the political broadcast video like IPPON Grand Prix (OpenCV: Python version)
I tried to make a generator that generates a C # container class from CSV with Python
I tried to make a function to judge whether the major stock exchanges in the world are daylight saving time with python
[5th] I tried to make a certain authenticator-like tool with python
Rubyist tried to make a simple API with Python + bottle + MySQL
I tried to get the index of the list using the enumerate function
[2nd] I tried to make a certain authenticator-like tool with python
[Introduction to Python] How to split a character string with the split function
Process Splunk execution results using Python and save to a file
[3rd] I tried to make a certain authenticator-like tool with python
I tried to display the video playback time (OpenCV: Python version)
I tried to make a 2channel post notification application with Python
[Python3] Define a decorator to measure the execution time of a function
[4th] I tried to make a certain authenticator-like tool with python
I tried to cut out a still image from the video
[1st] I tried to make a certain authenticator-like tool with python
[Python] A simple function to find the center coordinates of a circle
I tried to make an image similarity function with Python + OpenCV
"Cython" tutorial to make Python explosive: When a function on the C ++ side has an overload.
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
[Python] How to make a class iterable
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Python] Explains how to use the range function with a concrete example
A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
[Introduction to Python] How to write a character string with the format function
I tried to make a Web API
I tried to create a sample to access Salesforce using Python and Bottle
Python: I want to measure the processing time of a function neatly
I tried to analyze the New Year's card by myself using python
I want to make a web application using React and Python flask
I made a function to see the movement of a two-dimensional array (Python)
I tried to understand the learning function of neural networks carefully without using a machine learning library (first half).
"Cython" tutorial to make Python explosive: Handling when a function on the C ++ side is passed by reference.