YOLO on Raspberry Pi LESSON 3: YOLO Object Detection Over an IP Security Camera

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:

  1. 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=320 with 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.

  2. 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_OPTIONS to rtsp_transport;tcp tells FFmpeg to use TCP rather than letting UDP packet loss scramble your stream.

  • Dedicated background frameGrabber thread: 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 a threading.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 crisp displayFrame every 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:

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 when frameGrabber writes 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) using cv2.INTER_AREA (great for clean downscaling/sizing) and updates ipFrame inside a with lock: block.

  • When running becomes False, it exits the loop, releases cap, 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:

  1. Grab a thread-safe frame: Locks lock, copies ipFrame into ipFrameShow, and releases the lock immediately so frameGrabber is barely blocked.

  2. 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.

  3. Run YOLO on alternating frames: Increments cnt and runs model(ipFrameShow, imgsz=IMG_SZ, conf=CONF_THRES, verbose=False) when cnt%2 == 1 or on the very first pass (results is None). Reusing the latest results on even frames trades a tiny bit of box-update latency for noticeably higher loop throughput.

  4. 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 press q.

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.