Skip to content

Two-stage detectors: Fast R-CNN, Faster R-CNN and Mask R-CNN

How region-based detectors got fast: features computed once and cropped per region, proposals learned from anchors, and a mask head that samples between pixels. Faster R-CNN and Mask R-CNN run in CodeSplash.

Advanced ~16 min9 steps

What runs in CodeSplash

You will be able to

  • Explain how RoI pooling lets every proposal share one feature map
  • Encode and decode a box as offsets from an anchor
  • Describe what a region proposal network predicts at each position
  • Say why Mask R-CNN samples features with RoIAlign instead of rounding

Read first

01

Compute features once

Read
Reference · VIS002 · Explained hereFast R-CNNFast R-CNN shares convolutional computation across proposed regions and jointly trains classification and box refinement.

Fast R-CNN fixed R-CNN's waste: run the CNN once on the whole image, then cut each proposal's piece out of the shared feature map. RoI poolingRoI pooling and RoIAlignCutting a fixed-size feature grid out of shared features for each proposal. RoIAlign samples between pixels instead of rounding. divides that piece into a fixed grid and takes the maximum in each cell, so every proposal, whatever its size, becomes the same small block for the classifier.

In the program a 4 × 4 region holding 1 to 16 is pooled to 2 × 2: the cell maxima are 6, 8, 14 and 16.

02

One loss for class and box

Read

Fast R-CNN trains classification and box refinement together. The box part uses smooth L1Smooth L1 lossSquared error for small box errors and absolute error for large ones, so one badly placed box can't dominate training.: squared error for small mistakes, absolute error beyond one unit, so a single badly placed box can't dominate. The program's four coordinate errors give a smooth L1 sum of 1.045; the largest error counts linearly, not squared.

The proposals still came from an outside algorithm, which now took most of the time.

03

Learn the proposals

Read
Reference · VIS003 · Runs in CodeSplashFaster R-CNNFaster R-CNN learns region proposals through a region proposal network sharing image features with the detector.

Faster R-CNN adds a region proposal networkRegion proposal network (RPN)A small head on shared CNN features that scores fixed anchor boxes at every position and nudges them into proposals. on the shared features. At every position it considers a few anchor boxes of set sizes and shapes, scores each for "object or not" and predicts how to move it. The best few hundred become proposals for the second stage, which classifies them and refines their boxes again.

Modern versions add a feature pyramidFeature pyramid networkAdds a top-down path that sends coarse, meaningful features back to finer maps, so objects of every size are found. so small objects are proposed from fine maps and large ones from coarse maps.

04

Boxes as offsets

Read

The network never outputs coordinates directly. Box regressionBox regression (box deltas)Predicting how to shift and rescale a reference box: center moves in units of its size, width and height as log ratios. predicts offsets from the anchor: the center shift divided by the anchor's size, and width and height as log ratios.

The program's anchor is centered at (10, 20), 8 wide and 6 tall; the object is centered at (12, 19), 12 wide and 3 tall. The offsets are 0.250 and −0.167 for the center, and 0.405 and −0.693 for the size. Decoding them gives back exactly 12, 19, 12 and 3.

05

Why log ratios?

Predict

Predict first

Why predict log(w / w_anchor) instead of w − w_anchor?

They are faster to computeDoubling and halving get offsets of the same sizeThey keep widths below one
Reveal

Doubling and halving get offsets of the same size, log 2 and −log 2. A plain difference would treat a box twice too big very differently from one twice too small, and would depend on the object's size in pixels.

06

Masks from the same proposals

Read
Reference · VIS009 · Runs in CodeSplashMask R-CNNMask R-CNN adds per-instance segmentation to a region-based object detector. Its RoIAlign operation avoids coarse coordinate quantization so that region features remain spatially aligned for mask prediction.

Mask R-CNN adds a third head: a small convolutional network that paints a 28 × 28 mask inside each detected box, one mask per class, scored by per-pixel binary cross-entropy for the predicted class only.

Masks exposed a flaw in RoI pooling: box edges were rounded to the feature grid, shifting masks by a few pixels. RoIAlignRoI pooling and RoIAlignCutting a fixed-size feature grid out of shared features for each proposal. RoIAlign samples between pixels instead of rounding. samples between grid points by bilinear interpolation. In the program, the value a quarter row down and three quarters of a column across from grid point (1, 1) is 6.75, where rounding would read 6. The mask loss for the toy mask is 0.198.

07

Run them in CodeSplash

In the app

Object detection runs Faster R-CNN with a ResNet-50 feature pyramid (accurate) or a MobileNetV3 backbone (fast), pretrained on COCO. A lower score threshold finds more objects and more false ones:

Object detection (Faster R-CNN, COCO)Recorded · Python and R agreeRecorded 2026-11-25 · 44 values compared
R

13 objects in 4 of 5 images; most common: spoon (3).

Objects
13
Images
5
Classes found
9
Objects per image
2.600

Plots

Detected objectsWhat did the detector or segmenter find in each image, and where exactly?
View data
Height (px)ImageClassMedia idScoreWidth (px)x0x1y0y1
160cat.pngcat0eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a500.99222400205.840.0685157.26
160cat.pngcouch0eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a500.358424036.679239.4966.913159.17
160cat.pngcouch0eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a500.2182240174.79239.4862.905159.08
160cup.pngcup0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a60.992924067.755167.576.800117.48
160cup.pngspoon0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a60.9919240130.01170.3926.719130.77
160cup.pngdining table0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a60.94952403.777236.330159.47
160cup.pngspoon0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a60.4946240127.67161.3262.072127.06
160cup.pngspoon0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a60.2787240100.91165.8824.010124.23
192astronaut.pngpersonf37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d220.99851920.6465133.802.109192.00
192astronaut.pngtoiletf37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d220.4424192104.77189.91129.27191.52
192astronaut.pnghair drierf37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d220.3858192104.17187.08127.62191.18
192astronaut.pngpersonf37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d220.30191920.059718.60594.720191.74
150shapes.pngstop signfb6409af86ab2ef69eff6ef058e1227929f5a75ad407435a729a370097b2578c0.521720030.94589.62140.88799.707
48flat.png—81d0ef9f87003b2a8f4726bd99d84744e070a37fc2ba0a63f1537fd951587a11—64————
Objects by classHow often does each category occur?
View data
Class
cat
couch
couch
cup
spoon
dining table
spoon
spoon
person
toilet
hair drier
person
stop sign

