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.
What runs in CodeSplash
- VIS002Fast R-CNN Explained here
- VIS003Faster R-CNN Runs in CodeSplash (Experimental)
- VIS009Mask R-CNN Runs in CodeSplash (Experimental)
- Object detection (Faster R-CNN, COCO) Experimental
- Instance segmentation (Mask R-CNN, COCO) Experimental
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
Compute features once
ReadFast 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.
One loss for class and box
ReadFast 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.
Learn the proposals
ReadFaster 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.
Boxes as offsets
ReadThe 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.
Why log ratios?
PredictPredict first
Why predict log(w / w_anchor) instead of w − w_anchor?
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.
Masks from the same proposals
ReadMask 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.
Run them in CodeSplash
In the appObject 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:
13 objects in 4 of 5 images; most common: spoon (3).
- Objects
- 13
- Images
- 5
- Classes found
- 9
- Objects per image
- 2.600
Plots
View data
| Height (px) | Image | Class | Media id | Score | Width (px) | x0 | x1 | y0 | y1 |
|---|---|---|---|---|---|---|---|---|---|
| 160 | cat.png | cat | 0eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a50 | 0.9922 | 240 | 0 | 205.84 | 0.0685 | 157.26 |
| 160 | cat.png | couch | 0eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a50 | 0.3584 | 240 | 36.679 | 239.49 | 66.913 | 159.17 |
| 160 | cat.png | couch | 0eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a50 | 0.2182 | 240 | 174.79 | 239.48 | 62.905 | 159.08 |
| 160 | cup.png | cup | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.9929 | 240 | 67.755 | 167.57 | 6.800 | 117.48 |
| 160 | cup.png | spoon | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.9919 | 240 | 130.01 | 170.39 | 26.719 | 130.77 |
| 160 | cup.png | dining table | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.9495 | 240 | 3.777 | 236.33 | 0 | 159.47 |
| 160 | cup.png | spoon | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.4946 | 240 | 127.67 | 161.32 | 62.072 | 127.06 |
| 160 | cup.png | spoon | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.2787 | 240 | 100.91 | 165.88 | 24.010 | 124.23 |
| 192 | astronaut.png | person | f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d22 | 0.9985 | 192 | 0.6465 | 133.80 | 2.109 | 192.00 |
| 192 | astronaut.png | toilet | f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d22 | 0.4424 | 192 | 104.77 | 189.91 | 129.27 | 191.52 |
| 192 | astronaut.png | hair drier | f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d22 | 0.3858 | 192 | 104.17 | 187.08 | 127.62 | 191.18 |
| 192 | astronaut.png | person | f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d22 | 0.3019 | 192 | 0.0597 | 18.605 | 94.720 | 191.74 |
| 150 | shapes.png | stop sign | fb6409af86ab2ef69eff6ef058e1227929f5a75ad407435a729a370097b2578c | 0.5217 | 200 | 30.945 | 89.621 | 40.887 | 99.707 |
| 48 | flat.png | — | 81d0ef9f87003b2a8f4726bd99d84744e070a37fc2ba0a63f1537fd951587a11 | — | 64 | — | — | — | — |
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
| Class | Objects | Images | Mean score | Highest score |
|---|---|---|---|---|
| spoon | 3 | 1 | 0.5884 | 0.9919 |
| couch | 2 | 1 | 0.2883 | 0.3584 |
| person | 2 | 1 | 0.6502 | 0.9985 |
| cat | 1 | 1 | 0.9922 | 0.9922 |
| cup | 1 | 1 | 0.9929 | 0.9929 |
| dining table | 1 | 1 | 0.9495 | 0.9495 |
| hair drier | 1 | 1 | 0.3858 | 0.3858 |
| stop sign | 1 | 1 | 0.5217 | 0.5217 |
| toilet | 1 | 1 | 0.4424 | 0.4424 |
Objects per image
| Row | File | Objects | Classes |
|---|---|---|---|
| 1 | cat.png | 3 | couch × 2, cat |
| 2 | cup.png | 5 | spoon × 3, cup, dining table |
| 3 | astronaut.png | 4 | person × 2, hair drier, toilet |
| 4 | shapes.png | 1 | stop sign |
| 5 | flat.png | 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)
# 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"))
))
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
| Class | Objects | Images | Mean score | Highest score |
|---|---|---|---|---|
| spoon | 3 | 1 | 0.5884 | 0.9919 |
| couch | 2 | 1 | 0.2883 | 0.3584 |
| person | 2 | 1 | 0.6502 | 0.9985 |
| cat | 1 | 1 | 0.9922 | 0.9922 |
| cup | 1 | 1 | 0.9929 | 0.9929 |
| dining table | 1 | 1 | 0.9495 | 0.9495 |
| hair drier | 1 | 1 | 0.3858 | 0.3858 |
| stop sign | 1 | 1 | 0.5217 | 0.5217 |
| toilet | 1 | 1 | 0.4424 | 0.4424 |
Objects per image
| Row | File | Objects | Classes |
|---|---|---|---|
| 1 | cat.png | 3 | couch × 2, cat |
| 2 | cup.png | 5 | spoon × 3, cup, dining table |
| 3 | astronaut.png | 4 | person × 2, hair drier, toilet |
| 4 | shapes.png | 1 | stop sign |
| 5 | flat.png | 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
# 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:
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
View data
| Height (px) | Image | Class | Mask (COCO RLE) | Media id | Score | Width (px) | x0 | x1 | y0 | y1 |
|---|---|---|---|---|---|---|---|---|---|---|
| 160 | cat.png | cat | b7\2[2:L3N3N1N2O1N2O1N2N2O1N2L4I7F:J6J6L4L4L4M3N200O100O100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001O0000000000000000000000000000000000000_NOSN1l12RNNl16RNJm18RNHl1;SNEj1?UNAh1b0XN^Oe1f0ZNZOc1j0\NVOa1o0]NQOa1Q1_NoN32OS1MkN0<Jm05gNOm0TOe0m0^NLk23UMKn24RMJQ35oLIT36lLHW37iLHY37gLG]36dLFa39_LDg39YLEk39ULEP48PLGV43lKJZ42fKKa41[f4 | 0eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a50 | 0.9968 | 240 | 0 | 217.65 | 0.7896 | 160 |
| 160 | cup.png | spoon | UXd02l43ZK7R4=O2N100N2O1N2O000O100O100O1O1O1N2O1M3O1M3M2N3NkNkLb0S3[OWM`0h2_O]M>b2AbM=]2CgM9W2HmM6Q2JSN2m1MZNMP1MTN8a3?4L4N3M4K4M5JVm: | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.9988 | 240 | 127.82 | 169.71 | 25.976 | 129.97 |
| 160 | cup.png | cup | Ve::b4;F>B;F5L3L4M3M3M2M3N3N1N2N1O2O0O2O1N100O2O000O2O00001N101O0O2O00001O0O2O1O1O1O000000001O0000000000O10000000001O0L4O1O2O00001N10000O2L30001O1N101O0O2O001N2M2N3M201N2N2N2L5M2M3M3M2N3M2M3L4K5N2L5K4KX\; | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.9978 | 240 | 68.305 | 168.32 | 7.286 | 105.16 |
| 160 | cup.png | dining 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@j3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000O101O0000000O2N5FO | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.9567 | 240 | 0 | 239.89 | 0 | 160 |
| 160 | cup.png | spoon | `Xd05g48I6J5N1N2N2N2N101N101N100O1O1N2O1N2O1N1O2N2N1O1NmNiLc0U3YOUMb0i2\O^Ma0b2]ObMa0_2\OeMa0]2\OhM`0^3M4LgR< | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.6700 | 240 | 128.76 | 163.23 | 68.674 | 132.83 |
| 192 | astronaut.png | person | dd1>Y5b0@?C:G7I5J6K4M4N1M3N2N2O1N2O1N2O1O1O1O1N2O100O1O1O1N2O1O1O1O100N2M3N2N2N2O1O1O1N200O100O100000000POSLLn30ZLLf32^LLb32bLL^32fLLZ33iLJX35kLIU36mLHT37[100O100O1O1O1O10000O1000000000000000000000000000000000000001O00001oKFZ2;_MM_24^M0`21^M1a2O^M3`2O]M5a2L\M7b2K\M7m1`0QNBh1e0VN^Of1g0UN]Og1g0TN^Og1i0RN[Ok1`2M2M4L3N3L3N2N1O2N2N2O1N2N2N2N2N2O3L3N2M3M6I`h: | f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d22 | 0.9987 | 192 | 4.024 | 138.15 | 7.449 | 190.46 |
| 192 | astronaut.png | cell phone | nc52n5000O100S^m0 | f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d22 | 0.5628 | 192 | 27.013 | 35.785 | 189.99 | 192.00 |
| 150 | shapes.png | — | — | fb6409af86ab2ef69eff6ef058e1227929f5a75ad407435a729a370097b2578c | — | 200 | — | — | — | — |
| 48 | flat.png | — | — | 81d0ef9f87003b2a8f4726bd99d84744e070a37fc2ba0a63f1537fd951587a11 | — | 64 | — | — | — | — |
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
| Class | Objects | Images | Mean score | Highest score |
|---|---|---|---|---|
| spoon | 2 | 1 | 0.8344 | 0.9988 |
| cat | 1 | 1 | 0.9968 | 0.9968 |
| cell phone | 1 | 1 | 0.5628 | 0.5628 |
| cup | 1 | 1 | 0.9978 | 0.9978 |
| dining table | 1 | 1 | 0.9567 | 0.9567 |
| person | 1 | 1 | 0.9987 | 0.9987 |
Objects per image
| Row | File | Objects | Classes | Share covered |
|---|---|---|---|---|
| 1 | cat.png | 1 | cat | 77.4% |
| 2 | cup.png | 4 | spoon × 2, cup, dining table | 93.6% |
| 3 | astronaut.png | 2 | cell phone, person | 40.8% |
| 4 | shapes.png | 0 | 0.0% | |
| 5 | flat.png | 0 | 0.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"))
))
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
| Class | Objects | Images | Mean score | Highest score |
|---|---|---|---|---|
| spoon | 2 | 1 | 0.8344 | 0.9988 |
| cat | 1 | 1 | 0.9968 | 0.9968 |
| cell phone | 1 | 1 | 0.5628 | 0.5628 |
| cup | 1 | 1 | 0.9978 | 0.9978 |
| dining table | 1 | 1 | 0.9567 | 0.9567 |
| person | 1 | 1 | 0.9987 | 0.9987 |
Objects per image
| Row | File | Objects | Classes | Share covered |
|---|---|---|---|---|
| 1 | cat.png | 1 | cat | 77.4% |
| 2 | cup.png | 4 | spoon × 2, cup, dining table | 93.6% |
| 3 | astronaut.png | 2 | cell phone, person | 40.8% |
| 4 | shapes.png | 0 | 0.0% | |
| 5 | flat.png | 0 | 0.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"}],
})
Check: two-stage detectors
CheckpointCheck 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.
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