Taking pictures with Picamera 2 and Raspberry Pi using coroutines in Python
Using the Picamera2 library and Camera Module 3 is one of the many ways to take pictures with Raspberry PI. Once the hardware module is installed you can try the code proposed by the official documentation (The Picamera 2 Manual, cap 2.3):
This program launches a preview window, so in a headless Raspberry Pi 4 board (without monitor and keyboard) it can be simplified:
If the program is complex and photo processing takes time, you can take advantage of concurrent execution on the processor cores of the Raspberry board. Python offers the asyncio
library (Asynchronous I/O) which allows the use of the async/await
syntax.
When the program has to carry out some heavy tasks, it launches them in parallel, waiting for the end of the execution only when it needs the results, as in the figure:
In the following example, I only use the coroutines startup and sync apis: concurrent functions are declared as async
and are launched in parallel with asyncio.create_task()
. This method returns a Task
object, which can then be used for a later sync using the await
command:
Note that asyncio requires to launch the main function with asyncio.run(...)
.
References
- The Picamera 2 Manual: datasheets.raspberrypi.com/camera/picamera2-manual.pdf
- Raspberry Pi Camera Module 3 : datasheets.raspberrypi.com/camera/camera-module-3-product-brief.pdf
- Raspberry Pi 4 Model B Datasheet: datasheets.raspberrypi.com/rpi4/raspberry-pi-4-datasheet.pdf
- Python asyncio, Asynchronous I/O: docs.python.org/3/library/asyncio.html