Skip to content

Python API

Trackflow ships inline type annotations (py.typed) and exposes both a high-level batch/streaming pipeline (TrackflowPipeline) and every underlying detector, tracker, Re-ID, VLM, and analytics building block.

Quick examples

Batch run with exports

from trackflow import CountingLine, TrackflowPipeline

pipeline = TrackflowPipeline(
    model="rtdetr-v2-r18",
    tracker="botsort",
    reid="osnet",
    classes=["person"],
    lines=[CountingLine("door", (640, 300), (640, 720))],
    anonymize="face-blur",
)
summary = pipeline.run("crowd.mp4", exports=("parquet", "jsonl"))
print(f"{summary.unique_tracks} tracks at {summary.avg_fps:.1f} FPS -> {summary.output_files['parquet']}")

Zero-disk in-memory streaming

import cv2
from trackflow import TrackflowPipeline

pipeline = TrackflowPipeline(model="rfdetr-nano", tracker="bytetrack")
cap = cv2.VideoCapture("rtsp://camera.local/stream")

def frames():
    while True:
        ok, frame = cap.read()
        if not ok:
            return
        yield frame  # BGR uint8

for result in pipeline.stream(frames(), fps=25.0):
    for track in result.tracks:
        print(result.frame_idx, result.timestamp_s, track.track_id, track.class_name, track.bbox)

Pipeline

TrackflowPipeline

TrackflowPipeline(*, model: str | Path | None = None, precision: Precision = 'fp32', tracker: str = 'bytetrack', use_cmc: bool = True, device: str = 'auto', threshold: float = 0.45, classes: Sequence[str] | None = ('person',), reid: ReidBackend = 'none', vlm: VlmBackend | None = None, reid_merge: bool = False, postprocess: bool = False, query: str | None = None, query_threshold: float | None = None, anonymize: AnonymizeMode = 'none', homography: FloorplanHomography | str | Path | None = None, lines: Sequence[CountingLine] = (), detector: Detector | None = None, tracker_factory: Callable[[], Tracker] | None = None, reid_embedder: ReidEmbedder | None = None, vlm_embedder: VlmEmbedder | None = None, mask_fallback: str | None = None, mask_propagator: MaskPropagator | None = None, mask_fallback_config: MaskFallbackConfig | None = None, cache_dir: str | Path | None = None)

Unified real-time tracking pipeline combining detection, MOT, Re-ID/NL query, privacy & floorplan.

stream

stream(frames: Iterable[ndarray], *, fps: float = 30.0) -> Iterator[FrameResult]

Yield observations for consecutive BGR uint8 frames without writing any files.

Each call starts a fresh tracker. With re-entry merging or mask fallback enabled, committed fixes apply to subsequent frames; observations already yielded keep their original ID.

run

run(source: str | Path | int, *, output_dir: str | Path | None = None, skip: int = 0, fps: float | None = None, max_frames: int | None = None, save_video: bool = True, exports: Sequence[str] = ('parquet', 'jsonl', 'html'), display: bool = False, progress_callback: Callable[[int, int, float], None] | None = None) -> RunSummary

Execute tracking on source and write requested artifacts into output_dir.

Ctrl-C stops reading frames and still writes every artifact for the frames processed so far, which is how a camera or stream run ends. A second Ctrl-C aborts.


Detectors

create_detector

create_detector(model: str | Path = 'rtdetr-v2-r18', *, precision: Precision = 'fp32', device: str = 'auto', threshold: float = 0.45, classes: Sequence[str] | None = ('person',), cache_dir: str | Path | None = None) -> Detector

Load a preset, compatible ONNX graph/repository, or hf:owner/repo Transformers checkpoint.

Detector

Bases: Protocol

A detector accepts one BGR uint8 frame and returns pixel-space xyxy boxes.

OnnxDetrDetector

OnnxDetrDetector(model: str = 'rtdetr-v2-r18', *, precision: Precision = 'fp32', device: str = 'auto', threshold: float = 0.45, classes: Sequence[str] | None = ('person',), cache_dir: str | Path | None = None)

End-to-end transformer object detector powered by ONNX Runtime.

preprocess

preprocess(frame_bgr: ndarray) -> np.ndarray

