Tracking by detection: SORT, Deep SORT and ByteTrack
Link a detector's boxes into identities: predict where each track goes, match detections to tracks, update. SORT matches by overlap, Deep SORT adds appearance inside a motion gate, ByteTrack rescues low-confidence boxes.
What runs in CodeSplash
- VID034Simple Online and Realtime Tracking (SORT) Runs in CodeSplash (Experimental)
- VID035Deep SORT Runs in CodeSplash (Experimental)
- VID036ByteTrack Runs in CodeSplash (Experimental)
- Track objects across frames (SORT, ByteTrack, DeepSORT-style) Experimental
You will be able to
- Describe the predict, associate and update loop and the track life cycle
- Write SORT's assignment problem and say what it can't see
- Explain Deep SORT's appearance distance and motion gate
- Explain ByteTrack's two matching rounds and why low-confidence boxes help
- Run all three on a table of boxes in CodeSplash, holding the detections fixed
Predict, match, update
ReadA detector finds boxes in each frame but doesn't know that the person in frame 40 is the person in frame 41. Tracking by detectionMulti-object tracking (tracking by detection)Linking detections in consecutive frames into tracks, so each object keeps one id while it moves through the video. adds that, frame by frame:
- Predict. A Kalman filterKalman filterExact filtering for linear-Gaussian state-space models: the hidden state's mean and variance, updated step by step. moves each track's box forward by its estimated velocity.
- Match. Predicted boxes are paired one-to-one with this frame's detections.
- Update. Matched tracks correct their state; unmatched detections may start tracks; tracks unmatched for too long end.
The time-series track teaches the same method from the app's side ("Following objects through a video"); this lesson follows the reference's three algorithms.
SORT: overlap and assignment
ReadSORT's cost of pairing track with detection is one minus their IoUIntersection over union (IoU) of boxesThe area two boxes share divided by the area they cover together: 1 for the same box, 0 when they don't touch., and the Hungarian methodHungarian method (linear assignment)Pairs two lists (tracks and detections) one-to-one so the total cost is smallest; ties go to the lowest index in CodeSplash. finds the pairing with the lowest total cost:
Pairs below a minimum overlap are refused, and those tracks and detections stay unmatched. In the reference's toy, two tracks and two detections pair diagonally at a total cost of 0.3. SORT has no learned weights of its own; the detector is the deep part.
DExplorable · Boxes, IoU, non-maximum suppression and average precision
How does a detector turn a cloud of overlapping guesses into one box per object, and how is it scored?
After NMS at this threshold, will every object still have at least one box?
Scene
Three well-separated objects, two people standing close together plus one more, or four small objects.
A box is dropped when it overlaps a higher-scoring kept box by more than this IoU.
Candidates scoring below this are dropped before NMS.
IoU to count a hit
A kept box counts as a true positive when it overlaps an unmatched object by at least this much.
How far the detector's guesses wander from each true box, as a share of its size.
Numbers on the kept boxes are their scores. AP averages the best precision reachable at 101 recall levels, so a false positive ranked above a hit costs more than one ranked last.
Commit your prediction above to see the result
Make your prediction to see the result.
Two people cross
PredictPredict first
Two pedestrians walk toward each other, overlap for a few frames and part. SORT sees only boxes and motion. What can go wrong?
Reveal
The identities can swap, or a track can end and restart with a new id. While the boxes overlap, overlap can't tell the people apart, and a constant-velocity guess breaks if either one turns. Nothing in SORT knows what either person looks like. That gap is what Deep SORT fills.
Deep SORT: what it looks like, where it could be
ReadDeep SORT gives each box an appearance embeddingAppearance embeddingA vector describing how an object looks, so the same object can be recognized after it was hidden. from a re-identification network and keeps a short gallery of each track's recent embeddings. The cost is the cosine distance to the closest one:
A motion gateMotion gateA rule that forbids a match when a detection is too far from where the motion model expects the track to be. forbids pairs the Kalman filter finds implausible, and recently seen tracks are matched first. In the reference's toy, the matching pairs cost 0.0061 and the gated pairs are set to infinity: allowed only where motion agrees.
DeepSORT-style matching in CodeSplash
Explore7 tracks from 184 detections in 2 sequences (DeepSORT-style association); 178 detections joined a track. Against 7 reference tracks: MOTA 0.886, IDF1 0.939, 0 identity switches.
- Tracks
- 7
- MOTA
- 0.8856
- IDF1
- 0.9393
- Identity switches
- 0
Plots
Bars break where a track missed more than one frame.
View data
| media_id | Last frame | Track | frame |
|---|---|---|---|
| cam1 | 5 | 1 · person | 0 |
| cam1 | 11 | 1 · person | 7 |
| cam1 | 15 | 1 · person | 14 |
| cam1 | 22 | 1 · person | 17 |
| cam1 | 34 | 1 · person | 24 |
| cam1 | 39 | 1 · person | 36 |
| cam1 | 3 | 2 · person | 0 |
| cam1 | 6 | 2 · person | 5 |
| cam1 | 22 | 2 · person | 8 |
| cam1 | 26 | 2 · person | 24 |
| cam1 | 36 | 2 · person | 28 |
| cam1 | 39 | 2 · person | 38 |
| cam1 | 29 | 3 · car | 5 |
| cam1 | 21 | 4 · person | 18 |
| cam1 | 25 | 4 · person | 23 |
| cam1 | 30 | 4 · person | 27 |
| cam1 | 39 | 4 · person | 32 |
| cam2 | 10 | 5 · car | 0 |
| cam2 | 13 | 5 · car | 12 |
| cam2 | 17 | 5 · car | 15 |
| cam2 | 23 | 5 · car | 20 |
| cam2 | 25 | 5 · car | 25 |
| cam2 | 29 | 5 · car | 27 |
| cam2 | 23 | 6 · person | 3 |
| cam2 | 25 | 6 · person | 25 |
| cam2 | 29 | 6 · person | 27 |
| cam2 | 25 | 7 · person | 10 |
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
- Embeddings describe appearance — DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 34 | 0.7042 |
| 2 | cam1 | person | 0 | 39 | 40 | 35 | 0.7363 |
| 3 | cam1 | car | 5 | 29 | 25 | 25 | 0.7794 |
| 4 | cam1 | person | 18 | 39 | 22 | 19 | 0.8095 |
| 5 | cam2 | car | 0 | 29 | 30 | 24 | 0.7069 |
| 6 | cam2 | person | 3 | 29 | 27 | 25 | 0.7759 |
| 7 | cam2 | person | 10 | 25 | 16 | 16 | 0.8254 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8856 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.9393 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8808 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 20 | A tracked object was lost and found again |
| Misses | 23 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 7 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact R script · R R version 4.5.1 (2025-06-13)
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 0821a0bf81fcd49d
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_track_objects (tracker), cs_eval_mot (tracking metrics), cs_eval_stacked
# %% Data
SEQ <- "media_id"; FRAME <- "frame"
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
SCORE <- "score"
LABEL <- "label"
FEATURES <- c("emb_1", "emb_2", "emb_3", "emb_4", "emb_5", "emb_6")
SOURCE <- "source"
TRUTH <- "track_id"
MODE <- "deepsort" # sort | bytetrack | deepsort
OPTS <- list(iou = 0.3, min_hits = as.integer(3), max_age = as.numeric(30),
min_score = 0, high = 0.6, low = 0.1,
low_iou = 0.5, max_cosine = 0.3, motion_weight = 0.2,
per_class = TRUE)
MOT_IOU <- 0.5
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction") # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
FEATURES <- if (length(FEATURES)) as.character(FEATURES) else character(0)
columns <- unique(c(SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH, FEATURES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_tracks.parquet", col_select = columns))
df$`__row` <- seq_len(nrow(df)) - 1L # position in the analysis input
n_input <- nrow(df)
if (MODE == "bytetrack" && is.null(SCORE)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or DeepSORT-style unless a confidence score column is set", value = "ByteTrack")
if (MODE == "deepsort" && !length(FEATURES)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or ByteTrack unless embedding columns are set", value = "DeepSORT-style")
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above the detections under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/track.objects/deepsort-embeddings/out-r", "reference_table"),
list(sequence = SEQ, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, score = SCORE, label = LABEL, truth = TRUTH),
REF_ROLES, list(label = "Class"), SOURCE, REF_LEVEL, c("sequence", "frame", "x0", "y0", "x1", "y1", if (!is.null(LABEL)) "label"))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
SEQ <- wc$sequence; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
LABEL <- wc$label; TRUTH <- wc$truth
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
}
needed <- c(SEQ, FRAME, X0, Y0, X1, Y1, LABEL)
numeric_cols <- c(FRAME, X0, Y0, X1, Y1, SCORE, FEATURES)
if (!is.null(SOURCE)) {
st <- cs_eval_stacked(df, c(needed, SOURCE), numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
} else {
if (n_input == 0L) cs_error("CS_E_NO_ROWS")
for (c in needed) if (all(is.na(df[[c]]))) cs_error("CS_E_ALL_MISSING", column = c)
keep <- rep(TRUE, n_input)
for (c in needed) keep <- keep & !is.na(df[[c]])
df <- df[keep, , drop = FALSE]
warnings <- if (nrow(df) < n_input) list(cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input)) else list()
if (nrow(df) == 0L) cs_error("CS_E_NO_ROWS")
for (c in numeric_cols) {
k <- sum(is.infinite(as.numeric(df[[c]])))
if (k > 0) cs_error("CS_E_NOT_FINITE", column = c, count = k)
}
is_ref <- logical(nrow(df))
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
det <- !is_ref
if (!is.null(SCORE)) {
no_score <- det & is.na(as.numeric(df[[SCORE]]))
if (any(no_score)) {
warnings <- c(warnings, sprintf("%d detections have no %s and were left out.", sum(no_score), SCORE))
det <- det & !no_score
}
}
if (length(FEATURES)) {
no_feat <- det & !stats::complete.cases(df[FEATURES])
if (any(no_feat)) {
warnings <- c(warnings, sprintf("%d detections miss an embedding value and were left out.", sum(no_feat)))
det <- det & !no_feat
}
}
if (sum(det) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Tracking", min = 2, n = sum(det))
# %% Tracks
di <- which(det)
seq_all <- as.character(df[[SEQ]])
frame_all <- as.numeric(df[[FRAME]])
lab_all <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
feats <- if (length(FEATURES)) as.matrix(df[di, FEATURES, drop = FALSE]) else NULL
if (!is.null(feats)) storage.mode(feats) <- "double"
res <- cs_track_objects(seq_all[di], frame_all[di], box[di, , drop = FALSE], if (!is.null(SCORE)) as.numeric(df[[SCORE]])[di] else NULL,
if (!is.null(LABEL)) lab_all[di] else NULL, feats, MODE, OPTS)
tid_det <- res$track
track_id <- rep(NA_integer_, n_input) # per input row; rows that weren't tracked stay empty
track_id[df$`__row`[di][tid_det > 0L] + 1L] <- tid_det[tid_det > 0L]
tracks <- res$tracks
n_tracks <- length(tracks)
n_assigned <- sum(tid_det > 0L)
# %% Against the reference tracks
metrics <- NULL
switch_events <- list()
if (!is.null(SOURCE) && !is.null(TRUTH) && sum(is_ref) > 0) {
truth_ok <- is_ref & !is.na(df[[TRUTH]])
if (sum(is_ref & !truth_ok) > 0) warnings <- c(warnings, sprintf("%d reference boxes have no %s and were left out of the tracking metrics.", sum(is_ref & !truth_ok), TRUTH))
truth_all <- as.character(df[[TRUTH]])
gi <- which(truth_ok)
hi <- di[tid_det > 0L]
hyp_of <- integer(nrow(df))
hyp_of[di] <- tid_det
seqs <- list()
for (sq in sort(unique(c(seq_all[gi], seq_all[hi])), method = "radix")) {
g_s <- gi[seq_all[gi] == sq]
h_s <- hi[seq_all[hi] == sq]
frames <- list()
for (f in sort(unique(c(frame_all[g_s], frame_all[h_s])))) {
g_f <- g_s[frame_all[g_s] == f]
h_f <- h_s[frame_all[h_s] == f]
# paste() would recycle an empty id vector into one id: frames with predictions but no reference boxes get none.
gt_ids <- if (length(g_f)) paste(sq, truth_all[g_f], sep = "\u001f") else character(0)
frames[[length(frames) + 1L]] <- list(frame = f, gt_ids = gt_ids, gt_boxes = box[g_f, , drop = FALSE],
hyp_ids = as.character(hyp_of[h_f]), hyp_boxes = box[h_f, , drop = FALSE])
}
seqs[[length(seqs) + 1L]] <- frames
}
metrics <- cs_eval_mot(seqs, MOT_IOU)
switch_events <- metrics$switch_events
}
# %% Assumptions
assumptions <- list(
list(key = "frames", label = "Frames are in order", status = "info",
detail = "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."),
list(key = "motion", label = "Objects move smoothly", status = "info",
detail = "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.")
)
if (length(FEATURES)) assumptions[[3]] <- list(key = "appearance", label = "Embeddings describe appearance", status = "info",
detail = "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.")
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tl <- vapply(tracks, function(t) if (is.na(t$label)) NA_character_ else t$label, character(1))
labels_seen <- sort(unique(tl[!is.na(tl)]), method = "radix")
seq_list <- sort(unique(seq_all[di]), method = "radix")
n_frames <- sum(!duplicated(paste(seq_all[di], sprintf("%.17g", frame_all[di]), sep = "\u001f")))
nz <- function(v) if (is.null(v)) NA_real_ else v
values <- list(association = MODE, n_sequences = length(seq_list), n_frames = n_frames, n_detections = length(di), n_tracks = n_tracks,
n_assigned = n_assigned, n_unassigned = length(di) - n_assigned,
mean_track_length = if (n_tracks) mean(vapply(tracks, function(t) t$n_detections, numeric(1))) else NA_real_,
mota = NA_real_, motp = NA_real_, idf1 = NA_real_, idp = NA_real_, idr = NA_real_, id_switches = NA_real_, fragmentations = NA_real_,
false_positives = NA_real_, misses = NA_real_, mostly_tracked = NA_real_, partially_tracked = NA_real_, mostly_lost = NA_real_,
precision = NA_real_, recall = NA_real_, n_gt_tracks = NA_real_, n_gt_boxes = NA_real_, track_id = I(track_id))
for (lab in labels_seen) values[[sprintf("tracks[%s]", lab)]] <- sum(tl == lab, na.rm = TRUE)
if (!is.null(metrics)) {
values$mota <- metrics$mota; values$motp <- metrics$motp; values$idf1 <- metrics$idf1; values$idp <- metrics$idp; values$idr <- metrics$idr
values$id_switches <- metrics$switches; values$fragmentations <- metrics$fragmentations; values$false_positives <- metrics$false_positives
values$misses <- metrics$misses; values$mostly_tracked <- metrics$mostly_tracked; values$partially_tracked <- metrics$partially_tracked
values$mostly_lost <- metrics$mostly_lost; values$precision <- metrics$precision; values$recall <- metrics$recall
values$n_gt_tracks <- metrics$n_gt_tracks; values$n_gt_boxes <- metrics$objects
}
trk_rows <- lapply(tracks, function(t) list(track_id = t$track_id, sequence = t$sequence, label = t$label, first_frame = t$first_frame,
last_frame = t$last_frame, span = t$last_frame - t$first_frame + 1, n_detections = t$n_detections,
mean_score = t$mean_score))
tcols <- c(list(list(key = "track_id", label = "Track", type = "integer"), list(key = "sequence", label = SEQ, type = "string")),
if (!is.null(LABEL)) list(list(key = "label", label = LABEL, type = "string")),
list(list(key = "first_frame", label = "First frame", type = "number"), list(key = "last_frame", label = "Last frame", type = "number"),
list(key = "span", label = "Frames spanned", type = "number"), list(key = "n_detections", label = "Detections", type = "integer")),
if (!is.null(SCORE)) list(list(key = "mean_score", label = "Mean score", type = "number")))
tables <- list(list(key = "tracks", title = "Tracks", columns = tcols, rows = utils::head(trk_rows, 500),
note = if (length(trk_rows) > 500) "First 500 tracks." else NULL))
if (!is.null(metrics)) {
mrows <- list(list("MOTA", metrics$mota, "1 − (misses + false positives + identity switches) / reference boxes"),
list("IDF1", metrics$idf1, "Share of boxes on the right identity (global track matching)"),
list("MOTP (mean IoU)", metrics$motp, "Mean overlap of the paired boxes"),
list("Identity switches", metrics$switches, "A reference object took a different track"),
list("Fragmentations", metrics$fragmentations, "A tracked object was lost and found again"),
list("Misses", metrics$misses, "Reference boxes with no track"), list("False positives", metrics$false_positives, "Tracked boxes with no reference object"),
list("Mostly tracked", metrics$mostly_tracked, "Reference tracks paired in at least 80% of their frames"),
list("Mostly lost", metrics$mostly_lost, "Reference tracks paired in under 20% of their frames"))
tables[[length(tables) + 1L]] <- list(key = "mot", title = sprintf("Against the reference tracks (IoU ≥ %g)", MOT_IOU),
columns = list(list(key = "metric", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "meaning", label = "Meaning", type = "string")),
rows = lapply(mrows, function(r) list(metric = r[[1]], value = r[[2]], meaning = r[[3]])))
if (length(switch_events)) {
tables[[length(tables) + 1L]] <- list(key = "switches", title = "Identity switches",
columns = list(list(key = "sequence", label = SEQ, type = "string"), list(key = "frame", label = "Frame", type = "number"),
list(key = "object", label = "Reference object", type = "string"), list(key = "from", label = "From track", type = "string"),
list(key = "to", label = "To track", type = "string")),
rows = lapply(utils::head(switch_events, 200), function(e) { p <- strsplit(e$object, "\u001f", fixed = TRUE)[[1]]
list(sequence = p[1], frame = e$frame, object = p[2], from = e$from, to = e$to) }),
note = if (length(switch_events) > 200) "First 200 switches." else NULL)
}
}
charts <- list()
if (n_tracks) {
lane_of <- function(t) paste0(t$track_id, if (!is.na(t$label)) paste0(" · ", t$label) else "")
shown <- utils::head(tracks, 60)
color_of <- function(t) if (length(seq_list) > 1L) t$sequence else if (!is.na(t$label)) t$label else t$sequence
ln <- character(0); s0 <- numeric(0); s1 <- numeric(0); col <- character(0); ev <- character(0)
fr_det <- frame_all[di]
for (t in shown) {
fr <- sort(fr_det[tid_det == t$track_id])
brk <- which(diff(fr) > 1)
starts <- c(fr[1], fr[brk + 1L])
ends <- c(fr[brk], fr[length(fr)])
ln <- c(ln, rep(lane_of(t), length(starts))); s0 <- c(s0, starts); s1 <- c(s1, ends)
col <- c(col, rep(color_of(t), length(starts))); ev <- c(ev, rep(NA_character_, length(starts)))
}
shown_ids <- vapply(shown, function(t) t$track_id, numeric(1))
for (e in switch_events) {
to <- as.integer(e$to)
if (to %in% shown_ids) {
t <- shown[[which(shown_ids == to)[1]]]
ln <- c(ln, lane_of(t)); s0 <- c(s0, e$frame); s1 <- c(s1, e$frame); col <- c(col, color_of(t)); ev <- c(ev, "Identity switch")
}
}
roles <- list(lane = cs_col("Track", ln, "categorical", levels = vapply(shown, lane_of, character(1))),
start = cs_col(FRAME, s0, "numeric"), end = cs_col("Last frame", s1, "numeric"),
color = cs_col(if (length(seq_list) > 1L) SEQ else if (!is.null(LABEL)) LABEL else SEQ, col, "categorical"))
if (any(!is.na(ev))) roles$event <- cs_col("Event", ev, "categorical")
charts[[1]] <- cs_chart("timeline", "track-timeline", "When each track was seen", roles,
note = paste0(if (n_tracks > 60) "The first 60 tracks. " else "", "Bars break where a track missed more than one frame."))
}
out <- cs_ml_out_dir("target/academy-parity/run-8142/track.objects/deepsort-embeddings/out-r")
labels_path <- file.path(out, "labels.parquet")
nanoparquet::write_parquet(data.frame(row = as.numeric(seq_len(n_input) - 1L), cluster = as.numeric(ifelse(is.na(track_id), -1L, track_id))), labels_path)
names_mode <- c(sort = "SORT", bytetrack = "ByteTrack", deepsort = "DeepSORT-style")
summary <- sprintf("%d track%s from %d detections in %d sequence%s (%s association); %d detections joined a track.", n_tracks, if (n_tracks != 1) "s" else "",
length(di), length(seq_list), if (length(seq_list) != 1) "s" else "", names_mode[[MODE]], n_assigned)
if (!is.null(metrics)) summary <- paste0(summary, sprintf(" Against %d reference tracks: MOTA %s, IDF1 %s, %d identity switches.", as.integer(metrics$n_gt_tracks),
f3(metrics$mota), f3(metrics$idf1), as.integer(metrics$switches)))
cs_publish(list(
method = "track.objects",
methodVersion = "1.1.1",
title = "Object tracks",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = c(list(list(key = "n_tracks", label = "Tracks", value = n_tracks)),
if (!is.null(metrics)) list(list(key = "mota", label = "MOTA", value = metrics$mota), list(key = "idf1", label = "IDF1", value = metrics$idf1),
list(key = "id_switches", label = "Identity switches", value = metrics$switches))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Tracks start from detections and are confirmed after %d detections; a confirmed track ends after %g frames without one. ", OPTS$min_hits, OPTS$max_age),
if (!is.null(LABEL) && OPTS$per_class) "Boxes pair only within the same class. " else "",
"Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).")),
charts = charts,
artifacts = list(list(key = "labels", path = labels_path, format = "parquet")),
values = values
))
7 tracks from 184 detections in 2 sequences (DeepSORT-style association); 178 detections joined a track. Against 7 reference tracks: MOTA 0.886, IDF1 0.939, 0 identity switches.
- Tracks
- 7
- MOTA
- 0.8856
- IDF1
- 0.9393
- Identity switches
- 0
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
- Embeddings describe appearance — DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.
Tracks
| Track | media_id | label | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|---|
| 1 | cam1 | person | 0 | 39 | 40 | 34 | 0.7042 |
| 2 | cam1 | person | 0 | 39 | 40 | 35 | 0.7363 |
| 3 | cam1 | car | 5 | 29 | 25 | 25 | 0.7794 |
| 4 | cam1 | person | 18 | 39 | 22 | 19 | 0.8095 |
| 5 | cam2 | car | 0 | 29 | 30 | 24 | 0.7069 |
| 6 | cam2 | person | 3 | 29 | 27 | 25 | 0.7759 |
| 7 | cam2 | person | 10 | 25 | 16 | 16 | 0.8254 |
Against the reference tracks (IoU ≥ 0.5)
| Measure | Value | Meaning |
|---|---|---|
| MOTA | 0.8856 | 1 − (misses + false positives + identity switches) / reference boxes |
| IDF1 | 0.9393 | Share of boxes on the right identity (global track matching) |
| MOTP (mean IoU) | 0.8808 | Mean overlap of the paired boxes |
| Identity switches | 0 | A reference object took a different track |
| Fragmentations | 20 | A tracked object was lost and found again |
| Misses | 23 | Reference boxes with no track |
| False positives | 0 | Tracked boxes with no reference object |
| Mostly tracked | 7 | Reference tracks paired in at least 80% of their frames |
| Mostly lost | 0 | Reference tracks paired in under 20% of their frames |
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Boxes pair only within the same class. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 0821a0bf81fcd49d
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import mot # twin: codesplashr cs_eval_mot
from codesplash.evaluate.stacked import stacked # twin: cs_eval_stacked
from codesplash import ml as csml
from codesplash.track import objects as tr # twin: codesplashr cs_track_objects
# %% Data
SEQ, FRAME = "media_id", "frame"
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
SCORE = "score"
LABEL = "label"
FEATURES = ["emb_1", "emb_2", "emb_3", "emb_4", "emb_5", "emb_6"]
SOURCE = "source"
TRUTH = "track_id"
MODE = "deepsort" # sort | bytetrack | deepsort
OPTS = {"iou": 0.3, "min_hits": int(3), "max_age": float(30),
"min_score": 0, "high": 0.6, "low": 0.1,
"low_iou": 0.5, "max_cosine": 0.3, "motion_weight": 0.2,
"per_class": True}
MOT_IOU = 0.5
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"] # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH] + FEATURES if c))
df = pd.read_parquet("tests/parity/fixtures/img4_tracks.parquet", columns=columns)
df["__row"] = np.arange(len(df)) # position in the analysis input
n_input = len(df)
if MODE == "bytetrack" and not SCORE:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or DeepSORT-style unless a confidence score column is set", value="ByteTrack")
if MODE == "deepsort" and not FEATURES:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or ByteTrack unless embedding columns are set", value="DeepSORT-style")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above the detections under an added source column (twin: cs_eval_with_reference).
from codesplash.graph import dataset_option # the table the host wrote for the option
from codesplash.evaluate.stacked import with_reference
w = with_reference(df, dataset_option("target/academy-parity/run-8142/track.objects/deepsort-embeddings/out-python", "reference_table"),
{"sequence": SEQ, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "score": SCORE, "label": LABEL, "truth": TRUTH},
REF_ROLES, {"label": "Class"}, SOURCE, REF_LEVEL, ["sequence", "frame", "x0", "y0", "x1", "y1"] + (["label"] if LABEL else []))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
SEQ, FRAME, X0, Y0, X1, Y1 = wc["sequence"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
LABEL, TRUTH = wc["label"], wc["truth"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
needed = [SEQ, FRAME, X0, Y0, X1, Y1] + ([LABEL] if LABEL else [])
numeric = [c for c in [FRAME, X0, Y0, X1, Y1, SCORE] if c] + FEATURES
if SOURCE:
st = stacked(df, needed + [SOURCE], numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
else:
if n_input == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in needed:
if df[c].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=c)
keep = np.ones(n_input, dtype=bool)
for c in needed:
keep &= df[c].notna().to_numpy()
df = df.loc[keep].reset_index(drop=True)
warnings = [cs.cs_warning("CS_W_ROWS_DROPPED", dropped=int(n_input - len(df)), total=n_input)] if len(df) < n_input else []
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in numeric:
k = int(np.isinf(df[c].to_numpy(dtype=float, na_value=np.nan)).sum())
if k:
cs.cs_error("CS_E_NOT_FINITE", column=c, count=k)
is_ref = np.zeros(len(df), dtype=bool)
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
det = ~is_ref
if SCORE:
no_score = det & np.isnan(df[SCORE].to_numpy(dtype=float, na_value=np.nan))
if no_score.any():
warnings.append(f"{int(no_score.sum())} detections have no {SCORE} and were left out.")
det &= ~no_score
if FEATURES:
no_feat = det & df[FEATURES].isna().any(axis=1).to_numpy()
if no_feat.any():
warnings.append(f"{int(no_feat.sum())} detections miss an embedding value and were left out.")
det &= ~no_feat
if int(det.sum()) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Tracking", min=2, n=int(det.sum()))
# %% Tracks
di = np.flatnonzero(det)
seq_all = np.asarray([str(x) for x in df[SEQ].tolist()], dtype=object)
frame_all = df[FRAME].to_numpy(dtype=float)
lab_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object) if LABEL else None
res = tr.track(seq_all[di], frame_all[di], box[di], df[SCORE].to_numpy(dtype=float)[di] if SCORE else None,
lab_all[di] if LABEL else None, df[FEATURES].to_numpy(dtype=float)[di] if FEATURES else None, MODE, **OPTS)
tid_det = res["track"]
track_id = [None] * n_input # per input row; rows that weren't tracked stay empty
for k, i in enumerate(di):
if tid_det[k] > 0:
track_id[int(df["__row"].iloc[i])] = int(tid_det[k])
tracks = res["tracks"]
n_tracks = len(tracks)
n_assigned = int(np.sum(tid_det > 0))
# %% Against the reference tracks
metrics = None
switch_events = []
if SOURCE and TRUTH and int(is_ref.sum()):
truth_ok = is_ref & df[TRUTH].notna().to_numpy()
if int((is_ref & ~truth_ok).sum()):
warnings.append(f"{int((is_ref & ~truth_ok).sum())} reference boxes have no {TRUTH} and were left out of the tracking metrics.")
truth_all = np.asarray([str(x) for x in df[TRUTH].tolist()], dtype=object)
gi = np.flatnonzero(truth_ok)
hi = di[tid_det > 0]
hyp_id = {int(i): str(int(t)) for i, t in zip(di, tid_det) if t > 0}
seqs = []
for sq in sorted(set(seq_all[gi].tolist()) | set(seq_all[hi].tolist())):
g_s = gi[seq_all[gi] == sq]
h_s = hi[seq_all[hi] == sq]
frames = []
for f in sorted(set(frame_all[g_s].tolist()) | set(frame_all[h_s].tolist())):
g_f = g_s[frame_all[g_s] == f]
h_f = h_s[frame_all[h_s] == f]
frames.append({"frame": f, "gt_ids": [f"{sq}\x1f{truth_all[i]}" for i in g_f], "gt_boxes": box[g_f],
"hyp_ids": [hyp_id[int(i)] for i in h_f], "hyp_boxes": box[h_f]})
seqs.append(frames)
metrics = mot.clear_mot(seqs, MOT_IOU)
switch_events = metrics["switch_events"]
# %% Assumptions
assumptions = [
{"key": "frames", "label": "Frames are in order", "status": "info",
"detail": "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."},
{"key": "motion", "label": "Objects move smoothly", "status": "info",
"detail": "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks."},
]
if FEATURES:
assumptions.append({"key": "appearance", "label": "Embeddings describe appearance", "status": "info",
"detail": "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close."})
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
labels_seen = sorted(set(t["label"] for t in tracks if t["label"] is not None))
seq_list = sorted(set(seq_all[di].tolist()))
n_frames = len(set(zip(seq_all[di].tolist(), frame_all[di].tolist())))
values = {"association": MODE, "n_sequences": len(seq_list), "n_frames": n_frames, "n_detections": int(di.size), "n_tracks": n_tracks,
"n_assigned": n_assigned, "n_unassigned": int(di.size - n_assigned),
"mean_track_length": float(np.mean([t["n_detections"] for t in tracks])) if tracks else None,
"mota": None, "motp": None, "idf1": None, "idp": None, "idr": None, "id_switches": None, "fragmentations": None,
"false_positives": None, "misses": None, "mostly_tracked": None, "partially_tracked": None, "mostly_lost": None,
"precision": None, "recall": None, "n_gt_tracks": None, "n_gt_boxes": None, "track_id": track_id}
for lab in labels_seen:
values[f"tracks[{lab}]"] = sum(1 for t in tracks if t["label"] == lab)
if metrics is not None:
values.update({"mota": metrics["mota"], "motp": metrics["motp"], "idf1": metrics["idf1"], "idp": metrics["idp"], "idr": metrics["idr"],
"id_switches": metrics["switches"], "fragmentations": metrics["fragmentations"], "false_positives": metrics["false_positives"],
"misses": metrics["misses"], "mostly_tracked": metrics["mostly_tracked"], "partially_tracked": metrics["partially_tracked"],
"mostly_lost": metrics["mostly_lost"], "precision": metrics["precision"], "recall": metrics["recall"],
"n_gt_tracks": metrics["n_gt_tracks"], "n_gt_boxes": metrics["objects"]})
trk_rows = [{"track_id": t["track_id"], "sequence": t["sequence"], "label": t["label"], "first_frame": t["first_frame"], "last_frame": t["last_frame"],
"span": t["last_frame"] - t["first_frame"] + 1.0, "n_detections": t["n_detections"], "mean_score": t["mean_score"]} for t in tracks]
tables = [{"key": "tracks", "title": "Tracks",
"columns": [{"key": "track_id", "label": "Track", "type": "integer"}, {"key": "sequence", "label": SEQ, "type": "string"}]
+ ([{"key": "label", "label": LABEL, "type": "string"}] if LABEL else [])
+ [{"key": "first_frame", "label": "First frame", "type": "number"}, {"key": "last_frame", "label": "Last frame", "type": "number"},
{"key": "span", "label": "Frames spanned", "type": "number"}, {"key": "n_detections", "label": "Detections", "type": "integer"}]
+ ([{"key": "mean_score", "label": "Mean score", "type": "number"}] if SCORE else []),
"rows": trk_rows[:500], "note": "First 500 tracks." if len(trk_rows) > 500 else None}]
if metrics is not None:
mrows = [("MOTA", metrics["mota"], "1 − (misses + false positives + identity switches) / reference boxes"),
("IDF1", metrics["idf1"], "Share of boxes on the right identity (global track matching)"),
("MOTP (mean IoU)", metrics["motp"], "Mean overlap of the paired boxes"),
("Identity switches", metrics["switches"], "A reference object took a different track"),
("Fragmentations", metrics["fragmentations"], "A tracked object was lost and found again"),
("Misses", metrics["misses"], "Reference boxes with no track"), ("False positives", metrics["false_positives"], "Tracked boxes with no reference object"),
("Mostly tracked", metrics["mostly_tracked"], "Reference tracks paired in at least 80% of their frames"),
("Mostly lost", metrics["mostly_lost"], "Reference tracks paired in under 20% of their frames")]
tables.append({"key": "mot", "title": f"Against the reference tracks (IoU ≥ {MOT_IOU:g})",
"columns": [{"key": "metric", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "meaning", "label": "Meaning", "type": "string"}],
"rows": [{"metric": a, "value": b, "meaning": c} for a, b, c in mrows]})
if switch_events:
tables.append({"key": "switches", "title": "Identity switches",
"columns": [{"key": "sequence", "label": SEQ, "type": "string"}, {"key": "frame", "label": "Frame", "type": "number"},
{"key": "object", "label": "Reference object", "type": "string"}, {"key": "from", "label": "From track", "type": "string"},
{"key": "to", "label": "To track", "type": "string"}],
"rows": [{"sequence": e["object"].split("\x1f")[0], "frame": e["frame"], "object": e["object"].split("\x1f")[1],
"from": e["from"], "to": e["to"]} for e in switch_events[:200]],
"note": "First 200 switches." if len(switch_events) > 200 else None})
charts = []
if tracks:
lane_of = {t["track_id"]: f"{t['track_id']}" + (f" · {t['label']}" if t["label"] is not None else "") for t in tracks}
shown = tracks[:60]
ln, s0, s1, col, ev = [], [], [], [], []
for t in shown:
fr = np.sort(frame_all[di][tid_det == t["track_id"]])
brk = np.flatnonzero(np.diff(fr) > 1.0)
starts = np.concatenate([[fr[0]], fr[brk + 1]])
ends = np.concatenate([fr[brk], [fr[-1]]])
for a, b in zip(starts, ends):
ln.append(lane_of[t["track_id"]])
s0.append(float(a))
s1.append(float(b))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append(None)
shown_ids = {t["track_id"] for t in shown}
for e in switch_events:
if int(e["to"]) in shown_ids:
t = next(x for x in shown if x["track_id"] == int(e["to"]))
ln.append(lane_of[t["track_id"]])
s0.append(float(e["frame"]))
s1.append(float(e["frame"]))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append("Identity switch")
roles = {"lane": cs.col("Track", ln, "categorical", levels=[lane_of[t["track_id"]] for t in shown]),
"start": cs.col(FRAME, s0, "numeric"), "end": cs.col("Last frame", s1, "numeric"),
"color": cs.col(SEQ if len(seq_list) > 1 else (LABEL or SEQ), col, "categorical")}
if any(v is not None for v in ev):
roles["event"] = cs.col("Event", ev, "categorical")
charts.append(cs.chart("timeline", "track-timeline", "When each track was seen", roles,
note=("The first 60 tracks. " if len(tracks) > 60 else "") + "Bars break where a track missed more than one frame."))
out = csml.out_dir("target/academy-parity/run-8142/track.objects/deepsort-embeddings/out-python")
labels_path = os.path.join(out, "labels.parquet")
pd.DataFrame({"row": np.arange(n_input, dtype=np.int64), "cluster": np.asarray([-1 if v is None else v for v in track_id], dtype=np.int64)}).to_parquet(labels_path, index=False)
summary = (f"{n_tracks} track{'s' if n_tracks != 1 else ''} from {int(di.size)} detections in {len(seq_list)} sequence{'s' if len(seq_list) != 1 else ''} "
f"({ {'sort': 'SORT', 'bytetrack': 'ByteTrack', 'deepsort': 'DeepSORT-style'}[MODE] } association); {n_assigned} detections joined a track.")
if metrics is not None:
summary += (f" Against {metrics['n_gt_tracks']} reference tracks: MOTA {f3(metrics['mota'])}, IDF1 {f3(metrics['idf1'])}, "
f"{metrics['switches']} identity switches.")
cs.publish({
"method": "track.objects",
"methodVersion": "1.1.1",
"title": "Object tracks",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "n_tracks", "label": "Tracks", "value": n_tracks}]
+ ([{"key": "mota", "label": "MOTA", "value": metrics["mota"]}, {"key": "idf1", "label": "IDF1", "value": metrics["idf1"]},
{"key": "id_switches", "label": "Identity switches", "value": metrics["switches"]}] if metrics is not None else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Tracks start from detections and are confirmed after {OPTS['min_hits']} detections; a confirmed track ends after {OPTS['max_age']:g} frames without one. "
+ ("Boxes pair only within the same class. " if (LABEL and OPTS["per_class"]) else "")
+ "Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers)."],
"charts": charts,
"artifacts": [{"key": "labels", "path": labels_path, "format": "parquet"}],
"values": values,
})
Track objects with the DeepSORT-style option matches by the distance between supplied embedding columns inside a motion gate. On this table it formed 7 tracks, with IDF1 0.939, the same as SORT's 0.939 on the same boxes.
SORT made 0 identity switches here, so appearance had nothing to fix. Its value shows up when objects cross or hide.
ByteTrack: don't throw weak boxes away
ReadWhen an object is partly hidden, the detector's confidence drops. Discarding low-confidence boxes then breaks the track exactly when it matters. ByteTrack matches in two rounds:
- confident boxes (score at least 0.6) against all tracks;
- the leftover tracks against low-confidence boxes, by overlap only. These boxes may extend a track but never start one.
In the reference's toy, round one matches detection 0, and round two recovers detection 1 for a track that lost its confident box; the lowest-scoring box is ignored.
Boxes only, no reference
Explore7 tracks from 184 detections in 2 sequences (SORT association); 152 detections joined a track.
- Tracks
- 7
Plots
Bars break where a track missed more than one frame.
View data
| media_id | Last frame | Track | frame |
|---|---|---|---|
| cam1 | 5 | 1 | 0 |
| cam1 | 11 | 1 | 7 |
| cam1 | 15 | 1 | 14 |
| cam1 | 22 | 1 | 17 |
| cam1 | 34 | 1 | 29 |
| cam1 | 37 | 1 | 36 |
| cam1 | 39 | 1 | 39 |
| cam1 | 3 | 2 | 0 |
| cam1 | 6 | 2 | 5 |
| cam1 | 11 | 2 | 8 |
| cam1 | 22 | 2 | 15 |
| cam1 | 36 | 2 | 29 |
| cam1 | 39 | 2 | 38 |
| cam1 | 11 | 3 | 7 |
| cam1 | 13 | 3 | 13 |
| cam1 | 29 | 3 | 15 |
| cam1 | 21 | 4 | 18 |
| cam1 | 24 | 4 | 23 |
| cam1 | 30 | 4 | 27 |
| cam1 | 38 | 4 | 32 |
| cam2 | 10 | 5 | 3 |
| cam2 | 13 | 5 | 12 |
| cam2 | 17 | 5 | 15 |
| cam2 | 20 | 5 | 20 |
| cam2 | 22 | 5 | 22 |
| cam2 | 25 | 5 | 25 |
| cam2 | 29 | 5 | 27 |
| cam2 | 11 | 6 | 3 |
| cam2 | 20 | 6 | 13 |
| cam2 | 23 | 6 | 22 |
| cam2 | 25 | 6 | 25 |
| cam2 | 29 | 6 | 27 |
| cam2 | 25 | 7 | 10 |
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|
| 1 | cam1 | 0 | 39 | 40 | 28 | 0.7934 |
| 2 | cam1 | 0 | 39 | 40 | 28 | 0.8313 |
| 3 | cam1 | 7 | 29 | 23 | 21 | 0.8348 |
| 4 | cam1 | 18 | 38 | 21 | 17 | 0.8549 |
| 5 | cam2 | 3 | 29 | 27 | 19 | 0.7588 |
| 6 | cam2 | 3 | 29 | 27 | 23 | 0.8104 |
| 7 | cam2 | 10 | 25 | 16 | 16 | 0.8254 |
- 201 detections have no score and were left out.
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact R script · R R version 4.5.1 (2025-06-13)
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 953cbf889d3f3c76
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_track_objects (tracker), cs_eval_mot (tracking metrics), cs_eval_stacked
# %% Data
SEQ <- "media_id"; FRAME <- "frame"
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
SCORE <- "score"
LABEL <- NULL
FEATURES <- c()
SOURCE <- NULL
TRUTH <- NULL
MODE <- "sort" # sort | bytetrack | deepsort
OPTS <- list(iou = 0.3, min_hits = as.integer(3), max_age = as.numeric(30),
min_score = 0.5, high = 0.6, low = 0.1,
low_iou = 0.5, max_cosine = 0.3, motion_weight = 0,
per_class = TRUE)
MOT_IOU <- 0.5
REF_LEVEL <- NULL
SOURCE_LEVELS <- NULL # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
FEATURES <- if (length(FEATURES)) as.character(FEATURES) else character(0)
columns <- unique(c(SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH, FEATURES))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_tracks.parquet", col_select = columns))
df$`__row` <- seq_len(nrow(df)) - 1L # position in the analysis input
n_input <- nrow(df)
if (MODE == "bytetrack" && is.null(SCORE)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or DeepSORT-style unless a confidence score column is set", value = "ByteTrack")
if (MODE == "deepsort" && !length(FEATURES)) cs_error("CS_E_INVALID_OPTION", option = "Association", allowed = "SORT or ByteTrack unless embedding columns are set", value = "DeepSORT-style")
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above the detections under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/track.objects/detections-only/out-r", "reference_table"),
list(sequence = SEQ, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, score = SCORE, label = LABEL, truth = TRUTH),
REF_ROLES, list(label = "Class"), SOURCE, REF_LEVEL, c("sequence", "frame", "x0", "y0", "x1", "y1", if (!is.null(LABEL)) "label"))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
SEQ <- wc$sequence; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
LABEL <- wc$label; TRUTH <- wc$truth
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
}
needed <- c(SEQ, FRAME, X0, Y0, X1, Y1, LABEL)
numeric_cols <- c(FRAME, X0, Y0, X1, Y1, SCORE, FEATURES)
if (!is.null(SOURCE)) {
st <- cs_eval_stacked(df, c(needed, SOURCE), numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
} else {
if (n_input == 0L) cs_error("CS_E_NO_ROWS")
for (c in needed) if (all(is.na(df[[c]]))) cs_error("CS_E_ALL_MISSING", column = c)
keep <- rep(TRUE, n_input)
for (c in needed) keep <- keep & !is.na(df[[c]])
df <- df[keep, , drop = FALSE]
warnings <- if (nrow(df) < n_input) list(cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input)) else list()
if (nrow(df) == 0L) cs_error("CS_E_NO_ROWS")
for (c in numeric_cols) {
k <- sum(is.infinite(as.numeric(df[[c]])))
if (k > 0) cs_error("CS_E_NOT_FINITE", column = c, count = k)
}
is_ref <- logical(nrow(df))
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
det <- !is_ref
if (!is.null(SCORE)) {
no_score <- det & is.na(as.numeric(df[[SCORE]]))
if (any(no_score)) {
warnings <- c(warnings, sprintf("%d detections have no %s and were left out.", sum(no_score), SCORE))
det <- det & !no_score
}
}
if (length(FEATURES)) {
no_feat <- det & !stats::complete.cases(df[FEATURES])
if (any(no_feat)) {
warnings <- c(warnings, sprintf("%d detections miss an embedding value and were left out.", sum(no_feat)))
det <- det & !no_feat
}
}
if (sum(det) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Tracking", min = 2, n = sum(det))
# %% Tracks
di <- which(det)
seq_all <- as.character(df[[SEQ]])
frame_all <- as.numeric(df[[FRAME]])
lab_all <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else NULL
feats <- if (length(FEATURES)) as.matrix(df[di, FEATURES, drop = FALSE]) else NULL
if (!is.null(feats)) storage.mode(feats) <- "double"
res <- cs_track_objects(seq_all[di], frame_all[di], box[di, , drop = FALSE], if (!is.null(SCORE)) as.numeric(df[[SCORE]])[di] else NULL,
if (!is.null(LABEL)) lab_all[di] else NULL, feats, MODE, OPTS)
tid_det <- res$track
track_id <- rep(NA_integer_, n_input) # per input row; rows that weren't tracked stay empty
track_id[df$`__row`[di][tid_det > 0L] + 1L] <- tid_det[tid_det > 0L]
tracks <- res$tracks
n_tracks <- length(tracks)
n_assigned <- sum(tid_det > 0L)
# %% Against the reference tracks
metrics <- NULL
switch_events <- list()
if (!is.null(SOURCE) && !is.null(TRUTH) && sum(is_ref) > 0) {
truth_ok <- is_ref & !is.na(df[[TRUTH]])
if (sum(is_ref & !truth_ok) > 0) warnings <- c(warnings, sprintf("%d reference boxes have no %s and were left out of the tracking metrics.", sum(is_ref & !truth_ok), TRUTH))
truth_all <- as.character(df[[TRUTH]])
gi <- which(truth_ok)
hi <- di[tid_det > 0L]
hyp_of <- integer(nrow(df))
hyp_of[di] <- tid_det
seqs <- list()
for (sq in sort(unique(c(seq_all[gi], seq_all[hi])), method = "radix")) {
g_s <- gi[seq_all[gi] == sq]
h_s <- hi[seq_all[hi] == sq]
frames <- list()
for (f in sort(unique(c(frame_all[g_s], frame_all[h_s])))) {
g_f <- g_s[frame_all[g_s] == f]
h_f <- h_s[frame_all[h_s] == f]
# paste() would recycle an empty id vector into one id: frames with predictions but no reference boxes get none.
gt_ids <- if (length(g_f)) paste(sq, truth_all[g_f], sep = "\u001f") else character(0)
frames[[length(frames) + 1L]] <- list(frame = f, gt_ids = gt_ids, gt_boxes = box[g_f, , drop = FALSE],
hyp_ids = as.character(hyp_of[h_f]), hyp_boxes = box[h_f, , drop = FALSE])
}
seqs[[length(seqs) + 1L]] <- frames
}
metrics <- cs_eval_mot(seqs, MOT_IOU)
switch_events <- metrics$switch_events
}
# %% Assumptions
assumptions <- list(
list(key = "frames", label = "Frames are in order", status = "info",
detail = "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."),
list(key = "motion", label = "Objects move smoothly", status = "info",
detail = "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.")
)
if (length(FEATURES)) assumptions[[3]] <- list(key = "appearance", label = "Embeddings describe appearance", status = "info",
detail = "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close.")
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tl <- vapply(tracks, function(t) if (is.na(t$label)) NA_character_ else t$label, character(1))
labels_seen <- sort(unique(tl[!is.na(tl)]), method = "radix")
seq_list <- sort(unique(seq_all[di]), method = "radix")
n_frames <- sum(!duplicated(paste(seq_all[di], sprintf("%.17g", frame_all[di]), sep = "\u001f")))
nz <- function(v) if (is.null(v)) NA_real_ else v
values <- list(association = MODE, n_sequences = length(seq_list), n_frames = n_frames, n_detections = length(di), n_tracks = n_tracks,
n_assigned = n_assigned, n_unassigned = length(di) - n_assigned,
mean_track_length = if (n_tracks) mean(vapply(tracks, function(t) t$n_detections, numeric(1))) else NA_real_,
mota = NA_real_, motp = NA_real_, idf1 = NA_real_, idp = NA_real_, idr = NA_real_, id_switches = NA_real_, fragmentations = NA_real_,
false_positives = NA_real_, misses = NA_real_, mostly_tracked = NA_real_, partially_tracked = NA_real_, mostly_lost = NA_real_,
precision = NA_real_, recall = NA_real_, n_gt_tracks = NA_real_, n_gt_boxes = NA_real_, track_id = I(track_id))
for (lab in labels_seen) values[[sprintf("tracks[%s]", lab)]] <- sum(tl == lab, na.rm = TRUE)
if (!is.null(metrics)) {
values$mota <- metrics$mota; values$motp <- metrics$motp; values$idf1 <- metrics$idf1; values$idp <- metrics$idp; values$idr <- metrics$idr
values$id_switches <- metrics$switches; values$fragmentations <- metrics$fragmentations; values$false_positives <- metrics$false_positives
values$misses <- metrics$misses; values$mostly_tracked <- metrics$mostly_tracked; values$partially_tracked <- metrics$partially_tracked
values$mostly_lost <- metrics$mostly_lost; values$precision <- metrics$precision; values$recall <- metrics$recall
values$n_gt_tracks <- metrics$n_gt_tracks; values$n_gt_boxes <- metrics$objects
}
trk_rows <- lapply(tracks, function(t) list(track_id = t$track_id, sequence = t$sequence, label = t$label, first_frame = t$first_frame,
last_frame = t$last_frame, span = t$last_frame - t$first_frame + 1, n_detections = t$n_detections,
mean_score = t$mean_score))
tcols <- c(list(list(key = "track_id", label = "Track", type = "integer"), list(key = "sequence", label = SEQ, type = "string")),
if (!is.null(LABEL)) list(list(key = "label", label = LABEL, type = "string")),
list(list(key = "first_frame", label = "First frame", type = "number"), list(key = "last_frame", label = "Last frame", type = "number"),
list(key = "span", label = "Frames spanned", type = "number"), list(key = "n_detections", label = "Detections", type = "integer")),
if (!is.null(SCORE)) list(list(key = "mean_score", label = "Mean score", type = "number")))
tables <- list(list(key = "tracks", title = "Tracks", columns = tcols, rows = utils::head(trk_rows, 500),
note = if (length(trk_rows) > 500) "First 500 tracks." else NULL))
if (!is.null(metrics)) {
mrows <- list(list("MOTA", metrics$mota, "1 − (misses + false positives + identity switches) / reference boxes"),
list("IDF1", metrics$idf1, "Share of boxes on the right identity (global track matching)"),
list("MOTP (mean IoU)", metrics$motp, "Mean overlap of the paired boxes"),
list("Identity switches", metrics$switches, "A reference object took a different track"),
list("Fragmentations", metrics$fragmentations, "A tracked object was lost and found again"),
list("Misses", metrics$misses, "Reference boxes with no track"), list("False positives", metrics$false_positives, "Tracked boxes with no reference object"),
list("Mostly tracked", metrics$mostly_tracked, "Reference tracks paired in at least 80% of their frames"),
list("Mostly lost", metrics$mostly_lost, "Reference tracks paired in under 20% of their frames"))
tables[[length(tables) + 1L]] <- list(key = "mot", title = sprintf("Against the reference tracks (IoU ≥ %g)", MOT_IOU),
columns = list(list(key = "metric", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "meaning", label = "Meaning", type = "string")),
rows = lapply(mrows, function(r) list(metric = r[[1]], value = r[[2]], meaning = r[[3]])))
if (length(switch_events)) {
tables[[length(tables) + 1L]] <- list(key = "switches", title = "Identity switches",
columns = list(list(key = "sequence", label = SEQ, type = "string"), list(key = "frame", label = "Frame", type = "number"),
list(key = "object", label = "Reference object", type = "string"), list(key = "from", label = "From track", type = "string"),
list(key = "to", label = "To track", type = "string")),
rows = lapply(utils::head(switch_events, 200), function(e) { p <- strsplit(e$object, "\u001f", fixed = TRUE)[[1]]
list(sequence = p[1], frame = e$frame, object = p[2], from = e$from, to = e$to) }),
note = if (length(switch_events) > 200) "First 200 switches." else NULL)
}
}
charts <- list()
if (n_tracks) {
lane_of <- function(t) paste0(t$track_id, if (!is.na(t$label)) paste0(" · ", t$label) else "")
shown <- utils::head(tracks, 60)
color_of <- function(t) if (length(seq_list) > 1L) t$sequence else if (!is.na(t$label)) t$label else t$sequence
ln <- character(0); s0 <- numeric(0); s1 <- numeric(0); col <- character(0); ev <- character(0)
fr_det <- frame_all[di]
for (t in shown) {
fr <- sort(fr_det[tid_det == t$track_id])
brk <- which(diff(fr) > 1)
starts <- c(fr[1], fr[brk + 1L])
ends <- c(fr[brk], fr[length(fr)])
ln <- c(ln, rep(lane_of(t), length(starts))); s0 <- c(s0, starts); s1 <- c(s1, ends)
col <- c(col, rep(color_of(t), length(starts))); ev <- c(ev, rep(NA_character_, length(starts)))
}
shown_ids <- vapply(shown, function(t) t$track_id, numeric(1))
for (e in switch_events) {
to <- as.integer(e$to)
if (to %in% shown_ids) {
t <- shown[[which(shown_ids == to)[1]]]
ln <- c(ln, lane_of(t)); s0 <- c(s0, e$frame); s1 <- c(s1, e$frame); col <- c(col, color_of(t)); ev <- c(ev, "Identity switch")
}
}
roles <- list(lane = cs_col("Track", ln, "categorical", levels = vapply(shown, lane_of, character(1))),
start = cs_col(FRAME, s0, "numeric"), end = cs_col("Last frame", s1, "numeric"),
color = cs_col(if (length(seq_list) > 1L) SEQ else if (!is.null(LABEL)) LABEL else SEQ, col, "categorical"))
if (any(!is.na(ev))) roles$event <- cs_col("Event", ev, "categorical")
charts[[1]] <- cs_chart("timeline", "track-timeline", "When each track was seen", roles,
note = paste0(if (n_tracks > 60) "The first 60 tracks. " else "", "Bars break where a track missed more than one frame."))
}
out <- cs_ml_out_dir("target/academy-parity/run-8142/track.objects/detections-only/out-r")
labels_path <- file.path(out, "labels.parquet")
nanoparquet::write_parquet(data.frame(row = as.numeric(seq_len(n_input) - 1L), cluster = as.numeric(ifelse(is.na(track_id), -1L, track_id))), labels_path)
names_mode <- c(sort = "SORT", bytetrack = "ByteTrack", deepsort = "DeepSORT-style")
summary <- sprintf("%d track%s from %d detections in %d sequence%s (%s association); %d detections joined a track.", n_tracks, if (n_tracks != 1) "s" else "",
length(di), length(seq_list), if (length(seq_list) != 1) "s" else "", names_mode[[MODE]], n_assigned)
if (!is.null(metrics)) summary <- paste0(summary, sprintf(" Against %d reference tracks: MOTA %s, IDF1 %s, %d identity switches.", as.integer(metrics$n_gt_tracks),
f3(metrics$mota), f3(metrics$idf1), as.integer(metrics$switches)))
cs_publish(list(
method = "track.objects",
methodVersion = "1.1.1",
title = "Object tracks",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = c(list(list(key = "n_tracks", label = "Tracks", value = n_tracks)),
if (!is.null(metrics)) list(list(key = "mota", label = "MOTA", value = metrics$mota), list(key = "idf1", label = "IDF1", value = metrics$idf1),
list(key = "id_switches", label = "Identity switches", value = metrics$switches))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Tracks start from detections and are confirmed after %d detections; a confirmed track ends after %g frames without one. ", OPTS$min_hits, OPTS$max_age),
if (!is.null(LABEL) && OPTS$per_class) "Boxes pair only within the same class. " else "",
"Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).")),
charts = charts,
artifacts = list(list(key = "labels", path = labels_path, format = "parquet")),
values = values
))
7 tracks from 184 detections in 2 sequences (SORT association); 152 detections joined a track.
- Tracks
- 7
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Frames are in order — Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age.
- Objects move smoothly — The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks.
Tracks
| Track | media_id | First frame | Last frame | Frames spanned | Detections | Mean score |
|---|---|---|---|---|---|---|
| 1 | cam1 | 0 | 39 | 40 | 28 | 0.7934 |
| 2 | cam1 | 0 | 39 | 40 | 28 | 0.8313 |
| 3 | cam1 | 7 | 29 | 23 | 21 | 0.8348 |
| 4 | cam1 | 18 | 38 | 21 | 17 | 0.8549 |
| 5 | cam2 | 3 | 29 | 27 | 19 | 0.7588 |
| 6 | cam2 | 3 | 29 | 27 | 23 | 0.8104 |
| 7 | cam2 | 10 | 25 | 16 | 16 | 0.8254 |
- 201 detections have no score and were left out.
- Tracks start from detections and are confirmed after 3 detections; a confirmed track ends after 30 frames without one. Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Track objects across frames (SORT, ByteTrack, DeepSORT-style)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method track.objects 1.1.1 · spec 953cbf889d3f3c76
# Dataset: img4_tracks (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import mot # twin: codesplashr cs_eval_mot
from codesplash.evaluate.stacked import stacked # twin: cs_eval_stacked
from codesplash import ml as csml
from codesplash.track import objects as tr # twin: codesplashr cs_track_objects
# %% Data
SEQ, FRAME = "media_id", "frame"
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
SCORE = "score"
LABEL = None
FEATURES = []
SOURCE = None
TRUTH = None
MODE = "sort" # sort | bytetrack | deepsort
OPTS = {"iou": 0.3, "min_hits": int(3), "max_age": float(30),
"min_score": 0.5, "high": 0.6, "low": 0.1,
"low_iou": 0.5, "max_cosine": 0.3, "motion_weight": 0,
"per_class": True}
MOT_IOU = 0.5
REF_LEVEL = None
SOURCE_LEVELS = None # stored order
# Reference tracks from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [SEQ, FRAME, X0, Y0, X1, Y1, SCORE, LABEL, SOURCE, TRUTH] + FEATURES if c))
df = pd.read_parquet("tests/parity/fixtures/img4_tracks.parquet", columns=columns)
df["__row"] = np.arange(len(df)) # position in the analysis input
n_input = len(df)
if MODE == "bytetrack" and not SCORE:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or DeepSORT-style unless a confidence score column is set", value="ByteTrack")
if MODE == "deepsort" and not FEATURES:
cs.cs_error("CS_E_INVALID_OPTION", option="Association", allowed="SORT or ByteTrack unless embedding columns are set", value="DeepSORT-style")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above the detections under an added source column (twin: cs_eval_with_reference).
from codesplash.graph import dataset_option # the table the host wrote for the option
from codesplash.evaluate.stacked import with_reference
w = with_reference(df, dataset_option("target/academy-parity/run-8142/track.objects/detections-only/out-python", "reference_table"),
{"sequence": SEQ, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "score": SCORE, "label": LABEL, "truth": TRUTH},
REF_ROLES, {"label": "Class"}, SOURCE, REF_LEVEL, ["sequence", "frame", "x0", "y0", "x1", "y1"] + (["label"] if LABEL else []))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
SEQ, FRAME, X0, Y0, X1, Y1 = wc["sequence"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
LABEL, TRUTH = wc["label"], wc["truth"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
needed = [SEQ, FRAME, X0, Y0, X1, Y1] + ([LABEL] if LABEL else [])
numeric = [c for c in [FRAME, X0, Y0, X1, Y1, SCORE] if c] + FEATURES
if SOURCE:
st = stacked(df, needed + [SOURCE], numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
else:
if n_input == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in needed:
if df[c].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=c)
keep = np.ones(n_input, dtype=bool)
for c in needed:
keep &= df[c].notna().to_numpy()
df = df.loc[keep].reset_index(drop=True)
warnings = [cs.cs_warning("CS_W_ROWS_DROPPED", dropped=int(n_input - len(df)), total=n_input)] if len(df) < n_input else []
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
for c in numeric:
k = int(np.isinf(df[c].to_numpy(dtype=float, na_value=np.nan)).sum())
if k:
cs.cs_error("CS_E_NOT_FINITE", column=c, count=k)
is_ref = np.zeros(len(df), dtype=bool)
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
det = ~is_ref
if SCORE:
no_score = det & np.isnan(df[SCORE].to_numpy(dtype=float, na_value=np.nan))
if no_score.any():
warnings.append(f"{int(no_score.sum())} detections have no {SCORE} and were left out.")
det &= ~no_score
if FEATURES:
no_feat = det & df[FEATURES].isna().any(axis=1).to_numpy()
if no_feat.any():
warnings.append(f"{int(no_feat.sum())} detections miss an embedding value and were left out.")
det &= ~no_feat
if int(det.sum()) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Tracking", min=2, n=int(det.sum()))
# %% Tracks
di = np.flatnonzero(det)
seq_all = np.asarray([str(x) for x in df[SEQ].tolist()], dtype=object)
frame_all = df[FRAME].to_numpy(dtype=float)
lab_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object) if LABEL else None
res = tr.track(seq_all[di], frame_all[di], box[di], df[SCORE].to_numpy(dtype=float)[di] if SCORE else None,
lab_all[di] if LABEL else None, df[FEATURES].to_numpy(dtype=float)[di] if FEATURES else None, MODE, **OPTS)
tid_det = res["track"]
track_id = [None] * n_input # per input row; rows that weren't tracked stay empty
for k, i in enumerate(di):
if tid_det[k] > 0:
track_id[int(df["__row"].iloc[i])] = int(tid_det[k])
tracks = res["tracks"]
n_tracks = len(tracks)
n_assigned = int(np.sum(tid_det > 0))
# %% Against the reference tracks
metrics = None
switch_events = []
if SOURCE and TRUTH and int(is_ref.sum()):
truth_ok = is_ref & df[TRUTH].notna().to_numpy()
if int((is_ref & ~truth_ok).sum()):
warnings.append(f"{int((is_ref & ~truth_ok).sum())} reference boxes have no {TRUTH} and were left out of the tracking metrics.")
truth_all = np.asarray([str(x) for x in df[TRUTH].tolist()], dtype=object)
gi = np.flatnonzero(truth_ok)
hi = di[tid_det > 0]
hyp_id = {int(i): str(int(t)) for i, t in zip(di, tid_det) if t > 0}
seqs = []
for sq in sorted(set(seq_all[gi].tolist()) | set(seq_all[hi].tolist())):
g_s = gi[seq_all[gi] == sq]
h_s = hi[seq_all[hi] == sq]
frames = []
for f in sorted(set(frame_all[g_s].tolist()) | set(frame_all[h_s].tolist())):
g_f = g_s[frame_all[g_s] == f]
h_f = h_s[frame_all[h_s] == f]
frames.append({"frame": f, "gt_ids": [f"{sq}\x1f{truth_all[i]}" for i in g_f], "gt_boxes": box[g_f],
"hyp_ids": [hyp_id[int(i)] for i in h_f], "hyp_boxes": box[h_f]})
seqs.append(frames)
metrics = mot.clear_mot(seqs, MOT_IOU)
switch_events = metrics["switch_events"]
# %% Assumptions
assumptions = [
{"key": "frames", "label": "Frames are in order", "status": "info",
"detail": "Tracks follow the frame numbers within each sequence; a gap between frame numbers counts as that many frames of motion and age."},
{"key": "motion", "label": "Objects move smoothly", "status": "info",
"detail": "The constant-velocity motion model expects small changes from frame to frame; fast jumps between frames break tracks."},
]
if FEATURES:
assumptions.append({"key": "appearance", "label": "Embeddings describe appearance", "status": "info",
"detail": "DeepSORT-style matching trusts the embedding columns to tell objects apart; embeddings of the same object should be close."})
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
labels_seen = sorted(set(t["label"] for t in tracks if t["label"] is not None))
seq_list = sorted(set(seq_all[di].tolist()))
n_frames = len(set(zip(seq_all[di].tolist(), frame_all[di].tolist())))
values = {"association": MODE, "n_sequences": len(seq_list), "n_frames": n_frames, "n_detections": int(di.size), "n_tracks": n_tracks,
"n_assigned": n_assigned, "n_unassigned": int(di.size - n_assigned),
"mean_track_length": float(np.mean([t["n_detections"] for t in tracks])) if tracks else None,
"mota": None, "motp": None, "idf1": None, "idp": None, "idr": None, "id_switches": None, "fragmentations": None,
"false_positives": None, "misses": None, "mostly_tracked": None, "partially_tracked": None, "mostly_lost": None,
"precision": None, "recall": None, "n_gt_tracks": None, "n_gt_boxes": None, "track_id": track_id}
for lab in labels_seen:
values[f"tracks[{lab}]"] = sum(1 for t in tracks if t["label"] == lab)
if metrics is not None:
values.update({"mota": metrics["mota"], "motp": metrics["motp"], "idf1": metrics["idf1"], "idp": metrics["idp"], "idr": metrics["idr"],
"id_switches": metrics["switches"], "fragmentations": metrics["fragmentations"], "false_positives": metrics["false_positives"],
"misses": metrics["misses"], "mostly_tracked": metrics["mostly_tracked"], "partially_tracked": metrics["partially_tracked"],
"mostly_lost": metrics["mostly_lost"], "precision": metrics["precision"], "recall": metrics["recall"],
"n_gt_tracks": metrics["n_gt_tracks"], "n_gt_boxes": metrics["objects"]})
trk_rows = [{"track_id": t["track_id"], "sequence": t["sequence"], "label": t["label"], "first_frame": t["first_frame"], "last_frame": t["last_frame"],
"span": t["last_frame"] - t["first_frame"] + 1.0, "n_detections": t["n_detections"], "mean_score": t["mean_score"]} for t in tracks]
tables = [{"key": "tracks", "title": "Tracks",
"columns": [{"key": "track_id", "label": "Track", "type": "integer"}, {"key": "sequence", "label": SEQ, "type": "string"}]
+ ([{"key": "label", "label": LABEL, "type": "string"}] if LABEL else [])
+ [{"key": "first_frame", "label": "First frame", "type": "number"}, {"key": "last_frame", "label": "Last frame", "type": "number"},
{"key": "span", "label": "Frames spanned", "type": "number"}, {"key": "n_detections", "label": "Detections", "type": "integer"}]
+ ([{"key": "mean_score", "label": "Mean score", "type": "number"}] if SCORE else []),
"rows": trk_rows[:500], "note": "First 500 tracks." if len(trk_rows) > 500 else None}]
if metrics is not None:
mrows = [("MOTA", metrics["mota"], "1 − (misses + false positives + identity switches) / reference boxes"),
("IDF1", metrics["idf1"], "Share of boxes on the right identity (global track matching)"),
("MOTP (mean IoU)", metrics["motp"], "Mean overlap of the paired boxes"),
("Identity switches", metrics["switches"], "A reference object took a different track"),
("Fragmentations", metrics["fragmentations"], "A tracked object was lost and found again"),
("Misses", metrics["misses"], "Reference boxes with no track"), ("False positives", metrics["false_positives"], "Tracked boxes with no reference object"),
("Mostly tracked", metrics["mostly_tracked"], "Reference tracks paired in at least 80% of their frames"),
("Mostly lost", metrics["mostly_lost"], "Reference tracks paired in under 20% of their frames")]
tables.append({"key": "mot", "title": f"Against the reference tracks (IoU ≥ {MOT_IOU:g})",
"columns": [{"key": "metric", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "meaning", "label": "Meaning", "type": "string"}],
"rows": [{"metric": a, "value": b, "meaning": c} for a, b, c in mrows]})
if switch_events:
tables.append({"key": "switches", "title": "Identity switches",
"columns": [{"key": "sequence", "label": SEQ, "type": "string"}, {"key": "frame", "label": "Frame", "type": "number"},
{"key": "object", "label": "Reference object", "type": "string"}, {"key": "from", "label": "From track", "type": "string"},
{"key": "to", "label": "To track", "type": "string"}],
"rows": [{"sequence": e["object"].split("\x1f")[0], "frame": e["frame"], "object": e["object"].split("\x1f")[1],
"from": e["from"], "to": e["to"]} for e in switch_events[:200]],
"note": "First 200 switches." if len(switch_events) > 200 else None})
charts = []
if tracks:
lane_of = {t["track_id"]: f"{t['track_id']}" + (f" · {t['label']}" if t["label"] is not None else "") for t in tracks}
shown = tracks[:60]
ln, s0, s1, col, ev = [], [], [], [], []
for t in shown:
fr = np.sort(frame_all[di][tid_det == t["track_id"]])
brk = np.flatnonzero(np.diff(fr) > 1.0)
starts = np.concatenate([[fr[0]], fr[brk + 1]])
ends = np.concatenate([fr[brk], [fr[-1]]])
for a, b in zip(starts, ends):
ln.append(lane_of[t["track_id"]])
s0.append(float(a))
s1.append(float(b))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append(None)
shown_ids = {t["track_id"] for t in shown}
for e in switch_events:
if int(e["to"]) in shown_ids:
t = next(x for x in shown if x["track_id"] == int(e["to"]))
ln.append(lane_of[t["track_id"]])
s0.append(float(e["frame"]))
s1.append(float(e["frame"]))
col.append(t["sequence"] if len(seq_list) > 1 else (t["label"] if t["label"] is not None else t["sequence"]))
ev.append("Identity switch")
roles = {"lane": cs.col("Track", ln, "categorical", levels=[lane_of[t["track_id"]] for t in shown]),
"start": cs.col(FRAME, s0, "numeric"), "end": cs.col("Last frame", s1, "numeric"),
"color": cs.col(SEQ if len(seq_list) > 1 else (LABEL or SEQ), col, "categorical")}
if any(v is not None for v in ev):
roles["event"] = cs.col("Event", ev, "categorical")
charts.append(cs.chart("timeline", "track-timeline", "When each track was seen", roles,
note=("The first 60 tracks. " if len(tracks) > 60 else "") + "Bars break where a track missed more than one frame."))
out = csml.out_dir("target/academy-parity/run-8142/track.objects/detections-only/out-python")
labels_path = os.path.join(out, "labels.parquet")
pd.DataFrame({"row": np.arange(n_input, dtype=np.int64), "cluster": np.asarray([-1 if v is None else v for v in track_id], dtype=np.int64)}).to_parquet(labels_path, index=False)
summary = (f"{n_tracks} track{'s' if n_tracks != 1 else ''} from {int(di.size)} detections in {len(seq_list)} sequence{'s' if len(seq_list) != 1 else ''} "
f"({ {'sort': 'SORT', 'bytetrack': 'ByteTrack', 'deepsort': 'DeepSORT-style'}[MODE] } association); {n_assigned} detections joined a track.")
if metrics is not None:
summary += (f" Against {metrics['n_gt_tracks']} reference tracks: MOTA {f3(metrics['mota'])}, IDF1 {f3(metrics['idf1'])}, "
f"{metrics['switches']} identity switches.")
cs.publish({
"method": "track.objects",
"methodVersion": "1.1.1",
"title": "Object tracks",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "n_tracks", "label": "Tracks", "value": n_tracks}]
+ ([{"key": "mota", "label": "MOTA", "value": metrics["mota"]}, {"key": "idf1", "label": "IDF1", "value": metrics["idf1"]},
{"key": "id_switches", "label": "Identity switches", "value": metrics["switches"]}] if metrics is not None else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Tracks start from detections and are confirmed after {OPTS['min_hits']} detections; a confirmed track ends after {OPTS['max_age']:g} frames without one. "
+ ("Boxes pair only within the same class. " if (LABEL and OPTS["per_class"]) else "")
+ "Constant-velocity Kalman filter per box coordinate; assignment by the Hungarian method (clean-room implementation from the published papers)."],
"charts": charts,
"artifacts": [{"key": "labels", "path": labels_path, "format": "parquet"}],
"values": values,
})
Without reference tracks there is no accuracy score, only what the tracker did. Here SORT ignored boxes scoring below 0.5 and formed 7 tracks from 184 detections; 32 detections got no track id. The mean track lasted 21.7 frames.
Open the track timeline: each lane is a track, and gaps are frames where it coasted on its prediction.
Compare trackers fairly
ReadA tracker is only as good as the boxes it gets. To compare association methods:
- fix the detector and its score threshold, and run every tracker on the same boxes;
- report detection and association separately, because a better detector can hide a worse tracker;
- tune noise settings, gates, confirmation hits and track lifetime on validation sequences, never on the test sequences;
- for ByteTrack, check how sensitive results are to the thresholds, since detectors' scores aren't calibrated the same way.
What runs here
Read| Entry | In CodeSplash |
|---|---|
| VID034 · Simple Online and Realtime Tracking | Runs in CodeSplash on tables (Experimental): Track objects, SORT |
| VID035 · Deep SORT | Runs in CodeSplash on tables (Experimental): Track objects, DeepSORT-style option |
| VID036 · ByteTrack | Runs in CodeSplash on tables (Experimental): Track objects, ByteTrack option |
Check: tracking by detection
CheckpointCheck yourself
In what order does SORT handle each new frame?
Show the answer
Answer: b
Predict, associate, update, with a life cycle for unmatched tracks and detections.
Check yourself
What does the Hungarian method solve in SORT?
Show the answer
Answer: b
A linear assignment over the cost matrix, with pairs below the minimum overlap refused.
Check yourself
What information does SORT not use?
Show the answer
Answer: c
Only boxes and motion. Crossings and long occlusions cause identity switches it can't resolve.
Check yourself
In the boxes-only run above (SORT, no reference tracks), how many tracks were formed?
Show the answer
Answer: 7
The run formed that many tracks. Without reference tracks you can count tracks, but not whether each one is a single object.
Check yourself
How does Deep SORT measure how well a detection fits a track?
Show the answer
Answer: b
Appearance carries identity through occlusions; the gate keeps look-alikes far away from stealing a track.
Check yourself
Why does Deep SORT keep a motion gate when it already has appearance?
Show the answer
Answer: a
Two people in similar clothes look alike; where they could be tells them apart.
Check yourself
A detector misses one pedestrian in most frames. Can a better appearance embedding fix the track?
Show the answer
Answer: b
Re-identification links detections; it can't create the ones the detector never produced.
Check yourself
What can a low-confidence box do in ByteTrack?
Show the answer
Answer: b
Weak boxes are often partly hidden objects. They may continue tracks but never start them, which keeps clutter out.
Check yourself
You switch to a different detector. What should you do about ByteTrack's score thresholds?
Show the answer
Answer: b
Confidence scores aren't calibrated the same way across detectors, cameras and classes.
Check yourself
You want to know whether ByteTrack associates better than SORT. Which comparison is fair?
Show the answer
Answer: a
Hold the boxes fixed so differences come from association, not detection.
Recap
Recap- Tracking by detection predicts, matches and updates, with a life cycle for tracks.
- SORT matches by overlap with the Hungarian method; it can't see appearance.
- Deep SORT adds appearance embeddings inside a motion gate; it can't recover missed detections.
- ByteTrack lets low-confidence boxes extend tracks but not start them.
- Track objects runs all three on tables of boxes; fix the detector when comparing.
Concepts in this lesson