YOLO on Raspberry Pi LESSON 2: Blinding Fast Object Detection on Raspberry Pi 5

What’s up guys! Paul McWhorter here with toptechboy.com, coming to you today with Lesson Number 2 in our brand-new tutorial series where we are learning how to run YOLO on the Raspberry Pi 5!

Now, if you were with us in Lesson 1, we got our environment set up, we got Ultralytics installed, and we got standard YOLO object detection up and running on our Pi 5. And look—it worked! It detected objects, it drew the bounding boxes, and it showed us what YOLO could do. HOWEVER, if you ran that standard PyTorch .pt model on a crisp 1280×720 HD video feed, you probably noticed something right away: the frame rate was crawling along like a three-legged dog in wet concrete! You were getting maybe 4, 5, or 6 frames per second. Now, that might be okay if you are taking still pictures of a bowl of fruit, but if you are building real-time robotics, tracking fast-moving objects, or running true AI on the Edge, 5 frames per second is not going to cut it. We need speed. We need blinding-fast, real-time performance!

And guys, that is exactly what we are going to unlock in today’s lesson!

Why Standard YOLO Models Bog Down the Raspberry Pi 5

Before we just start blindly copying and pasting code, I want you to understand why things slowed down and how we are going to fix it—because around here, we don’t just guess, we understand the engineering under the hood!

When you download a standard YOLO model like yolo26n.pt, that model is packaged in PyTorch format. PyTorch is fantastic for training massive neural networks on big, power-hungry desktop GPUs. The problem is that PyTorch carries a whole lot of overhead when you try to run inference on an ARM CPU like the one inside your Raspberry Pi 5. It is doing math in heavy 32-bit floating-point precision, and it isn’t optimized to squeeze every drop of performance out of the Pi’s ARM architecture.

So how do we turn our Raspberry Pi 5 into an absolute speed demon? We export the model to NCNN format!

Step 1: Converting Your Model to NCNN (With Half-Precision FP16!)

NCNN is a high-performance neural network inference framework built specifically from the ground up for mobile and ARM processors—no clunky dependencies, no bloated runtime overhead, just pure, bare-metal speed tailored directly for ARM CPUs. To improve the FPS we need to ditch the pytorch, and export the model as a ncnn model. To do that, we need to set up a virtual python environment, which will serve as a sandbox for us to play in, so as to not disturb our system python install. To set up the venv we do the following:

# 1. Open a new terminal and create the YOLO working folder and virtual environment (put these commands in one at a time)

Now you will want to activate your virtual environment, using the command:

We are now ready to install pip, ncnn, and pnnx. Type these commands into the same terminal used above:

Now deactivate your virtual environment by typing this into your terminal:

Now, for these lessons, we will want to be using the virtual environment we just created. Rather than activating it every time you work on YOLO, simply poiont your Thonny IDE to the virtual environment. As shown in the video, in Thonny select tools, then options, then click on interpreter tab. In the lower dialog box, click on the three dot icons and navigate to:

/home/pi/YOLO/YOLOvenv/bin/python3

With that path in the lower dialog box, your thonny will now use your virtual environment every time you run a program. Remember to set it back to the default python when you are done playing with YOLO.

You are now ready to create and export your first ARM NCNN model optimized for your raspberry pi.

When we export our .pt model to NCNN, we are going to pass two critical parameters:

  1. imgsz=320: Instead of forcing the neural network to crunch through a massive grid of pixels on every single frame, we lock the inference input size to 320×320. Your camera still captures and displays in gorgeous 1280×720 HD, while YOLO spots objects at lightning speed!

  2. half=True: This converts the model weights from 32-bit floating point (FP32) down to 16-bit half-precision (FP16). You cut your memory bandwidth in half and dramatically accelerate the math on the Pi 5, with virtually zero noticeable loss in detection accuracy!

Run this quick conversion script first. Make sure to save this script in your ~/YOLO folder. You only have to run this one time—it will look for the model yolo26n.pt in the YOLO folder, a nd not find it, and will then automatically download it to that folder and then generate a brand-new folder right in your working directory called yolo26n_ncnn_model:

This is the code to create and export the optimised model:

Once you see Export Complete! print out in your terminal, you are locked, loaded, and ready to fly!

Now, we are ready to run YOLO at high speed. This is the code you want to use, as explained in the video:

Step 2: Blinding Fast 25 FPS Object Detection on HD Video

Now let’s put that newly minted yolo26n_ncnn_model to work!