Convert OpenCV BGR uint8 frame to NCHW float tensor.

detect

detect(frame_bgr: ndarray, threshold: float | None = None) -> list[Detection]

Run object detection on a single BGR frame.

ModelSpec dataclass

ModelSpec(name: str, repo_id: str, architecture: str, license: str, approx_size_mb: float, default_input_size: tuple[int, int], description: str, revision: str | None = None, backend: Literal['onnx', 'transformers'] = 'onnx', onnx_file: str | None = None, normalize: bool = False, coreml_format: Literal['MLProgram', 'NeuralNetwork'] = 'MLProgram', trt_fp16: bool = True, letterbox: bool = False)

Descriptor for a built-in detector. Sizes are decimal MB at FP32.


Trackers

create_tracker

create_tracker(tracker_name: str = 'bytetrack', *, track_high_thresh: float = 0.5, track_low_thresh: float = 0.15, new_track_thresh: float = 0.55, track_buffer: int = 30, iou_buffer: float = 0.0, use_cmc: bool = True) -> Tracker

Factory for the built-in multi-object trackers, named as in :data:TRACKER_NAMES.

Tracker

Bases: Protocol

A stateful per-source tracker. Return the observations for the current frame.

ByteTracker

ByteTracker(*, track_high_thresh: float = 0.5, track_low_thresh: float = 0.15, new_track_thresh: float = 0.55, match_thresh: float = 0.8, second_match_thresh: float = 0.5, unconfirmed_match_thresh: float = 0.7, track_buffer: int = 30, spawn_overlap_thresh: float = 0.8, duplicate_iou: float = 0.85, iou_buffer: float = 0.0)

ByteTrack multi-object tracker (Zhang et al., ECCV 2022) with diagnostic event reporting.

Follows the reference association order:

  1. confirmed + lost tracks <-> high-score detections (IoU, optionally buffered)
  2. remaining tracked tracks <-> low-score detections (IoU)
  3. unconfirmed tracks <-> remaining high-score detections (IoU, optionally buffered); unmatched ones are dropped
  4. new unconfirmed tracks from leftover high-score detections. A track only gets a public ID (and is only output) once a second detection confirms it, so one-frame false positives never show up as IDs. Detections mostly covered by a track already updated this frame (spawn_overlap_thresh, intersection over detection area) don't start new tracks, which stops partial-body duplicate boxes from spawning ghost IDs.
  5. tracked/lost tracks overlapping by IoU > duplicate_iou are de-duplicated (older wins).

update

update(detections: list[Detection], frame_bgr: ndarray | None = None) -> list[Track]

Advance the tracker by one frame and return the confirmed tracks observed this frame.

coasting_tracks

coasting_tracks(max_frames: int = 3) -> list[Track]

Confirmed tracks missed for at most max_frames frames, at their predicted position.

Useful for display and anonymization so boxes don't blink when the detector misses a frame. These are predictions, not observations; they are never written to exports.

BotSortTracker

BotSortTracker(*, track_high_thresh: float = 0.5, track_low_thresh: float = 0.15, new_track_thresh: float = 0.55, match_thresh: float = 0.8, second_match_thresh: float = 0.5, unconfirmed_match_thresh: float = 0.7, track_buffer: int = 45, spawn_overlap_thresh: float = 0.8, iou_buffer: float = 0.0, use_cmc: bool = True, proximity_thresh: float = 0.5, appearance_thresh: float = 0.25)

Bases: ByteTracker

BoT-SORT tracker: ByteTrack + camera motion compensation + appearance Re-ID fusion.

Differs from :class:ByteTracker in three ways:

  • a Kalman filter on [cx, cy, w, h] with confidence-scaled measurement noise (see :class:XywhKalmanFilter);
  • camera motion estimated from background corners only (see :class:SparseOpticalFlowCMC), warping each track's position, size, velocity and covariance into the current frame;
  • optional appearance fusion with person Re-ID embeddings.

Appearance only helps when embeddings come from a person Re-ID model (--reid osnet); CLIP/SigLIP image embeddings barely separate different people and must not be used here.

OcSortTracker

