The one-line mental model
A still frame tells you who is present; a video clip tells you what they are doing. Aerial video analysis samples clips from the live stream, extracts spatial and temporal features, and converts the results into action labels, anomaly alerts, and a human-readable event timeline.
You will be able to:
- Choose clip sampling strategies that balance detail against compute
- Recognize coarse actions from two-stream and 3D-convolution features
- Detect anomalies with baseline statistics rather than labeled data
- Merge frame-level detections into a narrated event summary
Prerequisites
- !Image classification and CNNs
- !Object detection and tracking
- !Basic probability and statistics
What You'll Learn
- 1Compare two-stream, 3D CNN, and video-transformer architectures
- 2Implement a motion-history anomaly detector
- 3Design alert cooldowns that keep operator screens readable
From live stream to analyzable clips
A drone camera delivers 30 frames per second at 1080p or higher. Running a heavy video model on every frame is neither necessary nor affordable on embedded hardware. Most systems instead maintain a ring buffer and analyze clips of 8 to 32 frames sampled every few frames â enough temporal context to distinguish walking from running, sparse enough to leave compute headroom for detection and tracking running in parallel.
The sampling policy itself is a modeling decision. Uniform sampling over a 2-second window gives a good average view of sustained actions. Adaptive sampling â denser frames when motion is high, sparser when the scene is static â concentrates compute where events live. Keyframe extraction driven by scene-change detection ensures rare events are not missed by a fixed stride. Whatever policy you choose, keep the clip length constant during training and inference; models trained on 16-frame clips degrade unpredictably on 8-frame ones.
Architectures for action understanding
Four families cover most deployed systems. Two-stream networks process RGB frames with one CNN and optical-flow frames with another, then fuse â simple, proven, and easy to fine-tune. 3D convolutional networks such as I3D and SlowFast learn joint spatiotemporal features directly, at higher compute cost. Video transformers tokenize space and time and excel at long-range dependencies, but need substantial data and hardware. Finally, lightweight pose-plus-features pipelines â like the one in the pose estimation lesson â remain competitive when the actions of interest are person-centric and the detector is already running.
For a drone specifically, SlowFast is often the pragmatic sweet spot. Its slow pathway samples a few high-resolution frames for appearance detail; its fast pathway samples many low-resolution frames for motion. The dual rate matches how aerial missions actually run: operators care about fine appearance at moments, and about coarse motion continuously.
| Architecture | Temporal signal | Compute profile | Best fit |
|---|---|---|---|
| Two-stream CNN | Optical flow | Medium | Labeled action sets, retrofitting existing CNNs |
| 3D CNN (I3D, C3D) | Volumetric convolutions | High | Offline clip classification |
| SlowFast | Dual-rate sampling | Medium-high | Real-time surveillance on edge GPUs |
| Video transformer | Global attention | Very high | Offline analysis, long videos |
| Pose + features | Keypoint trajectories | Very low | Person actions when pose already runs |
Recognizing actions with a two-stream baseline
Below is a compact two-stream recognizer you can wire to a real backbone. The spatial stream scores individual frames; the temporal stream scores frame differences as a flow approximation; logits are averaged late in the pipeline.
from collections import deque
from dataclasses import dataclass
import numpy as np
ACTIONS = ["walking", "running", "standing", "sitting",
"fighting", "falling", "entering_vehicle", "waving"]
@dataclass
class ActionPrediction:
action: str
confidence: float
frame: int
class TwoStreamActionRecognizer:
"""Late-fusion spatial and temporal action scoring."""
def __init__(self, clip_len=16):
self.clip_len = clip_len
self.frames = deque(maxlen=clip_len)
rng = np.random.default_rng(0)
self.spatial_w = rng.normal(0, 0.05, size=(len(ACTIONS), 64))
self.temporal_w = rng.normal(0, 0.05, size=(len(ACTIONS), 32))
def _spatial_features(self, frame):
"""Placeholder for a CNN embedding: coarse color and edge stats."""
small = frame[::8, ::8].astype(np.float64)
means = small.reshape(-1, 3).mean(axis=0)
edges = np.abs(np.diff(small, axis=0)).mean()
vec = np.concatenate([means, [edges]])
vec = np.concatenate([vec, vec * vec])
return np.pad(vec, (0, 64 - len(vec)))[:64]
def _temporal_features(self, frames):
"""Frame-difference motion profile."""
diffs = []
for a, b in zip(frames[:-1], frames[1:]):
diffs.append(np.mean(np.abs(a.astype(np.float64) - b)))
if not diffs:
return np.zeros(32)
d = np.array(diffs)
stats = [d.mean(), d.std(), d.max(), d.min()]
return np.pad(np.tile(stats, 8), (0, 32 - 32))[:32]
def update(self, frame, frame_idx):
self.frames.append(frame)
if len(self.frames) < self.clip_len:
return None
clips = list(self.frames)
spatial = np.mean([self._spatial_features(f) for f in clips[::4]], axis=0)
temporal = self._temporal_features(clips)
logits = spatial @ self.spatial_w.T + temporal @ self.temporal_w.T
# Bias toward standing when almost nothing moves
motion = np.mean(np.abs(
np.diff([f.astype(np.float64).mean() for f in clips])))
if motion < 0.5:
logits[ACTIONS.index("standing")] += 3.0
logits -= logits.max()
probs = np.exp(logits) / np.exp(logits).sum()
i = int(probs.argmax())
return ActionPrediction(ACTIONS[i], float(probs[i]), frame_idx)
rng = np.random.default_rng(6)
rec = TwoStreamActionRecognizer(clip_len=10)
base = rng.integers(60, 120, size=(240, 320, 3)).astype(np.uint8)
for idx in range(20):
frame = base.copy()
if idx > 8:
shift = (idx - 8) * 6
frame[:, shift:shift + 40] = [150, 90, 40] # moving subject
frame = np.roll(frame, shift % 20, axis=1)
pred = rec.update(frame, idx)
if pred:
print(f"frame {pred.frame}: {pred.action} ({pred.confidence:.0%})")
In a production build the two placeholder feature functions become a ResNet or EfficientNet trunk loaded from ONNX or TensorRT; the surrounding buffer, fusion, and bias logic stays exactly the same.
Anomaly detection without labels
Surveillance anomalies â loitering, fights, crowd formation, abandoned objects â are, by definition, rare, so labeled training sets do not exist for them. The practical approach is unsupervised: learn what normal looks like per zone and per hour, then alert when observations deviate. Motion magnitude, person density, and track dwell time are three channels that are cheap to compute and surprisingly expressive.
from collections import defaultdict, deque
from dataclasses import dataclass
import numpy as np
@dataclass
class Anomaly:
kind: str
severity: str
frame: int
detail: str
class BaselineAnomalyDetector:
"""Per-zone statistical baselines for motion and density."""
def __init__(self, warmup=60, z=3.0):
self.motion = defaultdict(list)
self.density = defaultdict(list)
self.dwell = defaultdict(int)
self.warmup = warmup
self.z = z
def observe(self, zone, frame, motion_value, person_count, track_id=None):
alerts = []
if frame < self.warmup:
self.motion[zone].append(motion_value)
self.density[zone].append(person_count)
return alerts
m = np.array(self.motion[zone][-500:])
d = np.array(self.density[zone][-500:])
m_mu, m_sd = m.mean(), m.std() + 1e-6
d_mu, d_sd = d.mean(), d.std() + 1e-6
if motion_value > m_mu + self.z * m_sd:
alerts.append(Anomaly(
"unusual_motion", "medium", frame,
f"motion {motion_value:.1f} vs baseline {m_mu:.1f}"))
if person_count > d_mu + self.z * d_sd and person_count >= 8:
alerts.append(Anomaly(
"crowd_formation", "high", frame,
f"{person_count} persons, baseline {d_mu:.1f}"))
if track_id is not None:
self.dwell[track_id] += 1
if self.dwell[track_id] > 240 and person_count <= d_mu + 1:
alerts.append(Anomaly(
"loitering", "medium", frame,
f"track {track_id} present {self.dwell[track_id]} frames"))
elif track_id in self.dwell:
del self.dwell[track_id]
return alerts
det = BaselineAnomalyDetector(warmup=20, z=3.0)
rng = np.random.default_rng(8)
for frame in range(120):
motion = float(rng.normal(5, 1.5))
people = int(rng.poisson(3))
if frame > 80:
motion = 25.0 # sudden activity spike
people = 14 # crowd appears
hits = det.observe("plaza", frame, motion, people,
track_id=1 if frame > 40 else None)
for h in hits:
print(f"frame {h.frame}: [{h.severity}] {h.kind} â {h.detail}")
Two details make this usable in the field. The warm-up window prevents first-hour baselines from generating noise alerts, and the per-zone split stops a busy plaza from inflating the baseline of a quiet courtyard. Always record the baseline parameters with the alert so an analyst can judge whether the environment drifted or an event truly occurred.
Summarizing a shift into a timeline
Operators cannot watch eight hours of footage. The last stage merges frame-level outputs into events, deduplicates bursts, and renders a narrative. The merging rule is simple: same type, same zone, within a few seconds of each other, collapse into one event whose start is the first trigger and whose end is the last.
from dataclasses import dataclass, field
@dataclass
class Event:
kind: str
zone: str
start: float
end: float
severity: str
detail: str
class EventSummarizer:
"""Merge bursty frame alerts into sparse timeline events."""
def __init__(self, merge_gap_s=4.0, fps=30):
self.events: list[Event] = []
self.gap = merge_gap_s
self.fps = fps
def add(self, kind, zone, frame, severity, detail):
t = frame / self.fps
if self.events:
last = self.events[-1]
if (last.kind == kind and last.zone == zone
and t - last.end <= self.gap):
last.end = t
return None
event = Event(kind, zone, t, t, severity, detail)
self.events.append(event)
return event
def narrative(self):
if not self.events:
return "No significant events during this period."
lines = []
for e in sorted(self.events, key=lambda x: x.start):
dur = e.end - e.start
lines.append(
f"[{e.start:6.1f}s-{e.end:6.1f}s] {e.zone} "
f"{e.kind} ({e.severity}, {dur:.1f}s): {e.detail}")
return "\n".join(lines)
summ = EventSummarizer()
for frame, kind, sev, detail in [
(150, "loitering", "medium", "track 3 dwelling near gate"),
(155, "loitering", "medium", "track 3 dwelling near gate"),
(162, "loitering", "medium", "track 3 dwelling near gate"),
(400, "crowd_formation", "high", "14 persons at plaza center"),
(402, "crowd_formation", "high", "14 persons at plaza center"),
]:
summ.add(kind, "zone_a", frame, sev, detail)
print(summ.narrative())
print(f"events retained: {len(summ.events)} from 5 raw alerts")
The three loitering frames collapse into one event; the two crowd frames collapse into another. That compression â often 50 to 1 against raw alerts â is what makes a surveillance log actually reviewable.
Putting it together
A deployed pipeline runs detection and tracking on every frame, action recognition on the clip buffer, the anomaly detector on tracked scene statistics, and the summarizer at the top. Alert cooldowns per type per zone prevent a single persistent condition from flooding the screen. Everything upstream of the operator should degrade gracefully: when compute saturates, drop action recognition before dropping tracking, because track continuity anchors every downstream alert to a concrete place and time.
Sizing the pipeline starts from a compute budget. On a Jetson-class board, a detector-plus-tracker loop can typically hold 15 to 25 frames per second at VGA resolution while leaving headroom for one clip-based action model running at two to four inferences per second. Budget the anomaly detector last â it is cheap â but give it priority over action recognition when an alert-bandwidth problem appears, because anomaly signals are what actually page a human. Log per-stage latency histograms, not just averages; a pipeline that runs at 20 FPS on average but stalls to 4 FPS during crowd formation is a pipeline that loses exactly the events you most need to see.
Common Mistakes
Running a video model on every frame
Fix: Buffer clips and analyze at a fixed cadence; detection and tracking already run per frame.
One global anomaly baseline for the whole site
Fix: Learn per-zone, ideally per-hour baselines; a busy plaza and a quiet courtyard have different normals.
Forwarding every frame-level alert to the operator
Fix: Merge bursts into events and apply per-type cooldowns before anything reaches the screen.
Treating the action label as ground truth
Fix: Display confidence and the underlying clip so the operator can judge; actions are hypotheses, not verdicts.
Best Practices
- Keep clip length and sampling policy identical between training and deployment
- Log model version, clip bounds, and baseline parameters with every emitted alert
- Simulate compute saturation in staging so degradation order is a tested behavior, not a guess
- Review false-alert rates weekly and retune z-scores; baselines drift with seasons and construction
Key Takeaways
- Video analysis converts frames into actions, anomalies, and events through a staged pipeline
- SlowFast-style dual-rate sampling suits the edge-compute profile of drone surveillance
- Unsupervised anomaly detection with per-zone baselines is the realistic path because labeled anomalies do not exist
- Event merging and alert cooldowns compress noisy frame-level signals into a reviewable timeline
- Degrade gracefully under load â tracking continuity is the load-bearing component of every alert