In our main detection script below, we fire up Picamera2 configured for a full 1280×720 RGB888 feed, load our yolo26n_ncnn_model, and run real-time inference inside our main OpenCV display loop. Notice we also built in an exponential moving average low-pass filter (fps = fps*.95 + (1/deltaT)*.05) so you get a rock-solid, jitter-free Frames Per Second readout right in the upper-left corner of your screen.

Fire this bad boy up, step in front of your camera, wave a coffee cup, a cell phone, or whatever you’ve got sitting on your desk, and watch that FPS counter climb right up to 25 FPS on full 1280×720 HD video!

Your Homework Assignment!

Now guys, you know I never leave you without a homework assignment! Don’t just run this code, say “Oh, that’s cool,” and move on. I want you to experiment and see the trade-offs for yourself:

  1. Try changing imgsz=320 in your export and detection scripts to imgsz=640. Watch what happens to your frame rate versus how well it picks up small objects across the room.

  2. Adjust the confidence threshold (conf=.25) up and down to see how it filters out false positives.

  3. Drop a comment over on the YouTube video and tell me what exact FPS you are hitting on your Raspberry Pi 5!

If you enjoyed this lesson, make sure you give the video a thumbs up, subscribe to the channel so you don’t miss Lesson 3, and share it with someone who wants to learn real AI on the Edge. Until next time—Paul McWhorter with toptechboy.com, signing off!

YOLO on Raspberry Pi LESSON 1: Run Your First Object Detection Program Using YOLO

Welcome back, folks! If you’ve been hanging out with me through the earlier computer vision and edge AI lessons, you know how we do things: we don’t just wave our hands and hope the magic smoke stays inside the silicon—we measure, we look at frame rates, and we understand what the code is actually doing.

In Lesson #1 of our YOLO series, we’re jumping straight into a working, real-time object detection loop on the Raspberry Pi using Picamera2, OpenCV, and Ultralytics YOLO (yolov8n.pt). Notice that this first script runs the .pt PyTorch weights directly as our baseline. That’s deliberate. You need a clean baseline measurement before you start optimizing, exporting, or chasing higher FPS later in the series.

Introduction to YOLO: Why “You Only Look Once” Matters at the Edge

Traditional or older multi-stage object detection pipelines often split the job up—proposing regions of interest first and then classifying them in a separate pass. That extra overhead adds latency fast when you’re running on an embedded processor instead of a massive data center GPU rack.

YOLO (You Only Look Once) takes a single neural network pass over the input image, predicting bounding boxes and class probabilities simultaneously in one forward shot. That architecture makes it a natural fit for real-time camera streams on edge hardware like the Raspberry Pi.

In this lesson, we load yolov8n.pt—the nano variant of YOLOv8. It’s lightweight and compact compared to larger variants (s, m, l, x), making it a practical starting point when you want to see boxes drawn on live video without waiting five seconds per frame. Even better, watching your live frame rate right on the display gives you immediate, honest feedback on how your resolution, confidence threshold, and model format affect real-world throughput.

Code Walkthrough: What Happens Inside the Loop

Let’s break down the script piece by piece so you aren’t just copying and pasting blindly.

1. Imports, Camera Setup, and Frame Rate Initialization

We bring in cv2 for drawing text and displaying the OpenCV window, time for measuring elapsed time between frames, Picamera2 to grab frames from the Pi camera pipeline, and YOLO from ultralytics.

  • Resolution & Format: We set W=1280 and H=720 (RES = (W,H)) and configure preview_configuration.main.format = "RGB888" with FrameRate=60 requested on the camera controls, followed by piCam.align(), piCam.configure("preview"), and piCam.start().

  • FPS Smoothing Variables: We initialize tStart = time.time() and fps = 0. Notice how we don’t just print raw instantaneous 1 / deltaT every single frame—raw instantaneous FPS jumps around like a flea on a hot skillet.

2. Loading the Model and Scaling the HUD

Right after starting the camera, we load the model weights:

model = YOLO("/home/pi/ai-lab-kit/yolo/yolov8n.pt")

Then we calculate our on-screen text parameters proportionally to W and H (textLowerLeft, fontThickness, fontScale, and fontColor = (0,0,255)). Scaling font thickness and size off resolution is good practice—if you change W and H later, your FPS overlay won’t suddenly turn into microscopic confetti or a giant red blob.

3. The Real-Time Inference & Display Loop