OcSortTracker(*, det_thresh: float = 0.5, low_thresh: float = 0.1, iou_threshold: float = 0.3, max_age: int = 30, min_hits: int = 3, delta_t: int = 3, inertia: float = 0.2, use_byte: bool = True, iou_buffer: float = 0.0, use_cmc: bool = True, new_track_thresh: float | None = None)

Bases: _SortStyleTracker

OC-SORT: SORT made robust to occlusion by trusting observations over predictions.

Each frame:

  1. high-score detections <-> confirmed tracks' predicted boxes, by IoU plus observation-centric momentum (OCM): a bonus, weighted by inertia and the detection score, when the direction from the track's observation delta_t frames back to the detection agrees with the track's recent direction of motion;
  2. observation-centric recovery (OCR): remaining high-score detections <-> remaining tracks' last observed boxes by IoU, which recovers tracks the filter has drifted off;
  3. with use_byte, low-score detections <-> remaining confirmed tracks seen on the previous frame, by IoU;
  4. remaining high-score detections <-> tentative (not yet confirmed) tracks, by IoU;
  5. unmatched detections at or above new_track_thresh spawn tracks, unless mostly covered by a box matched this frame. A tentative track that misses a frame is dropped.

A track that matches again after missing frames is re-updated along a virtual trajectory (ORU). Confirmed tracks report the matched detection's box.

update

update(detections: list[Detection], frame_bgr: ndarray | None = None) -> list[Track]

Advance the tracker by one frame and return the tracks reported on it.

BoostTracker

BoostTracker(*, det_thresh: float = 0.5, iou_threshold: float = 0.3, max_age: int = 30, min_hits: int = 3, lambda_iou: float = 0.5, lambda_mhd: float = 0.25, lambda_shape: float = 0.25, dlo_boost: bool = True, duo_boost: bool = False, use_cmc: bool = True, iou_buffer: float = 0.0, new_track_thresh: float | None = None)

Bases: _SortStyleTracker

BoostTrack++: SORT with a richer similarity and detection-confidence boosting.

Each frame:

  1. tracks move with camera motion (use_cmc), then are predicted;
  2. detection scores are boosted. A detection that closely matches a track (by Mahalanobis distance, shape and a soft buffered IoU) is likely a real object (DLO boost). A low-score detection far from every track, and stronger than overlapping such detections, is likely a new object (DUO boost). Detections still below det_thresh are dropped;
  3. detections <-> tracks by IoU, plus IoU weighted by detection and track confidence, Mahalanobis and shape similarity, and appearance when detections carry Re-ID embeddings. A pair needs IoU >= iou_threshold, or half that with appearance similarity >= 0.75;
  4. unmatched detections spawn tracks.

A track's confidence is low while it is young and decays while it goes unmatched. Confirmed tracks report the filter's estimate.

update

update(detections: list[Detection], frame_bgr: ndarray | None = None) -> list[Track]

Advance the tracker by one frame and return the tracks reported on it.

NonLinearTracker

NonLinearTracker(*, track_high_thresh: float = 0.5, track_low_thresh: float = 0.15, new_track_thresh: float = 0.55, track_buffer: int = 60, iou_buffer: float = 0.0, use_cmc: bool = True, vel_damp: float = 0.9, delta_t: int = 3, inertia: float = 0.15, bank_size: int = 15, clean_ovl_thresh: float = 0.4, emb_weight: float = 3.5, softmax_temp: float = 0.13, null_std: float = 1.0, margin_weight: float = 0.25, ema_blend: float = 0.5, occ_exp_max: float = 0.2, occ_exp_rate: float = 0.03, active_iou_gate: float = 0.2, lost_iou_gate: float = 0.18, reid_active_iou_gate: float = 0.05, reid_rescue_z: float = 1.3, reid_rescue_margin: float = 0.25, reid_rescue_max_disp: float = 8.0, active_low_iou: float = 0.5, lost_low_max_tsu: int = 14, lost_low_iou: float = 0.6, lost_low_conf: float = 0.2, stage2_min_rel_height: float = 0.52, stage2_high_frac: float = 0.92, tai_iou_thresh: float = 0.55, spawn_overlap_thresh: float = 0.8, duplicate_iou: float = 0.85, min_confirm_hits: int = 4)

