Video anomaly detection pipeline for real-time surveillance
Machine LearningModel answerLast updated
Design an ML system to identify threatening behaviors in live camera feeds, handling extreme class imbalance and deployment constraints.
Problem Statement
Design a computer vision pipeline that monitors live security camera feeds to identify threatening behaviors—such as weapon display, forced access, or hostile movements—and generates silent notifications to monitoring staff when potential incidents occur.
System Requirements
-
Architecture: Outline an approach to recognize threat patterns in continuous video streams. Consider whether frame-by-frame analysis, temporal modeling, or hybrid methods are appropriate.
-
Data Collection: Threatening events occur extremely infrequently, creating severe class imbalance. Describe how you would gather, organize, and annotate training data when real incidents are scarce.
-
Operational Constraints: The system must run on existing on-premises infrastructure with limited compute capacity, processing multiple camera feeds simultaneously with minimal latency.
-
Evaluation Framework: Define how you would measure system performance given the unusual cost asymmetry—missing a genuine threat is critically expensive, but excessive false notifications undermine trust and waste resources.
-
Risk Mitigation: Identify potential biases, failure modes, and ethical concerns in automated surveillance, and propose concrete mitigation strategies.
Expected Deliverable
Present a structured technical design covering:
- Data acquisition strategy for extremely rare events
- Model architecture selection and justification
- Deployment approach balancing accuracy and resource constraints
- Evaluation methodology appropriate for extreme imbalance
- Safeguards addressing bias and operational risks
Hints
Hint 1
Think about multi-stage pipelines where cheap filters eliminate most normal footage before expensive models run
Hint 2
Synthetic data and staged scenarios may be more valuable than waiting for organic incidents
Hint 3
The base rate of genuine threats (perhaps 1 per million camera-hours) makes traditional accuracy metrics misleading
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time Threat Detection Pipeline
This question tests your ability to design ML systems for rare, high-stakes events. Strong candidates immediately recognize that extreme rarity drives every design choice—data strategy, architecture, metrics, and the human-in-the-loop requirement.
1. Scope and Assumptions
Start by establishing scale and constraints with concrete numbers:
- Volume: 500 locations, 10–15 cameras each, yielding ~7,000 concurrent streams at 1080p, 12–15 fps
- Infrastructure: Existing network video recorders plus one edge compute unit per location (modest GPU or CPU with inference accelerator)
- Latency target: Notification reaches monitoring center within 3–5 seconds of observable threat behavior
- Base rate: Perhaps one genuine incident per location every 3–5 years, translating to roughly 1 event per million camera-hours
- Alert budget: Business tolerance might be 1–2 false notifications per location monthly; law enforcement dispatch only after human confirmation
- Detection scope: Behavioral and object cues (weapon visibility, aggressive posture, unauthorized entry patterns), not person identification
2. Architecture: Cascaded Processing Pipeline
Build a multi-stage funnel where each layer is computationally cheap and filters aggressively, so expensive models process only promising segments.
Stage 1: Motion-Based Gate Run simple background subtraction or frame differencing at reduced resolution (240p–360p) and low frame rate (2–3 fps). This eliminates 70–90% of footage—empty rooms, static scenes, after-hours periods—at negligible cost.
Stage 2: Per-Frame Object and Pose Detection Apply a quantized single-shot detector (YOLO variant compiled to INT8 via TensorRT) to identify persons and potentially threatening objects. Add lightweight pose estimation (MoveNet or MediaPipe) to extract skeletal keypoints. Feed results into a multi-object tracker (ByteTrack or DeepSORT) to construct tracklets across frames.
Stage 3: Temporal Behavior Analysis Only tracklets passing earlier gates enter this stage. The model consumes 2–4 second temporal windows containing:
- Pose keypoint sequences
- Object detection scores and bounding boxes
- Cropped person ROIs
Architecture options:
- Lightweight Transformer: Encode per-frame features, apply temporal self-attention over the sequence
- Efficient 3D ConvNet: MoViNet or X3D operating on cropped video clips
Output: threat probability score plus specific cue labels (e.g., "raised-arm-toward-staff", "object-extended", "rapid-approach").
Why temporal models matter: A single frame showing a raised hand or held object is ambiguous (could be a phone, greeting, normal transaction). Temporal patterns—approach counter, extend arm, hold position while staff reacts—disambiguate intent.
Stage 4: Multi-Camera Fusion and Context Aggregate scores across time (persistence over multiple windows) and space (corroborating evidence from adjacent cameras). Incorporate zone semantics: events near cash-handling areas, entry points, or restricted zones receive higher weight. Simple rule integration helps: "door sensor breach AND person detected in restricted zone after hours."
Stage 5: Human Review Layer
- High-confidence alerts: Immediate notification with video clip to monitoring personnel
- Medium-confidence: Logged for batch review
- External escalation: Only after human confirmation or physical panic button activation
This design balances the asymmetric costs: missing genuine threats is catastrophic, but false police dispatch to innocent situations creates serious risk.
3. Data Strategy for Rare Events
Acquisition Sources:
- Historical incidents: Actual footage from past events (likely tens to low hundreds of clips), used under legal and privacy frameworks
- Public datasets: UCF-Crime, RWF-2000 (violence detection), for initial pretraining of behavior recognition
- Staged scenarios: Highest ROI approach—hire actors to perform scripted threat scenarios in actual locations using real camera angles, lighting conditions, and prop weapons. Capture dozens of variations per location.
- Synthetic generation: Render branch interiors in game engines with varied avatars, objects, viewpoints, and lighting. Composite weapons into real benign footage using augmentation techniques.
- Hard negatives (critical): Collect extensive footage of confounding scenarios—people handling phones, wallets, umbrellas, tools during maintenance; staff transporting cash; children running; people in hoodies or masks conducting normal business
Annotation Strategy:
- Temporal segment labels marking threat onset/offset
- Object bounding boxes on key frames
- Weak supervision via multiple-instance learning when only video-level labels exist
- Active learning loop: route production uncertainties and false alarms to annotators for labeling, continuously improving the model
Training Approach:
- Pretrain perception modules on broad datasets
- Apply focal loss or class-balanced sampling to handle imbalance
- Aggressive augmentation: simulate low-light conditions, infrared/night-vision appearance, motion blur, compression artifacts, occlusions, varied viewpoints
- Complementary anomaly detection: Train an unsupervised model per camera on normal-only footage. This catches novel threat patterns the supervised model never encountered, serving as a secondary signal.
Critical: Split data by location and incident, never by frame. Frame-level splits leak nearly identical frames between train and test, inflating performance estimates.
4. Deployment Under Resource Constraints
Compute Budget Example:
- 15 cameras × 4 fps (after motion gating) × quantized detector = ~60 inferences/second per location, feasible on one edge accelerator with batching
- Temporal model processes <5% of tracklets due to upstream filtering
Optimization Techniques:
- Hardware video decode acceleration
- Process only person ROIs, not full frames
- Adaptive frame rate: increase sampling rate only when early stages trigger
- Model quantization (INT8) and compilation (TensorRT, OpenVINO, CoreML)
Infrastructure Pattern:
- Video remains on-premises; only alert clips and metadata transmit to central monitoring
- Models deploy via over-the-air updates with shadow-mode evaluation before activation
- Per-camera threshold calibration based on local false-positive rates
5. Evaluation Methodology
Standard accuracy is meaningless—a model always predicting "normal" achieves 99.999%+ accuracy.
Appropriate Metrics:
- Event-level recall at your operating threshold, measured on held-out real and staged incidents
- False alert rate per camera-hour or per location-week (what operators actually experience)
- Precision at the monitoring-center level (of alerts reaching humans)
- Time-to-detect from first observable threat cue
- Sliced evaluation across lighting conditions, camera types, locations, and demographic subgroups when available
Use precision-recall curves, not ROC curves—ROC obscures poor precision under extreme imbalance.
Threshold Selection: Model the cost trade-off explicitly:
- Cost(miss) = very high (danger to people, liability)
- Cost(false_alarm) = moderate (operator fatigue, eroded trust)
- Cost(false_police_dispatch) = high (dangerous armed response to innocent situation)
This asymmetry justifies high-recall operating points combined with mandatory human review before external escalation.
6. Bias and Ethical Safeguards
Key Risks:
- Performance degradation in low-light conditions or on darker skin tones (both from dataset bias and sensor physics)
- Proxy features: system learns to flag hoodies, religious headwear, or masks as threat indicators rather than actual behaviors
- Atypical movement from people with disabilities misclassified as threatening
- Object confusion: mobility aids, tools, or personal items misidentified as weapons
Mitigation Strategies:
- Disaggregated evaluation across demographic groups, lighting conditions, and camera types; set minimum performance requirements per slice
- Diverse staging scenarios explicitly including protected characteristics, religious attire, mobility devices
- Regular bias audits with external review
- Behavioral focus over demographic proxies—detection should trigger on actions (extended object + fixed posture toward staff), not appearance
- Transparency to staff and legal review of deployment
- Clear data retention limits: delete routine footage rapidly, retain alert clips only as long as legally required
- Continuous monitoring of false-alarm patterns by demographic slice with automatic alerts when disparities emerge
Common Mistakes
- Treating this as a standard classification problem and proposing frame-level models without temporal context
- Overlooking the human review requirement and proposing fully automated dispatch
- Ignoring the data scarcity problem or proposing to "just collect more real incidents"
- Using accuracy or ROC-AUC as primary metrics
- Proposing cloud-based inference without considering bandwidth, latency, and privacy constraints
- Failing to address bias and fairness concerns in surveillance contexts
Complexity Note: The cascade architecture reduces average per-frame cost to approximately O(1) for the cheap stages, with the expensive temporal model at O(T·F) where T is window length and F is feature dimension, but running on <5% of frames after filtering.