Assumptions

  • COCO's 80 classes — Only COCO's everyday classes (people, vehicles, animals, household objects) can be found; anything else is missed or given the nearest class.
  • Score threshold — Objects scored below 0.2 are dropped. Lower it to find more objects (and more false ones).
  • Photos like COCO's — The model learned from everyday photos; drawings, microscopy, aerial or medical images need a model trained on them.
  • People in images — 1 images show people. Treat them as personal data; results stay on this computer.

Objects by class

ClassObjectsImagesMean scoreHighest score
spoon310.58840.9919
couch210.28830.3584
person210.65020.9985
cat110.99220.9922
cup110.99290.9929
dining table110.94950.9495
hair drier110.38580.3858
stop sign110.52170.5217
toilet110.44240.4424

Objects per image

RowFileObjectsClasses
1cat.png3couch × 2, cat
2cup.png5spoon × 3, cup, dining table
3astronaut.png4person × 2, hair drier, toilet
4shapes.png1stop sign
5flat.png0
  • 1 rows have no path and are left out.
  • 1 files could not be decoded and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Object detection (Faster R-CNN, COCO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method detect.objects 1.0.1 · spec ae5a1401cdbe9cb0
# Dataset: img3_photos (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

ARCH <- "fasterrcnn_resnet50_fpn_v2"
# %% Images listed in the path column
PATH <- "path"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img3_photos.parquet", col_select = PATH))
if (!nrow(df)) cs_error("CS_E_NO_ROWS")
warnings <- character(0)
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"within\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[1333,1333]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/detect.objects/accurate_low_threshold/out-r", df,
                        "tests/parity/fixtures/img3_photos.parquet")
media_ids <- cs_media_ids(media, df)