Dual-anchor non-linear tracker with clean-bank adaptive appearance and lost-track recovery.

update

update(detections: list[Detection], frame_bgr: ndarray | None = None) -> list[Track]

Advance the tracker by one frame and return confirmed tracks observed this frame.

coasting_tracks

coasting_tracks(max_frames: int = 3) -> list[Track]

Confirmed tracks missed for at most max_frames frames, at their predicted position.


ReidEmbedder

ReidEmbedder(backend: ReidBackend = 'osnet', *, device: str = 'auto', cache_dir: str | Path | None = None)

Person identity embeddings: OSNet-AIN (ONNX) or a weight-free HSV color descriptor.

encode_images

encode_images(crops: list[ndarray | None]) -> list[np.ndarray | None]

Embed a batch of BGR crops; None/empty crops map to None.

VlmEmbedder

VlmEmbedder(backend: VlmBackend = 'clip', *, precision: Precision = 'int8', device: str = 'auto', cache_dir: str | Path | None = None)

CLIP / SigLIP image+text embeddings for natural-language queries and search.

encode_image

encode_image(crop_bgr: ndarray | None) -> np.ndarray | None

Encode a BGR crop into an L2-normalized image embedding (text-aligned).

encode_text

encode_text(query: str) -> np.ndarray

Encode a natural-language query into the shared vision-language embedding space.

TrackCardIndex

TrackCardIndex(*, vlm: VlmEmbedder | None = None, reid: ReidEmbedder | None = None, query: str | None = None, query_threshold: float | None = None, reid_merge: bool = False, reid_merge_threshold: float = 0.8, reid_merge_margin: float = 0.05, merge_min_samples: int = 3, reid_sample_every: int = 3, min_reid_height: float = 48.0, min_exit_gap_frames: int = 8, crops_dir: Path | None = None)

Persistent Track Cards, NL query scores, and opt-in cross-exit identity merges.

Cross-exit merging (reid_merge=True, requires a :class:ReidEmbedder) gives a returning person their earlier ID. A new track is compared only after merge_min_samples identity samples, only against cards that ended at least min_exit_gap_frames before it started (so two people visible at the same time can never share an ID), and it merges only when the best match clears reid_merge_threshold and beats the runner-up by reid_merge_margin. Look-alikes (e.g. several people in dark jackets) are left unmerged rather than guessed.

reconcile_relink(src_id: int, dst_id: int) -> None

Fold a short-lived fragmented track card into its mask-reconciled destination.

update

update(frame_idx: int, timestamp_s: float, frame_bgr: ndarray, tracks: list[Track], frame_dt_s: float = 0.0) -> list[dict[str, Any]]

Update Track Cards, perform opt-in cross-exit merges, and score NL queries.

rebuild_from_postprocess

rebuild_from_postprocess(records: list[dict[str, Any]], source_row_indices: ndarray, raw_track_ids: list[int], *, frame_dt_s: float = 0.0, reid_merges: int = 0) -> None

Rebuild Track Cards from finalized offline post-processed records.

Carries over saved thumbnails and VLM embeddings from contributing raw cards (averaging embeddings across merged raw IDs), recomputes query scores, and updates each record's query_score and query_match fields in place. Never writes crops when self.crops_dir is None (anonymized runs).


Analytics & Privacy

CountingLine dataclass

CountingLine(name: str, start: Point, end: Point)

Named line segment in image pixels.

A crossing to the right of the direction from start to end counts as in, the other way as out. For a line drawn left to right, in means moving down the frame.

parse classmethod

parse(spec: str, default_name: str) -> CountingLine

Parse [name=]x1,y1,x2,y2, as passed to trackflow run --line.

side

side(point: Point) -> float

Positive on the in side, negative on the out side, zero on the line.

spans

spans(p: Point, q: Point) -> bool

Whether the infinite line through p and q meets this segment.

FloorplanHomography dataclass

FloorplanHomography(image_points: list[tuple[float, float]], world_points: list[tuple[float, float]], width_m: float = 10.0, height_m: float = 10.0, zones: list[DwellZone] = list(), _trajectories: dict[int, list[tuple[float, float]]] = dict(), zone_dwell_totals_s: dict[str, float] = dict())

