Lab 04 / UDP H.264
Purpose
Read a digital FPV ground link that arrives as H.264 on a UDP port, on a Raspberry Pi that stays on the bench, and draw person boxes.
Two packet shapes are common:
- rtp – RTP-wrapped H.264. wfb-ng and several OpenHD-style ground apps can emit this. Default port in the script is 5600. OpenCV's GStreamer backend pulls the frames. If that backend is missing, the script falls back to an ffmpeg pipe.
- ts – MPEG-TS over UDP (
udp://0.0.0.0:5600). ffmpeg decodes it to raw BGR and the script reads stdout.
The script joins a picture that another program is already sending to this machine. It does not start the aircraft radio.
Words
- H.264, also called AVC (Advanced Video Coding). The compressed video most digital FPV links still send.
- UDP (User Datagram Protocol). A port full of packets. No connection setup. Often port 5600.
- RTP (Real-time Transport Protocol). A wrapper that puts H.264 packets in order and marks time.
--mode rtpexpects this wrapper. - MPEG-TS (MPEG Transport Stream). A different wrapper, the one televisions use.
--mode tsexpects this. The picture inside is still H.264. - GStreamer. A toolkit that builds a pipe: UDP in, unwrap, decode, hand frames to Python.
appsinkis the end of that pipe. - ffmpeg. The fallback decoder. It writes raw pixels to this script.
- BGR (Blue, Green, Red). The pixel order OpenCV wants. Not the red-green-blue order some other libraries use.
- OpenCV (Open Source Computer Vision Library). Reads those pixels and draws the boxes.
- HOG (Histogram of Oriented Gradients). The person shape model shared with the other labs.
What you need
sudo apt install python3-opencv ffmpeg gstreamer1.0-tools gstreamer1.0-libav v4l-utils
python3 -c "import cv2; print(cv2.getBuildInformation())" | head
Look for GStreamer: YES if you want the RTP path without the ffmpeg fallback. Width and height for --mode ts must match the stream. A mismatch paints diagonal garbage.
Run
python3 detect_persons.py --mode rtp --port 5600
python3 detect_persons.py --mode ts --port 5600 --width 1280 --height 720
python3 detect_persons.py --file sample.mp4
Press q or Esc to stop.
What the code does
open_rtp() builds a GStreamer pipeline: UDP in, RTP depay, H.264 decode, BGR frames into OpenCV. FfmpegPipe is a small stand-in for VideoCapture so show_stream() can use either source. PersonDetector is the shared HOG model in ../common.
Command
python3 detect_persons.py --mode rtp --port 5600
detect_persons.py
#!/usr/bin/env python3
"""Person boxes on a UDP H.264 FPV feed. The Pi stays on the bench.
Two shapes show up from digital ground links (wfb-ng, OpenHD, and similar):
- rtp: RTP H.264 packets on a UDP port (GStreamer inside OpenCV)
- ts: MPEG-TS over UDP, decoded by ffmpeg into raw frames
If the GStreamer backend is missing, rtp mode falls back to the ffmpeg pipe.
"""
import argparse
import subprocess
import sys
from pathlib import Path
import cv2
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common.person_detector import PersonDetector, show_stream
RTP_PIPELINE = (
"udpsrc port={port} buffer-size=212992 ! "
"application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96 ! "
"rtph264depay ! h264parse ! avdec_h264 ! videoconvert ! "
"video/x-raw,format=BGR ! appsink drop=1 sync=false"
)
class FfmpegPipe:
"""A capture object with the same read/release shape as VideoCapture."""
def __init__(self, url, width, height):
self.width = int(width)
self.height = int(height)
self.frame_bytes = self.width * self.height * 3
self.proc = subprocess.Popen(
[
"ffmpeg",
"-loglevel", "error",
"-fflags", "nobuffer",
"-flags", "low_delay",
"-i", url,
"-an",
"-f", "rawvideo",
"-pix_fmt", "bgr24",
"-s", "{}x{}".format(self.width, self.height),
"-",
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
def isOpened(self):
return self.proc.poll() is None
def read(self):
raw = self.proc.stdout.read(self.frame_bytes)
if len(raw) != self.frame_bytes:
return False, None
frame = np.frombuffer(raw, dtype=np.uint8).reshape((self.height, self.width, 3))
return True, frame.copy()
def release(self):
if self.proc.poll() is None:
self.proc.kill()
self.proc.wait(timeout=2)
def open_rtp(port):
capture = cv2.VideoCapture(RTP_PIPELINE.format(port=int(port)), cv2.CAP_GSTREAMER)
if capture.isOpened():
return capture
capture.release()
print("OpenCV has no GStreamer backend. Falling back to ffmpeg on udp://0.0.0.0:{}".format(port))
return None
def open_capture(args):
if args.file:
return cv2.VideoCapture(args.file)
if args.mode == "rtp":
capture = open_rtp(args.port)
if capture is not None:
return capture
url = "udp://0.0.0.0:{}?overrun_nonfatal=1&fifo_size=50000000".format(args.port)
return FfmpegPipe(url, args.width, args.height)
url = args.url or "udp://0.0.0.0:{}?overrun_nonfatal=1&fifo_size=50000000".format(args.port)
return FfmpegPipe(url, args.width, args.height)
def main():
parser = argparse.ArgumentParser(description="Detect people on a UDP H.264 FPV feed.")
parser.add_argument("--mode", default="rtp", choices=("rtp", "ts"))
parser.add_argument("--port", default=5600, type=int)
parser.add_argument("--url", default="", help="Override the ffmpeg UDP URL in ts mode")
parser.add_argument("--width", default=1280, type=int, help="Frame width for the ffmpeg pipe")
parser.add_argument("--height", default=720, type=int, help="Frame height for the ffmpeg pipe")
parser.add_argument("--file", default="", help="MP4 to rehearse with no UDP source")
parser.add_argument("--max-width", default=480, type=int)
args = parser.parse_args()
show_stream(open_capture(args), PersonDetector(max_width=args.max_width))
if __name__ == "__main__":
main()
common/person_detector.py
#!/usr/bin/env python3
"""Mark people in one video frame.
The detector is the HOG + SVM person model that ships inside OpenCV.
No weight file to download. On a Raspberry Pi the search is slow, so each
frame is narrowed before the scan and the boxes are drawn back on the
full picture.
This file does not open a radio, a camera, or a network port. Each lab
opens its own picture source and calls PersonDetector.
"""
import time
import cv2
def _as_float(value):
if hasattr(value, "ravel"):
flat = value.ravel()
if len(flat):
return float(flat[0])
return float(value)
class PersonDetector:
"""Find people in a BGR frame and draw a box around each one."""
def __init__(self, max_width=480, hit_threshold=0.0):
self.hog = cv2.HOGDescriptor()
self.hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
self.max_width = int(max_width)
self.hit_threshold = float(hit_threshold)
def detect(self, frame):
"""Return (x, y, w, h, score) boxes in the original frame."""
height, width = frame.shape[:2]
scale = 1.0
work = frame
if width > self.max_width and self.max_width > 0:
scale = self.max_width / float(width)
work = cv2.resize(frame, (self.max_width, max(1, int(height * scale))))
rects, weights = self.hog.detectMultiScale(
work,
winStride=(8, 8),
padding=(8, 8),
scale=1.05,
hitThreshold=self.hit_threshold,
)
boxes = []
inv = 1.0 / scale
for rect, weight in zip(rects, weights):
x, y, w, h = rect
boxes.append((int(x * inv), int(y * inv), int(w * inv), int(h * inv), _as_float(weight)))
return boxes
def draw(self, frame, boxes):
for x, y, w, h, score in boxes:
cv2.rectangle(frame, (x, y), (x + w, y + h), (80, 180, 70), 2)
cv2.putText(
frame,
"person {:.2f}".format(score),
(x, max(18, y - 6)),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(80, 180, 70),
1,
cv2.LINE_AA,
)
cv2.putText(
frame,
"persons {}".format(len(boxes)),
(12, 28),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(230, 220, 180),
2,
cv2.LINE_AA,
)
return frame
def show_stream(capture, detector, window_name="FPV persons"):
"""Read until the picture ends or the operator presses q or Esc.
capture must provide isOpened(), read() -> (ok, frame), and release().
A cv2.VideoCapture does. The UDP lab's ffmpeg pipe does too.
"""
if capture is None or not capture.isOpened():
raise SystemExit("No picture. Check the source, then run again.")
last = time.time()
frames = 0
try:
while True:
ok, frame = capture.read()
if not ok or frame is None:
time.sleep(0.05)
continue
boxes = detector.detect(frame)
detector.draw(frame, boxes)
frames += 1
now = time.time()
if now - last >= 1.0:
print("frames/s {:.1f} persons {}".format(frames / (now - last), len(boxes)))
frames = 0
last = now
cv2.imshow(window_name, frame)
key = cv2.waitKey(1) & 0xFF
if key in (ord("q"), 27):
break
finally:
capture.release()
cv2.destroyAllWindows()
Copy both files, keep person_detector.py in a common folder next to the lab folder, and run the command above from the lab folder. Props off while you prove the picture. The Pi stays on the ground.