Skip to article content All articles

How We Turned Dumb CCTV Footage into a Smart API

A production-minded computer-vision pipeline for asynchronous video ingestion, spatial mapping, reviewable incidents, and responsible operation.

Abhishek Choudhury

Abhishek Choudhury

February 20, 2025 · Updated July 29, 2026 · 7 min read

Security-camera footage flowing into a machine that prints a structured incident card
On this page7 min left

At a glance

  1. Large-video analysis is an asynchronous job system: the request API, object storage, queue, workers, and incident API have different scaling and failure boundaries.

  2. A detection becomes actionable only after time, camera geometry, location mapping, event aggregation, and human-review evidence are attached.

  3. Surveillance systems need privacy, retention, access, appeal, and human-verification controls designed alongside model accuracy.

01The boundary

Return incidents, not model output

The business request sounds simple: accept CCTV footage and identify when and where a rule violation occurred. A vision model, however, returns labels, scores, and coordinates. The API must turn those uncertain observations into a reviewable incident with a timestamp, camera, mapped zone, supporting evidence, and lifecycle state.

  • Input contract: an authenticated upload intent, camera identity, capture time range, content metadata, checksum, and purpose.
  • Job contract: a durable identifier and explicit states for upload, processing, review, completion, expiry, cancellation, and failure.
  • Incident contract: zero or more candidates with evidence, confidence, mapping rationale, review status, and stable identifiers.
  • No-result contract: distinguish a completed analysis with no incident from unsupported media, model failure, or expired input.

02The system map

Move video outside the request path

Video is too large and processing too variable for a single request-response transaction. The API should create a job and issue a time-limited upload capability. The client uploads directly to object storage, and a verified completion event makes the job eligible for processing.

Loading diagram…

  1. The authenticated CRM creates an analysis job with camera and capture metadata.
  2. The API issues a short-lived upload capability for one object key.
  3. The CRM uploads the video directly to object storage with a checksum.
  4. Validation confirms media type, size, checksum, ownership, and supported codecs.
  5. A durable queue schedules the verified job.
  6. Workers decode video and select frames according to a sampling policy.
  7. Detections are normalized, spatially mapped, and aggregated into candidate incidents.
  8. An authorised reviewer verifies evidence when required.
  9. The incident API returns completed or reviewable results.
The asynchronous video-to-incident pipeline. Large media bypasses the request server, while every processing stage has a durable job identity and explicit failure boundary.

Amazon S3 presigned URLs are one dated implementation example of time-limited object access. Equivalent object stores can provide the same architectural boundary. The upload key must be unique, scoped, short-lived, checksum-validated, and unusable for arbitrary overwrite.

03Video I/O

Frame selection is a quality decision

A video is a time-indexed sequence, not merely a folder of pictures. Sampling too sparsely can miss a brief event; sampling every frame multiplies decoding, inference, storage, and review cost. The right strategy depends on event duration, camera motion, scene stability, and model behavior.

Three frame-selection strategiesEvaluate sampling against event-level recall and cost. Frame-level model accuracy does not reveal whether the pipeline missed the event entirely.
DecisionBaselineFixed intervalAdaptiveMotion or scene-awareTemporalTracking-assisted
Best forStable cameras and events that last longer than the sampling interval.Mostly static footage where activity is sparse.Events requiring trajectories, continuity, or deduplication.
You ownTimestamp accuracy, decoder seeking behavior, and interval tuning.Motion thresholds, scene-change rules, and fallback sampling.Track lifecycle, occlusion, identity switches, and temporal evaluation.
Trade-offPredictable cost, but short events can fall between samples.Reduces empty work, but camera shake, weather, and lighting create noise.Stronger event context with higher compute and tuning complexity.
ExamplesDecode or seek one frame every configured number of milliseconds.Background change triggers a denser sampling window.Detect periodically and track objects between inference frames.

Baseline

Fixed interval

Best for
Stable cameras and events that last longer than the sampling interval.
You own
Timestamp accuracy, decoder seeking behavior, and interval tuning.
Trade-off
Predictable cost, but short events can fall between samples.
Examples
Decode or seek one frame every configured number of milliseconds.

Adaptive

Motion or scene-aware

Best for
Mostly static footage where activity is sparse.
You own
Motion thresholds, scene-change rules, and fallback sampling.
Trade-off
Reduces empty work, but camera shake, weather, and lighting create noise.
Examples
Background change triggers a denser sampling window.

Temporal

Tracking-assisted

Best for
Events requiring trajectories, continuity, or deduplication.
You own
Track lifecycle, occlusion, identity switches, and temporal evaluation.
Trade-off
Stronger event context with higher compute and tuning complexity.
Examples
Detect periodically and track objects between inference frames.