Maps 2D camera ground points onto a top-down bird's-eye floorplan via 4-point homography.

fresh

fresh() -> FloorplanHomography

Reuse this calibration for an independent stream with empty trajectories and dwell totals.

project

project(image_xy: tuple[float, float]) -> tuple[float, float]

Project a single 2D image pixel point (e.g. foot point) into floorplan (x, y).

observe

observe(track_id: int, foot_xy: tuple[float, float], dt_s: float = 0.0) -> tuple[tuple[float, float], str | None]

Project a track observation, accumulate heatmap & dwell metrics, and return (world_xy, zone).

render_floorplan

render_floorplan(out_path: str | Path, canvas_size: tuple[int, int] = (800, 600)) -> Path

Render a high-contrast bird's-eye floorplan PNG with heatmap, dwell zones, and trajectories.

DwellZone dataclass

DwellZone(name: str, polygon: list[tuple[float, float]], color: str = '#38bdf8')

Named polygon in top-down floorplan coordinates.

PrivacyAnonymizer

PrivacyAnonymizer(mode: AnonymizeMode = 'none', *, strength: int = 31, margin: float = 0.08)

Applies privacy-preserving transformations to every detected person box.

apply

apply(frame_bgr: ndarray, tracks: Sequence[Track], *, detections: Sequence[Detection] = (), coasting: Sequence[Track] = ()) -> np.ndarray

Return an anonymized copy of frame_bgr.

Anonymizes the boxes of tracks, of briefly-missed coasting tracks, and of all raw detections (pass every detection, not only the ones that became tracks).


Data Types

Detection dataclass

Detection(bbox: tuple[float, float, float, float], confidence: float, class_id: int, class_name: str, embedding: ndarray | None = None)

Single object detection in pixel coordinates (x1, y1, x2, y2).

foot_point property

foot_point: tuple[float, float]

Bottom-center ground contact point used for floorplan homography.

Track dataclass

Track(track_id: int, bbox: tuple[float, float, float, float], confidence: float, class_id: int, class_name: str, age: int = 1, hits: int = 1, recovered: bool = False, coasting: bool = False, query_score: float | None = None, query_match: bool = True, world_xy: tuple[float, float] | None = None, zone: str | None = None, reid_merged_from: int | None = None)

Active tracked object at a specific frame.

FrameResult dataclass

FrameResult(frame_idx: int, timestamp_s: float, tracks: list[Track], num_detections: int, inference_ms: float, tracking_ms: float, events: list[dict[str, Any]] = list())

Per-frame tracking output and timing telemetry.

RunSummary dataclass

RunSummary(source: str, model: str, tracker: str, device: str, total_frames: int, processed_frames: int, source_fps: float, avg_fps: float, avg_inference_ms: float, avg_tracking_ms: float, total_detections: int, total_track_observations: int, unique_tracks: int, recovered_tracks: int, reid_merges: int, elapsed_s: float, frame_width: int, frame_height: int, classes: list[str], query: str | None = None, anonymize_mode: str = 'none', output_files: dict[str, str] = dict(), zone_dwell_totals_s: dict[str, float] = dict(), line_counts: dict[str, dict[str, int]] = dict(), frame_stride: int = 1, model_revision: str | None = None, precision: str | None = None, tracking_threshold: float | None = None, mask_fallback: dict[str, Any] | None = None, postprocessed: bool = False)

Aggregate summary of a completed Trackflow run.

TrackCard dataclass

TrackCard(track_id: int, class_name: str, first_frame: int, last_frame: int, first_timestamp_s: float, last_timestamp_s: float, frame_count: int, best_confidence: float, best_frame: int, best_bbox: tuple[float, float, float, float], thumbnail_relpath: str | None = None, embedding: list[float] | None = None, query_score: float | None = None, query_match: bool = True, merged_track_ids: list[int] = list(), zones_visited: list[str] = list(), dwell_seconds: dict[str, float] = dict())

Persistent entity summary for a tracked person/object across its lifetime.

HomographyPoint dataclass

HomographyPoint(image_xy: tuple[float, float], world_xy: tuple[float, float])

A 2D image-to-floorplan calibration correspondence.