TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Project 7: Real-Time Video Analytics

Project 7: Real-Time Video Analytics

A city wants to know how many vehicles pass a junction in each direction and to be warned when a vehicle crawls through a bus stop zone. Nobody will watch the video: the system must turn a camera stream into a few events ("vehicle 12 crossed the line eastbound at 3.52 s", "vehicle 20 spent 1.28 s in the zone") as the frames arrive, on a fixed compute budget. This is video analytics: detection and tracking are only the middle of the pipeline, and the parts around them (events, a latency budget, what to do when the hardware is too slow) decide whether it works.

You build the whole pipeline in this project: a streaming source, a detector, a compact SORT-style tracker, line-crossing and dwell-time events written as JSON lines, a latency budget computed from a fixed cost model, the effect of skipping frames, and a comparison of stream and batch processing. The tracker is the one from multi-object tracking, reduced to its core (constant-velocity prediction without the Kalman covariance, IoU cost, Hungarian matching, min_hits, max_age); read that lesson for the full version and the tracking metrics.

Note: Traffic cameras see people and number plates. Counting vehicles needs neither, so a privacy-friendly design processes frames on the device, emits only counts and anonymous track numbers, and stores no video (privacy, consent and licensing). The video here is synthetic.

Goal and success criteria

Item Target
Input a 25 fps stream, 160 x 90 pixels, three lanes (eastbound, westbound, slow eastbound)
Events line crossings per direction at x=80x = 80; dwell time in the zone 100≤x<140100 \le x < 140, alert above 1 s
Output one JSON object per event (JSON lines), as the frames arrive
Accuracy crossing counts and alerts equal to the ground truth on the test clip
Budget mean processing time per frame within 1000/25=401000 / 25 = 40 ms by the cost model; extra delay of a count under 1 s
line x = 80zone 100-140 east, 2.5 px/framewest, 3.0 px/frameeast, 1.2 px/frame camera25 fps decodeevery frame detectevery k-th trackids, velocity eventsline, zone JSON linesevent log sum of stage costs per frame must stay within 1000 / fps = 40 ms

Step 1: a stream and a detector

The source is a variant of the course's make_video: vehicles enter on three lanes at random times and drive across at a constant speed per lane, for 240 frames (9.6 s at 25 fps). It is written as a Python generator: it yields one frame and its ground truth at a time, like a camera, so the pipeline can never peek at future frames and holds one frame in memory. The detector thresholds the bright vehicles and takes connected components (morphology and contours); to behave like a real detector it is made imperfect on purpose: it misses 10 % of the objects, jitters box edges by a pixel, and produces a false alarm in 5 % of the frames.

python · try it yourself
import numpy as np
import cv2
from scipy.optimize import linear_sum_assignment
cv2.setLogLevel(0)

FPS, W, H = 25, 160, 90
LANES = [(12, 2.5), (40, -3.0), (66, 1.2)]          # (top row, pixels per frame): east, west, slow east

def traffic_stream(rng, n_frames=240):
    """Project variant of make_video: vehicles enter on three lanes at random times and drive across.
    A generator: yields (t, frame, ground truth [(vehicle id, [x1, y1, x2, y2]), ...]) one frame at a time."""
    vehicles = []
    for y, v in LANES:
        t0 = int(rng.integers(0, 20))
        while t0 < n_frames - 20:
            vehicles.append(dict(id=len(vehicles), t0=t0, y=y + int(rng.integers(-2, 3)), v=v,
                                 w=int(rng.integers(14, 24)), h=int(rng.integers(8, 12)), g=int(rng.integers(170, 250))))
            t0 += int(rng.integers(35, 70))
    for t in range(n_frames):
        f = rng.normal(60, 6, (H, W))
        gt = []
        for o in vehicles:
            if t < o["t0"]:
                continue
            dist = abs(o["v"]) * (t - o["t0"])
            x1 = int(round(dist - o["w"])) if o["v"] > 0 else int(round(W - dist))
            if x1 >= W or x1 + o["w"] <= 0:
                continue
            f[o["y"]:o["y"] + o["h"], max(x1, 0):x1 + o["w"]] = o["g"]
            gt.append((o["id"], [max(x1, 0), o["y"], min(x1 + o["w"], W), o["y"] + o["h"]]))
        yield t, f.clip(0, 255).astype(np.uint8), gt

def detect(frame, rng, p_miss=0.1, p_false=0.05):
    """Threshold + connected components, made imperfect on purpose: misses, 1 px jitter, false alarms."""
    n, _, stats, _ = cv2.connectedComponentsWithStats((frame > 120).astype(np.uint8), connectivity=4)
    boxes = []
    for x, y, w, h, area in stats[1:].tolist():
        if area >= 30 and w >= 4 and rng.random() > p_miss:
            boxes.append([x + int(rng.integers(-1, 2)), y, x + w + int(rng.integers(-1, 2)), y + h])
    if rng.random() < p_false:
        x, y = int(rng.integers(0, W - 16)), int(rng.integers(0, H - 10))
        boxes.append([x, y, x + 16, y + 10])
    return boxes

def iou_matrix(a, b):
    a, b = np.asarray(a, float)[:, None], np.asarray(b, float)[None]
    iw = (np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0])).clip(0)
    ih = (np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1])).clip(0)
    inter = iw * ih
    area = lambda x: (x[..., 2] - x[..., 0]) * (x[..., 3] - x[..., 1])
    return inter / (area(a) + area(b) - inter)

rng, det_rng = np.random.default_rng(0), np.random.default_rng(100)
stream = traffic_stream(rng)
print("a generator, not an array:", type(stream).__name__)
tp = fp = fn = 0
vehicles, frames = set(), 0
for t, frame, gt in stream:
    frames += 1
    vehicles |= {vid for vid, _ in gt}
    dets = detect(frame, det_rng)
    boxes = [b for _, b in gt if (b[2] - b[0]) * (b[3] - b[1]) >= 30]      # objects the detector can see
    if boxes and dets:
        iou = iou_matrix(boxes, dets)
        r, c = linear_sum_assignment(-iou)
        hits = int((iou[r, c] >= 0.5).sum())
    else:
        hits = 0
    tp += hits; fn += len(boxes) - hits; fp += len(dets) - hits
