ADescribe · detect.objects
Object detection (Faster R-CNN, COCO)
Which everyday objects — people, vehicles, animals, furniture — are in these images, where, and how many?
Finds objects of COCO's 80 everyday classes in a column of images with a pretrained Faster R-CNN detector (torchvision's COCO weights, converted once to safetensors and a one-time download you approve): a box, a class and a score for every object above the score threshold. Choose the accurate ResNet-50 FPN v2 model or the fast MobileNetV3 model. Results: counts per class and per image, a gallery of images with their boxes, and a boxes table (one row per object) you can save as a dataset and score against annotations with Evaluate detections. Python and R run the same network on the same weights and give the same boxes.
A real result
Example “Fast defaults small”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
3 objects in 3 of 5 images; most common: cat (1).
- Objects
- 3
- Images
- 5
- Classes found
- 3
- Objects per image
- 0.6000
Plots
View data
| Height (px) | Image | Class | Media id | Score | Width (px) | x0 | x1 | y0 | y1 |
|---|---|---|---|---|---|---|---|---|---|
| 160 | cat.png | cat | 0eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a50 | 0.9945 | 240 | 4.049 | 210.15 | 0.2764 | 158.14 |
| 160 | cup.png | cup | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.9756 | 240 | 65.684 | 168.94 | 7.390 | 123.73 |
| 192 | astronaut.png | person | f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d22 | 0.8918 | 192 | 6.176 | 141.00 | 5.883 | 190.94 |
| 150 | shapes.png | — | fb6409af86ab2ef69eff6ef058e1227929f5a75ad407435a729a370097b2578c | — | 200 | — | — | — | — |
| 48 | flat.png | — | 81d0ef9f87003b2a8f4726bd99d84744e070a37fc2ba0a63f1537fd951587a11 | — | 64 | — | — | — | — |
View data
| Class |
|---|
| cat |
| cup |
| person |
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).
- 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 |
|---|---|---|---|---|
| cat | 1 | 1 | 0.9945 | 0.9945 |
| cup | 1 | 1 | 0.9756 | 0.9756 |
| person | 1 | 1 | 0.8918 | 0.8918 |
Objects per image
| Row | File | Objects | Classes |
|---|---|---|---|
| 1 | cat.png | 1 | cat |
| 2 | cup.png | 1 | cup |
| 3 | astronaut.png | 1 | person |
| 4 | shapes.png | 0 | |
| 5 | flat.png | 0 |
- 1 rows have no path and are left out.
- 1 files could not be decoded and are left out.
3 objects in 3 of 5 images; most common: cat (1).
- Objects
- 3
- Images
- 5
- Classes found
- 3
- Objects per image
- 0.6000
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).
- 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 |
|---|---|---|---|---|
| cat | 1 | 1 | 0.9945 | 0.9945 |
| cup | 1 | 1 | 0.9756 | 0.9756 |
| person | 1 | 1 | 0.8918 | 0.8918 |
Objects per image
| Row | File | Objects | Classes |
|---|---|---|---|
| 1 | cat.png | 1 | cat |
| 2 | cup.png | 1 | cup |
| 3 | astronaut.png | 1 | person |
| 4 | shapes.png | 0 | |
| 5 | flat.png | 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
- Fast defaults smallimg3_photos · image: path
- Accurate low thresholdimg3_photos · image: path
- Fast classes filterimg3_photos · image: path
- Degenerate all naimg3_photos · image: path
- Fast 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
model
- Detectordefault fasterrcnn_resnet50_fpn_v2
The pretrained COCO detector. Each is a one-time download that states its size and license first.
- Accurate: Faster R-CNN ResNet-50 FPN v2 (175 MB)(default) — COCO box mAP 46.7; several seconds per image on the CPU.
- Fast: Faster R-CNN MobileNetV3-Large FPN (78 MB) — COCO box mAP 32.8; several times faster, misses more small objects.
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.
Photos like COCO's
The detector 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.
- 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; 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 “Fast defaults small” · 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 8b376c52a30d1405
# 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_mobilenet_v3_large_fpn"
# %% 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/fast_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)
# %% Detect objects (torchvision fasterrcnn_mobilenet_v3_large_fpn on the converted COCO weights)
SCORE = 0.5
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=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 table (one row per object) and one row per image
out = csml.out_dir("target/academy-parity/run-8142/detect.objects/fast_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"]} 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"}],
})
The exact script CodeSplash ran for example “Fast defaults small” · 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 8b376c52a30d1405
# 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_mobilenet_v3_large_fpn"
# %% 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/fast_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)
# %% Detect objects (torchvision fasterrcnn_mobilenet_v3_large_fpn on the converted COCO weights)
SCORE <- 0.5
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 = 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 table (one row per object) and one row per image
out <- cs_ml_out_dir("target/academy-parity/run-8142/detect.objects/fast_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), 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"))
))
Sources
- 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).
- Howard A, Sandler M, Chu G, et al. (2019). Searching for MobileNetV3. ICCV 2019, 1314–1324.
- 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 detection weights.
From the CodeSplash method registry · detect.objects v1.0.1.