Inside while True:, every iteration does five clear jobs:

  1. Exponential Moving Average (EMA) FPS: We compute deltaT = time.time() - tStart, update tStart, and smooth fps using:fps = fps*.95 + (1/deltaT)*.05 That 0.95 / 0.05 blend gives you a steady, readable frame-rate estimate that still responds to changes over time.

  2. Capture the Frame:frame = piCam.capture_array() pulls the current image array from Picamera2. You’ll also see the commented-out line #frame=cv2.flip(frame,-1) ready if your camera is mounted upside down.

  3. Run YOLO Inference:results = model(frame, conf=.25, verbose=False) runs detection on frame. Setting conf=.25 keeps detections with at least 25% confidence, and verbose=False keeps your terminal clean instead of flooding the console every frame.

  4. Annotate & Overlay FPS:frame = results[0].plot() draws the predicted bounding boxes and labels onto the frame, and cv2.putText(...) stamps FPS: ... in the upper-left area of the image (y at 5% of H from the top edge in OpenCV image coordinates).

  5. Show Window & Clean Exit:cv2.imshow("Camera", frame) and cv2.moveWindow("Camera",0,60) position the preview window cleanly on screen, while if cv2.waitKey(1)==ord('q'): break lets you exit cleanly by pressing q. Once broken out of the loop, cv2.destroyAllWindows() cleans up the GUI windows and prints 'Program Terminated'.

Homework Assignment

Don’t just watch the video and move on—put your hands on the keyboard and gather some real data:

  1. Run the Baseline & Log Your FPS: Run the program as written and note your steady-state FPS on screen. Point the camera at a few everyday objects (a mug, a phone, a keyboard, yourself) and see what labels and confidence scores pop up.

  2. Test the Confidence Threshold (conf): Change conf=.25 to conf=.60 and then to conf=.10. Describe what happens to false positives, missed detections, and your displayed FPS.

  3. Experiment with Resolution (W and H): Drop the resolution from 1280x720 down to 640x480 (and try 960x540 if you want an intermediate step). Compare the FPS before and after—how much faster does it run when you feed fewer pixels into the pipeline?

  4. Verify Clean Shutdown: Test exiting with the q key and confirm the window closes cleanly and Program Terminated prints without hanging your terminal.

Drop your FPS numbers and what you observed in the comments on the video—I love seeing real measurements from your setups!

AI on the Edge LESSON 59: Object Detection with Active Scanning in MediaPipe with Pi 5

Hello everyone! Paul McWhorter here from toptechboy.com, and welcome back to our thrilling adventure into computer vision and edge AI. Today, we are dropping Lesson 59 of our AI on the Edge series.

In our previous sessions, we got our Raspberry Pi 5 looking at the world using MediaPipe object detection, we learned how to lock onto targets using pan-and-tilt servos, and we even brought in speech-to-text and text-to-speech capabilities via the Fusion Hat so our system could actually listen and talk back to us.

But there has been one nagging limitation: Static tracking. Up until now, if your object of interest wasn’t sitting right inside the camera’s initial field of view, your Pi just sat there blindly staring straight ahead, waiting for magic to happen.

Well, no more! Today, we are leveling up our system to feature Active Scanning.

The Motivation: From Passive Waiting to Active Hunting

Think about how human vision works. If you are looking for your coffee mug in a messy room, you don’t just stare at the wall and hope it walks past your nose. You move your head, you scan the environment, and your eyes sweep back and forth across different zones until you spot what you are looking for.

That is exactly what we are building in Lesson 59. We are combining three powerful pillars:

  1. Computer Vision (MediaPipe & OpenCV): Running blazing-fast object detection on the Raspberry Pi 5 using the PiCamera2 module.

  2. Robotic Actuation (Pan and Tilt Servos): Giving our camera a physical body with a dynamic range of motion.

  3. Conversational AI (Speech-to-Text & Text-to-Speech): Enabling voice command processing so you can simply tell your Pi what to find, while the system talks back to confirm its state.

How the Active Scanning System Works

In this lesson, our program operates across a few distinct operational modes managed seamlessly through threaded execution:

  • The Voice Listener Thread: Running independently in the background, this thread listens for your spoken commands using the speech-to-text engine. You can say things like “find”, “track”, “scan”, or name a specific object of interest (like “cup”, “person”, or “cell phone”). Saying “quit” gracefully terminates the application with a polite audio farewell.

  • Find Mode: The system rests or holds position while waiting for a target instruction or manual queue update.

  • Scan Mode: If the camera doesn’t immediately see your requested object of interest, it enters active scan mode. The pan servo sweeps smoothly back and forth across its horizontal range, stepping up or down the tilt angle after each pass. It systematically sweeps the room like a radar system.

  • Track Mode: The moment MediaPipe detects the target object with high confidence during a scan, the system instantly halts the scanning pattern, announces “Target Found” via text-to-speech, and switches over to active track mode. Using error correction based on the center of the bounding box versus the center of the screen, the servos continuously adjust to keep the target dead-centered in the frame.