print(f"{frames} frames of {frame.shape}, {frame.nbytes} bytes each; the whole clip would be {frames * frame.nbytes} bytes")
print(f"{len(vehicles)} vehicles; detector over all frames: precision {tp / (tp + fp):.3f}, recall {tp / (tp + fn):.3f} (IoU >= 0.5)")
a generator, not an array: generator
240 frames of (90, 160), 14400 bytes each; the whole clip would be 3456000 bytes
14 vehicles; detector over all frames: precision 0.982, recall 0.902 (IoU >= 0.5)

The pipeline holds one 14,400-byte frame at a time instead of the 3.5 MB clip; at 1920 x 1080 in colour a single frame is already 6.2 MB, and a minute of video over 9 GB, which is why analytics pipelines stream. The detector finds 90.2 % of the visible vehicle boxes at IoU 0.5 (the designed 10 % misses) with precision 0.982 (the occasional false alarm). Fourteen vehicles drive through the 9.6-second clip.

Step 2: detect, track, count

Events are computed from tracks, not detections: a vehicle crosses the line once, but it is detected in dozens of frames. The event rules:

  • Line crossing: a confirmed track whose box centre moves from one side of x=80x = 80 to the other, counted once per track (box jitter can move a centre back and forth across the line, which would otherwise count the same vehicle twice).
  • Dwell: the time between the first and the last frame in which the track's centre is inside the zone, plus one frame, reported when the track is first seen outside again; an alert if it exceeds 1 s. Using the first and last time seen, not a count of frames, makes the dwell time robust to missed detections.

The same rules are applied to the ground-truth boxes, so the pipeline's events can be compared one to one with the true ones. Every event is a flat dictionary, printed as one JSON line, ready for a message queue or a log file.

python · try it yourself
import json
import numpy as np
import cv2
from scipy.optimize import linear_sum_assignment
cv2.setLogLevel(0)

FPS, W, H = 25, 160, 90
LANES = [(12, 2.5), (40, -3.0), (66, 1.2)]          # (top row, pixels per frame): east, west, slow east

def traffic_stream(rng, n_frames=240):
    """Project variant of make_video: vehicles enter on three lanes at random times and drive across.
    A generator: yields (t, frame, ground truth [(vehicle id, [x1, y1, x2, y2]), ...]) one frame at a time."""
    vehicles = []
    for y, v in LANES:
        t0 = int(rng.integers(0, 20))
        while t0 < n_frames - 20:
            vehicles.append(dict(id=len(vehicles), t0=t0, y=y + int(rng.integers(-2, 3)), v=v,
                                 w=int(rng.integers(14, 24)), h=int(rng.integers(8, 12)), g=int(rng.integers(170, 250))))
            t0 += int(rng.integers(35, 70))
    for t in range(n_frames):
        f = rng.normal(60, 6, (H, W))
        gt = []
        for o in vehicles:
            if t < o["t0"]:
                continue
            dist = abs(o["v"]) * (t - o["t0"])
            x1 = int(round(dist - o["w"])) if o["v"] > 0 else int(round(W - dist))
            if x1 >= W or x1 + o["w"] <= 0:
                continue
            f[o["y"]:o["y"] + o["h"], max(x1, 0):x1 + o["w"]] = o["g"]
            gt.append((o["id"], [max(x1, 0), o["y"], min(x1 + o["w"], W), o["y"] + o["h"]]))
        yield t, f.clip(0, 255).astype(np.uint8), gt

def detect(frame, rng, p_miss=0.1, p_false=0.05):
    """Threshold + connected components, made imperfect on purpose: misses, 1 px jitter, false alarms."""
    n, _, stats, _ = cv2.connectedComponentsWithStats((frame > 120).astype(np.uint8), connectivity=4)
    boxes = []
    for x, y, w, h, area in stats[1:].tolist():
        if area >= 30 and w >= 4 and rng.random() > p_miss:
            boxes.append([x + int(rng.integers(-1, 2)), y, x + w + int(rng.integers(-1, 2)), y + h])
    if rng.random() < p_false:
        x, y = int(rng.integers(0, W - 16)), int(rng.integers(0, H - 10))
        boxes.append([x, y, x + 16, y + 10])
    return boxes

def iou_matrix(a, b):
    a, b = np.asarray(a, float)[:, None], np.asarray(b, float)[None]
    iw = (np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0])).clip(0)
    ih = (np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1])).clip(0)
    inter = iw * ih
    area = lambda x: (x[..., 2] - x[..., 0]) * (x[..., 3] - x[..., 1])
    return inter / (area(a) + area(b) - inter)

class Tracker:
    """Compact SORT-style tracker: constant-velocity prediction, IoU + Hungarian matching; a track is
    reported after min_hits matches and deleted after max_age processed frames without one."""
    def __init__(self, iou_thr=0.1, max_age=3, min_hits=2):
        self.iou_thr, self.max_age, self.min_hits = iou_thr, max_age, min_hits
        self.tracks, self.next_id = [], 1

    def step(self, dets, dt=1):
        for tr in self.tracks:
            tr["since"] += dt
        dets = [np.array(d, float) for d in dets]
        used_t, used_d = set(), set()
        if self.tracks and dets:
            iou = iou_matrix([tr["last"] + tr["vel"] * tr["since"] for tr in self.tracks], dets)
            for i, j in zip(*linear_sum_assignment(-iou)):
                if iou[i, j] >= self.iou_thr:
                    tr = self.tracks[i]
                    v = (dets[j] - tr["last"]) / tr["since"]
                    tr["vel"] = v if tr["hits"] == 1 else 0.5 * tr["vel"] + 0.5 * v
                    tr["last"], tr["since"], tr["misses"] = dets[j], 0, 0
                    tr["hits"] += 1
                    used_t.add(i); used_d.add(j)
        for i, tr in enumerate(self.tracks):
            if i not in used_t:
                tr["misses"] += 1
        self.tracks = [tr for tr in self.tracks if tr["misses"] <= self.max_age]
        for j, d in enumerate(dets):
            if j not in used_d:
                self.tracks.append(dict(id=self.next_id, last=d, vel=np.zeros(4), since=0, misses=0, hits=1))
                self.next_id += 1
        return [(tr["id"], tr["last"]) for tr in self.tracks if tr["since"] == 0 and tr["hits"] >= self.min_hits]

LINE_X, ZONE, SLOW_S = 80, (100, 140), 1.0          # counting line, dwell zone (x range), alert above 1 s

