Following one object's mask: STCN, XMem and SAM 2
Given an object's mask in the first frame, mark it in every later frame. Memory-based models read stored frames to find it (STCN), manage memory for long videos (XMem) or take prompts and corrections (SAM 2).
What runs in CodeSplash
- VID037Space-Time Correspondence Networks (STCN) Explained here
- VID038XMem Explained here
- VID039Segment Anything Model 2 (SAM 2) Explained here
- Segmentation quality (IoU, Dice, segment F1) Experimental
You will be able to
- Define semi-supervised video object segmentation and what counts as supervision
- Describe reading a space-time memory by key similarity
- Explain why long videos need memory that is merged or pruned, and how errors spread through memory
- Report a promptable segmenter's results with the corrections it needed
The task
ReadIn video object segmentationVideo object segmentationGiven an object's mask in the first frame, mark the same object's pixels in every later frame., someone marks an object's pixels in the first frame, and the model marks the same object in every later frame. That first mask is supervision: the model is told which object, and the task is to keep it through motion, occlusion and changes of look.
Benchmarks score each frame's mask against the reference by region overlap (J, the mask IoU) and by how well the outline matches (F), averaged over objects and frames.
Read the past from memory
ReadSTCN keeps a space-time memorySpace-time memoryFeatures of past frames stored as keys and values; the current frame reads them by key similarity to find the object. of past frames: a key per pixel for matching and a value per pixel carrying the mask. Each pixel of the current frame compares its key with every memory key and reads a weighted mix of their values:
In the reference's toy, the query is close to two object pixels and far from a background one: weights 0.454, 0.092 and 0.454, so it reads an object value of 0.908. That is a match score, not a calibrated probability.
Memory for long videos
ReadKeeping every frame makes memory grow without end. XMem splits it into a short-lived sensory memory, a working memory of recent frames and a compact long-term memory. When working memory fills, its contents are consolidated into long-term memory.
In the reference's toy, two working-memory entries are averaged into one long-term entry, 0.9 and 0.1, leaving the newest, 0.6 and 0.4, in working memory. XMem learns how to do this; compressing can still forget a rare view of the object.
A bad frame enters memory
PredictPredict first
At frame 50 a similar-looking object passes close by, and the model's mask briefly covers it. That mask is written to memory. What happens next?
Reveal
The error tends to spread. Later frames read the wrong pixels from memory as "the object", so the mistake can grow. Report results over long sequences and after occlusions, and count how often a correction was needed.
Prompts and corrections
ReadSAM 2 extends promptable segmentationPromptable segmentation (SAM)Returning a mask for whatever a click, box or rough mask points at, without a fixed class list. to video: a point, box or mask picks the object in any frame, and a streaming memory carries it forward. When the mask goes wrong, a user adds a correction and the model continues from it.
In the reference's toy, a predicted mask overlaps the truth with IoU 0.5; after 1 supplied correction it reaches 1. The correction did the work, so it belongs in the evaluation budget: report masks and the clicks needed. A correction made after seeing later frames isn't a live result.
Scoring masks in CodeSplash
ExploreAcross 10 images and 4 classes, mean IoU = 0.403, mean Dice = 0.513 and pixel accuracy = 0.550.
- Mean IoU
- 0.4027
- Mean Dice
- 0.5126
- Pixel accuracy
- 0.5497
Plots
View data
| label | Measure | Overlap |
|---|---|---|
| bicycle | IoU | 0.4855 |
| bicycle | Dice | 0.6537 |
| car | IoU | 0.3607 |
| car | Dice | 0.5301 |
| dog | IoU | 0 |
| dog | Dice | 0 |
| person | IoU | 0.7645 |
| person | Dice | 0.8666 |
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (pixels summed over images)
| label | Reference pixels | Predicted pixels | Overlap (pixels) | IoU | Dice |
|---|---|---|---|---|---|
| bicycle | 9,844 | 14,196 | 7,857 | 0.4855 | 0.6537 |
| car | 64,322 | 26,067 | 23,959 | 0.3607 | 0.5301 |
| dog | 0 | 3,012 | 0 | 0 | 0 |
| person | 38,221 | 30,924 | 29,959 | 0.7645 | 0.8666 |
Mean IoU per image
| media_id | Mean IoU |
|---|---|
| img01 | 0.4776 |
| img02 | 0.4692 |
| img03 | 0.2155 |
| img04 | 0.3200 |
| img05 | 0.6104 |
| img06 | 0.5888 |
| img07 | 0.3134 |
| img08 | 0.8444 |
| img09 | 0 |
| img10 | 0 |
- Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded).
The exact R script · R R version 4.5.1 (2025-06-13)
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec ebc2b9896c4c2c9c
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_eval_seg_* (segmentation scores), cs_eval_det_runs, cs_eval_stacked, cs_rle_* (COCO RLE)
# %% Data
GROUP <- "media_id"
FRAME <- NULL
LABEL <- "label"
SOURCE <- "source"
MASK <- "mask_rle"
WIDTH <- "image_width"
HEIGHT <- "image_height"
CROWD <- NULL
START <- NULL
END <- NULL
SCORE <- NULL
KIND <- "masks" # masks | intervals
BACKGROUND <- FALSE
THRESHOLDS <- as.numeric(unlist(c(0.1, 0.25, 0.5)))
if (!length(THRESHOLDS)) THRESHOLDS <- 0.5
THRESHOLDS <- sort(unique(THRESHOLDS))
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction") # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
columns <- unique(c(GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_boxes.parquet", col_select = columns))
if (KIND == "masks" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "time intervals unless the mask, width and height columns are set", value = "masks")
}
if (KIND == "intervals" && (is.null(START) || is.null(END))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "masks unless the start and end columns are set", value = "time intervals")
}
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above this table's rows under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/evaluate.segments/masks-no-background/out-r", "reference_table"),
list(group = GROUP, frame = FRAME, label = LABEL, mask = MASK, width = WIDTH, height = HEIGHT, crowd = CROWD,
start = START, end = END, score = SCORE), REF_ROLES,
c(list(frame = "Frame"), if (KIND == "masks") list(mask = "Mask", width = "Image width", height = "Image height") else list(start = "Start", end = "End")),
SOURCE, REF_LEVEL, c("group", "label", if (KIND == "masks") c("mask", "width", "height") else c("start", "end")))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
GROUP <- wc$group; FRAME <- wc$frame; LABEL <- wc$label; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
CROWD <- wc$crowd; START <- wc$start; END <- wc$end
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
} else if (is.null(SOURCE)) {
cs_error("CS_E_INVALID_OPTION", option = "Reference table", allowed = "a table of reference rows unless the Reference or prediction column is set", value = "none")
}
needed <- c(GROUP, LABEL, SOURCE, if (KIND == "masks") c(MASK, WIDTH, HEIGHT) else c(START, END))
numeric_cols <- if (KIND == "masks") c(WIDTH, HEIGHT) else c(START, END, SCORE)
st <- cs_eval_stacked(df, needed, numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
labels_all <- as.character(df[[LABEL]])
crowd <- if (!is.null(CROWD) && KIND == "masks") cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE
classes <- sort(unique(labels_all[!crowd]), method = "radix")
if (KIND == "masks") {
# %% Masks -> runs, per image
ik <- cs_eval_image_keys(df[[GROUP]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
img_idx <- ik$index
ws <- as.numeric(df[[WIDTH]])
hs <- as.numeric(df[[HEIGHT]])
runs <- lapply(seq_len(nrow(df)), function(i) {
tryCatch(cs_eval_det_runs(cs_rle_string_to_counts(as.character(df[[MASK]][i])), as.integer(hs[i]), as.integer(ws[i])),
error = function(e) NULL)
})
n_bad <- sum(vapply(runs, is.null, logical(1)))
if (n_bad > 0) cs_error("CS_E_INVALID_VALUES", column = MASK, requirement = "a COCO RLE string that covers width × height pixels", count = n_bad)
ims <- lapply(seq_along(ik$media), function(i) list(n = NULL, size = NULL, ref = list(), pred = list(), void = list()))
for (i in seq_along(runs)) {
q <- img_idx[i] + 1L
r <- runs[[i]]
if (is.null(ims[[q]]$n)) {
ims[[q]]$n <- as.numeric(r$size[1]) * as.numeric(r$size[2])
ims[[q]]$size <- r$size
} else if (!identical(ims[[q]]$size, r$size)) {
cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", WIDTH, HEIGHT), requirement = "the same size for every mask of an image", count = 1)
}
rr <- list(s = r$s, e = r$e)
if (crowd[i]) {
ims[[q]]$void[[length(ims[[q]]$void) + 1L]] <- rr
} else if (is_ref[i]) {
lab <- labels_all[i]
ims[[q]]$ref[[lab]] <- c(if (is.null(ims[[q]]$ref[[lab]])) list() else ims[[q]]$ref[[lab]], list(rr))
} else {
lab <- labels_all[i]
ims[[q]]$pred[[lab]] <- c(if (is.null(ims[[q]]$pred[[lab]])) list() else ims[[q]]$pred[[lab]], list(rr))
}
}
res <- cs_eval_seg_masks(ims, classes, BACKGROUND)
names_ <- res$classes
n_ref <- sum(is_ref & !crowd)
n_pred <- sum(!is_ref)
unit <- "pixels"
group_rows <- lapply(seq_along(ik$media), function(i) list(group = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i],
miou = if (is.null(res$per_image[[i]])) NA_real_ else res$per_image[[i]]))
n_groups <- length(ik$media)
has_score <- FALSE
} else {
# %% Intervals per recording
s_all <- as.numeric(df[[START]])
e_all <- as.numeric(df[[END]])
bad <- e_all < s_all
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = END, requirement = sprintf("at least %s", START), count = sum(bad))
sc_all <- if (!is.null(SCORE)) as.numeric(df[[SCORE]]) else rep(NA_real_, nrow(df))
has_score <- !is.null(SCORE)
if (has_score) {
miss <- !is_ref & is.na(sc_all)
if (any(miss)) {
warnings <- c(warnings, sprintf("%d predicted segments have no %s and were left out.", sum(miss), SCORE))
keep <- !miss
df <- df[keep, , drop = FALSE]; is_ref <- is_ref[keep]; labels_all <- labels_all[keep]
s_all <- s_all[keep]; e_all <- e_all[keep]; sc_all <- sc_all[keep]
classes <- sort(unique(labels_all), method = "radix")
}
}
grp <- as.character(df[[GROUP]])
groups <- sort(unique(grp), method = "radix")
recs <- lapply(groups, function(g) {
rows <- which(grp == g)
rr <- rows[is_ref[rows]]
pr <- rows[!is_ref[rows]]
list(ref = data.frame(start = s_all[rr], end = e_all[rr], label = labels_all[rr], stringsAsFactors = FALSE),
pred = data.frame(start = s_all[pr], end = e_all[pr], label = labels_all[pr], score = if (has_score) sc_all[pr] else rep(0, length(pr)),
row = pr - 1L, stringsAsFactors = FALSE))
})
res <- cs_eval_seg_intervals(recs, classes, THRESHOLDS, has_score)
names_ <- res$classes
n_ref <- res$n_ref
n_pred <- res$n_pred
unit <- "seconds"
n_groups <- length(groups)
}
# %% Assumptions
assumptions <- list(
list(key = "complete", label = "The reference is complete", status = "info",
detail = "Regions or segments missing from the reference turn correct predictions into errors."),
list(key = "overlap", label = "Reference classes don't overlap", status = "info",
detail = "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.")
)
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tkey <- function(t) sprintf("%g", t)
values <- list(kind = KIND, n_groups = n_groups, n_classes = length(names_), n_reference = n_ref, n_predictions = n_pred,
accuracy = res$accuracy, miou = res$miou, mean_dice = res$mean_dice, fw_iou = res$fw_iou,
scored = if (!is.null(res$scored)) res$scored else sum(res$gsum), ignored = if (!is.null(res$ignored)) res$ignored else NA_real_,
map = NA_real_)
for (j in seq_along(names_)) {
values[[sprintf("iou[%s]", names_[j])]] <- res$iou[j]
values[[sprintf("dice[%s]", names_[j])]] <- res$dice[j]
}
cls_cols <- list(list(key = "class", label = LABEL, type = "string"), list(key = "ref", label = sprintf("Reference %s", unit), type = "number"),
list(key = "pred", label = sprintf("Predicted %s", unit), type = "number"), list(key = "inter", label = sprintf("Overlap (%s)", unit), type = "number"),
list(key = "iou", label = "IoU", type = "number"), list(key = "dice", label = "Dice", type = "number"))
cls_rows <- lapply(seq_along(names_), function(j) list(class = names_[j], ref = res$gsum[j], pred = res$psum[j], inter = res$inter[j],
iou = res$iou[j], dice = res$dice[j]))
tables <- list()
charts <- list()
if (KIND == "intervals") {
m_rows <- res$matching
for (r in m_rows) {
values[[sprintf("f1[%s]", tkey(r$threshold))]] <- r$f1
values[[sprintf("precision[%s]", tkey(r$threshold))]] <- r$precision
values[[sprintf("recall[%s]", tkey(r$threshold))]] <- r$recall
if (has_score) values[[sprintf("ap[%s]", tkey(r$threshold))]] <- r$map
}
if (has_score) {
maps <- vapply(m_rows, function(r) r$map, numeric(1))
maps <- maps[!is.na(maps)]
values$map <- if (length(maps)) mean(maps) else NA_real_
for (r in m_rows) {
key <- sprintf("ap_%s", tkey(r$threshold))
cls_cols[[length(cls_cols) + 1L]] <- list(key = key, label = sprintf("AP@%s", tkey(r$threshold)), type = "number")
for (j in seq_along(cls_rows)) cls_rows[[j]][[key]] <- if (is.null(r$ap[[cls_rows[[j]]$class]])) NA_real_ else r$ap[[cls_rows[[j]]$class]]
}
}
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (time overlap)", columns = cls_cols, rows = cls_rows)
mcols <- list(list(key = "threshold", label = "IoU threshold", type = "number"), list(key = "tp", label = "Matched", type = "integer"),
list(key = "fp", label = "False alarms", type = "integer"), list(key = "fn", label = "Missed", type = "integer"),
list(key = "precision", label = "Precision", type = "number"), list(key = "recall", label = "Recall", type = "number"),
list(key = "f1", label = "F1", type = "number"))
if (has_score) mcols[[length(mcols) + 1L]] <- list(key = "map", label = "mAP", type = "number")
tables[[length(tables) + 1L]] <- list(key = "matching", title = "Segments matched at each IoU threshold", columns = mcols,
rows = lapply(m_rows, function(r) r[c("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")]))
pc <- character(0); pm <- character(0); pv <- numeric(0)
for (r in m_rows) for (km in list(c("f1", "F1"), c("precision", "Precision"), c("recall", "Recall"))) if (!is.na(r[[km[1]]])) {
pc <- c(pc, sprintf("IoU %s", tkey(r$threshold))); pm <- c(pm, km[2]); pv <- c(pv, r[[km[1]]])
}
if (length(pv)) {
charts[[length(charts) + 1L]] <- cs_chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", list(
category = cs_col("IoU threshold", pc, "categorical", levels = vapply(m_rows, function(r) sprintf("IoU %s", tkey(r$threshold)), character(1))),
value = cs_col("Share", pv, "numeric"),
group = cs_col("Measure", pm, "categorical", levels = c("F1", "Precision", "Recall"))))
}
} else {
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (pixels summed over images)", columns = cls_cols, rows = cls_rows)
tables[[length(tables) + 1L]] <- list(key = "images", title = "Mean IoU per image", rows = utils::head(group_rows, 500),
columns = c(list(list(key = "group", label = GROUP, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
list(list(key = "miou", label = "Mean IoU", type = "number"))),
note = if (length(group_rows) > 500) "First 500 images." else NULL)
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (j in seq_along(names_)) for (km in list(c("iou", "IoU"), c("dice", "Dice"))) if (!is.na(res[[km[1]]][j])) {
dc <- c(dc, names_[j]); dm <- c(dm, km[2]); dv <- c(dv, res[[km[1]]][j])
}
if (length(dv)) {
charts <- c(list(cs_chart("by-class", "cleveland-dot", "IoU and Dice by class", list(
category = cs_col(LABEL, dc, "categorical", levels = names_), value = cs_col("Overlap", dv, "numeric"),
group = cs_col("Measure", dm, "categorical", levels = c("IoU", "Dice"))))), charts)
}
what <- if (KIND == "masks") "pixel accuracy" else "time-weighted accuracy"
summary <- sprintf("Across %d %s and %d classes, mean IoU = %s, mean Dice = %s and %s = %s.", n_groups, if (KIND == "masks") "images" else "recordings",
length(names_), f3(res$miou), f3(res$mean_dice), what, f3(res$accuracy))
if (KIND == "intervals") {
summary <- paste0(summary, " Segment F1: ", paste(vapply(res$matching, function(r) sprintf("%s at IoU %s", f3(r$f1), tkey(r$threshold)), character(1)), collapse = ", "), ".")
if (has_score && !is.na(values$map)) summary <- paste0(summary, sprintf(" mAP over the thresholds = %s.", f3(values$map)))
}
cs_publish(list(
method = "evaluate.segments",
methodVersion = "1.1.0",
title = "Segmentation quality",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = list(list(key = "miou", label = "Mean IoU", value = res$miou), list(key = "mean_dice", label = "Mean Dice", value = res$mean_dice),
list(key = "accuracy", label = if (KIND == "masks") "Pixel accuracy" else "Time-weighted accuracy", value = res$accuracy)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(if (is.null(REF_ROLES)) sprintf("Reference rows: %s = %s; predictions: %s = %s. ", SOURCE, st$reference, SOURCE, st$prediction)
else "Reference rows come from the reference table; this table's rows are the predictions. ",
if (KIND == "masks") paste0("Masks are compared on their run lengths (no pixels decoded)", if (BACKGROUND) "; unlabeled pixels form a background class" else "",
if (!is.null(CROWD)) "; crowd regions are left out of scoring" else "", ".")
else paste0("Segments match within a recording and class, ", if (!is.null(SCORE)) "highest score first." else "earliest first."))),
charts = charts,
values = values
))
Across 10 images and 4 classes, mean IoU = 0.403, mean Dice = 0.513 and pixel accuracy = 0.550.
- Mean IoU
- 0.4027
- Mean Dice
- 0.5126
- Pixel accuracy
- 0.5497
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (pixels summed over images)
| label | Reference pixels | Predicted pixels | Overlap (pixels) | IoU | Dice |
|---|---|---|---|---|---|
| bicycle | 9,844 | 14,196 | 7,857 | 0.4855 | 0.6537 |
| car | 64,322 | 26,067 | 23,959 | 0.3607 | 0.5301 |
| dog | 0 | 3,012 | 0 | 0 | 0 |
| person | 38,221 | 30,924 | 29,959 | 0.7645 | 0.8666 |
Mean IoU per image
| media_id | Mean IoU |
|---|---|
| img01 | 0.4776 |
| img02 | 0.4692 |
| img03 | 0.2155 |
| img04 | 0.3200 |
| img05 | 0.6104 |
| img06 | 0.5888 |
| img07 | 0.3134 |
| img08 | 0.8444 |
| img09 | 0 |
| img10 | 0 |
- Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec ebc2b9896c4c2c9c
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import detection as det # RLE runs (twin: cs_eval_det_runs)
from codesplash.evaluate import segmentation as seg # twin: codesplashr cs_eval_seg_*
from codesplash.evaluate.stacked import flags, image_keys, stacked # twin: cs_eval_stacked
from codesplash.vision import boxes as vb # COCO RLE strings (twin: cs_rle_*)
# %% Data
GROUP = "media_id"
FRAME = None
LABEL = "label"
SOURCE = "source"
MASK = "mask_rle"
WIDTH = "image_width"
HEIGHT = "image_height"
CROWD = None
START = None
END = None
SCORE = None
KIND = "masks" # masks | intervals
BACKGROUND = False
THRESHOLDS = [float(t) for t in [0.1, 0.25, 0.5]] or [0.5]
THRESHOLDS = sorted(set(THRESHOLDS))
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"] # stored order
# Reference rows 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 [GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_boxes.parquet", columns=columns)
if KIND == "masks" and not (MASK and WIDTH and HEIGHT):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="time intervals unless the mask, width and height columns are set", value="masks")
if KIND == "intervals" and not (START and END):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="masks unless the start and end columns are set", value="time intervals")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above this table's rows 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/evaluate.segments/masks-no-background/out-python", "reference_table"),
{"group": GROUP, "frame": FRAME, "label": LABEL, "mask": MASK, "width": WIDTH, "height": HEIGHT, "crowd": CROWD,
"start": START, "end": END, "score": SCORE}, REF_ROLES,
{"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if KIND == "masks" else {"start": "Start", "end": "End"})},
SOURCE, REF_LEVEL, ["group", "label"] + (["mask", "width", "height"] if KIND == "masks" else ["start", "end"]))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
GROUP, FRAME, LABEL, MASK, WIDTH, HEIGHT = wc["group"], wc["frame"], wc["label"], wc["mask"], wc["width"], wc["height"]
CROWD, START, END = wc["crowd"], wc["start"], wc["end"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
elif SOURCE is None:
cs.cs_error("CS_E_INVALID_OPTION", option="Reference table", allowed="a table of reference rows unless the Reference or prediction column is set", value="none")
needed = [GROUP, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if KIND == "masks" else [START, END])
numeric = [WIDTH, HEIGHT] if KIND == "masks" else [c for c in [START, END, SCORE] if c]
st = stacked(df, needed, numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
if int(is_ref.sum()) == 0 or int((~is_ref).sum()) == 0:
cs.cs_error("CS_E_GROUP_COUNT", column=SOURCE, expected=2, k=1)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)
crowd = flags(df[CROWD]) if (CROWD and KIND == "masks") else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False
classes = sorted(set(labels_all[~crowd].tolist()))
if KIND == "masks":
# %% Masks → runs, per image
img_idx, images = image_keys(df[GROUP], df[FRAME] if FRAME else None)
ws, hs = df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)
runs, n_bad = [], 0
for s, w, h in zip(df[MASK].tolist(), ws, hs):
try:
runs.append(det.runs_from_counts(vb.string_to_counts(str(s)), int(h), int(w)))
except (ValueError, OverflowError):
runs.append(None)
n_bad += 1
if n_bad:
cs.cs_error("CS_E_INVALID_VALUES", column=MASK, requirement="a COCO RLE string that covers width × height pixels", count=n_bad)
ims = [{"n": None, "ref": {}, "pred": {}, "void": []} for _ in images]
for i, r in enumerate(runs):
im = ims[int(img_idx[i])]
n = float(r[2][0]) * float(r[2][1])
if im["n"] is None:
im["n"], im["size"] = n, r[2]
elif im["size"] != r[2]:
cs.cs_error("CS_E_INVALID_VALUES", column=f"{WIDTH} and {HEIGHT}", requirement="the same size for every mask of an image", count=1)
if crowd[i]:
im["void"].append(r[:2])
else:
side = im["ref"] if is_ref[i] else im["pred"]
side.setdefault(labels_all[i], []).append(r[:2])
res = seg.mask_scores(ims, classes, BACKGROUND)
names = res["classes"]
n_ref = int(np.sum(is_ref & ~crowd))
n_pred = int(np.sum(~is_ref))
unit = "pixels"
group_rows = [{"group": m, "frame": None if f == float("-inf") else f, "miou": res["per_image"][i]} for i, (m, f) in enumerate(images)]
n_groups = len(images)
else:
# %% Intervals per recording
s_all, e_all = df[START].to_numpy(dtype=float), df[END].to_numpy(dtype=float)
bad = e_all < s_all
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=END, requirement=f"at least {START}", count=int(bad.sum()))
sc_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan) if SCORE else np.full(len(df), np.nan)
has_score = SCORE is not None
if has_score:
miss = ~is_ref & np.isnan(sc_all)
if miss.any():
warnings.append(f"{int(miss.sum())} predicted segments have no {SCORE} and were left out.")
keep = ~miss
df, is_ref, labels_all, s_all, e_all, sc_all = df.loc[keep].reset_index(drop=True), is_ref[keep], labels_all[keep], s_all[keep], e_all[keep], sc_all[keep]
classes = sorted(set(labels_all.tolist()))
grp = np.asarray([str(x) for x in df[GROUP].tolist()], dtype=object)
groups = sorted(set(grp.tolist()))
recs = []
for g in groups:
rows = np.flatnonzero(grp == g)
recs.append({"ref": [(s_all[i], e_all[i], labels_all[i]) for i in rows if is_ref[i]],
"pred": [(s_all[i], e_all[i], labels_all[i], float(sc_all[i]) if has_score else 0.0, int(i)) for i in rows if not is_ref[i]]})
res = seg.interval_scores(recs, classes, THRESHOLDS, has_score)
names = res["classes"]
n_ref, n_pred = res["n_ref"], res["n_pred"]
unit = "seconds"
n_groups = len(groups)
# %% Assumptions
assumptions = [
{"key": "complete", "label": "The reference is complete", "status": "info",
"detail": "Regions or segments missing from the reference turn correct predictions into errors."},
{"key": "overlap", "label": "Reference classes don't overlap", "status": "info",
"detail": "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area."},
]
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
tkey = lambda t: "%g" % t
values = {"kind": KIND, "n_groups": n_groups, "n_classes": len(names), "n_reference": n_ref, "n_predictions": n_pred,
"accuracy": res["accuracy"], "miou": res["miou"], "mean_dice": res["mean_dice"], "fw_iou": res["fw_iou"],
"scored": res.get("scored", float(np.sum(res["gsum"]))), "ignored": res.get("ignored"), "map": None}
for j, c in enumerate(names):
values[f"iou[{c}]"] = res["iou"][j]
values[f"dice[{c}]"] = res["dice"][j]
cls_cols = [{"key": "class", "label": LABEL, "type": "string"}, {"key": "ref", "label": f"Reference {unit}", "type": "number"},
{"key": "pred", "label": f"Predicted {unit}", "type": "number"}, {"key": "inter", "label": f"Overlap ({unit})", "type": "number"},
{"key": "iou", "label": "IoU", "type": "number"}, {"key": "dice", "label": "Dice", "type": "number"}]
cls_rows = [{"class": c, "ref": float(res["gsum"][j]), "pred": float(res["psum"][j]), "inter": float(res["inter"][j]),
"iou": res["iou"][j], "dice": res["dice"][j]} for j, c in enumerate(names)]
tables = []
charts = []
if KIND == "intervals":
m_rows = res["matching"]
for r in m_rows:
values[f"f1[{tkey(r['threshold'])}]"] = r["f1"]
values[f"precision[{tkey(r['threshold'])}]"] = r["precision"]
values[f"recall[{tkey(r['threshold'])}]"] = r["recall"]
if has_score:
values[f"ap[{tkey(r['threshold'])}]"] = r["map"]
if has_score:
maps = [r["map"] for r in m_rows if r["map"] is not None]
values["map"] = float(np.mean(maps)) if maps else None
for r in m_rows:
cls_cols.append({"key": f"ap_{tkey(r['threshold'])}", "label": f"AP@{tkey(r['threshold'])}", "type": "number"})
for row in cls_rows:
row[f"ap_{tkey(r['threshold'])}"] = r["ap"].get(row["class"])
tables.append({"key": "classes", "title": "Per class (time overlap)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "matching", "title": "Segments matched at each IoU threshold",
"columns": [{"key": "threshold", "label": "IoU threshold", "type": "number"}, {"key": "tp", "label": "Matched", "type": "integer"},
{"key": "fp", "label": "False alarms", "type": "integer"}, {"key": "fn", "label": "Missed", "type": "integer"},
{"key": "precision", "label": "Precision", "type": "number"}, {"key": "recall", "label": "Recall", "type": "number"},
{"key": "f1", "label": "F1", "type": "number"}] + ([{"key": "map", "label": "mAP", "type": "number"}] if has_score else []),
"rows": [{k: r[k] for k in ("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")} for r in m_rows]})
pts = [(f"IoU {tkey(r['threshold'])}", lab, r[key]) for r in m_rows for key, lab in (("f1", "F1"), ("precision", "Precision"), ("recall", "Recall")) if r[key] is not None]
if pts:
charts.append(cs.chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", {
"category": cs.col("IoU threshold", [p[0] for p in pts], "categorical", levels=[f"IoU {tkey(r['threshold'])}" for r in m_rows]),
"value": cs.col("Share", [p[2] for p in pts], "numeric"),
"group": cs.col("Measure", [p[1] for p in pts], "categorical", levels=["F1", "Precision", "Recall"])}))
else:
tables.append({"key": "classes", "title": "Per class (pixels summed over images)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "images", "title": "Mean IoU per image", "rows": group_rows[:500],
"columns": [{"key": "group", "label": GROUP, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else [])
+ [{"key": "miou", "label": "Mean IoU", "type": "number"}], "note": "First 500 images." if len(group_rows) > 500 else None})
dots = [(c, m, res[key][j]) for j, c in enumerate(names) for key, m in (("iou", "IoU"), ("dice", "Dice")) if res[key][j] is not None]
if dots:
charts.insert(0, cs.chart("by-class", "cleveland-dot", "IoU and Dice by class", {
"category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=names),
"value": cs.col("Overlap", [d[2] for d in dots], "numeric"),
"group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["IoU", "Dice"])}))
what = "pixel accuracy" if KIND == "masks" else "time-weighted accuracy"
summary = (f"Across {n_groups} {'images' if KIND == 'masks' else 'recordings'} and {len(names)} classes, mean IoU = {f3(res['miou'])}, "
f"mean Dice = {f3(res['mean_dice'])} and {what} = {f3(res['accuracy'])}.")
if KIND == "intervals":
summary += " Segment F1: " + ", ".join(f"{f3(r['f1'])} at IoU {tkey(r['threshold'])}" for r in res["matching"]) + "."
if has_score and values["map"] is not None:
summary += f" mAP over the thresholds = {f3(values['map'])}."
cs.publish({
"method": "evaluate.segments",
"methodVersion": "1.1.0",
"title": "Segmentation quality",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "miou", "label": "Mean IoU", "value": res["miou"]}, {"key": "mean_dice", "label": "Mean Dice", "value": res["mean_dice"]},
{"key": "accuracy", "label": "Pixel accuracy" if KIND == "masks" else "Time-weighted accuracy", "value": res["accuracy"]}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [(f"Reference rows: {SOURCE} = {st['reference']}; predictions: {SOURCE} = {st['prediction']}. " if REF_ROLES is None
else "Reference rows come from the reference table; this table's rows are the predictions. ")
+ ("Masks are compared on their run lengths (no pixels decoded)" + ("; unlabeled pixels form a background class" if BACKGROUND else "")
+ ("; crowd regions are left out of scoring" if CROWD else "") + "." if KIND == "masks"
else "Segments match within a recording and class, " + ("highest score first." if SCORE else "earliest first."))],
"charts": charts,
"values": values,
})
Segmentation quality scores predicted masks against reference masks class by class. Across 10 images, mean IoU is 0.403: high for people, 0.765, and zero for dogs.
For video frames, the method's Frame role scores each image-and-frame pair as its own picture, which is J per frame. Contour accuracy (F) isn't computed.
What runs here
Read| Entry | In CodeSplash |
|---|---|
| VID037 · Space-Time Correspondence Networks | Explained here |
| VID038 · XMem | Explained here |
| VID039 · Segment Anything Model 2 (SAM 2) | Explained here |
Check: video object segmentation
CheckpointCheck yourself
In semi-supervised video object segmentation, what is the supervision at prediction time?
Show the answer
Answer: b
The first mask says which object to follow; the model must keep it through the rest of the video.
Check yourself
How does STCN decide which stored information a current pixel reads?
Show the answer
Answer: a
Key distances become weights; the weighted memory values carry the mask information.
Check yourself
A memory readout gives a pixel an object value close to one. Can you read it as a calibrated probability that the pixel belongs to the object?
Show the answer
Answer: b
Softmax weights sum to one, but that doesn't make the result calibrated against the truth.
Check yourself
Why does XMem split memory into working and long-term stores?
Show the answer
Answer: b
Consolidating older frames bounds memory growth on long recordings.
Check yourself
What can go wrong when XMem compresses older frames into long-term memory?
Show the answer
Answer: a
Compression loses detail, and memory errors propagate. Test reappearance after long occlusions.
Check yourself
SAM 2 reaches a high mask overlap after users added corrections. What must the report include?
Show the answer
Answer: b
Corrections are human work that improved the result. They belong in the budget, and future-frame corrections aren't live performance.
Check yourself
How does promptable segmentation differ from semantic segmentation?
Show the answer
Answer: b
A point, box or mask says "this one"; semantic segmentation labels every pixel with a category.
Recap
Recap- Video object segmentation follows one object given its first-frame mask; score masks (J) and outlines (F).
- STCN reads a key–value memory of past frames; readouts are match scores, not probabilities.
- XMem consolidates memory for long videos; errors written to memory spread.
- SAM 2 takes prompts and corrections; report the corrections with the masks.
Concepts in this lesson