What You Will Learn in the Video

In the accompanying video lesson, we break down the implementation step-by-step:

  • How to manage multi-threaded voice queues so your UI and camera feed don’t stutter while listening for audio.

  • Implementing state-machine logic to toggle cleanly between find, scan, and track modes.

  • Tuning servo gains, deadbands, and sweep step-sizes to achieve smooth, organic robotic movement without jitter.

  • Integrating real-time bounding box feedback, frames-per-second (FPS) monitoring, and dynamic visual overlays using OpenCV.

Grab your Raspberry Pi 5, fire up your Fusion Hat, and let’s write some code that brings hardware to life! Watch the full video lesson above, and let’s dive straight in!

 

AI on the Edge LESSON 58: Object Detection With Speech to Text Voice Control on Raspberry Pi 5

Welcome back, my friends! This is Paul McWhorter from toptechboy.com, and welcome to AI on the Edge LESSON 58: Object Detection With Speech to Text Voice Control on Raspberry Pi 5!

In this lesson, we take a massive leap forward in edge artificial intelligence and robotics by giving our Raspberry Pi 5 camera rig the gift of speech. Up until now, changing our target object of interest required editing our Python script and restarting the code. In Lesson 58, we bridge the gap between computer vision and natural human interaction by introducing local Speech-to-Text (STT) and Piper Text-to-Speech (TTS). Now, you can simply speak to your system, tell it what object you want to track, and watch as your pan-tilt camera locks on and follows your command!

Understanding the Program Architecture

The program is structured around a robust, multi-threaded architecture designed to handle audio recognition and high-speed computer vision simultaneously without lagging your video stream.

1. Voice-Driven Input via Background Threading

To ensure our camera stream maintains a smooth frame rate, we initialize a dedicated background worker thread using Python’s threading library. This thread runs independently, listening to microphone input via local STT tools.

  • When you speak your object of interest, the thread captures the audio, strips and lowercases the text, and checks for termination commands like quitting the program.

  • If a valid target is spoken, the thread pushes the string into a thread-safe communication queue and commands Piper TTS to talk back, audibly confirming your choice with a phrase like “Now Tracking”.

2. Thread-Safe Command Queuing

Because audio processing and computer vision operate on different timing loops, we use Python’s thread-safe queue mechanism. The background listening thread drops new target requests into the queue, while our main loop checks on every frame pass whether a new object of interest has arrived. This prevents race conditions and keeps our variable updates clean and reliable.

3. High-Speed OpenCV and MediaPipe Vision Loop

The main execution thread runs our primary while loop, capturing high-resolution frames from the Picamera2 camera module at 60 FPS, flipping the orientation, and feeding the frame data into MediaPipe’s efficient object detection model.

  • When detections match our active target class, the program extracts bounding box coordinates, calculates the geometric center of the object, renders visual confirmation boxes and confidence percentages on the screen, and computes pixel error offsets from the center of the display.

4. Proportional Servo Feedback Control

Once the pixel error between the target center and the screen center is calculated, our servo update function kicks in. By applying proportional gain multipliers to the horizontal and vertical error values, the script smoothly drives the SunFounder Fusion HAT servos, keeping your target locked right in the crosshairs.

Hardware Requirements

  • Raspberry Pi 5

  • Raspberry Pi Camera Module (configured with Picamera2 at 1280 by 720 resolution and 60 FPS)

  • SunFounder Fusion HAT (for driving pan and tilt servos)

  • USB Microphone (for local speech-to-text input)

  • Speaker or Headphones (for Piper text-to-speech audio feedback)

Homework Assignment for Next Week

Now that you have full voice-controlled object selection up and running, it is time for your next big challenge. For next week’s lesson, take the code provided at the bottom of this page and add mode control with three distinct operating states:

  1. find mode: In this mode, the servos remain completely switched off. The camera stays stationary, but MediaPipe actively finds, labels, and boxes your object of interest whenever it appears in the frame.

  2. track mode: In this mode, the servos are switched on, and the camera actively drives the pan-tilt rig to track and center the object of interest.

  3. scan mode: In this mode, if your target is out of view, the system actively sweeps and scans the room using the servos to find the object, and then automatically switches over to track mode once the object is located.

