[PYTHON] I tried to cut out a still image from the video


Background
I needed to annotate to create machine learning teacher data. For that reason, a large amount of still images were needed, so I decided to cut out still images from the video.

At first, I used to do it manually using a tool that extracts still images from videos. The task was tedious, so I decided to automate it.


Procedure
install openCV Loading video Cut out a still image for each unit frame Readjust the still image size

install openCV This time I did it with windows + anaconda, so at the anaconda prompt

Users\user\conda install -c conda-forge opencv


 I was able to install it with the command.
 Basically, it can be done fully automatically, but it took about 2 hours.

 A little Python description is required to actually make it work.


 <br> Code <br>
 A Laplacian filter is a spatial filter that extracts image contours using quadratic differentiation.
 laplacian.var looks at the variance of the Laplace distribution.

if ret and laplacian.var() >= laplacian_thr:
 laplacian_thr is a threshold for judging as a blurred image
 I decided to use this value by acquiring the parameters of the image that I recognized as being out of focus.
 This time, I decided to judge the image with the value of laplaciaan.var () of 800 or less as a blurred image.


```python
"""
@author: S.Nakamura     2020/10/18
A program that reads a video and divides it into images (jpg)
input_movie: Movie file name to read
cpf: How many frames to save
image_dir: Image output destination directory (create if not available)

・ Loading video
・ How many frames to read
-Specify the directory to output the image
・ Remove the out-of-focus image
・ Resize
・ Determine a name and output
""" 
import cv2
import numpy as np
import os

i=0
count = 0
cpf = 10                        #How many frames to cut out

#Image size
image_width =Width of image to resize
image_heigh =The height of the image to be resized
#Laplacian for judging blurred images.var
laplacian_thr = 800             #Threshold when making a blurred image judgment

#Loading video
cap = cv2.VideoCapture('Specify the video file to read')

while(cap.isOpened()):
    ret, frame = cap.read()                   #Load video
    #assert frame, "Failed to open"            #For debugging

    if ret == False:
        print('Finished')                    #When the video cutout is finished
        break

    if count%cpf == 0:                      #How many frames to cut out once

        #Reduce the size
        resize_frame = cv2.resize(frame,(image_width,image_heigh))

         #Check if the image is blurred
        laplacian = cv2.Laplacian(resize_frame, cv2.CV_64F)
        if ret and laplacian.var() >= laplacian_thr: #Output only those whose defocus judgment is above the threshold
            
            #File name of the first argument image, second argument The image you want to save
            write = cv2.imwrite('Name and extension of the image to save')  #Display the cropped image
            assert write, "Failed to save"
            print('Save',Name and extension of the image to save)          #Confirmation display
            i += 1
        
    count = count + 1

cap.release()

I haven't verified it in detail, but I was able to achieve the purpose of cutting out the image and resizing it. I am impressed to be able to cut out a still image from a video with such a simple description.


Reference information
Blur detection with OpenCV https://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/ note.nkmk.me  https://note.nkmk.me/python-opencv-video-to-still-image/ A program that cuts out images (jpg) from videos (mp4) https://www.souichi.club/deep-learning/spliter/

Recommended Posts

I tried to cut out a still image from the video
I tried to detect the iris from the camera image
I tried to sort out the objects from the image of the steak set meal-④ Clustering
I tried to sort out the objects from the image of the steak set meal-① Object detection
I tried to correct the keystone of the image
I tried to sort out the objects from the image of the steak set meal-② Overlap number sorting
I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~
I tried to sort out the objects from the image of the steak set meal --③ Similar image Heat map detection
I tried to extract a line art from an image with Deep Learning
[Python] I tried to get the type name as a string from the type function
How to take a captured image from a video (OpenCV)
I tried to sort out the objects from the image of the steak set meal-⑤ Similar image feature point detection
I tried to compress the image using machine learning
I tried to find the entropy of the image with python
I tried to find out the outline about Big Gorilla
I tried face recognition from the video (OpenCV: python version)
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
I tried to get various information from the codeforces API
Let's cut the face from the image
I tried to move the ball
I tried to estimate the interval.
I tried using PI Fu to generate a 3D model of a person from one image
I tried to build the SD boot image of LicheePi Nano
I tried to process the image in "sketch style" with OpenCV
I tried to display the video playback time (OpenCV: Python version)
I tried to register a station on the IoT platform "Rimotte"
I tried to process the image in "pencil style" with OpenCV
It is difficult to install a green screen, so I cut out only the face and superimposed it on the background image
I tried to create a linebot (implementation)
I tried to summarize the umask command
I tried to create a linebot (preparation)
I tried to summarize the graphical modeling.
I tried to estimate the pi stochastically
I tried to touch the COTOHA API
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
I tried to make a Web API
Video acquisition / image shooting from a webcam
I tried to transform the face image using sparse_image_warp of TensorFlow Addons
I tried to verify the best way to find a good marriage partner
I tried to execute SQL from the local environment using Looker SDK
I tried moving the image to the specified folder by right-clicking and left-clicking
I tried to get the batting results of Hachinai using image processing
I tried to learn the angle from sin and cos with chainer
I tried to send a registration completion email from Gmail with django.
Start the webcam to take a still image and save it locally
Get the song name from the title of the video you tried to sing
I tried to display the altitude value of DTM in a graph
I tried to verify the result of A / B test by chi-square test
I tried to make a thumbnail image of the best avoidance flag-chan! With RGB values ​​[Histogram] [Visualization]
I tried "smoothing" the image with Python + OpenCV
I tried to build a super-resolution method / ESPCN
I tried web scraping to analyze the lyrics.
I tried to build a super-resolution method / SRCNN ①
I tried "differentiating" the image with Python + OpenCV
I tried to optimize while drying the laundry
I tried to get an image by scraping
I tried to save the data with discord
I tried "binarizing" the image with Python + OpenCV
I tried to generate a random character string
I tried to build a super-resolution method / SRCNN ③
I tried to build a super-resolution method / SRCNN ②