text_ <- function(v) { v <- as.character(v); v[!is.na(v) & !nzchar(v)] <- NA_character_; v }
paths_ <- text_(df[[PATH]])
has_id <- which(!is.na(media_ids) & !is.na(paths_))
if (!length(has_id)) cs_error("CS_E_ALL_MISSING", column = PATH)
status_ <- cs_media_status(media, media_ids[has_id])
ok <- has_id[is.na(status_)]
n_no_path <- nrow(df) - length(has_id)
n_unreadable <- length(has_id) - length(ok)
if (!length(ok)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an image file that can be decoded", count = length(has_id))
if (n_no_path) warnings <- c(warnings, sprintf("%d rows have no path and are left out.", n_no_path))
if (n_unreadable) warnings <- c(warnings, sprintf("%d files could not be decoded and are left out.", n_unreadable))
items <- lapply(ok, function(k) list(media_id = media_ids[k], file = basename(paths_[k]), row = k - 1L))

# One decoded image (3, h, w) on 0-1 and its size before decoding (orientation applied).
load_image <- function(mid) {
  a <- cs_media_load(media, mid)
  list(image = array(a, dim = dim(a)[-1]), size = cs_media_source_size(media, mid)[[1]])
}

# %% Pretrained model and compute profile
cs_deep_profile_configure(list(profile = "parity"))
cs_deep_torch()
model <- cs_vis_load(ARCH, dtype = cs_deep_profile_current()$dtype)

# %% Detect objects (torchvision fasterrcnn_resnet50_fpn_v2 on the converted COCO weights)
SCORE <- 0.2
MIN_SIZE <- 320
CLASSES <- unlist(c())
run <- cs_vis_detect_images(model, items, load_image, masks = FALSE, min_size = MIN_SIZE, max_size = 1333,
                            score_threshold = SCORE, nms_threshold = 0.5,
                            max_detections = 20, classes = CLASSES)
table <- run$table
s <- cs_vis_summarize(table, run$images)
values <- c(list(n_rows = nrow(df), n_no_path = n_no_path, n_unreadable = n_unreadable), s$values,
            list(model = cs_vis_model_info(ARCH)$label, min_size = MIN_SIZE, score_threshold = SCORE))

# %% Artifacts: the boxes table (one row per object) and one row per image
out <- cs_ml_out_dir("target/academy-parity/run-8142/detect.objects/accurate_low_threshold/out-r")
cs_boxes_write(table, file.path(out, "boxes.parquet"))
per <- data.frame(row = vapply(run$images, function(r) r$row + 1L, 0L),
                  media_id = vapply(run$images, function(r) r$media_id, ""),
                  file = vapply(run$images, function(r) r$file, ""),
                  width = vapply(run$images, function(r) r$width, 0L),
                  height = vapply(run$images, function(r) r$height, 0L),
                  objects = vapply(run$images, function(r) as.integer(r$objects), 0L), stringsAsFactors = FALSE)
nanoparquet::write_parquet(per, file.path(out, "images.parquet"))

# %% Result
ov <- cs_vis_overlay_columns(table, run$images)
charts <- list(cs_chart("overlay", "image-overlay", "Detected objects", list(
  image = cs_col("Image", ov$image, "categorical"),
  media_id = cs_col("Media id", ov$media_id, "categorical"),
  x0 = cs_col("x0", ov$x0, "numeric"), y0 = cs_col("y0", ov$y0, "numeric"),
  x1 = cs_col("x1", ov$x1, "numeric"), y1 = cs_col("y1", ov$y1, "numeric"),
  label = cs_col("Class", ov$label, "categorical"),
  score = cs_col("Score", ov$score, "numeric"),
  width = cs_col("Width (px)", ov$width, "numeric"), height = cs_col("Height (px)", ov$height, "numeric")
), controls = list(threshold = SCORE)))
if (nrow(table)) {
  charts[[length(charts) + 1L]] <- cs_chart("classes", "bar", "Objects by class", list(
    x = cs_col("Class", as.character(table$label), "categorical", s$order)))
}
n_person <- if (is.null(values[["n[person]"]])) 0L else values[["n[person]"]]
img_person <- if (is.null(values[["images[person]"]])) 0L else values[["images[person]"]]
assumptions <- c(list(
  list(key = "coco_classes", label = "COCO's 80 classes", status = "info",
       detail = "Only COCO's everyday classes (people, vehicles, animals, household objects) can be found; anything else is missed or given the nearest class."),
  list(key = "threshold", label = "Score threshold", status = "info",
       detail = sprintf("Objects scored below %s are dropped. Lower it to find more objects (and more false ones).", format(SCORE))),
  list(key = "domain", label = "Photos like COCO's", status = "info",
       detail = "The model learned from everyday photos; drawings, microscopy, aerial or medical images need a model trained on them."),
  list(key = "people", label = "People in images", status = if (n_person > 0) "warn" else "pass",
       detail = if (n_person > 0) sprintf("%d images show people. Treat them as personal data; results stay on this computer.", img_person) else "No person was detected.")
), cs_deep_profile_warning_rows())
image_cols <- list(list(key = "row", label = "Row", type = "integer"), list(key = "file", label = "File"),
                   list(key = "objects", label = "Objects", type = "integer"), list(key = "classes", label = "Classes"))
class_cols <- list(list(key = "class", label = "Class"), list(key = "objects", label = "Objects", type = "integer"),
                   list(key = "images", label = "Images", type = "integer"), list(key = "mean_score", label = "Mean score", type = "number"),
                   list(key = "max_score", label = "Highest score", type = "number"))
cs_publish(list(
  title = "Object detection (Faster R-CNN, COCO)",
  engine = cs_engine_info("torch", "torchvision", "safetensors", "nanoparquet", "codesplashr"),
  n = values$n_images,
  summary = paste0(sprintf("%d objects in %d of %d images", values$n_objects, values$n_images_with_objects, values$n_images),
                   if (length(s$order)) sprintf("; most common: %s (%d).", s$order[1], values[[sprintf("n[%s]", s$order[1])]]) else "."),
  statistics = list(
    list(key = "n_objects", label = "Objects", value = values$n_objects, format = "integer"),
    list(key = "n_images", label = "Images", value = values$n_images, format = "integer"),
    list(key = "n_classes", label = "Classes found", value = values$n_classes, format = "integer"),
    list(key = "objects_per_image", label = "Objects per image", value = values$objects_per_image)
  ),
  tables = list(
    list(key = "classes", title = "Objects by class", columns = class_cols, rows = s$classes),
    list(key = "images", title = "Objects per image", columns = image_cols, rows = s$images[seq_len(min(200L, length(s$images)))])
  ),
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = as.list(warnings),
  artifacts = list(list(key = "boxes", path = file.path(out, "boxes.parquet"), format = "parquet"),
                   list(key = "images", path = file.path(out, "images.parquet"), format = "parquet"))
))
Python

13 objects in 4 of 5 images; most common: spoon (3).

Objects
13
Images
5
Classes found
9
Objects per image
2.600

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • COCO's 80 classes — Only COCO's everyday classes (people, vehicles, animals, household objects) can be found; anything else is missed or given the nearest class.
  • Score threshold — Objects scored below 0.2 are dropped. Lower it to find more objects (and more false ones).
  • Photos like COCO's — The model learned from everyday photos; drawings, microscopy, aerial or medical images need a model trained on them.
  • People in images — 1 images show people. Treat them as personal data; results stay on this computer.

Objects by class

ClassObjectsImagesMean scoreHighest score
spoon310.58840.9919
couch210.28830.3584
person210.65020.9985
cat110.99220.9922
cup110.99290.9929
dining table110.94950.9495
hair drier110.38580.3858
stop sign110.52170.5217
toilet110.44240.4424

Objects per image

RowFileObjectsClasses
1cat.png3couch × 2, cat
2cup.png5spoon × 3, cup, dining table
3astronaut.png4person × 2, hair drier, toilet
4shapes.png1stop sign
5flat.png0
  • 1 rows have no path and are left out.
  • 1 files could not be decoded and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Object detection (Faster R-CNN, COCO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method detect.objects 1.0.1 · spec ae5a1401cdbe9cb0
# Dataset: img3_photos (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 import media as cs_media
from codesplash import ml as csml
from codesplash.deep import core as cs_core
from codesplash.deep import profile as cs_profile
from codesplash.vision import boxes as vbox
from codesplash.vision import detect as vdet

ARCH = "fasterrcnn_resnet50_fpn_v2"
# %% Images listed in the path column
PATH = "path"
df = pd.read_parquet("tests/parity/fixtures/img3_photos.parquet", columns=[PATH])
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
warnings = []
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"within\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[1333,1333]}}"), "target/academy-parity/run-8142/detect.objects/accurate_low_threshold/out-python", df, "tests/parity/fixtures/img3_photos.parquet")
media_ids = cs_media.ids_of(media, df)


def _text(v):
    return None if pd.isna(v) else str(v)  # None, NaN, pd.NA


has_id = [k for k, m in enumerate(media_ids) if m is not None and _text(df[PATH].iloc[k]) not in (None, "")]
if not has_id:
    cs.cs_error("CS_E_ALL_MISSING", column=PATH)
_status = cs_media.status(media, [media_ids[k] for k in has_id])
ok = [k for k, s in zip(has_id, _status) if s is None]
n_no_path = len(df) - len(has_id)
n_unreadable = len(has_id) - len(ok)
if not ok:
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an image file that can be decoded", count=len(has_id))
if n_no_path:
    warnings.append(f"{n_no_path} rows have no path and are left out.")
if n_unreadable:
    warnings.append(f"{n_unreadable} files could not be decoded and are left out.")
items = [{"media_id": media_ids[k], "file": os.path.basename(str(df[PATH].iloc[k])), "row": k} for k in ok]


def load_image(mid):
    """One decoded image (3, h, w) on 0–1 and its size before decoding (orientation applied)."""
    return cs_media.load(media, [mid])[0], tuple(cs_media.source_size(media, [mid])[0])


# %% Pretrained model and compute profile
cs_profile.configure({"profile": "parity"})
cs_core.torch_init()
model = vdet.load(ARCH, dtype=cs_profile.current().dtype)

