I am providing a Quick Start with Raspberry Pi, Pi Camera (or webcam), and Libcamera:
With the release of Raspberry Pi OS Bullseye, the default camera stack is now libcamera.
This guide explains how to deploy a trained YOLOv5 model on a Raspberry Pi 3 or Pi 4 running the 64 bit version of the operating system with the libcamera camera stack.
Install the Raspberry Pi Operating System
Prepare a micro SD card with the latest version of the Raspberry Pi Operating System (64-bit). You can use the Raspberry Pi Imager tool to get everything set up properly:
Install Necessary Packages
- Make sure the Raspberry Pi is up-to-date
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get autoremove -y
- Clone the YOLOv5 repository
cd ~
git clone GitHub - ultralytics/yolov5: YOLOv5 🚀 in PyTorch > ONNX > CoreML > TFLite
- Install the required dependencies
cd ~/yolov5
sudo pip3 install -r requirements.txt
- Install the correct version of PyTorch and Torchvision (at the time of writing, PyTorch 1.13.0 and Torchvision 0.14.0 were not supported)
sudo pip3 install torch==1.11.0
sudo pip3 install torchvision==0.12.0
Adjust detect.py
By default, detect.py doesn’t allow TCP streams to be used as a source and fails when used via SSH or the Raspberry Pi Command Line Interface. To fix this, make two minor modifications to detect.py:
- Open detect.py and find the ‘is_url’ line
cd ~/yolov5
sudo nano detect.py
CTRL + W → is_url → ENTER
- Add TCP streams as an accepted url-format
is_url = source.lower().startswith((‘rtsp://’, ‘rtmp://’, ‘tcp://’, ‘http://’, ‘https://’))
- Find the line that says ‘view_img = check_imshow(warn=True)’
CTRL + W → view_img = check_imshow(warn=True) → ENTER
- Comment out this line
*#*view_img = check_imshow(warn=True)
- Save the modifications and close detect.py
CTRL + O → ENTER → CTRL + X
Initiate a TCP stream with the Libcamera driver
libcamera-vid -n -t 0 --width 1280 --height 960 --framerate 1 --inline --listen -o tcp://127.0.0.1:8888
Perform YOLOv5 inference on the TCP stream
- Navigate into the yolov5 directory
cd ~/yolov5
- Run detect.py with the TCP stream as its source
python3 detect.py --source tcp://127.0.0.1:8888
- Note: by commenting out ‘view_img = check_imshow(warn=True)’ we made sure detect.py no longer display its source + predicted bounding boxes by default to enable inference via SSH or the Command Line Interface. To re-enable this feature, run detect.py with the --view-img argument:
python3 detect.py --source tcp://127.0.0.1:8888 --view-img