Welcome back, folks. Paul McWhorter here from toptechboy.com. In Lesson 1 and Lesson 2, we got Ultralytics YOLO running fast on the Raspberry Pi 5 using the exported NCNN model (yolo26n_ncnn_model). That gets you solid real-time detection when you are pulling frames straight from a local camera.
Now in Lesson 3, we take things out onto the network and run YOLO object detection over an RTSP IP security camera stream. If you have ever hooked up an IP camera with OpenCV in a naive single-thread loop, you already know what happens: cap.read() blocks while waiting for network packets or chews through stale buffered frames, turning your live security feed into a lagging, rubber-banding mess. Today we fix that cleanly and get smooth, responsive detection on the Pi.
I am using the Amcrest pan tilt zoom outdoor camera. I have had this camera for 5 years, and it has worked flawlessly. Any IP camera that makes it RTSP stream generally available will work, but if you want to use my high performance camera, you can get it on amazon here:
https://link.amazon/B0ghiQ356
Why We Thread the RTSP Stream and Pace Inference
When you pull video over RTSP (rtsp://...), two bottlenecks fight each other on an edge device like the Raspberry Pi 5:
-
Network I/O vs. Inference Time: Grabbing frames from an IP camera over the network has variable latency, while running YOLO inference takes dedicated CPU cycles even at
imgsz=320with an NCNN model. If frame grabbing and model inference sit on the exact same thread, every slow network read stalls your loop—and every heavy inference pass delays your next camera read. -
Stale Buffer Lag: Video capture backends often buffer frames internally. If you process old frames from a backlog, your bounding boxes show where an object was a couple of seconds ago rather than where it is now.
Here is how we engineer around both issues in this lesson:
-
Force TCP transport for RTSP: Setting
OPENCV_FFMPEG_CAPTURE_OPTIONStortsp_transport;tcptells FFmpeg to use TCP rather than letting UDP packet loss scramble your stream. -
Dedicated background
frameGrabberthread: A daemon thread continuously pulls fresh frames from the IP camera, resizes them once to our working display size (1280x720), and stores the latest frame behind athreading.Lock(). -
Decoupled display & inference loop: The main thread grabs a safe copy of the newest frame (
ipFrame.copy()), updates a smoothed FPS meter, runs YOLO inference every other frame (cnt%2 == 1), and still renders a crispdisplayFrameevery iteration so the window stays fluid.
How the Code Works
Let’s walk through the script from top to bottom so every line makes complete engineering sense.
1. Imports, Transport Setup, and Tunables
We bring in cv2, YOLO from ultralytics, your private secret module (so your camera URL stays out of public code), threading, time, and os. Right before opening any capture stream, we set:
|
1 2 |
os.environ.setdefault(<span class="hljs-string">"OPENCV_FFMPEG_CAPTURE_OPTIONS"</span>, <span class="hljs-string">"rtsp_transport;tcp"</span>) |
We also define our display resolution (W = 1280, H = 720), YOLO input resolution (IMG_SZ = 320), and confidence threshold (CONF_THRES = .25). Keeping IMG_SZ = 320 keeps inference brisk on the Pi 5 while still catching objects cleanly across a 1280x720 view.
2. Loading the NCNN Model and Shared State
We load yolo26n_ncnn_model with task = 'detect'. Next, we set up the shared variables between the camera thread and the main display loop:
-
ipFrame: Holds the most recent resized frame from the camera. -
lock = threading.Lock(): Prevents race conditions whenframeGrabberwrites a new frame at the same moment the main loop reads it. -
running = True: Gives us a clean flag to stop the background thread when we quit.
3. The frameGrabber Thread
frameGrabber(url) opens the RTSP stream using cv2.CAP_FFMPEG and sets cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) to keep buffering minimal. Inside while running::
-
It calls
cap.read()continuously. -
When a valid frame arrives (
ret == True and frame is not None), it resizes to(W, H)usingcv2.INTER_AREA(great for clean downscaling/sizing) and updatesipFrameinside awith lock:block. -
When
runningbecomesFalse, it exits the loop, releasescap, and prints"Thread Terminated".
We launch it with daemon=True using args=(secret.RTSP8,) so the thread will not hang the interpreter if the program exits.
4. Window Setup and Warm-Up
Before entering the main loop, we create a resizable "IP Camera" window at (0, 60), wait two seconds (time.sleep(2)) so the background thread can establish the RTSP connection and populate ipFrame, and initialize our frame counter cnt, results, tStart, and fps.
5. The Main Inference and Display Loop
Every pass through while True: does the following:
-
Grab a thread-safe frame: Locks
lock, copiesipFrameintoipFrameShow, and releases the lock immediately soframeGrabberis barely blocked. -
Smooth the FPS readout: Uses an exponential moving average (
fps = fps*.95 + .05/(time.time()-tStart)) so the number on screen is readable instead of jumping wildly every single frame. -
Run YOLO on alternating frames: Increments
cntand runsmodel(ipFrameShow, imgsz=IMG_SZ, conf=CONF_THRES, verbose=False)whencnt%2 == 1or on the very first pass (results is None). Reusing the latestresultson even frames trades a tiny bit of box-update latency for noticeably higher loop throughput. -
Annotate and show: Plots the detections onto
ipFrameShow, draws the FPS counter in red ((0, 0, 255)) near the top-left corner, displays"IP Camera", and exits cleanly when you pressq.
Wrapping Up
Scroll down to the bottom of the page for the complete script, hook up your secret.RTSP8 stream, and test it on your Raspberry Pi 5. Once you have the threaded grabber and inference pacing working reliably on a single camera, you have a rock-solid foundation for multi-camera monitoring and smart alerts on the edge.
|
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 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import cv2 from ultralytics import YOLO import secret import threading import time import os os.environ.setdefault("OPENCV_FFMPEG_CAPTURE_OPTIONS","rtsp_transport;tcp") W = 1280 H = 720 IMG_SZ = 320 CONF_THRES = .25 model = YOLO("yolo26n_ncnn_model", task = 'detect') ipFrame = None lock = threading.Lock() running = True def frameGrabber(url): global ipFrame, running cap = cv2.VideoCapture(url,cv2.CAP_FFMPEG) cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) while running: ret, frame = cap.read() if ret == True and frame is not None: resized = cv2.resize(frame, (W,H), interpolation=cv2.INTER_AREA) with lock: ipFrame = resized cap.release() print("Thread Terminated") thread = threading.Thread(target=frameGrabber, args=(secret.RTSP8,), daemon=True) thread.start() cv2.namedWindow("IP Camera", cv2.WINDOW_GUI_NORMAL) cv2.resizeWindow("IP Camera",W,H) cv2.moveWindow("IP Camera",0,60) time.sleep(2) cnt = 0 results = None tStart = time.time() fps = 0 while True: with lock: ipFrameShow = ipFrame.copy() fps = fps*.95 + .05/(time.time()-tStart) tStart = time.time() cnt = cnt + 1 if cnt%2 == 1 or results is None: results=model(ipFrameShow,imgsz=IMG_SZ,conf=CONF_THRES,verbose=False) displayFrame=results[0].plot(img=ipFrameShow) cv2.putText( displayFrame, "FPS: "+str(round(fps,1)), (int(W*.01),int(H*.075)), cv2.FONT_HERSHEY_SIMPLEX, H*.002, (0,0,255), 3, cv2.LINE_AA,) cv2.imshow("IP Camera",displayFrame) if cv2.waitKey(1) == ord('q'): break running = False time.sleep(1) cv2.destroyAllWindows() print("Program Terminated") |