# %% Detect objects (torchvision fasterrcnn_resnet50_fpn_v2 on the converted COCO weights)
SCORE = 0.2
MIN_SIZE = 320
CLASSES = [] or None
run = vdet.detect_images(model, items, load_image, masks=False, min_size=MIN_SIZE, max_size=1333, score_threshold=SCORE,
                         nms_threshold=0.5, max_detections=20, classes=CLASSES)
table = run["table"]
s = vdet.summarize(table, run["images"])
values = {"n_rows": len(df), "n_no_path": n_no_path, "n_unreadable": n_unreadable, **s["values"],
          "model": vdet.MODELS[ARCH]["label"], "min_size": MIN_SIZE, "score_threshold": SCORE}

# %% Artifacts: the boxes table (one row per object) and one row per image
out = csml.out_dir("target/academy-parity/run-8142/detect.objects/accurate_low_threshold/out-python")
vbox.write(table, os.path.join(out, "boxes.parquet"))
per = pd.DataFrame([{"row": r["row"] + 1, "media_id": r["media_id"], "file": r["file"], "width": r["width"],
                     "height": r["height"], "objects": r["objects"]} for r in run["images"]],
                   columns=["row", "media_id", "file", "width", "height", "objects"])
per.to_parquet(os.path.join(out, "images.parquet"), index=False)

# %% Result
ov = vdet.overlay_columns(table, run["images"])
charts = [cs.chart("overlay", "image-overlay", "Detected objects", {
    "image": cs.col("Image", ov["image"], "categorical"),
    "media_id": cs.col("Media id", ov["media_id"], "categorical"),
    "x0": cs.col("x0", ov["x0"], "numeric"), "y0": cs.col("y0", ov["y0"], "numeric"),
    "x1": cs.col("x1", ov["x1"], "numeric"), "y1": cs.col("y1", ov["y1"], "numeric"),
    "label": cs.col("Class", ov["label"], "categorical"),
    "score": cs.col("Score", ov["score"], "numeric"),
    "width": cs.col("Width (px)", ov["width"], "numeric"), "height": cs.col("Height (px)", ov["height"], "numeric"),
}, controls={"threshold": SCORE})]
if len(table):
    charts.append(cs.chart("classes", "bar", "Objects by class", {
        "x": cs.col("Class", [str(v) for v in table["label"].tolist()], "categorical", s["order"])}))
assumptions = [
    {"key": "coco_classes", "label": "COCO's 80 classes", "status": "info",
     "detail": "Only COCO's everyday classes (people, vehicles, animals, household objects) can be found; anything else is missed or given the nearest class."},
    {"key": "threshold", "label": "Score threshold", "status": "info",
     "detail": f"Objects scored below {SCORE:g} are dropped. Lower it to find more objects (and more false ones)."},
    {"key": "domain", "label": "Photos like COCO's", "status": "info",
     "detail": "The model learned from everyday photos; drawings, microscopy, aerial or medical images need a model trained on them."},
    {"key": "people", "label": "People in images", "status": "warn" if values.get("n[person]", 0) else "pass",
     "detail": f"{values.get('images[person]', 0)} images show people. Treat them as personal data; results stay on this computer." if values.get("n[person]", 0) else "No person was detected."},
] + cs_profile.warning_rows()
image_cols = [{"key": "row", "label": "Row", "type": "integer"}, {"key": "file", "label": "File"},
              {"key": "objects", "label": "Objects", "type": "integer"}, {"key": "classes", "label": "Classes"}]
class_cols = [{"key": "class", "label": "Class"}, {"key": "objects", "label": "Objects", "type": "integer"},
              {"key": "images", "label": "Images", "type": "integer"}, {"key": "mean_score", "label": "Mean score", "type": "number"},
              {"key": "max_score", "label": "Highest score", "type": "number"}]
cs.publish({
    "title": "Object detection (Faster R-CNN, COCO)",
    "engine": cs.engine_info("torch", "torchvision", "numpy", "pandas"),
    "n": values["n_images"],
    "summary": f"{values['n_objects']} objects in {values['n_images_with_objects']} of {values['n_images']} images"
               + (f"; most common: {s['order'][0]} ({values['n[' + s['order'][0] + ']']})." if s["order"] else "."),
    "statistics": [
        {"key": "n_objects", "label": "Objects", "value": values["n_objects"], "format": "integer"},
        {"key": "n_images", "label": "Images", "value": values["n_images"], "format": "integer"},
        {"key": "n_classes", "label": "Classes found", "value": values["n_classes"], "format": "integer"},
        {"key": "objects_per_image", "label": "Objects per image", "value": values["objects_per_image"]},
    ],
    "tables": [
        {"key": "classes", "title": "Objects by class", "columns": class_cols, "rows": s["classes"]},
        {"key": "images", "title": "Objects per image", "columns": image_cols, "rows": s["images"][:200]},
    ],
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "boxes", "path": os.path.join(out, "boxes.parquet"), "format": "parquet"},
                  {"key": "images", "path": os.path.join(out, "images.parquet"), "format": "parquet"}],
})

Instance segmentation runs Mask R-CNN and stores each mask in the boxes table as COCO run-length text:

Instance segmentation (Mask R-CNN, COCO)Recorded · Python and R agreeRecorded 2026-11-25 · 36 values compared
R

7 objects outlined in 3 of 5 images, covering 42.4% of an image on average; most common: spoon (2).

Objects
7
Images
5
Classes found
6
Share covered
42.4%

Plots

