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)
|
1 2 3 |
mkdir -p ~/YOLO cd ~/YOLO python3 -m venv --system-site-packages YOLOvenv |
Now you will want to activate your virtual environment, using the command:
|
1 |
source ~/YOLO/YOLOvenv/bin/activate |
We are now ready to install pip, ncnn, and pnnx. Type these commands into the same terminal used above:
|
1 2 |
pip install --upgrade pip pip install ncnn pnnx |
Now deactivate your virtual environment by typing this into your terminal:
|
1 |
deactivate |
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:
-
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 to320×320. Your camera still captures and displays in gorgeous 1280×720 HD, while YOLO spots objects at lightning speed! -
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:
|
1 2 3 4 5 |
from ultralytics import YOLO print('Exporting NCNN Model') model = YOLO('yolo26n.pt') model.export(format='ncnn', imgsz=320, half=True) print('Export Complete!') |
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!
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# ==================================================================== # DISCLAIMER: # This code is provided as-is for educational and experimental # purposes only. The author makes no representations or warranties of # any kind concerning the safety, suitability, or accuracy of this # code. Use at your own risk. The author assumes no liability for any # damages, system failures, security breaches, or network issues # resulting from the use or implementation of this script. # ==================================================================== import cv2 import time from picamera2 import Picamera2 from ultralytics import YOLO piCam = Picamera2(0) W=1280 H=720 tStart = time.time() fps = 0 RES = (W,H) piCam.preview_configuration.main.size = RES piCam.preview_configuration.main.format = "RGB888" piCam.preview_configuration.controls.FrameRate=60 piCam.preview_configuration.align() piCam.configure("preview") piCam.start() model = YOLO("yolo26n_ncnn_model", task ='detect') textLowerLeft = (int(W*.01),int(H*.05)) fontFace = cv2.FONT_HERSHEY_SIMPLEX fontThickness = int(W/425) fontScale = H*.0015 fontColor = (0,0,255) cv2.namedWindow("Camera", cv2.WINDOW_GUI_NORMAL) cv2.resizeWindow("Camera",(W,H)) cv2.moveWindow("Camera", 0, 60) while True: deltaT = time.time() - tStart tStart=time.time() fps = fps*.95 + (1/deltaT)*.05 frame= piCam.capture_array() #Uncomment Next Line if Your image is Upside Down #frame=cv2.flip(frame,-1) results=model(frame, imgsz=320,conf=.5, verbose=False) frame = results[0].plot() myText = "FPS: "+str(round(fps,1)) cv2.putText(frame,myText,textLowerLeft,fontFace,fontScale,fontColor,fontThickness) cv2.imshow("Camera", frame) #cv2.moveWindow("Camera",0,60) if cv2.waitKey(1)==ord('q'): break cv2.destroyAllWindows() print('Program Terminated') |
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:
-
Try changing
imgsz=320in your export and detection scripts toimgsz=640. Watch what happens to your frame rate versus how well it picks up small objects across the room. -
Adjust the confidence threshold (
conf=.25) up and down to see how it filters out false positives. -
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!