class Events:
    """Line crossings (once per track) and dwell time in the zone; every event is a dict (one JSON line)."""
    def __init__(self):
        self.last_cx, self.crossed, self.zone, self.log = {}, set(), {}, []

    def update(self, t, tracks, dt=1):
        for tid, box in tracks:
            cx = (box[0] + box[2]) / 2
            prev = self.last_cx.get(tid)
            if prev is not None and tid not in self.crossed and (prev < LINE_X) != (cx < LINE_X):
                self.crossed.add(tid)
                self.log.append({"t": round(t / FPS, 2), "event": "line_cross", "track": int(tid),
                                 "dir": "east" if cx > prev else "west"})
            self.last_cx[tid] = cx
            if ZONE[0] <= cx < ZONE[1]:                          # inside: remember first and last time seen
                first, _ = self.zone.get(tid, (t, t))
                self.zone[tid] = (first, t)
            elif tid in self.zone:                               # first sighting after leaving the zone
                first, last = self.zone.pop(tid)
                s = round((last - first + dt) / FPS, 2)
                self.log.append({"t": round(t / FPS, 2), "event": "dwell", "track": int(tid), "seconds": s,
                                 "alert": s > SLOW_S})

    def summary(self):
        cross = [e for e in self.log if e["event"] == "line_cross"]
        dwell = [e for e in self.log if e["event"] == "dwell"]
        return dict(east=sum(e["dir"] == "east" for e in cross), west=sum(e["dir"] == "west" for e in cross),
                    dwell=len(dwell), alerts=sum(e["alert"] for e in dwell))

rng, det_rng = np.random.default_rng(0), np.random.default_rng(100)
tracker, events, truth = Tracker(), Events(), Events()
vehicles, confirmed = set(), set()
for t, frame, gt in traffic_stream(rng):                  # one frame at a time, as from a camera
    truth.update(t, [(vid, np.array(box, float)) for vid, box in gt])    # the same rules on the ground truth
    vehicles |= {vid for vid, _ in gt}
    tracks = tracker.step(detect(frame, det_rng))
    confirmed |= {tid for tid, _ in tracks}
    events.update(t, tracks)
print(f"{len(vehicles)} vehicles in the clip, {len(confirmed)} confirmed track ids")
print("pipeline    :", events.summary())
print("ground truth:", truth.summary())
print("event log, first 5 JSON lines:")
for e in events.log[:5]:
    print(json.dumps(e))
dwell = lambda ev: sorted(e["seconds"] for e in ev.log if e["event"] == "dwell")
print("dwell seconds, pipeline    :", dwell(events))
print("dwell seconds, ground truth:", dwell(truth))
14 vehicles in the clip, 14 confirmed track ids
pipeline    : {'east': 7, 'west': 5, 'dwell': 11, 'alerts': 2}
ground truth: {'east': 7, 'west': 5, 'dwell': 11, 'alerts': 2}
event log, first 5 JSON lines:
{"t": 1.4, "event": "dwell", "track": 3, "seconds": 0.48, "alert": false}
{"t": 1.68, "event": "line_cross", "track": 3, "dir": "west"}
{"t": 2.12, "event": "line_cross", "track": 5, "dir": "east"}
{"t": 3.04, "event": "dwell", "track": 7, "seconds": 0.48, "alert": false}
{"t": 3.08, "event": "dwell", "track": 5, "seconds": 0.64, "alert": false}
dwell seconds, pipeline    : [0.48, 0.48, 0.52, 0.52, 0.56, 0.6, 0.64, 0.64, 0.68, 1.28, 1.32]
dwell seconds, ground truth: [0.52, 0.52, 0.52, 0.52, 0.56, 0.64, 0.64, 0.64, 0.64, 1.32, 1.32]

The tracker gives exactly one confirmed id per vehicle (14 and 14) despite the 10 % misses, and the counts (7 eastbound, 5 westbound) and the 2 slow-vehicle alerts match the ground truth. The dwell times agree to within 0.04 s, one frame: box jitter and missed detections at the zone edges shift the first or last sighting by a frame. The log shows the format downstream systems receive; note that track 3 is reported in the zone at 1.4 s before its line crossing at 1.68 s, because it is a westbound vehicle, which meets the zone (x 100 to 140) first.

Step 3: the latency budget

At 25 fps a new frame arrives every 40 ms. If processing a frame takes longer on average, a queue builds up without limit and the "real-time" counts drift ever later. The budget is checked here with a fixed cost model: assumed costs per operation for one CPU core, multiplied by the operation counts of the run. Timing the code itself would give different numbers on every machine (and in a browser), while the cost model makes the arithmetic reproducible; on real hardware you measure the constants once, per stage, and plug them in.

Stage Assumed cost Counted per
decode 1.0 ms every input frame
detect: threshold + blobs 2.0 ms processed frame
detect: small CNN (a nano-size detector at low resolution on a CPU) 60.0 ms processed frame
track 0.1 ms + 0.05 ms per detection processed frame
events 0.02 ms per reported track + 0.2 ms per logged event processed frame
python · try it yourself
import json
import numpy as np
import cv2
from scipy.optimize import linear_sum_assignment
cv2.setLogLevel(0)

FPS, W, H = 25, 160, 90
LANES = [(12, 2.5), (40, -3.0), (66, 1.2)]          # (top row, pixels per frame): east, west, slow east

def traffic_stream(rng, n_frames=240):
    """Project variant of make_video: vehicles enter on three lanes at random times and drive across.
    A generator: yields (t, frame, ground truth [(vehicle id, [x1, y1, x2, y2]), ...]) one frame at a time."""
    vehicles = []
    for y, v in LANES:
        t0 = int(rng.integers(0, 20))
        while t0 < n_frames - 20:
            vehicles.append(dict(id=len(vehicles), t0=t0, y=y + int(rng.integers(-2, 3)), v=v,
                                 w=int(rng.integers(14, 24)), h=int(rng.integers(8, 12)), g=int(rng.integers(170, 250))))
            t0 += int(rng.integers(35, 70))
    for t in range(n_frames):
        f = rng.normal(60, 6, (H, W))
        gt = []
        for o in vehicles:
            if t < o["t0"]:
                continue
            dist = abs(o["v"]) * (t - o["t0"])
            x1 = int(round(dist - o["w"])) if o["v"] > 0 else int(round(W - dist))
            if x1 >= W or x1 + o["w"] <= 0:
                continue
            f[o["y"]:o["y"] + o["h"], max(x1, 0):x1 + o["w"]] = o["g"]
            gt.append((o["id"], [max(x1, 0), o["y"], min(x1 + o["w"], W), o["y"] + o["h"]]))
        yield t, f.clip(0, 255).astype(np.uint8), gt

