Shoot time-lapse from a PC camera using Python and OpenCV

Introduction

I decided to keep an ant. This is Camponotus japonicus. Nests and colonies will arrive on Wednesday. I want to observe them while I go to the laboratory! However, it is too inconvenient to go out with your smartphone at home. I just had a private PC left over, so I decided to use this to take a time-lapse shot of the colony on the go. I'm a beginner in programming, so I'm writing elementary content as well as studying.

Method

Python 3.7.3 Anaconda Prompt Use the webcam that came with your PC You need to install OpenCV by typing the following on the command prompt in advance.

$ pip install opencv-python 

code

timelaps.py


import cv2
import glob
import os
import shutil
import time
from datetime import datetime

###Various initial settings

date = datetime.now().strftime("%Y%m%d_%H%M%S")
if not os.path.exists(date):
    os.mkdir(date)   #Create a folder for saving images

#Waiting for the time being_Wait for time seconds before starting shooting
capture_interval = 0.5 #Image acquisition interval (seconds)
waiting_time = 0
print('Recording will be started in {0} seconds'.format(waiting_time))
time.sleep(waiting_time)
print('Start')

###Taking an image
def capture():
    cap = cv2.VideoCapture(0) #Change to any camera number. If there is only one, the camera number is 0.
    while True: # capture_Interval Loads and saves images every second.
        ret, frame = cap.read() #Load the image captured from the camera as a frame
        cv2.imshow("camera", frame) #Display frame on the screen. If you don't leave this one for some reason, you can't stop the operation with enter.
        k = cv2.waitKey(1)&0xff #Wait for key input. The argument is the input wait time.
        #In the "img" folder in the current directory, "(date).Save the file with the file name "jpg"
        date_time = datetime.now().strftime("%Y%m%d%H%M%S")
        path = "./{0}/".format(date) + date_time + ".jpg "
        cv2.imwrite(path, frame) #Save images to folders

        #Shooting ends when you press the enter key
        if k == 13:
            break 
        time.sleep(capture_interval)
    cap.release()
    cv2.destroyAllWindows()

###Image time-lapse
def timelaps():
    images = sorted(glob.glob('{0}/*.jpg'.format(date))) #Loading the captured image.
    print("Total number of images{0}".format(len(images)))

    if len(images) < 30: #FPS settings
        frame_rate = 2  
    else:
        frame_rate = len(images)/30

    width = 640
    height = 480
    fourcc = cv2.VideoWriter_fourcc('m','p','4','v') #Specify the video codec as mp. Decide the extension of the video (although it is a little different),
    video = cv2.VideoWriter('{0}.mp4'.format(date), fourcc, frame_rate, (width, height)) #Specify the information of the video to be created (file name, extension, FPS, video size).

    print("During video conversion...")
    
    for i in range(len(images)):
        #Load image
        img = cv2.imread(images[i])
        #Match the size of the image.
        img = cv2.resize(img,(width,height))
        video.write(img) 
    
    video.release()
    print("Video conversion completed")

def capture_delete():
    shutil.rmtree(date)

if __name__ == '__main__':
    start = time.time()

    capture()
    timelaps()
    capture_delete()

    elapsed_time = time.time() - start
    print ("The time taken for processing:{0}".format(elapsed_time) + "[sec]")

Code description

Overview

  1. Take photos at regular intervals and save to a folder
  2. Create and save a video (timelapse) that connects the images saved in the folder
  3. Delete a large number of photos used as time-lapse materials for each folder
  4. Finally, report the time required.

def capture () or earlier

Create a folder to save the image with mkdir. The folder name can be anything. This time, if you create it at 13:57:09 on September 20, 2020, a folder named "20200920_135709" will be created. If a folder with the same name already exists, os.mkdir will throw an error, so I try to create a folder only if there is no folder with the same name. Set the interval (waiting_time) for acquiring images. If you start shooting suddenly after moving it, I will be reflected before the ants, so I will make you wait for waiting_time seconds.

capture() You can see what you're doing by reading the comments in the code. If the photo was taken on September 20, 2020 at 12:34:56, the file name will be "20200920123456". I'm afraid to eat too much space, so I use jpg instead of png. k == 13 is equivalent to pressing the enter key. The format () method was very convenient to specify the save destination.

timelaps() First, load the captured image. The sorted function is used to generate a sorted list in ascending order of numbers (that is, the order in which they were shot). But if this method is crazy

images = glob.glob('{0}/*.jpg'.format(date))

But it works fine. Next, set the number of images (FPS) used per second. For the time being, I tried to fit it in a 30-second video even if I shot it for a long time. After setting the screen size of the video (the default image is 640 * 480, match it), we will create the video. Read the i-th image with cv2.imread (), adjust the size of the image to the size for the video, and then insert it into the video. Create a video by repeating this for all images.

