Run YOLOv5 in Real-Time on Embedded Systems Like Raspberry Pi

Introduction

Object Detection is a critical task in Computer Vision, which has gained significant attention over the years. Among various algorithms available, YOLO (You Only Look Once) stands out due to its speed and efficiency. However, running such models on embedded systems like Raspberry Pi poses challenges due to limited resources. In this article, we’ll explore how to deploy YOLOv5 on a Raspberry Pi for real-time object detection.

Prerequisites

Before we dive into the implementation, ensure you have:

Installing Required Libraries

To run YOLOv5, you’ll need OpenCV for image processing. You also need torch and torchvision for PyTorch functionality.

# Update your system first
sudo apt-get update -qq && sudo apt-get upgrade -qq
# Install required libraries
sudo apt-get install libopencv-dev python-opencv python3-opencv
pip3 install torch torchvision

Running YOLOv5 on Raspberry Pi

YOLOv5 is designed for use with PyTorch. Ensure you have the latest version of YOLOv5 by cloning the official GitHub repository and following their instructions to download a compatible model.

# Clone YOLOv5 from its GitHub repository
git clone https://github.com/ultralytics/yolov5.git
# Navigate into the yolov5 directory
cd yolov5
# Install requirements for yolov5
pip3 install -r requirements.txt

Main Script

Now, let’s write a simple script to run YOLOv5 on your Raspberry Pi. This example uses the detect.py script provided by YOLOv5 and modifies it slightly to work with your camera.

# Import necessary libraries
import cv2
import torch
# Load YOLO model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
# Initialize the camera
cap = cv2.VideoCapture(0)
while True:
    # Read a frame from the camera
    ret, frame = cap.read()
    
    # If we can't read the frame, break the loop
    if not ret:
        break
        
    # Convert the frame to RGB (OpenCV uses BGR by default)
    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # Get the detections from YOLO model
    results = model(rgb_frame)
    # Loop through all detected objects and draw boxes
    for result in results.xyxy[0]:
        print(result)
        
# Release the camera
cap.release()

Conclusion

Running YOLOv5 on a Raspberry Pi is not only possible but also efficient. With this guide, you’ve successfully set up your system to run real-time object detection with YOLOv5. Remember, for more complex models or applications, consider using a more powerful embedded system or even a cloud-based solution.

Additional Tips