def detect(frame, rng, p_miss=0.1, p_false=0.05):
    """Threshold + connected components, made imperfect on purpose: misses, 1 px jitter, false alarms."""
    n, _, stats, _ = cv2.connectedComponentsWithStats((frame > 120).astype(np.uint8), connectivity=4)
    boxes = []
    for x, y, w, h, area in stats[1:].tolist():
        if area >= 30 and w >= 4 and rng.random() > p_miss:
            boxes.append([x + int(rng.integers(-1, 2)), y, x + w + int(rng.integers(-1, 2)), y + h])
    if rng.random() < p_false:
        x, y = int(rng.integers(0, W - 16)), int(rng.integers(0, H - 10))
        boxes.append([x, y, x + 16, y + 10])
    return boxes

def iou_matrix(a, b):
    a, b = np.asarray(a, float)[:, None], np.asarray(b, float)[None]
    iw = (np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0])).clip(0)
    ih = (np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1])).clip(0)
    inter = iw * ih
    area = lambda x: (x[..., 2] - x[..., 0]) * (x[..., 3] - x[..., 1])
    return inter / (area(a) + area(b) - inter)

class Tracker:
    """Compact SORT-style tracker: constant-velocity prediction, IoU + Hungarian matching; a track is
    reported after min_hits matches and deleted after max_age processed frames without one."""
    def __init__(self, iou_thr=0.1, max_age=3, min_hits=2):
        self.iou_thr, self.max_age, self.min_hits = iou_thr, max_age, min_hits
        self.tracks, self.next_id = [], 1

    def step(self, dets, dt=1):
        for tr in self.tracks:
            tr["since"] += dt
        dets = [np.array(d, float) for d in dets]
        used_t, used_d = set(), set()
        if self.tracks and dets:
            iou = iou_matrix([tr["last"] + tr["vel"] * tr["since"] for tr in self.tracks], dets)
            for i, j in zip(*linear_sum_assignment(-iou)):
                if iou[i, j] >= self.iou_thr:
                    tr = self.tracks[i]
                    v = (dets[j] - tr["last"]) / tr["since"]
                    tr["vel"] = v if tr["hits"] == 1 else 0.5 * tr["vel"] + 0.5 * v
                    tr["last"], tr["since"], tr["misses"] = dets[j], 0, 0
                    tr["hits"] += 1
                    used_t.add(i); used_d.add(j)
        for i, tr in enumerate(self.tracks):
            if i not in used_t:
                tr["misses"] += 1
        self.tracks = [tr for tr in self.tracks if tr["misses"] <= self.max_age]
        for j, d in enumerate(dets):
            if j not in used_d:
                self.tracks.append(dict(id=self.next_id, last=d, vel=np.zeros(4), since=0, misses=0, hits=1))
                self.next_id += 1
        return [(tr["id"], tr["last"]) for tr in self.tracks if tr["since"] == 0 and tr["hits"] >= self.min_hits]

LINE_X, ZONE, SLOW_S = 80, (100, 140), 1.0          # counting line, dwell zone (x range), alert above 1 s

class Events:
    """Line crossings (once per track) and dwell time in the zone; every event is a dict (one JSON line)."""
    def __init__(self):
        self.last_cx, self.crossed, self.zone, self.log = {}, set(), {}, []

    def update(self, t, tracks, dt=1):
        for tid, box in tracks:
            cx = (box[0] + box[2]) / 2
            prev = self.last_cx.get(tid)
            if prev is not None and tid not in self.crossed and (prev < LINE_X) != (cx < LINE_X):
                self.crossed.add(tid)
                self.log.append({"t": round(t / FPS, 2), "event": "line_cross", "track": int(tid),
                                 "dir": "east" if cx > prev else "west"})
            self.last_cx[tid] = cx
            if ZONE[0] <= cx < ZONE[1]:                          # inside: remember first and last time seen
                first, _ = self.zone.get(tid, (t, t))
                self.zone[tid] = (first, t)
            elif tid in self.zone:                               # first sighting after leaving the zone
                first, last = self.zone.pop(tid)
                s = round((last - first + dt) / FPS, 2)
                self.log.append({"t": round(t / FPS, 2), "event": "dwell", "track": int(tid), "seconds": s,
                                 "alert": s > SLOW_S})

    def summary(self):
        cross = [e for e in self.log if e["event"] == "line_cross"]
        dwell = [e for e in self.log if e["event"] == "dwell"]
        return dict(east=sum(e["dir"] == "east" for e in cross), west=sum(e["dir"] == "west" for e in cross),
                    dwell=len(dwell), alerts=sum(e["alert"] for e in dwell))

def run(k=1, seed=0):
    """Stream the clip once, detecting and tracking every k-th frame; ground-truth events on every frame."""
    rng, det_rng = np.random.default_rng(seed), np.random.default_rng(seed + 100)
    tracker, events, truth = Tracker(), Events(), Events()
    stats, ids = dict(frames=0, processed=0, dets=0, tracks=0), set()
    for t, frame, gt in traffic_stream(rng):
        stats["frames"] += 1
        truth.update(t, [(vid, np.array(box, float)) for vid, box in gt])
        if t % k:
            continue                                      # skipped: decoded, but not analysed
        stats["processed"] += 1
        dets = detect(frame, det_rng)
        tracks = tracker.step(dets, dt=k)
        stats["dets"] += len(dets); stats["tracks"] += len(tracks)
        ids |= {tid for tid, _ in tracks}
        events.update(t, tracks, dt=k)
    stats["events"], stats["ids"] = len(events.log), len(ids)
    return events, truth, stats

# Fixed cost model in milliseconds (assumed numbers for one CPU core; measure your own hardware)
COST_MS = {"decode": 1.0, "detect": {"threshold + blobs": 2.0, "small CNN": 60.0},
           "track_base": 0.1, "track_per_det": 0.05, "events_per_track": 0.02, "log_per_event": 0.2}
BUDGET_MS = 1000 / FPS                                    # 40 ms per frame at 25 fps

