Easy Raspberry pi 5 and OpenCV based object detection and sorting using python

Easy Raspberry Pi 5 and OpenCV-Based Object Detection and Sorting Using Python

Introduction

Hello, tech enthusiasts! Have you ever wondered how speed cameras detect vehicles exceeding speed limits, identify their owners, and issue fines? Or how autonomous vehicles and object-tracking robots function seamlessly? The answer lies in image processing and computer vision—the core technologies that power object detection and sorting.

In this blog, we will demonstrate a step-by-step guide to setting up Raspberry Pi 5 with OpenCV for object detection and sorting. Whether you are a beginner or an experienced programmer, this guide will help you through hardware setup, software installation, and writing the necessary Python code. Let’s get started!

Table of Contents

  • What is OpenCV?
  • Why Choose Raspberry Pi 5?
  • Hardware Requirements
  • Software Requirements
  • Setting Up Raspberry Pi 5
  • Installing OpenCV
  • Writing and Running the Code
  • Results
  • Conclusion

What is OpenCV?

OpenCV (Open-Source Computer Vision Library) is an open-source software library for computer vision and machine learning. It contains over 2,500 optimized algorithms that assist in various image processing tasks, including:

Key Features of OpenCV:

  1. Image Processing – Supports filtering, edge detection, and object recognition.
  2. Computer Vision – Enables object tracking, image stitching, and feature detection.
  3. Object Tracking – Used in video surveillance, augmented reality, and gesture recognition.
  4. Machine Learning – Provides deep learning capabilities for advanced image analysis.

For more details, visit the official OpenCV documentation.

Why Choose Raspberry Pi 5?

The Raspberry Pi 5 is a powerful and cost-effective single-board computer perfect for computer vision applications. With an upgraded processor and enhanced performance, it is well-suited for running OpenCV-based projects.

For more details, check the official Raspberry Pi website.

Hardware Requirements

To complete this project, you will need the following hardware components:

  • Raspberry Pi 5
  • Raspberry Pi 5 Case / Active Cooler
  • Power Adapter for Raspberry Pi 5
  • Micro-HDMI to HDMI Cable
  • Monitor/Screen
  • Keyboard & Mouse
  • Camera Module
  • Micro SD Card (Minimum 16GB)
  • SD Card Adapter/Card Reader
  • LED Light
  • Servo Motor

Software Requirements

  • Raspberry Pi OS (Latest Version)
  • Thonny Python IDE
  • Visual Studio Code
  • OpenCV Python Library

Setting Up Raspberry Pi 5

Before writing the code, let’s set up Raspberry Pi 5.

Steps to Install the Operating System:

  1. Download Raspberry Pi OS from the official Raspberry Pi website.
  2. Flash the OS onto a MicroSD card using Balena Etcher.
  3. Boot Up the Raspberry Pi – Insert the microSD card, connect the monitor, keyboard, and power it up.

For a detailed guide, refer to the Raspberry Pi 5 setup tutorial.

Installing OpenCV on Raspberry Pi 5

Run the following command to update and install OpenCV:

sudo apt-get update && sudo apt-get upgrade -y

sudo apt-get install python3-opencv

For a detailed OpenCV installation guide, visit this tutorial.

Writing and Running the Code

Get the complete Python source code from this GitHub repository: Object Recognition Code.

Code for Object Detection and Sorting

import cv2

import asyncio

import gpiod

import time

LED_PIN = 17

chip = gpiod.Chip(‘gpiochip4’)

led_line = chip.get_line(LED_PIN)

led_line.request(consumer=”LED”, type=gpiod.LINE_REQ_DIR_OUT)

classNames = []

classFile = “Files/coco.names”

with open(classFile,”rt”) as f:

    classNames = f.read().rstrip(“\n”).split(“\n”)

configPath = “Files/ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt”

weightsPath = “Files/frozen_inference_graph.pb”

net = cv2.dnn_DetectionModel(weightsPath,configPath)

net.setInputSize(320,320)

net.setInputScale(1.0/127.5)

net.setInputMean((127.5, 127.5, 127.5))

net.setInputSwapRB(True)

def getObjects(img, thres, nms, draw=True, objects=[]):

    classIds, confs, bbox = net.detect(img,confThreshold=thres,nmsThreshold=nms)

    if len(objects) == 0: objects = classNames

    objectInfo = []

    if len(classIds) != 0:

        for classId, confidence, box in zip(classIds.flatten(), confs.flatten(), bbox):

            className = classNames[classId – 1]

            if className in objects:

                objectInfo.append([box, className])

                if draw:

                    cv2.rectangle(img, box, color=(0,255,0), thickness=2)

                    cv2.putText(img, classNames[classId-1].upper(), (box[0]+10,box[1]+30),

                    cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)

    return img, objectInfo

def set_led(value):

    led_line.set_value(value)

async def main():

    cap = cv2.VideoCapture(0)

    cap.set(3,640)

    cap.set(4,480)

    while True:

        success, img = cap.read()

        result, objectInfo = getObjects(img, 0.45, 0.2, objects=[‘scissors’])

        found = any(‘scissors’ in sublist for sublist in objectInfo)

        if found:

            set_led(1)

            time.sleep(2)

            set_led(0)

            time.sleep(1)

        cv2.imshow(“Output”, img)

        cv2.waitKey(1)

if __name__ == “__main__”:

    asyncio.run(main())

Results

In this example, we programmed Raspberry Pi 5 to detect scissors and trigger an LED indicator. When scissors are detected, the LED turns ON for 2 seconds and then OFF.

By modifying the code, you can detect and sort other objects as well.

Conclusion

We have successfully set up Raspberry Pi 5 with OpenCV for object detection and sorting. This project showcases the powerful combination of computer vision and automation. You can expand this by integrating additional sensors, using machine learning models, or developing more advanced sorting mechanisms.

If you have any questions, feel free to leave a comment. Happy coding! 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top