Station open - training dossier Hangar Brief / UAV school Public release - not classified
Aviation dossier Hangar Brief

Home / FPV Video processing with Raspberry Pi

19 Oct 2026

A decoded FPV picture on a V4L2 loopback device

Lab 06 / V4L2 loopback

Blueprint of a ground program writing a decoded FPV picture into a V4L2 loopback device that Python only reads.
SIG-10 – Something else already decoded the picture. This lab only reads the virtual camera.

Purpose

Run the person detector on a picture that some other ground program has already decoded. The Raspberry Pi stays on the bench. The other program writes frames into a virtual camera. This script reads that camera.

Use this when wfb-ng, OpenHD, gstreamer, or ffmpeg already owns the radio or the UDP socket and you do not want a second copy of the depay pipeline. v4l2loopback adds a /dev/videoN node that ordinary OpenCV can open.

Words

  • V4L2 (Video for Linux 2). The Pi's camera interface. Real cameras and fake ones both appear as /dev/videoN.
  • Loopback. A pretend camera. Another program writes frames in. This script reads them out. Nothing is transmitted.
  • wfb-ng (Wi-Fi Broadcast, next generation). An open ground station that already decoded a digital picture.
  • OpenHD. Another open ground station for a high-definition picture. Same idea: it owns the radio, this script owns the pixels.
  • GStreamer and ffmpeg. Two tools that can push a decoded picture into the pretend camera.
  • OpenCV (Open Source Computer Vision Library). Opens /dev/video10 like any other camera.
  • HOG (Histogram of Oriented Gradients). The person model, unchanged from the other labs.
  • UDP (User Datagram Protocol). A packet port. If another program already owns it, this script does not open that port. It only reads the virtual camera.

What you need

sudo apt install python3-opencv v4l2loopback-dkms v4l-utils
sudo modprobe v4l2loopback devices=1 video_nr=10 card_label="FPV loopback" exclusive_caps=1
v4l2-ctl --list-devices

Point the program that already shows the FPV picture at /dev/video10. One gstreamer example that pushes a test pattern (stand-in until your real writer is aimed at the same node):

gst-launch-1.0 videotestsrc ! videoconvert ! v4l2sink device=/dev/video10

A real lab replaces videotestsrc with the depay and decode elements your ground app already uses.

Run

In a second terminal, from this folder:

python3 detect_persons.py --device /dev/video10
python3 detect_persons.py --file sample.mp4

Press q or Esc to stop.

What the code does

open_capture() opens the loopback node with the V4L2 backend and does not force a size unless you pass --width and --height. The writer chooses the real size. PersonDetector is unchanged from the other labs.

Command

python3 detect_persons.py --device /dev/video10

detect_persons.py

#!/usr/bin/env python3
"""Person boxes on a V4L2 loopback device. The Pi stays on the bench.

Another program already decoded the FPV picture and writes it to a virtual
camera such as /dev/video10. This script only reads that device. Typical
writers: gstreamer, ffmpeg, wfb-ng's ground display, or a browser capture
bridged onto v4l2loopback.
"""

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)
    source = args.device
    if str(source).isdigit():
        source = int(source)
    capture = cv2.VideoCapture(source, cv2.CAP_V4L2)
    if args.width:
        capture.set(cv2.CAP_PROP_FRAME_WIDTH, args.width)
    if args.height:
        capture.set(cv2.CAP_PROP_FRAME_HEIGHT, args.height)
    return capture


def main():
    parser = argparse.ArgumentParser(description="Detect people on a V4L2 loopback FPV picture.")
    parser.add_argument("--device", default="/dev/video10", help="Loopback node")
    parser.add_argument("--width", default=0, type=int, help="Optional width hint. 0 keeps the writer's size.")
    parser.add_argument("--height", default=0, type=int, help="Optional height hint.")
    parser.add_argument("--file", default="", help="MP4 to rehearse with no loopback device")
    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.