def cost_per_frame(stats, detector):
    c = COST_MS
    total = {"decode": c["decode"] * stats["frames"],
             "detect": c["detect"][detector] * stats["processed"],
             "track": c["track_base"] * stats["processed"] + c["track_per_det"] * stats["dets"],
             "events": c["events_per_track"] * stats["tracks"] + c["log_per_event"] * stats["events"]}
    return {name: v / stats["frames"] for name, v in total.items()}

events, truth, stats = run(k=1)
print("counts over the clip:", stats)
for detector in COST_MS["detect"]:
    per = cost_per_frame(stats, detector)
    total = sum(per.values())
    parts = ", ".join(f"{name} {ms:.2f}" for name, ms in per.items())
    print(f"{detector:17s}: {parts} -> {total:.2f} ms per frame of a {BUDGET_MS:.0f} ms budget "
          f"({'real time' if total <= BUDGET_MS else 'TOO SLOW'}, at most {1000 / total:.0f} fps)")
counts over the clip: {'frames': 240, 'processed': 240, 'dets': 955, 'tracks': 924, 'events': 23, 'ids': 14}
threshold + blobs: decode 1.00, detect 2.00, track 0.30, events 0.10 -> 3.40 ms per frame of a 40 ms budget (real time, at most 295 fps)
small CNN        : decode 1.00, detect 60.00, track 0.30, events 0.10 -> 61.40 ms per frame of a 40 ms budget (TOO SLOW, at most 16 fps)

The classical detector leaves the budget almost untouched (3.40 ms of 40, enough for 295 fps). The CNN detector alone takes 60 of the 61.40 ms: the pipeline could sustain only 16 fps, so at 25 fps the queue grows by about one frame in three and the counts fall further behind every second. Detection is the stage that sets the budget; tracking and events (0.4 ms together) are noise. This is the typical shape of a real pipeline, and the reason the detector is chosen, quantised or run at lower resolution first.

Step 4: skipping frames

When the detector is too expensive, the usual remedy is to analyse only every kk-th frame. Throughput improves almost by a factor kk, but three things get worse: the tracker sees each vehicle move kk times farther between two looks, so IoU with the prediction falls and tracks break; dwell times are measured in steps of kk frames; and a count can be up to (k−1)(k - 1) frames later. The sweep uses the CNN costs, because that is the detector that needs it.

python · try it yourself
import json
import numpy as np
import cv2
from scipy.optimize import linear_sum_assignment
cv2.setLogLevel(0)

FPS, W, H = 25, 160, 90
LANES = [(12, 2.5), (40, -3.0), (66, 1.2)]          # (top row, pixels per frame): east, west, slow east

def traffic_stream(rng, n_frames=240):
    """Project variant of make_video: vehicles enter on three lanes at random times and drive across.
    A generator: yields (t, frame, ground truth [(vehicle id, [x1, y1, x2, y2]), ...]) one frame at a time."""
    vehicles = []
    for y, v in LANES:
        t0 = int(rng.integers(0, 20))
        while t0 < n_frames - 20:
            vehicles.append(dict(id=len(vehicles), t0=t0, y=y + int(rng.integers(-2, 3)), v=v,
                                 w=int(rng.integers(14, 24)), h=int(rng.integers(8, 12)), g=int(rng.integers(170, 250))))
            t0 += int(rng.integers(35, 70))
    for t in range(n_frames):
        f = rng.normal(60, 6, (H, W))
        gt = []
        for o in vehicles:
            if t < o["t0"]:
                continue
            dist = abs(o["v"]) * (t - o["t0"])
            x1 = int(round(dist - o["w"])) if o["v"] > 0 else int(round(W - dist))
            if x1 >= W or x1 + o["w"] <= 0:
                continue
            f[o["y"]:o["y"] + o["h"], max(x1, 0):x1 + o["w"]] = o["g"]
            gt.append((o["id"], [max(x1, 0), o["y"], min(x1 + o["w"], W), o["y"] + o["h"]]))
        yield t, f.clip(0, 255).astype(np.uint8), gt

def detect(frame, rng, p_miss=0.1, p_false=0.05):
    """Threshold + connected components, made imperfect on purpose: misses, 1 px jitter, false alarms."""
    n, _, stats, _ = cv2.connectedComponentsWithStats((frame > 120).astype(np.uint8), connectivity=4)
    boxes = []
    for x, y, w, h, area in stats[1:].tolist():
        if area >= 30 and w >= 4 and rng.random() > p_miss:
            boxes.append([x + int(rng.integers(-1, 2)), y, x + w + int(rng.integers(-1, 2)), y + h])
    if rng.random() < p_false:
        x, y = int(rng.integers(0, W - 16)), int(rng.integers(0, H - 10))
        boxes.append([x, y, x + 16, y + 10])
    return boxes

def iou_matrix(a, b):
    a, b = np.asarray(a, float)[:, None], np.asarray(b, float)[None]
    iw = (np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0])).clip(0)
    ih = (np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1])).clip(0)
    inter = iw * ih
    area = lambda x: (x[..., 2] - x[..., 0]) * (x[..., 3] - x[..., 1])
    return inter / (area(a) + area(b) - inter)

class Tracker:
    """Compact SORT-style tracker: constant-velocity prediction, IoU + Hungarian matching; a track is
    reported after min_hits matches and deleted after max_age processed frames without one."""
    def __init__(self, iou_thr=0.1, max_age=3, min_hits=2):
        self.iou_thr, self.max_age, self.min_hits = iou_thr, max_age, min_hits
        self.tracks, self.next_id = [], 1

    def step(self, dets, dt=1):
        for tr in self.tracks:
            tr["since"] += dt
        dets = [np.array(d, float) for d in dets]
        used_t, used_d = set(), set()
        if self.tracks and dets:
            iou = iou_matrix([tr["last"] + tr["vel"] * tr["since"] for tr in self.tracks], dets)
            for i, j in zip(*linear_sum_assignment(-iou)):
                if iou[i, j] >= self.iou_thr:
                    tr = self.tracks[i]
                    v = (dets[j] - tr["last"]) / tr["since"]
                    tr["vel"] = v if tr["hits"] == 1 else 0.5 * tr["vel"] + 0.5 * v
                    tr["last"], tr["since"], tr["misses"] = dets[j], 0, 0
                    tr["hits"] += 1
                    used_t.add(i); used_d.add(j)
        for i, tr in enumerate(self.tracks):
            if i not in used_t:
                tr["misses"] += 1
        self.tracks = [tr for tr in self.tracks if tr["misses"] <= self.max_age]
        for j, d in enumerate(dets):
            if j not in used_d:
                self.tracks.append(dict(id=self.next_id, last=d, vel=np.zeros(4), since=0, misses=0, hits=1))
                self.next_id += 1
        return [(tr["id"], tr["last"]) for tr in self.tracks if tr["since"] == 0 and tr["hits"] >= self.min_hits]