capture_delete() Delete the folder (date) created for saving images. Since it is one line, it is not necessary to define it as a function, but it looks good somehow, so I made it a function.

result

When executed on the command prompt, the following text will be displayed.

Recording will be started in 0 seconds
Start
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-2b5g8ysb\opencv\modules\videoio\src\cap_msmf.cpp (435) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Total number of images 10
During video conversion...
Video conversion completed
The time taken for processing:12.048035621643066[sec]

I couldn't understand [WARN: 0] well. I am happy because it worked. It's a textbook. The video file is obtained in the directory where Python is run. After the ants arrive, I will post the video that I actually shot.

in conclusion

For beginners, I talked about a program that takes pictures from a PC camera and creates a time lapse based on the pictures taken. If you have knowledge of directories, for, while, etc., it is not so difficult, so even beginners of programming should definitely try it. Also, since I am studying, I would appreciate it if you could give me any suggestions, comments, or advice.

References

The pages that I referred to when creating the page are shown below.

format () method

https://gammasoft.jp/blog/python-string-format/ OpenCV OpenCV in general http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_gui/py_image_display/py_image_display.html http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_gui/py_video_display/py_video_display.html#display-video

Image capture http://rikoubou.hatenablog.com/entry/2019/03/07/153430

waitKey () function https://qrunch.net/@opqrstuvcut/entries/XZsZ0jUEX6RatMER?ref=qrunch https://www.kishugiken.co.jp/cn/code02.html

Image to video conversion https://yusei-roadstar.hatenablog.com/entry/2019/11/29/174448 os, shutil https://note.nkmk.me/python-os-remove-rmdir-removedirs-shutil-rmtree/

that's all. Thank you for reading this far.

Recommended Posts

Shoot time-lapse from a PC camera using Python and OpenCV
How to make a surveillance camera (Security Camera) with Opencv and Python
Image acquisition from camera with Python + OpenCV
Reading and creating a mark sheet using Python OpenCV (Tips for reading well)
Head orientation estimation using Python and OpenCV + dlib
I tried object detection using Python and OpenCV
Create a web map using Python and GDAL
Run a Python file from html using Django
Create a Mac app using py2app and Python3! !!
Run a python script from excel (using xlwings)
Python, OpenCV camera capture
Create a color sensor using a Raspberry Pi and a camera
Try creating a compressed file using Python and zlib
Implementing a generator using Python> link> yield and next ()> yield
Get files from Linux using paramiko and scp [Python]
Make a Sato Yohei discriminator using OpenCV and TensorFlow
A little bit from Python using the Jenkins API
[Python] Start a batch file from Python and pass variables.
[Python] Sort apples and pears from pixel values using a support vector machine (SVM)
View images in OpenCV from Python using an external USB camera on your MacBook
Flatten using Python yield from
Visualize plant activity from space using satellite data and Python
Create a web surveillance camera with Raspberry Pi and OpenCV
Building a Python environment on a Mac and using Jupyter lab
[Python] Using OpenCV with Python (Basic)
[Python] Chapter 01-03 About Python (Write and execute a program using PyCharm)
Switch camera resolution from OpenCV
Hash with python and escape from a certain minister's egosa
Python: Create a dictionary from a list of keys and values
Predict gender from name using Gender API and Pykakasi in Python
[Python] Random data extraction / combination from DataFrame using random and pandas
[Python] Accessing and cropping image pixels using OpenCV (for beginners)
I made a Chatbot using LINE Messaging API and Python
Using OpenCV with Python @Mac
Do a search by image from the camera roll using Pythonista3
Posture detection by openpose from USB camera image using python code
Build a game leaderboard on Alibaba cloud using Python and Redis
Process Splunk execution results using Python and save to a file
Create a striped illusion with gamma correction for Python3 and openCV3
How to get followers and followers from python using the Mastodon API
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
A little more about references ~ Using Python and Java as examples ~
[Image processing] Edge detection using Python and OpenCV makes Poo naked!
Draw a watercolor illusion with edge detection in Python3 and openCV3
Build and try an OpenCV & Python environment in minutes using Docker
Aligning scanned images of animated video paper using OpenCV and Python
[Note] Using 16x2-digit character LCD (1602A) from Python with Raspberry Pi
[Python] I wrote a REST API using AWS API Gateway and Lambda.
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
[Python] Try to recognize characters from images with OpenCV and pyocr
Python a + = b and a = a + b are different
Environment construction of python and opencv
Shining life with Python and OpenCV
Call a Python function from p5.js.
[Python] Using OpenCV with Python (Image Filtering)
Neural network with OpenCV 3 and Python 3
Touch a Python object from Elixir
Using Rstan from Python with PypeR
Create a python GUI using tkinter
Authentication using tweepy-User authentication and application authentication (Python)
Python, yield, return, and sometimes yield from