OpenCV VideoCapture can read video files, streams, and image sequences. Its documentation also notes that effective behavior depends on the backend, operating system, driver, and hardware, so timestamp and seeking assumptions need tests against the deployed codecs.

04Model boundary

Normalize detections before business rules

The detector should return a vendor-neutral observation: frame timestamp, class, confidence, bounding polygon, model version, and preprocessing version. This keeps the downstream mapping and incident rules independent of one vision service.

  • Version every prediction. Store the model, threshold set, class map, and frame-selection configuration used.
  • Retain bounded evidence. Preserve only the frames or short clips required for review and evaluation, subject to retention policy.
  • Calibrate confidence. Treat raw model scores as ranking signals until tested against the real cameras and target events.
  • Support multiple observations. A single frame can contain multiple objects, and a video can contain multiple incidents.

Google Cloud Vision object localization is a dated managed-service example that returns object names, scores, and normalized bounds. A generic object detector still requires task-specific data and evaluation before it can recognize a domain event such as falling waste.

05Camera geometry

Map pixels to configured zones

A bounding box does not contain a flat number. The application needs a calibrated map for each camera: image dimensions, active crop, camera revision, zone polygons, blind spots, and the rule for selecting the relevant point on a detected object or trajectory.

Loading diagram…

  1. Start with frame timestamp, normalized bounding geometry, class, score, and optional track.
  2. Reverse crop, resize, and rotation transforms into the calibrated coordinate system.
  3. Select the event point or trajectory feature used by the domain rule.
  4. Compare that geometry with versioned zone polygons for the camera and capture time.
  5. Return one or more candidate locations with overlap or distance rationale.
  6. Package calibration version and evidence frames for human review.
  7. Treat boundary overlap or missing calibration as ambiguity rather than a confident location.
From image coordinates to a reviewable location. A model supplies image coordinates. Versioned calibration and explicit spatial rules create the candidate physical location.
  1. Normalize coordinates. Convert detections into a consistent coordinate system after rotation, crop, and resize transformations.
  2. Choose the event point. A centroid, lower edge, trajectory crossing, or impact point can map to different zones.
  3. Match versioned polygons. Camera movement or replacement invalidates old calibration, so mappings need effective dates.
  4. Return the rationale. Include the matched zone, overlap or distance, calibration version, and evidence frame.

06From frames to incidents

Aggregate observations into events

Repeated detections across adjacent frames are usually evidence for one event, not dozens of incidents. Aggregation groups observations using time windows, track identity, spatial proximity, class, and camera.

  • Deduplicate temporally. Merge observations that describe the same continuous event.
  • Separate concurrent events. Different tracks or zones can produce multiple incidents in one source video.
  • Score the event. Combine supporting frames and mapping consistency rather than selecting only the highest frame score.
  • Create stable evidence references. Review and appeal flows should address the same immutable candidate package.
{
  "job_id": "job_01J...",
  "status": "review_required",
  "incidents": [
    {
      "incident_id": "inc_01J...",
      "camera_id": "camera-east-02",
      "occurred_at": "2026-07-29T09:14:32.480Z",
      "candidate_locations": [
        { "zone_id": "flat-7b", "confidence": 0.82 }
      ],
      "model_confidence": 0.88,
      "evidence": {
        "frame_ids": ["frame-1834", "frame-1842"],
        "calibration_version": "east-02-v4"
      },
      "review": { "status": "pending" }
    }
  ]
}

07API lifecycle

Make every long-running state explicit

Clients should not infer job state from missing results or HTTP timeouts. A state model gives the CRM, workers, operators, and retention tasks one vocabulary.

Loading diagram…

  1. Created jobs wait for an authenticated upload.
  2. An upload can complete and enter validation or expire before completion.
  3. Validated media enters the queue; invalid media fails with a reason.
  4. A worker claims queued work and marks it processing.
  5. Transient processing failure enters a bounded retryable state.
  6. Candidate incidents enter review-required; empty results can complete directly.
  7. Review can confirm completion or reject the candidate while still completing analysis.
  8. Created, uploading, queued, or processing work can be cancelled through guarded transitions.
The video-analysis job state machine. Explicit states let clients and operators distinguish waiting, no incident, review, retry, cancellation, expiry, and failure.

Transitions need idempotency and preconditions. An upload event delivered twice must not create two analyses. A late worker must not overwrite a cancelled job. A retry should continue from stored artifacts rather than repeating every completed stage.

08Production quality

Operate queues and measure events