LINE_X, ZONE, SLOW_S = 80, (100, 140), 1.0          # counting line, dwell zone (x range), alert above 1 s

class Events:
    """Line crossings (once per track) and dwell time in the zone; every event is a dict (one JSON line)."""
    def __init__(self):
        self.last_cx, self.crossed, self.zone, self.log = {}, set(), {}, []

    def update(self, t, tracks, dt=1):
        for tid, box in tracks:
            cx = (box[0] + box[2]) / 2
            prev = self.last_cx.get(tid)
            if prev is not None and tid not in self.crossed and (prev < LINE_X) != (cx < LINE_X):
                self.crossed.add(tid)
                self.log.append({"t": round(t / FPS, 2), "event": "line_cross", "track": int(tid),
                                 "dir": "east" if cx > prev else "west"})
            self.last_cx[tid] = cx
            if ZONE[0] <= cx < ZONE[1]:                          # inside: remember first and last time seen
                first, _ = self.zone.get(tid, (t, t))
                self.zone[tid] = (first, t)
            elif tid in self.zone:                               # first sighting after leaving the zone
                first, last = self.zone.pop(tid)
                s = round((last - first + dt) / FPS, 2)
                self.log.append({"t": round(t / FPS, 2), "event": "dwell", "track": int(tid), "seconds": s,
                                 "alert": s > SLOW_S})

    def summary(self):
        cross = [e for e in self.log if e["event"] == "line_cross"]
        dwell = [e for e in self.log if e["event"] == "dwell"]
        return dict(east=sum(e["dir"] == "east" for e in cross), west=sum(e["dir"] == "west" for e in cross),
                    dwell=len(dwell), alerts=sum(e["alert"] for e in dwell))

def run(k=1, seed=0):
    """Stream the clip once, detecting and tracking every k-th frame; ground-truth events on every frame."""
    rng, det_rng = np.random.default_rng(seed), np.random.default_rng(seed + 100)
    tracker, events, truth = Tracker(), Events(), Events()
    stats, ids = dict(frames=0, processed=0, dets=0, tracks=0), set()
    for t, frame, gt in traffic_stream(rng):
        stats["frames"] += 1
        truth.update(t, [(vid, np.array(box, float)) for vid, box in gt])
        if t % k:
            continue                                      # skipped: decoded, but not analysed
        stats["processed"] += 1
        dets = detect(frame, det_rng)
        tracks = tracker.step(dets, dt=k)
        stats["dets"] += len(dets); stats["tracks"] += len(tracks)
        ids |= {tid for tid, _ in tracks}
        events.update(t, tracks, dt=k)
    stats["events"], stats["ids"] = len(events.log), len(ids)
    return events, truth, stats

# Fixed cost model in milliseconds (assumed numbers for one CPU core; measure your own hardware)
COST_MS = {"decode": 1.0, "detect": {"threshold + blobs": 2.0, "small CNN": 60.0},
           "track_base": 0.1, "track_per_det": 0.05, "events_per_track": 0.02, "log_per_event": 0.2}
BUDGET_MS = 1000 / FPS                                    # 40 ms per frame at 25 fps

def cost_per_frame(stats, detector):
    c = COST_MS
    total = {"decode": c["decode"] * stats["frames"],
             "detect": c["detect"][detector] * stats["processed"],
             "track": c["track_base"] * stats["processed"] + c["track_per_det"] * stats["dets"],
             "events": c["events_per_track"] * stats["tracks"] + c["log_per_event"] * stats["events"]}
    return {name: v / stats["frames"] for name, v in total.items()}

print(" k  ms/frame (CNN)  real time  east west (GT)   dwell alerts (GT)  track ids  max wait")
for k in [1, 2, 3, 4, 6, 8]:
    events, truth, stats = run(k=k)
    s, g = events.summary(), truth.summary()
    ms = sum(cost_per_frame(stats, "small CNN").values())
    print(f"{k:2d}  {ms:14.2f}  {'yes' if ms <= BUDGET_MS else 'no ':3s}        {s['east']:4d} {s['west']:4d} ({g['east']}, {g['west']})"
          f"  {s['dwell']:5d} {s['alerts']:6d} ({g['dwell']}, {g['alerts']})  {stats['ids']:9d}  {(k - 1) / FPS:.2f} s")
 k  ms/frame (CNN)  real time  east west (GT)   dwell alerts (GT)  track ids  max wait
 1           61.40  no            7    5 (7, 5)     11      2 (11, 2)         14  0.00 s
 2           31.21  yes           7    5 (7, 5)     11      2 (11, 2)         14  0.04 s
 3           21.15  yes           7    5 (7, 5)     11      2 (11, 2)         14  0.08 s
 4           16.11  yes           7    5 (7, 5)     11      2 (11, 2)         14  0.12 s
 6           11.07  yes           5    2 (7, 5)      7      2 (11, 2)         10  0.20 s
 8            8.55  yes           4    0 (7, 5)      2      2 (11, 2)         15  0.28 s

Analysing every 2nd frame brings the CNN pipeline within budget (31.21 ms per frame), and up to k=4k = 4 the counts, dwell events and alerts still equal the ground truth, with at most 0.12 s of extra waiting. At k=6k = 6 the tracker loses vehicles (5 and 2 crossings instead of 7 and 5, 10 ids for 14 vehicles), and at k=8k = 8 no westbound vehicle is counted at all: at 3 pixels per frame they move 24 pixels between two looks, more than their 14 to 23 pixel length, so a new track's zero-velocity prediction never overlaps the next detection. The 15 ids at k=8k = 8 are broken eastbound tracks being reborn. The alerts survive even at k=8k = 8 only because the slow lane moves 9.6 pixels per look; that is luck, not robustness. The choice here is k=3k = 3 or 4: within budget with headroom (21.15 or 16.11 ms) and exact on this clip; confirm it on more clips before relying on it.

Step 5: stream versus batch

