Lab 05 / HTTP MJPEG
Purpose
Read a Motion-JPEG stream over HTTP on a grounded Raspberry Pi and mark people in the frames.
Use this when a ground recorder, a phone app, or a small receiver already serves the FPV picture as multipart/x-mixed-replace (the usual /video URL). The Pi is a client. It does not transmit video and it does not fly.
Words
- HTTP (Hypertext Transfer Protocol). The same kind of address a browser opens,
http://.... - JPEG (Joint Photographic Experts Group). One compressed still picture.
- MJPEG (Motion JPEG). Many JPEG stills sent one after another so they look like video.
- Multipart. The server marks where one JPEG ends and the next begins. A single
/shot.jpgis not this. The live path usually ends in/video. - URL (Uniform Resource Locator). That full address.
- FFmpeg. The decoder OpenCV uses to turn the JPEG stream into frames.
- OpenCV (Open Source Computer Vision Library). One frame in, person boxes out.
- HOG (Histogram of Oriented Gradients). The person shape model. SVM (Support Vector Machine) is the yes/no classifier inside it.
- VLC. A player. Open the URL there before you open it in Python.
What you need
- An HTTP URL that returns a JPEG stream. Test it in a browser or with VLC first.
- Python 3 and OpenCV with FFmpeg.
sudo apt install python3-opencv ffmpeg
Run
python3 detect_persons.py --url http://192.168.1.50:8080/video
python3 detect_persons.py --file sample.mp4
Press q or Esc to stop.
What the code does
open_capture() passes the URL to cv2.VideoCapture with the FFmpeg backend and a one-frame buffer. Each JPEG that arrives is a frame. PersonDetector draws the boxes. If the URL is a single snapshot rather than a multipart stream, the window will update once and then stall. Point --url at the live stream path, not a still /shot.jpg.
Command
python3 detect_persons.py --url http://192.168.1.50:8080/video
detect_persons.py
#!/usr/bin/env python3
"""Person boxes on an HTTP MJPEG FPV picture. The Pi stays on the bench.
Some ground apps and small receivers serve multipart Motion-JPEG at an
http URL. OpenCV reads that URL the same way it reads a file.
"""
import argparse
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)
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 HTTP MJPEG FPV stream.")
parser.add_argument("--url", default="http://127.0.0.1:8080/video", help="MJPEG HTTP URL")
parser.add_argument("--file", default="", help="MP4 to rehearse with no HTTP 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.