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.
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
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]")
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.
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.
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.
The pages that I referred to when creating the page are shown below.
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