The fastest way to get camera images regularly with python opencv

background

I will introduce how to easily acquire a camera image using opencv and how to execute it regularly. The cameras here are limited to cameras that can be controlled by opencv, such as USB cameras and built-in cameras. Settings etc. are based on the premise that you are using python with anaconda3 series. It works on any OS such as windows, mac and linux.

If you want to perform automatic control with a high-end camera such as a single-lens reflex camera, gphoto seems to be a must. The gphoto compatible models are at http://www.gphoto.org/proj/libgphoto2/support.php, and quite a few are supported. Control SLR camera from Raspberry Pi is helpful.

Environmental setting

opencv install

Since anaconda does not include opencv by default,

python


conda install -c conda-forge opencv

Execute and enter.

schedule

This is not included in anaconda, so you can use pip.

python


pip install schedule

The reason why anaconda is not included depends on the details of development, so there is no need to pursue deeply.

How to get a camera image only once

code

oneshot.py


#!/usr/bin/env python

import cv2

deviceid=0 # it depends on the order of USB connection. 
capture = cv2.VideoCapture(deviceid)

ret, frame = capture.read()
cv2.imwrite('test.jpg', frame)

--Capture = cv2. Get the device ID with VideoCapture (deviceid). However, note that the device ID changes depending on the order in which it is pointed, in the case of a USB camera. Normally, number 0 should be built-in, and USB camera should be number 1. --ret, frame = capture.read () At this moment, the image data is saved in frame. --Use cv2.imwrite ('test.jpg', frame) to save the acquired image in jpg. The save file format is determined by the extension.

For how to save images with OpenCV, refer to Reading and saving image files with Python, OpenCV. Capture video of Mac built-in camera with python can be used as a reference for determining errors and changing to grayscale.

Execution method

In the directory where oneshot.py is located, in an environment where python has a PATH

python


python oneshot.py

Or

python


chmod +x oneshot.py
./oneshot.py

is. If you are using linux or mac, use the terminal. Windows can be a command prompt, but it may be easier to run it from an IDE-like app.

How to get camera images according to schedule

code

scheduled_shot.py


#!/usr/bin/env python

import cv2
import datetime
import schedule
import time

deviceid=0 # it depends on the order of USB connection. 
capture = cv2.VideoCapture(deviceid)

def job():
	ret, frame = capture.read()
	strdate=datetime.datetime.now().strftime('%Y%m%dT%H%M%S') 
	fname="image_" + strdate + ".jpg "
	cv2.imwrite(fname, frame) 
	print(fname + " is created.")

#do job every 10 seconds
schedule.every(1/6).minutes.do(job)

while True:
  schedule.run_pending()
  time.sleep(1)

This time, the image is acquired once every 10 seconds. For how to use schedule, refer to Let's execute the module periodically using schedule.

The while True writing style may not be common in software, but it is a must-have writing style for hardware control. With this, you can implement a function that creates an infinite loop, for example, in the case of a rice cooker, if you point to the power cord, it will continue to work. Here, with While True, you can continue to take images once every 10 seconds indefinitely. To escape from the infinite loop, you need to forcibly terminate the program with cntl + c etc. (In this way of writing, you can also set a timer to terminate after a certain period of time).

Generate the file name using datetime so that the file name is not rewritten and the file names are arranged in chronological order. Please refer to Convert date, time and character string with Python datetime.

In the case of continuous acquisition, once you have acquired the image, check the file size and consider how much space you need. If you notice, the remaining capacity of the disk is often zero.

Execution method

python


python scheduled_shot.py
...
image_20201001T110144.jpg is created.
image_20201001T110154.jpg is created.
image_20201001T110204.jpg is created.

From now on, when executed, the image will be saved every 10 seconds. Since there is only forced termination, it is terminated by forcibly terminating the program with cntl + c or the like.

others

View images

When I try to view an image with imshow of python etc., the output of recent images is quite slow because of the large capacity. Save the image in png or jpeg before viewing it.

To a higher degree of automation

If this is not enough to use, [Let's make a GUI with PyQt5! You can easily create a GUI such as Explanation from introduction to usage. However, from the viewpoint of stability, it is better to make it work properly with CUI.

Also, in such a program, it is better to concentrate the data acquisition program on it. The CPU and programs that acquire and save images from the camera should concentrate on not losing the data. Secondary operations such as downloading, transferring, and processing data in the latter stage are performed by another program.

Recommended Posts

The fastest way to get camera images regularly with python opencv
The easiest way to use OpenCV with python
The fastest way for beginners to master Python
The easiest way to get started with Django
The easiest way to synthesize speech with python
Excel X Python The fastest way to work
Introduction to Python with Atom (on the way)
Camera capture with Python + OpenCV
Minimum knowledge to get started with the Python logging module
Probably the easiest way to create a pdf with Python3
How to get into the python development environment with Vagrant
Save images on the web to Drive with Python (Colab)
[Introduction to Python] How to get data with the listdir function
Get the source of the page to load infinitely with python.
Link to get started with python
Get the weather with Python requests
Get the weather with Python requests 2
How to get the Python version
Face recognition with camera with opencv3 + python2.7
Load gif images with Python + OpenCV
The fastest way to try EfficientNet
Easy way to round off to the nearest whole number with python3
How to make a surveillance camera (Security Camera) with Opencv and Python
[Python] Try to recognize characters from images with OpenCV and pyocr
PhytoMine-I tried to get the genetic information of plants with Python
Try using the camera with Python's OpenCV
[Python] Get the variable name with str
Capturing images with Pupil, python and OpenCV
Single pixel camera to experience with Python
[python, openCV] base64 Face recognition with images
[Python] Read images with OpenCV (for beginners)
Add Gaussian noise to images with python2.7
Upload images to Google Drive with Python
The road to compiling to Python 3 with Thrift
How to crop the lower right part of the image with Python OpenCV
How to get the date and time difference in seconds with python
I tried to get the authentication code of Qiita API with Python.
Get and estimate the shape of the head using Dlib and OpenCV with python
What is the fastest way to create a reverse dictionary in python?
I tried "smoothing" the image with Python + OpenCV
[Python] Get the files in a folder with Python
I tried "differentiating" the image with Python + OpenCV
Convert PDFs to images in bulk with Python
Try to solve the man-machine chart with Python
Specify the Python executable to use with virtualenv
Say hello to the world with Python with IntelliJ
I tried to get CloudWatch data with Python
I tried "binarizing" the image with Python + OpenCV
How to get the files in the [Python] folder
[Python] How to handle Japanese characters with openCV
A layman wants to get started with Python
Python script to get note information with REAPER
Try to detect fish with python + OpenCV2.4 (unfinished)
How to get started with the 2020 Python project (windows wsl and mac standardization)
[Python] How to save images on the Web at once with Beautiful Soup
Note: How to get the last day of the month with python (added the first day of the month)
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
Try to measure the position of the object on the desk (real coordinate system) from the camera image with Python + OpenCV
Easy way to check the source of Python modules
Try to solve the programming challenge book with python3