The same analysis can run as a batch job over a recorded clip. Batch processing sees whole tracks, so it can decide per track after the fact (drop short tracks, count by the first and last position, interpolate gaps, run an offline tracker that looks ahead), and it needs no real-time guarantee. But it must store the video, and every result arrives only after the clip has ended. The example runs both on the same detections.

python · try it yourself
import json
import numpy as np
import cv2
from scipy.optimize import linear_sum_assignment
cv2.setLogLevel(0)

FPS, W, H = 25, 160, 90
LANES = [(12, 2.5), (40, -3.0), (66, 1.2)]          # (top row, pixels per frame): east, west, slow east

def traffic_stream(rng, n_frames=240):
    """Project variant of make_video: vehicles enter on three lanes at random times and drive across.
    A generator: yields (t, frame, ground truth [(vehicle id, [x1, y1, x2, y2]), ...]) one frame at a time."""
    vehicles = []
    for y, v in LANES:
        t0 = int(rng.integers(0, 20))
        while t0 < n_frames - 20:
            vehicles.append(dict(id=len(vehicles), t0=t0, y=y + int(rng.integers(-2, 3)), v=v,
                                 w=int(rng.integers(14, 24)), h=int(rng.integers(8, 12)), g=int(rng.integers(170, 250))))
            t0 += int(rng.integers(35, 70))
    for t in range(n_frames):
        f = rng.normal(60, 6, (H, W))
        gt = []
        for o in vehicles:
            if t < o["t0"]:
                continue
            dist = abs(o["v"]) * (t - o["t0"])
            x1 = int(round(dist - o["w"])) if o["v"] > 0 else int(round(W - dist))
            if x1 >= W or x1 + o["w"] <= 0:
                continue
            f[o["y"]:o["y"] + o["h"], max(x1, 0):x1 + o["w"]] = o["g"]
            gt.append((o["id"], [max(x1, 0), o["y"], min(x1 + o["w"], W), o["y"] + o["h"]]))
        yield t, f.clip(0, 255).astype(np.uint8), gt

def detect(frame, rng, p_miss=0.1, p_false=0.05):
    """Threshold + connected components, made imperfect on purpose: misses, 1 px jitter, false alarms."""
    n, _, stats, _ = cv2.connectedComponentsWithStats((frame > 120).astype(np.uint8), connectivity=4)
    boxes = []
    for x, y, w, h, area in stats[1:].tolist():
        if area >= 30 and w >= 4 and rng.random() > p_miss:
            boxes.append([x + int(rng.integers(-1, 2)), y, x + w + int(rng.integers(-1, 2)), y + h])
    if rng.random() < p_false:
        x, y = int(rng.integers(0, W - 16)), int(rng.integers(0, H - 10))
        boxes.append([x, y, x + 16, y + 10])
    return boxes

def iou_matrix(a, b):
    a, b = np.asarray(a, float)[:, None], np.asarray(b, float)[None]
    iw = (np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0])).clip(0)
    ih = (np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1])).clip(0)
    inter = iw * ih
    area = lambda x: (x[..., 2] - x[..., 0]) * (x[..., 3] - x[..., 1])
    return inter / (area(a) + area(b) - inter)

class Tracker:
    """Compact SORT-style tracker: constant-velocity prediction, IoU + Hungarian matching; a track is
    reported after min_hits matches and deleted after max_age processed frames without one."""
    def __init__(self, iou_thr=0.1, max_age=3, min_hits=2):
        self.iou_thr, self.max_age, self.min_hits = iou_thr, max_age, min_hits
        self.tracks, self.next_id = [], 1

    def step(self, dets, dt=1):
        for tr in self.tracks:
            tr["since"] += dt
        dets = [np.array(d, float) for d in dets]
        used_t, used_d = set(), set()
        if self.tracks and dets:
            iou = iou_matrix([tr["last"] + tr["vel"] * tr["since"] for tr in self.tracks], dets)
            for i, j in zip(*linear_sum_assignment(-iou)):
                if iou[i, j] >= self.iou_thr:
                    tr = self.tracks[i]
                    v = (dets[j] - tr["last"]) / tr["since"]
                    tr["vel"] = v if tr["hits"] == 1 else 0.5 * tr["vel"] + 0.5 * v
                    tr["last"], tr["since"], tr["misses"] = dets[j], 0, 0
                    tr["hits"] += 1
                    used_t.add(i); used_d.add(j)
        for i, tr in enumerate(self.tracks):
            if i not in used_t:
                tr["misses"] += 1
        self.tracks = [tr for tr in self.tracks if tr["misses"] <= self.max_age]
        for j, d in enumerate(dets):
            if j not in used_d:
                self.tracks.append(dict(id=self.next_id, last=d, vel=np.zeros(4), since=0, misses=0, hits=1))
                self.next_id += 1
        return [(tr["id"], tr["last"]) for tr in self.tracks if tr["since"] == 0 and tr["hits"] >= self.min_hits]

LINE_X, ZONE, SLOW_S = 80, (100, 140), 1.0          # counting line, dwell zone (x range), alert above 1 s

class Events:
    """Line crossings (once per track) and dwell time in the zone; every event is a dict (one JSON line)."""
    def __init__(self):
        self.last_cx, self.crossed, self.zone, self.log = {}, set(), {}, []

    def update(self, t, tracks, dt=1):
        for tid, box in tracks:
            cx = (box[0] + box[2]) / 2
            prev = self.last_cx.get(tid)
            if prev is not None and tid not in self.crossed and (prev < LINE_X) != (cx < LINE_X):
                self.crossed.add(tid)
                self.log.append({"t": round(t / FPS, 2), "event": "line_cross", "track": int(tid),
                                 "dir": "east" if cx > prev else "west"})
            self.last_cx[tid] = cx
            if ZONE[0] <= cx < ZONE[1]:                          # inside: remember first and last time seen
                first, _ = self.zone.get(tid, (t, t))
                self.zone[tid] = (first, t)
            elif tid in self.zone:                               # first sighting after leaving the zone
                first, last = self.zone.pop(tid)
                s = round((last - first + dt) / FPS, 2)
                self.log.append({"t": round(t / FPS, 2), "event": "dwell", "track": int(tid), "seconds": s,
                                 "alert": s > SLOW_S})

    def summary(self):
        cross = [e for e in self.log if e["event"] == "line_cross"]
        dwell = [e for e in self.log if e["event"] == "dwell"]
        return dict(east=sum(e["dir"] == "east" for e in cross), west=sum(e["dir"] == "west" for e in cross),
                    dwell=len(dwell), alerts=sum(e["alert"] for e in dwell))