Object masksWhat did the detector or segmenter find in each image, and where exactly?
View data
Height (px)ImageClassMask (COCO RLE)Media idScoreWidth (px)x0x1y0y1
160cat.pngcatb7\2[2:L3N3N1N2O1N2O1N2N2O1N2L4I7F:J6J6L4L4L4M3N200O100O100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001O0000000000000000000000000000000000000_NOSN1l12RNNl16RNJm18RNHl1;SNEj1?UNAh1b0XN^Oe1f0ZNZOc1j0\NVOa1o0]NQOa1Q1_NoN32OS1MkN0<Jm05gNOm0TOe0m0^NLk23UMKn24RMJQ35oLIT36lLHW37iLHY37gLG]36dLFa39_LDg39YLEk39ULEP48PLGV43lKJZ42fKKa41[f40eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a500.99682400217.650.7896160
160cup.pngspoonUXd02l43ZK7R4=O2N100N2O1N2O000O100O100O1O1O1N2O1M3O1M3M2N3NkNkLb0S3[OWM`0h2_O]M>b2AbM=]2CgM9W2HmM6Q2JSN2m1MZNMP1MTN8a3?4L4N3M4K4M5JVm:0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a60.9988240127.82169.7125.976129.97
160cup.pngcupVe::b4;F>B;F5L3L4M3M3M2M3N3N1N2N1O2O0O2O1N100O2O000O2O00001N101O0O2O00001O0O2O1O1O1O000000001O0000000000O10000000001O0L4O1O2O00001N10000O2L30001O1N101O0O2O001N2M2N3M201N2N2N2L5M2M3M3M2N3M2M3L4K5N2L5K4KX\;0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a60.997824068.305168.327.286105.16
160cup.pngdining table_6_3]15N1O2O0O1O1O1O100O100O100O100O1O1O100O1O100O100O1O1O1O100O100O1O1O1O1O1O100O1O1O100O1O1O100O100N2O1O1O100O1O1000000O1000000O100000000000000000000000000000000000000000O1000000[N1lL1T1NP2;oMEQ2;oMEQ2;oMEQ2<nMDR2<nMDR2<nMDR2=mMCS2=mMCS2>lMBT2>lMBT2>lMBT2>lMBT2>lMBT23hL5T1HT2OlL9P1H[27UMJHOS37SMMILT37RMNJKT37RMNJKT36SMOIKU35RM0IKU35RM0IKU34SM1HKU34SM1HKV32SM3GKV32SM3GKV32SM3GKU34VMMFOl22jL4S1JR24jL4R1HT2a0kM_OT2c0kM]OU2c0kM]OT2d0lM\OT2e0kM[OT2f0lMZOU2e0kM[OU2f0jMZOV2f0jMZOV2f0jMZOV2g0iMYOW2g0iMYOW2g0iMYOW2g0iMYOW2g0iMYOW2g0iMYOW2g0iMYOW2g0iMYOX2f0hMZOX2e0iM[OW2e0iM[OX2d0hM\OX2c0iM]OW2c0iM]OW2c0jM\OV2d0jM\OV2c0kM]OU2c0kM]OU2c0kM]OU2b0lM^OU2`0lM@j3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000O101O0000000O2N5FO0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a60.95672400239.890160
160cup.pngspoon`Xd05g48I6J5N1N2N2N2N101N101N100O1O1N2O1N2O1N1O2N2N1O1NmNiLc0U3YOUMb0i2\O^Ma0b2]ObMa0_2\OeMa0]2\OhM`0^3M4LgR<0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a60.6700240128.76163.2368.674132.83
192astronaut.pngpersondd1>Y5b0@?C:G7I5J6K4M4N1M3N2N2O1N2O1N2O1O1O1O1N2O100O1O1O1N2O1O1O1O100N2M3N2N2N2O1O1O1N200O100O100000000POSLLn30ZLLf32^LLb32bLL^32fLLZ33iLJX35kLIU36mLHT37[100O100O1O1O1O10000O1000000000000000000000000000000000000001O00001oKFZ2;_MM_24^M0`21^M1a2O^M3`2O]M5a2L\M7b2K\M7m1`0QNBh1e0VN^Of1g0UN]Og1g0TN^Og1i0RN[Ok1`2M2M4L3N3L3N2N1O2N2N2O1N2N2N2N2N2O3L3N2M3M6I`h:f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d220.99871924.024138.157.449190.46
192astronaut.pngcell phonenc52n5000O100S^m0f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d220.562819227.01335.785189.99192.00
150shapes.png——fb6409af86ab2ef69eff6ef058e1227929f5a75ad407435a729a370097b2578c—200————
48flat.png——81d0ef9f87003b2a8f4726bd99d84744e070a37fc2ba0a63f1537fd951587a11—64————
Objects by classHow often does each category occur?
View data
Class
cat
spoon
cup
dining table
spoon
person
cell phone

Assumptions

  • COCO's 80 classes — Only COCO's everyday classes (people, vehicles, animals, household objects) can be found; anything else is missed or given the nearest class.
  • Score threshold — Objects scored below 0.5 are dropped. Lower it to find more objects (and more false ones).
  • Masks at 28 × 28 — Each mask is predicted on a 28 × 28 grid inside its box and enlarged; a pixel is inside when its probability is above 0.5.
  • Photos like COCO's — The model learned from everyday photos; drawings, microscopy, aerial or medical images need a model trained on them.
  • People in images — 1 images show people. Treat them as personal data; results stay on this computer.

Objects by class

ClassObjectsImagesMean scoreHighest score
spoon210.83440.9988
cat110.99680.9968
cell phone110.56280.5628
cup110.99780.9978
dining table110.95670.9567
person110.99870.9987

Objects per image

RowFileObjectsClassesShare covered
1cat.png1cat77.4%
2cup.png4spoon × 2, cup, dining table93.6%
3astronaut.png2cell phone, person40.8%
4shapes.png00.0%
5flat.png00.0%
  • 1 rows have no path and are left out.
  • 1 files could not be decoded and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Instance segmentation (Mask R-CNN, COCO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method segment.instances 1.0.1 · spec 66718d969bbc93ff
# Dataset: img3_photos (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

ARCH <- "maskrcnn_resnet50_fpn_v2"
# %% Images listed in the path column
PATH <- "path"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img3_photos.parquet", col_select = PATH))
if (!nrow(df)) cs_error("CS_E_NO_ROWS")
warnings <- character(0)
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"within\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[1333,1333]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/segment.instances/defaults_small/out-r", df,
                        "tests/parity/fixtures/img3_photos.parquet")
media_ids <- cs_media_ids(media, df)

text_ <- function(v) { v <- as.character(v); v[!is.na(v) & !nzchar(v)] <- NA_character_; v }
paths_ <- text_(df[[PATH]])
has_id <- which(!is.na(media_ids) & !is.na(paths_))
if (!length(has_id)) cs_error("CS_E_ALL_MISSING", column = PATH)
status_ <- cs_media_status(media, media_ids[has_id])
ok <- has_id[is.na(status_)]
n_no_path <- nrow(df) - length(has_id)
n_unreadable <- length(has_id) - length(ok)
if (!length(ok)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an image file that can be decoded", count = length(has_id))
if (n_no_path) warnings <- c(warnings, sprintf("%d rows have no path and are left out.", n_no_path))
if (n_unreadable) warnings <- c(warnings, sprintf("%d files could not be decoded and are left out.", n_unreadable))
items <- lapply(ok, function(k) list(media_id = media_ids[k], file = basename(paths_[k]), row = k - 1L))

# One decoded image (3, h, w) on 0-1 and its size before decoding (orientation applied).
load_image <- function(mid) {
  a <- cs_media_load(media, mid)
  list(image = array(a, dim = dim(a)[-1]), size = cs_media_source_size(media, mid)[[1]])
}

# %% Pretrained model and compute profile
cs_deep_profile_configure(list(profile = "parity"))
cs_deep_torch()
model <- cs_vis_load(ARCH, dtype = cs_deep_profile_current()$dtype)

# %% Outline objects (torchvision Mask R-CNN on the converted COCO weights; a pixel is inside when p > 0.5)
SCORE <- 0.5
MIN_SIZE <- 320
CLASSES <- unlist(c())
run <- cs_vis_detect_images(model, items, load_image, masks = TRUE, min_size = MIN_SIZE, max_size = 1333,
                            score_threshold = SCORE, nms_threshold = 0.5,
                            max_detections = 100, classes = CLASSES)
table <- run$table
s <- cs_vis_summarize(table, run$images)
values <- c(list(n_rows = nrow(df), n_no_path = n_no_path, n_unreadable = n_unreadable), s$values,
            list(model = cs_vis_model_info(ARCH)$label, min_size = MIN_SIZE, score_threshold = SCORE))

# %% Artifacts: the boxes and masks table (one row per object, masks as COCO RLE) and one row per image
out <- cs_ml_out_dir("target/academy-parity/run-8142/segment.instances/defaults_small/out-r")
cs_boxes_write(table, file.path(out, "boxes.parquet"))
per <- data.frame(row = vapply(run$images, function(r) r$row + 1L, 0L),
                  media_id = vapply(run$images, function(r) r$media_id, ""),
                  file = vapply(run$images, function(r) r$file, ""),
                  width = vapply(run$images, function(r) r$width, 0L),
                  height = vapply(run$images, function(r) r$height, 0L),
                  objects = vapply(run$images, function(r) as.integer(r$objects), 0L),
                  covered = vapply(run$images, function(r) r$covered, 0), stringsAsFactors = FALSE)
nanoparquet::write_parquet(per, file.path(out, "images.parquet"))

# %% Result
ov <- cs_vis_overlay_columns(table, run$images)
charts <- list(cs_chart("overlay", "image-overlay", "Object masks", list(
  image = cs_col("Image", ov$image, "categorical"),
  media_id = cs_col("Media id", ov$media_id, "categorical"),
  x0 = cs_col("x0", ov$x0, "numeric"), y0 = cs_col("y0", ov$y0, "numeric"),
  x1 = cs_col("x1", ov$x1, "numeric"), y1 = cs_col("y1", ov$y1, "numeric"),
  label = cs_col("Class", ov$label, "categorical"),
  score = cs_col("Score", ov$score, "numeric"),
  mask = cs_col("Mask (COCO RLE)", ov$mask, "categorical"),
  width = cs_col("Width (px)", ov$width, "numeric"), height = cs_col("Height (px)", ov$height, "numeric")
), controls = list(threshold = SCORE)))
if (nrow(table)) {
  charts[[length(charts) + 1L]] <- cs_chart("classes", "bar", "Objects by class", list(
    x = cs_col("Class", as.character(table$label), "categorical", s$order)))
}
n_person <- if (is.null(values[["n[person]"]])) 0L else values[["n[person]"]]
img_person <- if (is.null(values[["images[person]"]])) 0L else values[["images[person]"]]
assumptions <- c(list(
  list(key = "coco_classes", label = "COCO's 80 classes", status = "info",
       detail = "Only COCO's everyday classes (people, vehicles, animals, household objects) can be found; anything else is missed or given the nearest class."),
  list(key = "threshold", label = "Score threshold", status = "info",
       detail = sprintf("Objects scored below %s are dropped. Lower it to find more objects (and more false ones).", format(SCORE))),
  list(key = "mask_resolution", label = "Masks at 28 \u00d7 28", status = "info",
       detail = "Each mask is predicted on a 28 \u00d7 28 grid inside its box and enlarged; a pixel is inside when its probability is above 0.5."),
  list(key = "domain", label = "Photos like COCO's", status = "info",
       detail = "The model learned from everyday photos; drawings, microscopy, aerial or medical images need a model trained on them."),
  list(key = "people", label = "People in images", status = if (n_person > 0) "warn" else "pass",
       detail = if (n_person > 0) sprintf("%d images show people. Treat them as personal data; results stay on this computer.", img_person) else "No person was detected.")
), cs_deep_profile_warning_rows())
image_cols <- list(list(key = "row", label = "Row", type = "integer"), list(key = "file", label = "File"),
                   list(key = "objects", label = "Objects", type = "integer"), list(key = "classes", label = "Classes"),
                   list(key = "covered", label = "Share covered", type = "percent"))
class_cols <- list(list(key = "class", label = "Class"), list(key = "objects", label = "Objects", type = "integer"),
                   list(key = "images", label = "Images", type = "integer"), list(key = "mean_score", label = "Mean score", type = "number"),
                   list(key = "max_score", label = "Highest score", type = "number"))
cs_publish(list(
  title = "Instance segmentation (Mask R-CNN, COCO)",
  engine = cs_engine_info("torch", "torchvision", "safetensors", "nanoparquet", "codesplashr"),
  n = values$n_images,
  summary = paste0(sprintf("%d objects outlined in %d of %d images, covering %.1f%% of an image on average", values$n_objects,
                           values$n_images_with_objects, values$n_images, values$covered_mean * 100),
                   if (length(s$order)) sprintf("; most common: %s (%d).", s$order[1], values[[sprintf("n[%s]", s$order[1])]]) else "."),
  statistics = list(
    list(key = "n_objects", label = "Objects", value = values$n_objects, format = "integer"),
    list(key = "n_images", label = "Images", value = values$n_images, format = "integer"),
    list(key = "n_classes", label = "Classes found", value = values$n_classes, format = "integer"),
    list(key = "covered_mean", label = "Share covered", value = values$covered_mean, format = "percent")
  ),
  tables = list(
    list(key = "classes", title = "Objects by class", columns = class_cols, rows = s$classes),
    list(key = "images", title = "Objects per image", columns = image_cols, rows = s$images[seq_len(min(200L, length(s$images)))])
  ),
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = as.list(warnings),
  artifacts = list(list(key = "boxes", path = file.path(out, "boxes.parquet"), format = "parquet"),
                   list(key = "images", path = file.path(out, "images.parquet"), format = "parquet"))
))
Python

7 objects outlined in 3 of 5 images, covering 42.4% of an image on average; most common: spoon (2).

Objects
7
Images
5
Classes found
6
Share covered
42.4%

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • COCO's 80 classes — Only COCO's everyday classes (people, vehicles, animals, household objects) can be found; anything else is missed or given the nearest class.
  • Score threshold — Objects scored below 0.5 are dropped. Lower it to find more objects (and more false ones).
  • Masks at 28 × 28 — Each mask is predicted on a 28 × 28 grid inside its box and enlarged; a pixel is inside when its probability is above 0.5.
  • Photos like COCO's — The model learned from everyday photos; drawings, microscopy, aerial or medical images need a model trained on them.
  • People in images — 1 images show people. Treat them as personal data; results stay on this computer.

Objects by class

ClassObjectsImagesMean scoreHighest score
spoon210.83440.9988
cat110.99680.9968
cell phone110.56280.5628
cup110.99780.9978
dining table110.95670.9567
person110.99870.9987

Objects per image

RowFileObjectsClassesShare covered
1cat.png1cat77.4%
2cup.png4spoon × 2, cup, dining table93.6%
3astronaut.png2cell phone, person40.8%
4shapes.png00.0%
5flat.png00.0%
  • 1 rows have no path and are left out.
  • 1 files could not be decoded and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Instance segmentation (Mask R-CNN, COCO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method segment.instances 1.0.1 · spec 66718d969bbc93ff
# Dataset: img3_photos (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 import media as cs_media
from codesplash import ml as csml
from codesplash.deep import core as cs_core
from codesplash.deep import profile as cs_profile
from codesplash.vision import boxes as vbox
from codesplash.vision import detect as vdet

ARCH = "maskrcnn_resnet50_fpn_v2"
# %% Images listed in the path column
PATH = "path"
df = pd.read_parquet("tests/parity/fixtures/img3_photos.parquet", columns=[PATH])
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
warnings = []
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"within\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[1333,1333]}}"), "target/academy-parity/run-8142/segment.instances/defaults_small/out-python", df, "tests/parity/fixtures/img3_photos.parquet")
media_ids = cs_media.ids_of(media, df)


def _text(v):
    return None if pd.isna(v) else str(v)  # None, NaN, pd.NA


has_id = [k for k, m in enumerate(media_ids) if m is not None and _text(df[PATH].iloc[k]) not in (None, "")]
if not has_id:
    cs.cs_error("CS_E_ALL_MISSING", column=PATH)
_status = cs_media.status(media, [media_ids[k] for k in has_id])
ok = [k for k, s in zip(has_id, _status) if s is None]
n_no_path = len(df) - len(has_id)
n_unreadable = len(has_id) - len(ok)
if not ok:
    cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an image file that can be decoded", count=len(has_id))
if n_no_path:
    warnings.append(f"{n_no_path} rows have no path and are left out.")
if n_unreadable:
    warnings.append(f"{n_unreadable} files could not be decoded and are left out.")
items = [{"media_id": media_ids[k], "file": os.path.basename(str(df[PATH].iloc[k])), "row": k} for k in ok]


def load_image(mid):
    """One decoded image (3, h, w) on 0–1 and its size before decoding (orientation applied)."""
    return cs_media.load(media, [mid])[0], tuple(cs_media.source_size(media, [mid])[0])


# %% Pretrained model and compute profile
cs_profile.configure({"profile": "parity"})
cs_core.torch_init()
model = vdet.load(ARCH, dtype=cs_profile.current().dtype)

# %% Outline objects (torchvision Mask R-CNN on the converted COCO weights; a pixel is inside when p > 0.5)
SCORE = 0.5
MIN_SIZE = 320
CLASSES = [] or None
run = vdet.detect_images(model, items, load_image, masks=True, min_size=MIN_SIZE, max_size=1333, score_threshold=SCORE,
                         nms_threshold=0.5, max_detections=100, classes=CLASSES)
table = run["table"]
s = vdet.summarize(table, run["images"])
values = {"n_rows": len(df), "n_no_path": n_no_path, "n_unreadable": n_unreadable, **s["values"],
          "model": vdet.MODELS[ARCH]["label"], "min_size": MIN_SIZE, "score_threshold": SCORE}

# %% Artifacts: the boxes and masks table (one row per object, masks as COCO RLE) and one row per image
out = csml.out_dir("target/academy-parity/run-8142/segment.instances/defaults_small/out-python")
vbox.write(table, os.path.join(out, "boxes.parquet"))
per = pd.DataFrame([{"row": r["row"] + 1, "media_id": r["media_id"], "file": r["file"], "width": r["width"],
                     "height": r["height"], "objects": r["objects"], "covered": r["covered"]} for r in run["images"]],
                   columns=["row", "media_id", "file", "width", "height", "objects", "covered"])
per.to_parquet(os.path.join(out, "images.parquet"), index=False)

# %% Result
ov = vdet.overlay_columns(table, run["images"])
charts = [cs.chart("overlay", "image-overlay", "Object masks", {
    "image": cs.col("Image", ov["image"], "categorical"),
    "media_id": cs.col("Media id", ov["media_id"], "categorical"),
    "x0": cs.col("x0", ov["x0"], "numeric"), "y0": cs.col("y0", ov["y0"], "numeric"),
    "x1": cs.col("x1", ov["x1"], "numeric"), "y1": cs.col("y1", ov["y1"], "numeric"),
    "label": cs.col("Class", ov["label"], "categorical"),
    "score": cs.col("Score", ov["score"], "numeric"),
    "mask": cs.col("Mask (COCO RLE)", ov["mask"], "categorical"),
    "width": cs.col("Width (px)", ov["width"], "numeric"), "height": cs.col("Height (px)", ov["height"], "numeric"),
}, controls={"threshold": SCORE})]
if len(table):
    charts.append(cs.chart("classes", "bar", "Objects by class", {
        "x": cs.col("Class", [str(v) for v in table["label"].tolist()], "categorical", s["order"])}))
assumptions = [
    {"key": "coco_classes", "label": "COCO's 80 classes", "status": "info",
     "detail": "Only COCO's everyday classes (people, vehicles, animals, household objects) can be found; anything else is missed or given the nearest class."},
    {"key": "threshold", "label": "Score threshold", "status": "info",
     "detail": f"Objects scored below {SCORE:g} are dropped. Lower it to find more objects (and more false ones)."},
    {"key": "mask_resolution", "label": "Masks at 28 × 28", "status": "info",
     "detail": "Each mask is predicted on a 28 × 28 grid inside its box and enlarged; a pixel is inside when its probability is above 0.5."},
    {"key": "domain", "label": "Photos like COCO's", "status": "info",
     "detail": "The model learned from everyday photos; drawings, microscopy, aerial or medical images need a model trained on them."},
    {"key": "people", "label": "People in images", "status": "warn" if values.get("n[person]", 0) else "pass",
     "detail": f"{values.get('images[person]', 0)} images show people. Treat them as personal data; results stay on this computer." if values.get("n[person]", 0) else "No person was detected."},
] + cs_profile.warning_rows()
image_cols = [{"key": "row", "label": "Row", "type": "integer"}, {"key": "file", "label": "File"},
              {"key": "objects", "label": "Objects", "type": "integer"}, {"key": "classes", "label": "Classes"},
              {"key": "covered", "label": "Share covered", "type": "percent"}]
class_cols = [{"key": "class", "label": "Class"}, {"key": "objects", "label": "Objects", "type": "integer"},
              {"key": "images", "label": "Images", "type": "integer"}, {"key": "mean_score", "label": "Mean score", "type": "number"},
              {"key": "max_score", "label": "Highest score", "type": "number"}]
cs.publish({
    "title": "Instance segmentation (Mask R-CNN, COCO)",
    "engine": cs.engine_info("torch", "torchvision", "numpy", "pandas"),
    "n": values["n_images"],
    "summary": f"{values['n_objects']} objects outlined in {values['n_images_with_objects']} of {values['n_images']} images, covering {values['covered_mean'] * 100:.1f}% of an image on average"
               + (f"; most common: {s['order'][0]} ({values['n[' + s['order'][0] + ']']})." if s["order"] else "."),
    "statistics": [
        {"key": "n_objects", "label": "Objects", "value": values["n_objects"], "format": "integer"},
        {"key": "n_images", "label": "Images", "value": values["n_images"], "format": "integer"},
        {"key": "n_classes", "label": "Classes found", "value": values["n_classes"], "format": "integer"},
        {"key": "covered_mean", "label": "Share covered", "value": values["covered_mean"], "format": "percent"},
    ],
    "tables": [
        {"key": "classes", "title": "Objects by class", "columns": class_cols, "rows": s["classes"]},
        {"key": "images", "title": "Objects per image", "columns": image_cols, "rows": s["images"][:200]},
    ],
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "boxes", "path": os.path.join(out, "boxes.parquet"), "format": "parquet"},
                  {"key": "images", "path": os.path.join(out, "images.parquet"), "format": "parquet"}],
})
08

Check: two-stage detectors

Checkpoint

Check yourself

What made Fast R-CNN much faster than R-CNN?

Show the answer

Answer: a

RoI pooling turns any proposal into a fixed-size block of the shared features, so nothing is recomputed per proposal.

Check yourself

Smooth L1 is 0.5·e² when |e| < 1 and |e| − 0.5 otherwise. What is the loss for a coordinate error of 1.5?

Show the answer

Answer: 1

|1.5| − 0.5 = 1. Squared error would give 2.25 × 0.5 = 1.125 and grow much faster beyond that.

Check yourself

What does Faster R-CNN's region proposal network predict for each anchor?

Show the answer

Answer: a

The first stage only asks "is something here, and where exactly?". Classes are decided in the second stage.

Check yourself

An anchor is 8 pixels wide. The predicted width offset is log 2. How wide is the decoded box?

Show the answer

Answer: 16

w = w_anchor × e^(log 2) = 8 × 2 = 16 pixels.

Check yourself

You run Object detection on photos of a factory floor looking for "forklift". What should you expect?

Show the answer

Answer: b

A pretrained detector only knows its training classes. A new class needs a detector trained on labeled examples of it.

Check yourself

Why does Mask R-CNN use RoIAlign rather than RoI pooling?

Show the answer

Answer: a

A shift of half a feature cell is several pixels in the image: harmless for a box score, visible in a mask.

Check yourself

How does Mask R-CNN produce a mask for each detected object?

Show the answer

Answer: b

Masks are per instance, inside boxes, so two touching people get two masks. Semantic segmentation instead gives one class per pixel.

09

Recap

Recap
  • Fast R-CNN: one CNN pass per image, RoI pooling crops a fixed block per proposal, smooth L1 for boxes.
  • Faster R-CNN: a region proposal network scores and moves anchors; boxes are offsets with log size ratios.
  • Mask R-CNN: a mask head per box and RoIAlign's bilinear sampling for pixel-accurate masks.
  • In CodeSplash, Object detection and Instance segmentation run these pretrained on COCO: they find COCO's classes, not yours.

Concepts in this lesson