Grab your coffee, fire up your Raspberry Pi 5, review the complete code at the bottom of this page, and I will see you in the next lesson!

 

AI on the Edge LESSON 57: Detecting and Tracking Objects with MediaPipe

Welcome back, my friends! This is Paul McWhorter from toptechboy.com, and welcome to LESSON 57 of our AI on the Edge tutorial series.

In this lesson, we take what we’ve learned about local object detection using MediaPipe and put it to work in the physical world! We are building an active target tracking system using a 2-DOF pan-tilt servo rig driven by the Raspberry Pi and the Fusion HAT.

By calculating the positional error between the center of our targeted object (in this case, a bottle) and the center of our frame, we compute feedback adjustments to continuously drive our pan and tilt servos—keeping the target locked right in the center of the camera view.

What You Will Learn in Lesson 57

  1. Setting Up MediaPipe Object Detection: Configuring the efficientdet_lite0.tflite model with threshold options and maximum result limits.

  2. Integrating Picamera2 with OpenCV: Capturing high-resolution camera feeds (1280 by 720 at 60 FPS) and converting raw frames to MediaPipe-compatible image formats.

  3. Bounding Box Analysis & Centroid Calculation: Extracting bounding box dimensions and computing the precise pixel center of detected targets.

  4. Proportional Error Servo Control: Using gain coefficients to convert pixel displacements into physical angle corrections for pan and tilt servos.

  5. Deadband Implementation: Preventing servo chatter and hunting by defining a deadband region around the center of the screen.

Hardware Requirements

  • Raspberry Pi 5 (or Raspberry Pi 4)

  • Raspberry Pi Camera Module (configured with Picamera2)

  • SunFounder Fusion HAT (or compatible servo controller HAT)

  • 2-DOF Pan-Tilt Servo Kit (Pan attached to Pin 2, Tilt attached to Pin 3)

  • Target Object (e.g., a water bottle or any object recognized by COCO dataset categories)

How the Proportional Tracking Control Works

To keep the target centered in the video frame, we continuously measure the distance in pixels between the frame’s center and the center of the target’s bounding box:

errorX = boxCenterX – screenCenterX

errorY = boxCenterY – screenCenterY

If the magnitude of the error exceeds our deadBand limit (15 pixels), we adjust the pan and tilt angles proportionally:

panAngle = panAngle – (errorX * panGain)

tiltAngle = tiltAngle + (errorY * tiltGain)

  • Pan Limits: Clamped between -90 and +90 degrees.

  • Tilt Limits: Clamped between -45 and +45 degrees.

Homework Assignment

Now that you have basic single-target tracking running smoothly:

  1. Multi-Target Priority: Modify the script so that if multiple target objects appear on screen, the camera locks onto the object closest to the center of the frame rather than defaulting to the first detected bounding box.

  2. Dynamic Smoothness Filter: Add an exponential moving average or low-pass filter to the bounding box center coordinates to smooth out tracking jitter when the object moves rapidly across the field of view.

  3. Audibly speak the Object of Interst to track. This will require you to incorporate Speech to Text voice recognition.

Get your coffee, fire up your Raspberry Pi, copy the code above into your IDE, and let’s get tracking!

General Artificial Intelligence & Edge Computing Concepts

What is Edge AI?

Edge AI refers to the deployment of artificial intelligence algorithms directly on hardware devices, such as microcontrollers, single-board computers, or edge accelerators, located close to the source of data generation rather than relying on cloud-based processing servers.

Key Advantages of Local Inference:

  • Low Latency: Processing video feeds directly on an edge device eliminates network transmission delay, enabling real-time feedback loops critical for robotics and physical pan-tilt tracking.

  • Privacy & Security: Sensitive visual or audio data remains on the local hardware without requiring continuous streaming to third-party cloud infrastructure.

  • Network Independence: Edge deployments operate reliably in remote or bandwidth-constrained environments without requiring active internet connectivity.

  • Cost Efficiency: Running localized models eliminates recurring per-API-call cloud infrastructure and compute costs.

Proportional-Integral-Derivative Control Concepts:

  • Proportional Control: Calculates an output value proportional to the current error magnitude. High proportional gain results in aggressive responses, while low gain yields sluggish tracking.

  • Deadband: A non-responsive range around the zero-error position where control adjustments are intentionally suspended to prevent motor oscillation, noise amplification, and mechanical wear.

 

Making The World a Better Place One High Tech Project at a Time. Enjoy!