A queue decouples ingestion from processing, but it does not guarantee that work happens exactly once. RabbitMQ’s reliability guidance describes acknowledgements, redelivery, publisher confirms, and the need for idempotent consumers.

  • Control backpressure. Bound upload size and duration, queue depth, per-tenant concurrency, worker memory, and inference rate.
  • Classify failures. Retry transient storage, network, and model-service errors with limits; dead-letter unsupported or repeatedly failing media.
  • Evaluate at event level. Measure missed incidents, duplicate incidents, false candidates, location accuracy, review correction, and time-to-result.
  • Stratify the dataset. Include camera angles, day/night, weather, compression, occlusion, event duration, and empty footage.
  • Monitor drift. Camera movement, scene changes, new codecs, and model updates can invalidate previous thresholds and calibration.

09People in the frame

Responsible use is part of the architecture

Surveillance data can expose residents, staff, visitors, homes, routines, and disputes. A technically accurate pipeline can still create unacceptable privacy or governance risk. The NIST Privacy Framework provides a general approach for identifying and managing privacy risk; applicable law and local policy require specialist review.

  • Define purpose and authority. Document which incidents the system may process, who authorised it, and which uses are prohibited.
  • Minimise collection and retention. Process only required cameras and time windows; delete source video, frames, and derived identifiers on defined schedules.
  • Restrict access. Separate upload, processing, review, administration, and export permissions; record every evidence access.
  • Require human verification. A trained, authorised reviewer confirms evidence before enforcement or communication.
  • Support correction and appeal. Preserve review rationale, notify through an appropriate process, and allow disputed results to be re-examined.
  • Provide notice. Signage, policy, and user communication should explain the system’s purpose, retention, contact, and complaint path.

10Implementation sketch

An idempotent processing worker

The worker should read a durable job record, claim one processing attempt, store intermediate artifacts by stable identity, and finish through a guarded state transition.

def process_video(job_id: str, delivery_id: str) -> None:
    job = jobs.claim(
        job_id=job_id,
        delivery_id=delivery_id,
        allowed_states={"queued", "retryable"},
    )
    if job is None:
        return

    media = object_store.open_verified(job.object_key, job.checksum)
    calibration = calibrations.for_camera(
        camera_id=job.camera_id,
        captured_at=job.capture_started_at,
    )

    observations = []
    for frame in sampler.frames(media, policy=job.sampling_policy):
        for detection in detector.detect(frame.image):
            observations.append(
                normalize(detection, frame, calibration)
            )

    candidates = aggregate_events(observations)
    incidents = [
        map_and_package(candidate, calibration)
        for candidate in candidates
    ]

    jobs.complete(
        job_id=job.id,
        attempt=job.attempt,
        incidents=incidents,
        next_state="review_required" if incidents else "completed",
    )

11Before launch

A video-intelligence checklist

  1. Version the contract. Job, observation, incident, evidence, and review schemas evolve independently of one model.
  2. Test real media. Validate codecs, timestamps, rotations, variable frame rates, corrupted files, and camera-specific calibration.
  3. Exercise queue failure. Duplicate, delay, reorder, retry, cancel, and dead-letter jobs without duplicating incidents.
  4. Evaluate event outcomes. Tune the complete pipeline against reviewed incidents and empty footage.
  5. Review privacy controls. Confirm purpose, notice, access, retention, deletion, review, appeal, and evidence-export behavior.
  6. Keep enforcement separate. The API produces reviewable evidence; authorised business processes decide what happens next.

12Working vocabulary

Glossary

Frame sampling
Selecting which video frames or time windows receive more expensive analysis.
Detection
A model observation containing a predicted class, score, and image coordinates.
Tracking
Associating observations across frames to estimate one object’s temporal path.
Calibration
Versioned information connecting image coordinates to the configured physical zones visible to a camera.
Event aggregation
Combining related frame-level observations into one candidate real-world incident.
Idempotent consumer
A worker that can receive the same job more than once without duplicating its intended outcome.
Dead-letter
Routing work that cannot be processed safely to a separate path for inspection, correction, or expiry.
Evidence package
The bounded frames, metadata, calibration identity, and rationale required to review a candidate incident.

13Sources and further reading

References

  1. How We Turned Dumb CCTV Footage into a Smart API

    Abhishek Choudhury

    Original project article, published February 2025.
  2. OpenCV VideoCapture class reference

    OpenCV

    Video-file, image-sequence, camera, and stream capture behavior.
  3. Download and upload objects with presigned URLs

    Amazon Web Services

    A dated example of scoped, time-limited object upload access.
  4. RabbitMQ Reliability Guide

    Broadcom

    Acknowledgements, redelivery, publisher safety, and consumer idempotency.
  5. Detect multiple objects with Object Localization

    Google Cloud

    A dated managed-service example of object bounds and scores.
  6. NIST Privacy Framework

    National Institute of Standards and Technology

    A voluntary framework for identifying and managing privacy risk.

From the archive

Keep reading

View all articles