rng, det_rng = np.random.default_rng(0), np.random.default_rng(100)
clip = list(traffic_stream(rng))                          # batch: the whole clip in memory first
video = np.array([frame for _, frame, _ in clip])
print(f"batch holds {video.nbytes} bytes of frames; the stream held {video[0].nbytes} at a time")

tracker, stream_events, truth = Tracker(), Events(), Events()
history = {}
for t, frame, gt in clip:
    truth.update(t, [(vid, np.array(box, float)) for vid, box in gt])
    tracks = tracker.step(detect(frame, det_rng))
    stream_events.update(t, tracks)                       # stream: decided as the frames arrive
    for tid, box in tracks:
        history.setdefault(tid, []).append((t, (box[0] + box[2]) / 2))

# Batch: decide per complete track, after the clip has ended; tracks shorter than 5 frames are dropped
batch = {"east": 0, "west": 0}
for tid, h in history.items():
    (t0, x0), (t1, x1) = h[0], h[-1]
    if len(h) >= 5 and (x0 < LINE_X) != (x1 < LINE_X):
        batch["east" if x1 > x0 else "west"] += 1
print("stream counts:", {k: stream_events.summary()[k] for k in ("east", "west")}, "| batch counts:", batch,
      "| ground truth:", {k: truth.summary()[k] for k in ("east", "west")})

def cross_times(ev, d):
    return sorted(e["t"] for e in ev.log if e["event"] == "line_cross" and e["dir"] == d)
delays_stream, delays_batch = [], []
for d in ("east", "west"):
    for ts, tg in zip(cross_times(stream_events, d), cross_times(truth, d)):
        delays_stream.append(ts - tg); delays_batch.append(len(clip) / FPS - tg)
print(f"time from a real crossing to its count: stream mean {np.mean(delays_stream):.2f} s (max {max(delays_stream):.2f} s), "
      f"batch mean {np.mean(delays_batch):.2f} s (max {max(delays_batch):.2f} s)")
batch holds 3456000 bytes of frames; the stream held 14400 at a time
stream counts: {'east': 7, 'west': 5} | batch counts: {'east': 7, 'west': 5} | ground truth: {'east': 7, 'west': 5}
time from a real crossing to its count: stream mean 0.01 s (max 0.08 s), batch mean 4.51 s (max 7.92 s)

On this clip the batch job's track-level counting gives the same counts as the stream, so the differences are elsewhere. Memory: the batch job holds all 3,456,000 bytes, 240 times what the stream needs, and grows with the clip. Latency: the stream reports a crossing on average 0.01 s after it happens (at most 0.08 s, the frames needed to confirm a track), while the batch job reports it 4.51 s later on average and up to 7.92 s for an early crossing, because nothing is known until the clip ends. For a junction dashboard the stream is the only option; for a monthly traffic report a nightly batch job over recorded video (if storing it is lawful) can afford slower, look-ahead methods.

Error analysis

Symptom Cause Remedy
a vehicle counted twice jitter moves the box centre back across the line count once per track (done); hysteresis band around the line
a crossing not counted track broken around the line by misses larger max_age, a lower IoU threshold, velocity prediction (done)
counts collapse at large kk displacement between looks exceeds the box size smaller kk, a cheaper detector, motion-aware matching (centre distance instead of IoU)
dwell alerts wrong dwell is quantised to kk frames; a value near the threshold flips report dwell with its resolution; alert thresholds well away from typical values
false alarms detector noise min_hits: one-frame tracks are never confirmed

Your turn

  1. Add a hysteresis band: a crossing counts only when the centre moves from x<76x < 76 to x≥84x \ge 84 (or back). Remove the once-per-track rule. Does the count stay correct?
Hint

Keep, per track, the last side it was clearly on (left of 76 or right of 84) and count a change of side. Jitter of one or two pixels can no longer flip it; a real U-turn still would, and is counted, which may be what you want.

  1. Make the stream harder: raise p_miss to 0.3. Which tracker parameter do you change first, and what does the event log show before and after?
Answer

max_age (how many processed frames a track survives without a match): with 30 % misses, runs of two or three misses are common, and a track that dies and is reborn gets a new id, which can lose its crossing (the new track starts on the far side) or split a dwell period. Raising max_age to 5 or 6 keeps the ids; the cost is ghost tracks that live longer after a vehicle leaves.

  1. With the CNN costs, find the smallest kk that fits the budget, and change the cost model so that decoding a skipped frame costs nothing (an intra-only stream, or a camera that sends only every kk-th frame). How does that change the smallest kk?
Hint

The mean cost per input frame is roughly cdecode+cdetect/k+…c_{\text{decode}} + c_{\text{detect}} / k + \dots; solve cdetect/k≤40−cdecode−…c_{\text{detect}} / k \le 40 - c_{\text{decode}} - \dots. With free skipped frames the decode term is divided by kk as well.

Write-up template

Section Content
Use case what is counted, where, why; who receives the events
Input camera, resolution, fps, test clips and their ground truth
Pipeline detector, tracker parameters, event rules (line position, zone, thresholds)
Accuracy counts per direction and alerts vs ground truth, per clip; failure cases
Budget cost per stage (measured on the target hardware), total per frame vs 1000/fps1000 / \text{fps}, chosen kk
Latency delay from a real crossing to its event (mean, max)
Stream or batch which, and why (latency need, storage, privacy)
Privacy what leaves the device (counts only?), retention, no video stored

Test yourself

At 25 fps a detector takes 30 ms per frame and everything else 5 ms. Is the pipeline real-time without skipping frames?

  1. No, any detector over 25 ms is too slow
  2. Yes: 35 ms per frame is within the 40 ms budget, but with little headroom
  3. Only at 50 fps
  4. It depends on the number of events only

Why do counts collapse when the tracker sees only every 8th frame of vehicles moving 3 pixels per frame?

  1. The detector gets slower
  2. Between two looks a vehicle moves 24 pixels, more than its width, so IoU with the prediction is often zero and tracks break or never start
  3. JSON lines cannot store more events
  4. The line moves

What does batch processing give you that streaming cannot?

  1. Lower delay of each count
  2. Decisions on complete tracks (look-ahead, gap filling, dropping short tracks), at the cost of storing the video and getting results only at the end
  3. Less memory
  4. No need for a detector