ADescribe · segment.instances
Instance segmentation (Mask R-CNN, COCO)
Which everyday objects are in these images, and exactly which pixels does each one cover?
Outlines every object of COCO's 80 everyday classes in a column of images with a pretrained Mask R-CNN (torchvision's COCO weights, converted once to safetensors and a one-time download you approve): a box, a class, a score and a pixel mask for each object above the score threshold. Results: counts per class and per image, the share of each image covered by objects, a gallery of images with their outlines, and a boxes table with each mask as COCO run-length encoding (one row per object) you can save as a dataset and score with Evaluate segments. Python and R run the same network on the same weights and give the same masks.
A real result
Example “Defaults small”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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.
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.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Defaults smallimg3_photos · image: path
- Low threshold classesimg3_photos · image: path
- Degenerate all naimg3_photos · image: path
- No objects foundimg3_photos · image: path
- Degenerate no readable imageimg3_unreadable · image: path
In the guides
Where it sits in the decision guides
- Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
What you need
- Image pathcategorical · 1 column
- A column of image file paths, such as the path column of an image folder (Data → Add image folder…). PNG, JPEG, WebP, GIF, BMP and TIFF are read.
Choices you make
options
- Score thresholddefault 0.5
Objects the detector is less sure of than this are dropped. Lower finds more objects and more false ones.
- Classes to keepdefault
Keep only these COCO classes. None selected keeps all 80.
- Person — Keep only this COCO class (people).
- Bicycle — Keep only this COCO class (vehicles).
- Car — Keep only this COCO class (vehicles).
- Motorcycle — Keep only this COCO class (vehicles).
- Airplane — Keep only this COCO class (vehicles).
- Bus — Keep only this COCO class (vehicles).
- Train — Keep only this COCO class (vehicles).
- Truck — Keep only this COCO class (vehicles).
- Boat — Keep only this COCO class (vehicles).
- Traffic light — Keep only this COCO class (outdoor).
- Fire hydrant — Keep only this COCO class (outdoor).
- Stop sign — Keep only this COCO class (outdoor).
- Parking meter — Keep only this COCO class (outdoor).
- Bench — Keep only this COCO class (outdoor).
- Bird — Keep only this COCO class (animals).
- Cat — Keep only this COCO class (animals).
- Dog — Keep only this COCO class (animals).
- Horse — Keep only this COCO class (animals).
- Sheep — Keep only this COCO class (animals).
- Cow — Keep only this COCO class (animals).
- Elephant — Keep only this COCO class (animals).
- Bear — Keep only this COCO class (animals).
- Zebra — Keep only this COCO class (animals).
- Giraffe — Keep only this COCO class (animals).
- Backpack — Keep only this COCO class (accessories).
- Umbrella — Keep only this COCO class (accessories).
- Handbag — Keep only this COCO class (accessories).
- Tie — Keep only this COCO class (accessories).
- Suitcase — Keep only this COCO class (accessories).
- Frisbee — Keep only this COCO class (sports).
- Skis — Keep only this COCO class (sports).
- Snowboard — Keep only this COCO class (sports).
- Sports ball — Keep only this COCO class (sports).
- Kite — Keep only this COCO class (sports).
- Baseball bat — Keep only this COCO class (sports).
- Baseball glove — Keep only this COCO class (sports).
- Skateboard — Keep only this COCO class (sports).
- Surfboard — Keep only this COCO class (sports).
- Tennis racket — Keep only this COCO class (sports).
- Bottle — Keep only this COCO class (kitchen).
- Wine glass — Keep only this COCO class (kitchen).
- Cup — Keep only this COCO class (kitchen).
- Fork — Keep only this COCO class (kitchen).
- Knife — Keep only this COCO class (kitchen).
- Spoon — Keep only this COCO class (kitchen).
- Bowl — Keep only this COCO class (kitchen).
- Banana — Keep only this COCO class (food).
- Apple — Keep only this COCO class (food).
- Sandwich — Keep only this COCO class (food).
- Orange — Keep only this COCO class (food).
- Broccoli — Keep only this COCO class (food).
- Carrot — Keep only this COCO class (food).
- Hot dog — Keep only this COCO class (food).
- Pizza — Keep only this COCO class (food).
- Donut — Keep only this COCO class (food).
- Cake — Keep only this COCO class (food).
- Chair — Keep only this COCO class (furniture).
- Couch — Keep only this COCO class (furniture).
- Potted plant — Keep only this COCO class (furniture).
- Bed — Keep only this COCO class (furniture).
- Dining table — Keep only this COCO class (furniture).
- Toilet — Keep only this COCO class (furniture).
- Tv — Keep only this COCO class (electronics).
- Laptop — Keep only this COCO class (electronics).
- Mouse — Keep only this COCO class (electronics).
- Remote — Keep only this COCO class (electronics).
- Keyboard — Keep only this COCO class (electronics).
- Cell phone — Keep only this COCO class (electronics).
- Microwave — Keep only this COCO class (appliances).
- Oven — Keep only this COCO class (appliances).
- Toaster — Keep only this COCO class (appliances).
- Sink — Keep only this COCO class (appliances).
- Refrigerator — Keep only this COCO class (appliances).
- Book — Keep only this COCO class (indoor).
- Clock — Keep only this COCO class (indoor).
- Vase — Keep only this COCO class (indoor).
- Scissors — Keep only this COCO class (indoor).
- Teddy bear — Keep only this COCO class (indoor).
- Hair drier — Keep only this COCO class (indoor).
- Toothbrush — Keep only this COCO class (indoor).
Advanced
- Detection size (short side)default 800
Each image is resized so its short side is this many pixels (long side at most 1,333) before detection. Smaller is faster and misses small objects.
- Most objects per imagedefault 100
At most this many objects are kept per image, the highest-scoring first.
- Overlap allowed (NMS IoU)default 0.5
Two boxes of the same class that overlap more than this (intersection over union) count as one object; the higher score is kept.
- Compute profiledefault parity
How precisely the network runs. Parity matches the other engine; Faster CPU is several times faster and can move scores slightly.
- Parity(default) — Double precision on one CPU thread: the same boxes in Python and R, run after run (the default).
- Faster CPU — Single precision on all performance cores; repeatable on this Mac, scores can differ slightly from Parity.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
COCO's 80 classes
Only COCO's everyday classes can be found; other objects are missed or given the nearest class.
Score threshold
The threshold trades missed objects against false ones; scores are confidence ranks, not calibrated probabilities.
Masks at 28 × 28
Each mask is predicted on a 28 × 28 grid inside its box and enlarged, so edges are smooth approximations; 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
Detecting people in photos handles personal data; results stay on this computer.
What it reports
- n_rows
- Rows whose image file could be decoded; rows without a path and files that can't be decoded are counted and left out.
- n_images
- Rows whose image file could be decoded; rows without a path and files that can't be decoded are counted and left out.
- n_no_path
- Rows whose image file could be decoded; rows without a path and files that can't be decoded are counted and left out.
- n_unreadable
- Rows whose image file could be decoded; rows without a path and files that can't be decoded are counted and left out.
- n_objects
- Finding each object in an image as a box with a class and a score, such as every person and car in a street photo.
- n_images_with_objects
- Finding each object in an image as a box with a class and a score, such as every person and car in a street photo.
- share_with_objects
- Finding each object in an image as a box with a class and a score, such as every person and car in a street photo.
- n_classes
- Finding each object in an image as a box with a class and a score, such as every person and car in a street photo.
- objects_per_image
- Finding each object in an image as a box with a class and a score, such as every person and car in a street photo.
- max_per_image
- Finding each object in an image as a box with a class and a score, such as every person and car in a street photo.
- score_mean
- How sure the detector is about one object, from 0 to 1; objects below the threshold are dropped. A rank, not a probability.
- score_min
- How sure the detector is about one object, from 0 to 1; objects below the threshold are dropped. A rank, not a probability.
- box_check
- The sum of every box corner (and of every area): one number that changes when any box does, used to compare runs.
- area_check
- The sum of every box corner (and of every area): one number that changes when any box does, used to compare runs.
- covered_mean
- Detection plus a pixel mask for every object, so each object's exact outline and area are known, not just its box.
- model
- The 80 everyday object classes of the COCO dataset (people, vehicles, animals, food, furniture) the detectors learned.
- min_size
- The short side, in pixels, each image is resized to before detection (long side at most 1,333). Smaller is faster.
- score_threshold
- How sure the detector is about one object, from 0 to 1; objects below the threshold are dropped. A rank, not a probability.
Per group, level or term: n[<class>], images[<class>], mean_score[<class>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses torch, torchvision, safetensors, numpy, pandas, codesplash; R uses torch, torchvision, safetensors, nanoparquet, codesplashr.
Default traps between the two languages
- Python runs torchvision's own modules and C++ operators (RoIAlign, NMS); R runs the CRAN torchvision modules with every inference step written out to match (codesplash.vision.detect ↔ codesplashr R/vision_detect.R), both on the same converted float32 weights in float64 (Parity profile, one thread). On the fixtures the same objects come out in the same order with identical masks; boxes agree to about 1e-13 px and scores to about 1e-15.
- A tie at the score threshold or between two boxes in non-maximum suppression could in principle resolve differently; none occurs on the fixtures. The Faster CPU profile (single precision) is labeled and not counted as Python ≡ R (decision 65).
- Without the downloaded weights the run stops with CS_WEIGHTS_MISSING in both engines; nothing is downloaded automatically.
The exact script CodeSplash ran for example “Defaults small” · 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"}],
})
The exact script CodeSplash ran for example “Defaults small” · 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"))
))
Sources
- He K, Gkioxari G, Dollár P, Girshick R (2017). Mask R-CNN. ICCV 2017, 2961–2969.
- Ren S, He K, Girshick R, Sun J (2015). Faster R-CNN: towards real-time object detection with region proposal networks. NeurIPS 2015, 91–99.
- Lin T-Y, Dollár P, Girshick R, He K, Hariharan B, Belongie S (2017). Feature pyramid networks for object detection. CVPR 2017, 2117–2125.
- Li Y, Xie S, Chen X, Dollár P, He K, Girshick R (2021). Benchmarking detection transfer learning with vision transformers. arXiv:2111.11429 (the v2 recipe torchvision trained).
- Lin T-Y, Maire M, Belongie S, et al. (2014). Microsoft COCO: common objects in context. ECCV 2014, 740–755.
- TorchVision maintainers and contributors (2016–). TorchVision: PyTorch's computer vision library (BSD-3-Clause); COCO_V1 Mask R-CNN weights.
From the CodeSplash method registry · segment.instances v1.0.1.