Lab 03 / RTSP and RTMP
Purpose
Open a network video URL on a grounded Raspberry Pi and run the person detector. Use this when the ground side already publishes the FPV picture, instead of a USB dongle.
Two URL schemes land in the same OpenCV call:
rtsp://from a digital ground unit, an NVR, or MediaMTXrtmp://from a restreamer that pushes or hosts an RTMP app
The Pi subscribes. It does not bind the aircraft radio and it does not send stick packets.
Words
- RTSP (Real Time Streaming Protocol). A common way for a camera or ground unit to say "the live picture is at this address."
- RTMP (Real Time Messaging Protocol). An older streaming address, still used by restreamers. Same OpenCV call, different letters at the front of the URL.
- URL (Uniform Resource Locator). The address, such as
rtsp://192.168.1.40:8554/fpv. - LAN (Local Area Network). The bench network between the ground unit and the Pi. This lab does not cross the internet.
- UDP (User Datagram Protocol). Packets with no handshake. Faster, and a lost packet stays lost. The usual RTSP transport.
- TCP (Transmission Control Protocol). A handshake and retries. Use it when UDP picture falls apart on a busy network.
- FFmpeg. The program inside OpenCV that decodes the stream.
CAP_FFMPEGis OpenCV's name for that door. - VLC. A player you use first, to prove the URL works before Python touches it.
- NVR (Network Video Recorder). A box that already stores or republishes a camera picture.
- OpenCV (Open Source Computer Vision Library). The library that opens the URL and draws the boxes.
- HOG (Histogram of Oriented Gradients). The person shape model this lab uses.
What you need
- A URL that already plays in VLC on the same Pi (
vlc rtsp://...) - Python 3 and an OpenCV build with FFmpeg (
cv2.getBuildInformation()should mention ffmpeg)
sudo apt install python3-opencv ffmpeg
Run
python3 detect_persons.py --url rtsp://192.168.1.40:8554/fpv
python3 detect_persons.py --url rtsp://192.168.1.40:8554/fpv --transport tcp
python3 detect_persons.py --url rtmp://192.168.1.40/live/fpv
python3 detect_persons.py --file sample.mp4
--transport only changes the RTSP hint (OPENCV_FFMPEG_CAPTURE_OPTIONS). RTMP ignores it. Press q or Esc to stop.
What the code does
open_capture() sets a one-frame buffer so the window does not sit on a stale queue, then opens the URL with cv2.CAP_FFMPEG. The shared PersonDetector scans each frame that arrives.
If VLC plays the URL and this script does not, the OpenCV package was built without FFmpeg. Use the apt package python3-opencv on Raspberry Pi OS rather than a headless wheel.
Command
python3 detect_persons.py --url rtsp://192.168.1.40:8554/fpv
detect_persons.py
#!/usr/bin/env python3
"""Person boxes on an RTSP or RTMP FPV restream. The Pi stays on the bench.
Some ground receivers, NVRs, and restreamers (MediaMTX and similar) publish
the picture as rtsp:// or rtmp://. This script only opens that URL.
"""
import argparse
import os
import sys
from pathlib import Path
import cv2
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common.person_detector import PersonDetector, show_stream
def open_capture(args):
if args.file:
return cv2.VideoCapture(args.file)
# Ask ffmpeg inside OpenCV to prefer UDP for RTSP unless you override it.
os.environ.setdefault("OPENCV_FFMPEG_CAPTURE_OPTIONS", "rtsp_transport;{}".format(args.transport))
capture = cv2.VideoCapture(args.url, cv2.CAP_FFMPEG)
capture.set(cv2.CAP_PROP_BUFFERSIZE, 1)
return capture
def main():
parser = argparse.ArgumentParser(description="Detect people on an RTSP or RTMP FPV URL.")
parser.add_argument("--url", default="rtsp://127.0.0.1:8554/fpv", help="rtsp:// or rtmp:// address")
parser.add_argument("--transport", default="udp", choices=("udp", "tcp"), help="RTSP transport")
parser.add_argument("--file", default="", help="MP4 to rehearse with no network receiver")
parser.add_argument("--max-width", default=480, type=int, help="Detector width. Lower is faster on a Pi.")
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.