diff --git a/docs/changelog.md b/docs/changelog.md index 8b4c847c..d0ce4d5b 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -13,6 +13,10 @@ date_modified: 2026-06-25 Users on Python 3.9 should upgrade their environment before updating supervision. +### Added +- `CompactMask.from_coco_rle` — efficient COCO RLE ingestion into crop-scoped compact mask format without materializing dense `(N, H, W)` arrays ([#2367](https://github.com/roboflow/supervision/pull/2367)) +- `Detections.from_inference(compact_masks=True)` — opt-in compact mask representation for Roboflow/Inference segmentation results; masks are cropped to detector bounding boxes ([#2367](https://github.com/roboflow/supervision/pull/2367)) + ### 0.29.1 Jun 23, 2026 - Fixed [#2353](https://github.com/roboflow/supervision/pull/2353): `sv.Detections.from_inference` no longer raises `TypeError` when the Inference package returns a mixed batch where only some predictions carry a `tracker_id`. `detections.tracker_id` is `None` for the full result in that case; fully-tracked and fully-untracked batches are unchanged. diff --git a/examples/compact_mask/README.md b/examples/compact_mask/README.md index a9dca913..cc8e3902 100644 --- a/examples/compact_mask/README.md +++ b/examples/compact_mask/README.md @@ -527,6 +527,69 @@ Run on any machine — no GPU or real model required: uv run python examples/compact_mask/benchmark.py ``` +For a focused benchmark of the Roboflow inference-result parser API, run: + +```bash +uv run python examples/compact_mask/bench_inference_api.py +``` + +This script downloads all supervision image assets plus the middle frame from every supervision video asset by default, runs one real segmentation inference per source image, requests native RLE masks from Inference, freezes that result, and then compares parser performance: + +```python +sv.Detections.from_inference(result) +sv.Detections.from_inference(result, compact_masks=True) +``` + +Timing repetitions, warmups, confidence, IoU, response mask format, and the default model live as constants in `bench_inference_api.py`. + +Inference runs and segmentation-derived box fields are outside the timed benchmark loop. By default the script uses `rfdetr-seg-large` with `response_mask_format="rle"`; set `BENCH_INFERENCE_MODEL_ID` to override the model. Set `ROBOFLOW_API_KEY` when your model requires authentication. Sources where the model returns no native RLE segmentation masks are skipped because there is no RLE parser work to benchmark. `rfdetr-large` is a valid local Inference model id, but it is object detection only; use an `rfdetr-seg-*` model for instance segmentation. + +Run one specific supervision image or video asset with `--asset`: + +```bash +uv run python examples/compact_mask/bench_inference_api.py --asset people-walking +uv run python examples/compact_mask/bench_inference_api.py --asset soccer +uv run python examples/compact_mask/bench_inference_api.py --asset vehicles +uv run python examples/compact_mask/bench_inference_api.py --asset people-walking-video +``` + +The output reports image size, segmented objects, median parser time, peak traced allocations, mask storage, and parser speedup (`dense parser time / compact parser time`). + +**Speedup column:** The `speedup` value reflects allocation savings — how much time is saved by skipping the dense `(N, H, W)` bool-stack allocation — not a faster RLE decode. Compact RLE arithmetic is typically slower than the dense NumPy path. The net result: + +- **Compact is faster** only when the dense `(N, H, W)` bool-stack allocation dominates — large images with many sparse masks where avoiding that allocation outweighs the RLE arithmetic cost. +- **Compact is slower** for small images or dense/overlapping masks, where Python RLE arithmetic dominates and the allocation cost is negligible. +- **The primary guaranteed benefit is memory**: compact masks use roughly 99% less memory than dense stacks for typical segmentation output, regardless of which parse direction is faster. + +The default run includes a `synthetic-dense-64` row (64×64 image, 4 fully-filled masks) to demonstrate the adversarial regime where compact is slower than dense. For each real source with segmentation masks, the script also writes a validation overlay to `examples/compact_mask/outputs/*_segmentations.jpg`. + +### Sample results — inference API + +Measured on macOS Apple M4 Max, 50 reps after 3 warmups, using `rfdetr-seg-large` via Roboflow Inference. + +| src | res | seg | dense ms | CM ms | speedup | peak MB (dense/compact) | mask MB (dense/compact) | ok | +| -------------------------- | --------- | --- | -------- | ----- | ------- | ----------------------- | ----------------------- | --- | +| synthetic-dense-64 | 64×64 | 4 | 0.03 | 0.11 | 0.31× | 0.04 / 0.05 | 0.02 / 0.00 | ✓ | +| people-walking.jpg | 1920×1080 | 53 | 85.56 | 12.55 | 6.82× | 219.86 / 0.11 | 109.90 / 0.02 | ✓ | +| soccer.jpg | 398×224 | 21 | 1.36 | 1.07 | 1.27× | 3.77 / 0.05 | 1.87 / 0.00 | ✓ | +| vehicles.mp4#269 | 3840×2160 | 7 | 46.03 | 2.60 | 18× | 116.13 / 0.07 | 58.06 / 0.00 | ✓ | +| milk-bottling-plant.mp4#94 | 1920×1080 | 9 | 15.61 | 11.57 | 1.35× | 37.34 / 0.53 | 18.66 / 0.03 | ✓ | +| vehicles-2.mp4#637 | 1920×1080 | 47 | 76.87 | 13.59 | 5.66× | 194.97 / 0.13 | 97.46 / 0.03 | ✓ | +| grocery-store.mp4#501 | 3840×2160 | 4 | 27.20 | 4.36 | 6.24× | 66.36 / 0.22 | 33.18 / 0.01 | ✓ | +| subway.mp4#649 | 2160×3840 | 42 | 325.71 | 32.21 | 10× | 696.78 / 0.80 | 348.36 / 0.09 | ✓ | +| market-square.mp4#237 | 2160×3840 | 96 | 732.98 | 27.24 | 27× | 1592.61 / 0.22 | 796.26 / 0.05 | ✓ | +| people-walking.mp4#170 | 1920×1080 | 60 | 100.99 | 12.69 | 7.96× | 248.89 / 0.12 | 124.42 / 0.02 | ✓ | +| beach-1.mp4#223 | 3840×2160 | 33 | 223.50 | 13.39 | 17× | 547.47 / 0.12 | 273.72 / 0.02 | ✓ | +| basketball-1.mp4#238 | 1920×1080 | 2 | 3.61 | 2.05 | 1.76× | 8.30 / 0.15 | 4.15 / 0.01 | ✓ | +| skiing.mp4#176 | 1920×1080 | 11 | 16.47 | 3.07 | 5.37× | 45.63 / 0.08 | 22.81 / 0.01 | ✓ | + +- **seg** — number of instance segmentations returned by the model +- **dense ms / CM ms** — median parse time for `from_inference()` vs `from_inference(compact_masks=True)` +- **speedup** — dense / compact parse time; values below 1× (e.g., synthetic-dense-64) indicate the adversarial regime where RLE arithmetic cost exceeds allocation savings +- **peak MB** — peak traced allocations during parsing (dense / compact) +- **mask MB** — mask storage only (dense / compact); compact is typically 100–5 000× smaller +- **ok** — `compact.to_dense()` pixel-exactly matches dense masks + Six image tiers x three fill fractions (5 / 20 / 50 %) x three vertex counts (8 / 128 / 600): | Tier | Resolution | Objects | Dense array | Notes | @@ -585,7 +648,8 @@ All non-skipped scenarios pass: pixel-perfect annotation, exact area, lossless ` ## Files -| File | Description | -| -------------- | ------------------------------------------------ | -| `benchmark.py` | Full benchmark across FHD / 4K / satellite tiers | -| `README.md` | This file | +| File | Description | +| ------------------------ | --------------------------------------------------- | +| `benchmark.py` | Full benchmark across FHD / 4K / satellite tiers | +| `bench_inference_api.py` | Focused dense vs compact `from_inference` benchmark | +| `README.md` | This file | diff --git a/examples/compact_mask/bench_inference_api.py b/examples/compact_mask/bench_inference_api.py new file mode 100644 index 00000000..aafa6fe6 --- /dev/null +++ b/examples/compact_mask/bench_inference_api.py @@ -0,0 +1,505 @@ +"""Benchmark dense vs compact Roboflow RLE ingestion. + +Run with: + uv run python examples/compact_mask/bench_inference_api.py + +The benchmark downloads supervision assets, runs one segmentation inference per +source image, then times dense vs compact parsing of that fixed inference result. +""" + +from __future__ import annotations + +import argparse +import gc +import os +import statistics +import time +import tracemalloc +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +from rich import box +from rich.console import Console +from rich.table import Table + +import supervision as sv +from supervision.assets import ImageAssets, VideoAssets, download_assets +from supervision.config import CLASS_NAME_DATA_FIELD +from supervision.detection.compact_mask import CompactMask + +console = Console(width=120, force_terminal=True) + +# Default segmentation model; use an rfdetr-seg-* id so masks are returned. +MODEL_ID = "rfdetr-seg-large" +# Environment variable that can override MODEL_ID without adding CLI noise. +MODEL_ID_ENV = "BENCH_INFERENCE_MODEL_ID" +# Optional Roboflow API key for models that require authentication. +API_KEY_ENV = "ROBOFLOW_API_KEY" +# Model confidence threshold used only for the one inference call per source. +CONFIDENCE = 0.2 +# Model IoU threshold used only for the one inference call per source. +IOU = 0.5 +# Request native RLE masks so the benchmark measures RLE parser ingestion. +RESPONSE_MASK_FORMAT = "rle" +# Parser timing repetitions; inference itself is not repeated. +REPETITIONS = 50 +# Untimed parser warmup calls before measurements. +WARMUP = 3 +# Visual segmentation overlays for manual validation. +ARTIFACT_DIR = Path("examples/compact_mask/outputs") + +ASSETS = {Path(asset.filename).stem: asset for asset in ImageAssets} +for video_asset in VideoAssets: + key = Path(video_asset.filename).stem + ASSETS[key if key not in ASSETS else f"{key}-video"] = video_asset + + +@dataclass +class ApiBenchmarkResult: + """Result for one dense-vs-compact parser benchmark run.""" + + source: str + resolution: str + segmented_objects: int + dense_s: float + compact_s: float + dense_peak_bytes: int + compact_peak_bytes: int + dense_mask_bytes: int + compact_mask_bytes: int + pixel_perfect: bool + + +def load_image_from_asset(path: Path | None, asset: str) -> tuple[np.ndarray, str]: + """Return ``(image, label)`` for an image or video middle frame.""" + if path is not None: + image = cv2.imread(str(path)) + if image is None: + raise FileNotFoundError(f"Could not read image: {path}") + return image, str(path) + + asset_obj = ASSETS[asset] + asset_path = Path(download_assets(asset_obj)) + if isinstance(asset_obj, ImageAssets): + image = cv2.imread(str(asset_path)) + if image is None: + raise FileNotFoundError(f"Could not read image: {asset_path}") + return image, str(asset_path) + + video = cv2.VideoCapture(str(asset_path)) + if not video.isOpened(): + raise FileNotFoundError(f"Could not read video: {asset_path}") + frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) + frame_index = max(0, frame_count // 2) + if frame_index: + video.set(cv2.CAP_PROP_POS_FRAMES, frame_index) + ok, frame = video.read() + video.release() + if not ok or frame is None: + raise FileNotFoundError(f"Could not read middle frame: {asset_path}") + return frame, f"{asset_path}#{frame_index}" + + +def freeze_result(inference_result: Any) -> dict[str, Any]: + """Convert one Inference result to a reusable dictionary.""" + if isinstance(inference_result, dict): + return inference_result + if hasattr(inference_result, "model_dump"): + return inference_result.model_dump(exclude_none=True, by_alias=True) + if hasattr(inference_result, "dict"): + return inference_result.dict(exclude_none=True, by_alias=True) + raise TypeError( + f"Expected dict-like Inference result, got {type(inference_result).__name__}" + ) + + +def count_rle_predictions(result: dict[str, Any]) -> int: + """Return the number of predictions carrying Roboflow RLE masks.""" + return sum( + isinstance(prediction.get("rle") or prediction.get("rle_mask"), dict) + for prediction in result.get("predictions", []) + ) + + +def synthetic_dense_small_result() -> tuple[np.ndarray, str, dict[str, Any]]: + """Return a small dense-mask adversarial payload where compact parsing is slower. + + Uses a 64x64 image with 4 fully-filled masks. At this scale the dense + ``(N, H, W)`` allocation cost is negligible; Python RLE arithmetic dominates, + making compact ingestion slower than the dense NumPy path. Included as a + clearly labeled adversarial row in the default benchmark run to show that + the ``speedup`` column reflects allocation savings, not decode speed. + """ + height, width = 64, 64 + image = np.zeros((height, width, 3), dtype=np.uint8) + predictions = [ + { + "x": width / 2, + "y": height / 2, + "width": width, + "height": height, + "confidence": 0.9, + "class_id": index, + "class": f"dense-{index}", + "rle": {"size": [height, width], "counts": [0, height * width]}, + } + for index in range(4) + ] + return ( + image, + "synthetic-dense-64", + { + "predictions": predictions, + "image": {"width": width, "height": height}, + }, + ) + + +def derive_boxes_from_rle_masks(result: dict[str, Any]) -> dict[str, Any]: + """Set prediction boxes from native RLE segmentation masks.""" + predictions = [] + for prediction in result.get("predictions", []): + rle = prediction.get("rle") or prediction.get("rle_mask") + if not isinstance(rle, dict): + predictions.append(prediction) + continue + + height, width = rle["size"] + mask = sv.rle_to_mask(rle["counts"], resolution_wh=(int(width), int(height))) + if not mask.any(): + predictions.append(prediction) + continue + + x1, y1, x2, y2 = sv.mask_to_xyxy(mask[np.newaxis, ...])[0] + predictions.append( + { + **prediction, + "x": float((x1 + x2) / 2), + "y": float((y1 + y2) / 2), + "width": float(x2 - x1), + "height": float(y2 - y1), + } + ) + return {**result, "predictions": predictions} + + +def artifact_path(source: str) -> Path: + """Return the segmentation validation artifact path for a source.""" + source_path, separator, frame = source.partition("#") + stem = Path(source_path).stem + suffix = f"_frame_{frame}" if separator else "" + return ARTIFACT_DIR / f"{stem}{suffix}_segmentations.jpg" + + +def detection_labels(detections: sv.Detections) -> list[str]: + """Return compact class/confidence labels for validation artifacts.""" + raw_class_names = detections.get_data(CLASS_NAME_DATA_FIELD) + class_names = ( + raw_class_names.astype(str).tolist() + if isinstance(raw_class_names, np.ndarray) + else [""] * len(detections) + ) + + labels = [] + for index in range(len(detections)): + class_name = class_names[index] if index < len(class_names) else "" + confidence = ( + "" + if detections.confidence is None + else f" {detections.confidence[index]:.2f}" + ) + labels.append(f"{class_name}{confidence}".strip() or str(index)) + return labels + + +def save_segmentation_artifact( + image: np.ndarray, + result: dict[str, Any], + source: str, +) -> Path | None: + """Draw parsed segmentation masks and save a validation artifact.""" + detections = sv.Detections.from_inference(result) + if detections.mask is None: + return None + + annotated = image.copy() + annotated = sv.MaskAnnotator( + color_lookup=sv.ColorLookup.INDEX, + opacity=0.45, + ).annotate(scene=annotated, detections=detections) + annotated = sv.LabelAnnotator( + color_lookup=sv.ColorLookup.INDEX, + text_scale=0.35, + text_padding=4, + ).annotate( + scene=annotated, + detections=detections, + labels=detection_labels(detections), + ) + + path = artifact_path(source) + path.parent.mkdir(parents=True, exist_ok=True) + if not cv2.imwrite(str(path), annotated): + raise OSError(f"Could not write segmentation artifact: {path}") + return path + + +def load_inference_model(model_id: str, api_key: str | None) -> Any: + """Load the requested Inference model.""" + try: + from inference import get_model + except ImportError as exc: + raise ImportError( + "Install the `inference` package to run this benchmark." + ) from exc + + model_kwargs = {"api_key": api_key} if api_key is not None else {} + return get_model(model_id=model_id, **model_kwargs) + + +def run_inference_once( + image: np.ndarray, + model: Any, + model_id: str, + confidence: float, + iou: float, +) -> dict[str, Any] | None: + """Run one real segmentation inference and return a frozen result.""" + # Inference still serializes instance segmentations with x/y/width/height. + # Derive those fields from the RLE masks so the benchmark uses segmentations, + # not the model-reported detector boxes, as the source of truth. + result = derive_boxes_from_rle_masks( + freeze_result( + model.infer( + image, + confidence=confidence, + iou=iou, + response_mask_format=RESPONSE_MASK_FORMAT, + )[0] + ) + ) + rle_count = count_rle_predictions(result) + if rle_count == 0: + console.print( + f"[yellow]skipped[/yellow] {model_id}: no native RLE segmentation " + f"predictions for response_mask_format={RESPONSE_MASK_FORMAT!r}" + ) + return None + return result + + +def median_seconds(fn: Callable[[], object], reps: int, warmup: int) -> float: + """Return median runtime for ``fn``.""" + for _ in range(warmup): + fn() + gc.collect() + + timings = [] + for _ in range(reps): + start = time.perf_counter() + fn() + timings.append(time.perf_counter() - start) + return statistics.median(timings) + + +def peak_bytes(fn: Callable[[], object]) -> int: + """Return peak traced allocations for one call.""" + gc.collect() + tracemalloc.start() + fn() + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + return int(peak) + + +def dense_mask_bytes(detections: sv.Detections) -> int: + """Return dense mask storage bytes.""" + return 0 if detections.mask is None else int(np.asarray(detections.mask).nbytes) + + +def compact_mask_bytes(detections: sv.Detections) -> int: + """Return compact mask storage bytes.""" + if not isinstance(detections.mask, CompactMask): + return 0 + return sum(rle.nbytes for rle in detections.mask._rles) + + +def _fmt_ratio(ratio: float) -> str: + """Format a speedup/compression ratio with colour coding.""" + fmt = f"{ratio:.0f}x" if ratio >= 10 else f"{ratio:.2f}x" + if ratio >= 10: + return f"[green]{fmt}[/green]" + elif ratio >= 1: + return f"[yellow]{fmt}[/yellow]" + else: + return f"[red]{fmt}[/red]" + + +def _fmt_mb(num_bytes: int) -> str: + """Format bytes as compact megabytes.""" + return f"{num_bytes / 1e6:.2f}" + + +def run_benchmark( + source: str, + image: np.ndarray, + result: dict[str, Any], + reps: int, + warmup: int, +) -> ApiBenchmarkResult: + """Run one dense-vs-compact parser benchmark.""" + + # Benchmark the public Roboflow/Inference adapter; RLE masks enter through + # the result payload and should stay compact when compact_masks=True. + def dense() -> sv.Detections: + return sv.Detections.from_inference(result) + + def compact() -> sv.Detections: + return sv.Detections.from_inference(result, compact_masks=True) + + dense_once = dense() + compact_once = compact() + if not isinstance(dense_once.mask, np.ndarray): + raise TypeError(f"Expected dense ndarray mask, got {type(dense_once.mask)}") + if not isinstance(compact_once.mask, CompactMask): + raise TypeError(f"Expected CompactMask, got {type(compact_once.mask)}") + np.testing.assert_array_equal(compact_once.mask.to_dense(), dense_once.mask) + + dense_s = median_seconds(dense, reps, warmup) + compact_s = median_seconds(compact, reps, warmup) + dense_peak = peak_bytes(dense) + compact_peak = peak_bytes(compact) + + return ApiBenchmarkResult( + source=source, + resolution=f"{image.shape[1]}x{image.shape[0]}", + segmented_objects=len(dense_once), + dense_s=dense_s, + compact_s=compact_s, + dense_peak_bytes=dense_peak, + compact_peak_bytes=compact_peak, + dense_mask_bytes=dense_mask_bytes(dense_once), + compact_mask_bytes=compact_mask_bytes(compact_once), + pixel_perfect=True, + ) + + +def print_summary(results: list[ApiBenchmarkResult], reps: int, warmup: int) -> None: + """Print a Rich summary table matching the compact mask benchmark style.""" + table = Table( + title="CompactMask from_inference", + box=box.ROUNDED, + show_lines=False, + header_style="bold cyan", + ) + table.add_column("src", style="bold", no_wrap=True) + table.add_column("res", no_wrap=True) + table.add_column("seg", justify="right") + table.add_column("dense ms", justify="right") + table.add_column("CM ms", justify="right", style="green") + table.add_column("speedup", justify="right") + table.add_column("peak MB", justify="right", style="cyan") + table.add_column("mask MB", justify="right") + table.add_column("ok", justify="center") + + for result in results: + speedup = result.dense_s / max(result.compact_s, 1e-9) + table.add_row( + result.source, + result.resolution, + str(result.segmented_objects), + f"{result.dense_s * 1e3:.2f}", + f"{result.compact_s * 1e3:.2f}", + _fmt_ratio(speedup), + f"{_fmt_mb(result.dense_peak_bytes)}/{_fmt_mb(result.compact_peak_bytes)}", + f"{_fmt_mb(result.dense_mask_bytes)}/{_fmt_mb(result.compact_mask_bytes)}", + "[green]✓[/green]" if result.pixel_perfect else "[red]✗[/red]", + ) + + console.print(table) + console.print( + "[dim]" + + " · ".join( + [ + f"timings are median of {reps} reps after {warmup} warmups", + "peak MB and mask MB are dense/compact", + "speedup = dense / compact parse time; gains are allocation-driven" + " (avoiding the dense (N,H,W) bool-stack), not faster RLE decode", + "compact RLE arithmetic is typically slower than the dense NumPy path" + " — synthetic-dense-64 shows this adversarial regime (speedup < 1x)", + "OK means compact.to_dense() exactly matches dense masks", + ] + ) + + "[/dim]" + ) + + +def main() -> None: + """Run the benchmark.""" + parser = argparse.ArgumentParser() + parser.add_argument("--asset", choices=ASSETS.keys(), default=None) + parser.add_argument("--image", type=Path, default=None) + args = parser.parse_args() + + assets = [args.asset] if args.asset is not None else list(ASSETS) + if args.image is not None: + assets = ["custom"] + + results = [] + if args.asset is None and args.image is None: + image, source, inference_result = synthetic_dense_small_result() + console.rule(f"[bold]{source}[/bold] | {image.shape[1]}x{image.shape[0]}") + results.append( + run_benchmark( + source=source, + image=image, + result=inference_result, + reps=REPETITIONS, + warmup=WARMUP, + ) + ) + model_id = os.getenv(MODEL_ID_ENV, MODEL_ID) + model = load_inference_model(model_id=model_id, api_key=os.getenv(API_KEY_ENV)) + for asset in assets: + image, source = load_image_from_asset(args.image, asset) + console.rule(f"[bold]{source}[/bold] | {image.shape[1]}x{image.shape[0]}") + inference_result = run_inference_once( + image=image, + model=model, + model_id=model_id, + confidence=CONFIDENCE, + iou=IOU, + ) + if inference_result is None: + continue + console.print( + f"[dim]captured {count_rle_predictions(inference_result)} RLE masks " + f"from {model_id}[/dim]" + ) + artifact = save_segmentation_artifact( + image=image, + result=inference_result, + source=source, + ) + if artifact is not None: + console.print(f"[dim]saved segmentation artifact: {artifact}[/dim]") + results.append( + run_benchmark( + source=source, + image=image, + result=inference_result, + reps=REPETITIONS, + warmup=WARMUP, + ) + ) + if not results: + raise ValueError(f"Model {model_id!r} returned no segmentation masks.") + print_summary(results, reps=REPETITIONS, warmup=WARMUP) + + +if __name__ == "__main__": + main() diff --git a/src/supervision/detection/compact_mask.py b/src/supervision/detection/compact_mask.py index 9244159e..ab7b0d7e 100644 --- a/src/supervision/detection/compact_mask.py +++ b/src/supervision/detection/compact_mask.py @@ -7,18 +7,28 @@ bounding-box crop, reducing typical usage to tens of MB. The bounding boxes (``xyxy``) already present in ``Detections`` serve as the crop boundaries, so no extra metadata is required from the caller. + +CompactMask reduces memory footprint but does not improve computational +speed. The ingestion path (base48 decode, column split, RLE trim) is +Python-level and is typically slower than the dense NumPy path. The primary +benefit is memory savings for large images with many sparse masks. """ from __future__ import annotations import os -from collections.abc import Iterator -from typing import cast, overload +from collections.abc import Iterator, Mapping, Sequence +from typing import Any, cast, overload import numpy as np import numpy.typing as npt +# _base48_decode and _delta_decode are private to the COCO RLE codec. They +# live in converters.py and are shared by public conversion helpers here and +# in that module. from supervision.detection.utils.converters import ( + _base48_decode, + _delta_decode, _mask_to_rle_counts, _rle_counts_to_mask, ) @@ -50,6 +60,8 @@ def _rle_split_cols( rle: npt.NDArray[np.int32], crop_h: int, crop_w: int, + x_start: int = 0, + x_stop: int | None = None, ) -> list[list[int]]: """Split a flat F-order RLE into per-column run lists. @@ -61,15 +73,31 @@ def _rle_split_cols( returned list starts with a ``False``-run count (possibly 0), matching the convention of :func:`_mask_to_rle_counts`. + When ``x_start`` and ``x_stop`` are provided, only columns in the closed + range ``[x_start, x_stop]`` are collected. Pixels in skipped columns + are consumed without being stored, which avoids O(W) allocation when + only a small crop of a wide image is needed. + + Note: + ``x_start`` uses ``np.cumsum`` + ``np.searchsorted`` to jump directly + to the first relevant run in O(log R) time, avoiding the O(pixel_prefix) + walk that previously made right-edge crops on wide images expensive. + Args: rle: int32 run-length array as produced by :func:`~supervision.detection.utils.converters._mask_to_rle_counts`. crop_h: Number of rows (pixels per column). crop_w: Number of columns. + x_start: First column to collect (0-indexed, inclusive). Columns + before ``x_start`` are skipped. Defaults to ``0``. + x_stop: Last column to collect (0-indexed, inclusive). Processing + stops after column ``x_stop`` is complete. Defaults to + ``crop_w - 1`` (collect all columns). Returns: - List of ``crop_w`` run lists, one per column. Each list sums to - ``crop_h``. + List of ``x_stop - x_start + 1`` run lists. Index ``i`` in the + returned list corresponds to column ``x_start + i``. Each list + sums to ``crop_h``. Examples: ```pycon @@ -82,43 +110,76 @@ def _rle_split_cols( [0, 2, 1, 1] >>> _rle_split_cols(rle, 2, 2) [[0, 2], [1, 1]] + >>> _rle_split_cols(rle, 2, 2, x_start=1) + [[1, 1]] ``` """ - per_col: list[list[int]] = [[] for _ in range(crop_w)] - col = 0 - row = 0 + if x_stop is None: + x_stop = crop_w - 1 - for run_idx, run_len in enumerate(rle): + # Convert numpy int32 array to Python ints to avoid scalar boxing overhead + # in the inner loop (np.int32 boxing/unboxing slows pure-Python loops). + rle_list: list[int] = rle.tolist() + + n_cols = x_stop - x_start + 1 + per_col: list[list[int]] = [[] for _ in range(n_cols)] + + # Fast-forward to the first run that overlaps column x_start using O(log R) + # searchsorted instead of an O(pixel_prefix) sequential walk. + start_pixel = x_start * crop_h + if start_pixel > 0 and len(rle_list) > 0: + cumsum_ends = np.cumsum(rle, dtype=np.int64) + first_run = int(np.searchsorted(cumsum_ends, start_pixel, side="right")) + if first_run >= len(rle_list): + for c in range(n_cols): + per_col[c] = [crop_h] + return per_col + prefix = int(cumsum_ends[first_run - 1]) if first_run > 0 else 0 + else: + first_run = 0 + prefix = 0 + + col = prefix // crop_h + row = prefix % crop_h + + for run_idx in range(first_run, len(rle_list)): + run_len = rle_list[run_idx] is_true = run_idx % 2 == 1 - remaining = int(run_len) + remaining = run_len while remaining > 0: + # Past the requested range — stop early. + if col > x_stop: + remaining = 0 + break space_in_col = crop_h - row take = min(remaining, space_in_col) - if len(per_col[col]) == 0: - if is_true: - per_col[col].append(0) # leading False count = 0 - # Check if last run has same parity (True/False) as current chunk. - # Last element's parity: index (len-1) odd → True, even → False. - elif is_true == ((len(per_col[col]) - 1) % 2 == 1): - per_col[col][-1] += take - remaining -= take - row += take - if row >= crop_h: - row = 0 - col += 1 - continue - per_col[col].append(take) + if col >= x_start: + local_col = col - x_start + if len(per_col[local_col]) == 0: + if is_true: + per_col[local_col].append(0) # leading False count = 0 + # Check if last run has same parity (True/False) as current chunk. + # Last element's parity: index (len-1) odd → True, even → False. + elif is_true == ((len(per_col[local_col]) - 1) % 2 == 1): + per_col[local_col][-1] += take + remaining -= take + row += take + if row >= crop_h: + row = 0 + col += 1 + continue + per_col[local_col].append(take) remaining -= take row += take if row >= crop_h: row = 0 col += 1 - if col >= crop_w: + if col > x_stop: break # Fill any empty columns (all-False). - for c in range(crop_w): + for c in range(n_cols): if not per_col[c]: per_col[c] = [crop_h] @@ -246,6 +307,113 @@ def _rle_join_cols( return np.array(output_runs if output_runs else [new_total], dtype=np.int32) +def _rle_trim_col_runs(col_runs: Sequence[int], y1: int, y2: int) -> list[int]: + """Restrict one full-height column RLE to inclusive rows ``[y1, y2]``. + + Args: + col_runs: Run lengths for one full-height column, starting with a + ``False`` run. + y1: Inclusive top row of the crop. + y2: Inclusive bottom row of the crop. + + Returns: + Run lengths for the cropped column, also starting with a ``False`` run. + + Examples: + ```pycon + >>> from supervision.detection.compact_mask import _rle_trim_col_runs + >>> # Full column F=2, T=2, F=2 (height 6); crop to rows 1..4 inclusive + >>> # yields rows [F, T, T, F] → F=1, T=2, F=1. + >>> _rle_trim_col_runs([2, 2, 2], y1=1, y2=4) + [1, 2, 1] + + ``` + """ + target_height = y2 - y1 + 1 + # Sum invariant: returned list sums to target_height. Correctness depends + # on the caller (from_coco_rle) having already validated that counts sum + # equals img_h * img_w; no re-validation here. + collected: list[tuple[bool, int]] = [] + row = 0 + for run_idx, run_len in enumerate(col_runs): + is_true = run_idx % 2 == 1 + start = row + end = row + int(run_len) + row = end + + crop_start = max(start, y1) + crop_end = min(end, y2 + 1) + if crop_end > crop_start: + collected.append((is_true, crop_end - crop_start)) + if row > y2: + break + + if not collected: + return [target_height] + + result: list[int] = [] + if collected[0][0]: + result.append(0) + for is_true, length in collected: + last_is_true = bool(result) and (len(result) - 1) % 2 == 1 + if result and last_is_true == is_true: + result[-1] += length + else: + result.append(length) + return result + + +def _coco_rle_counts_to_array(counts: Any) -> npt.NDArray[np.int32]: + """Decode COCO RLE counts into absolute F-order run lengths. + + Args: + counts: COCO compressed counts (``str`` or ``bytes``), or uncompressed + integer run lengths. + + Returns: + One-dimensional ``int32`` run-length array. + + Raises: + ValueError: If counts cannot be decoded into non-negative run lengths. + + Examples: + ```pycon + >>> from supervision.detection.compact_mask import _coco_rle_counts_to_array + >>> _coco_rle_counts_to_array([0, 2, 2, 2, 10]) + array([ 0, 2, 2, 2, 10], dtype=int32) + + ``` + """ + try: + if isinstance(counts, bytes): + counts = counts.decode("utf-8") + if isinstance(counts, str): + decoded_counts = _delta_decode(_base48_decode(counts)) + counts_arr = np.array(decoded_counts, dtype=np.int32) + else: + # Convert to int64 first, then range-check against int32 bounds before + # narrowing. A direct int32 cast wraps silently on some numpy versions + # and raises on others; this makes overflow detection deterministic. + counts_arr64 = np.asarray(counts, dtype=np.int64) + int32_info = np.iinfo(np.int32) + if counts_arr64.size and ( + counts_arr64.max() > int32_info.max + or counts_arr64.min() < int32_info.min + ): + raise ValueError("COCO RLE counts exceed int32 range.") + counts_arr = counts_arr64.astype(np.int32) + except (TypeError, ValueError, OverflowError) as exc: + raise ValueError("Invalid COCO RLE counts.") from exc + + if counts_arr.ndim != 1: + raise ValueError("COCO RLE counts must be one-dimensional.") + if counts_arr.size == 0: + raise ValueError("COCO RLE counts cannot be empty.") + if np.any(counts_arr < 0): + raise ValueError("COCO RLE counts must be non-negative.") + return counts_arr + + def _rle_resize( rle: npt.NDArray[np.int32], crop_h: int, @@ -323,10 +491,10 @@ def _rle_resize( col_cache: dict[int, list[int]] = {} scaled_cols = [] for src_c in col_map: - src_c_int = int(src_c) - if src_c_int not in col_cache: - col_cache[src_c_int] = _rle_scale_col(per_col[src_c_int], crop_h, row_map) - scaled_cols.append(col_cache[src_c_int]) + src_col = int(src_c) + if src_col not in col_cache: + col_cache[src_col] = _rle_scale_col(per_col[src_col], crop_h, row_map) + scaled_cols.append(col_cache[src_col]) return _rle_join_cols(scaled_cols, new_total) @@ -337,6 +505,13 @@ def _rle_resize( _L3_DENSITY_THRESHOLD: float = 0.25 # Thread overhead outweighs gains below this mask count. _PARALLEL_THRESHOLD: int = 8 +# Hard ceiling on each image dimension accepted by from_coco_rle, guarding +# against crafted payloads that allocate O(H x W) column lists. +_MAX_IMAGE_DIMENSION: int = 32768 +# Images at or below this pixel count use a fully-vectorised numpy dense-decode +# path inside from_coco_rle instead of the pure-Python column-split loop. +# Crossover measured at ~8-16 K px (128x128); threshold set at 128x128 = 16 384. +_SMALL_IMAGE_DENSE_THRESHOLD: int = 128 * 128 def _resize_crop( @@ -526,21 +701,29 @@ class CompactMask: for mask_idx in range(num_masks): x1, y1, x2, y2 = xyxy[mask_idx] - x1c = int(max(0, min(int(x1), img_w - 1))) - y1c = int(max(0, min(int(y1), img_h - 1))) - x2c = int(max(0, min(int(x2), img_w - 1))) - y2c = int(max(0, min(int(y2), img_h - 1))) + x1i, y1i, x2i, y2i = int(x1), int(y1), int(x2), int(y2) + x1c = int(max(0, min(x1i, img_w - 1))) + y1c = int(max(0, min(y1i, img_h - 1))) crop: npt.NDArray[np.bool_] # supervision xyxy uses inclusive max coords, so slicing must add +1. - if x2c < x1c or y2c < y1c: + if ( + x2i < x1i + or y2i < y1i + or x2i < 0 + or y2i < 0 + or x1i >= img_w + or y1i >= img_h + ): crop = np.zeros((1, 1), dtype=bool) - x2c, y2c = x1c, y1c + crop_h = 1 + crop_w = 1 else: + x2c = int(max(0, min(x2i, img_w - 1))) + y2c = int(max(0, min(y2i, img_h - 1))) crop = masks[mask_idx, y1c : y2c + 1, x1c : x2c + 1] - - crop_h = y2c - y1c + 1 - crop_w = x2c - x1c + 1 + crop_h = y2c - y1c + 1 + crop_w = x2c - x1c + 1 rles.append(_mask_to_rle_counts(crop)) crop_shapes_list.append((crop_h, crop_w)) offsets_list.append((x1c, y1c)) @@ -549,6 +732,170 @@ class CompactMask: offsets = np.array(offsets_list, dtype=np.int32) return cls(rles, crop_shapes, offsets, image_shape) + @classmethod + def from_coco_rle( + cls, + rles: Sequence[Mapping[str, Any]], + xyxy: npt.NDArray[np.floating], + image_shape: tuple[int, int], + ) -> CompactMask: + """Create a :class:`CompactMask` from full-frame COCO RLE masks. + + Transcodes full-image COCO RLE payloads into the crop-scoped RLE format + used by :class:`CompactMask`. The conversion uses run-length arithmetic + scoped by ``xyxy`` boxes and does not materialise a dense ``(N, H, W)`` + mask stack. + + Args: + rles: Sequence of COCO RLE dictionaries. Each dictionary must contain + ``"size"`` as ``[height, width]`` and ``"counts"`` as compressed + counts (``str`` or ``bytes``) or uncompressed integer run lengths. + xyxy: Bounding boxes of shape ``(N, 4)`` in ``[x1, y1, x2, y2]`` + format. Max coordinates follow supervision's inclusive convention. + image_shape: ``(H, W)`` of the full image. This must match every RLE + ``"size"`` value. + + Returns: + A new :class:`CompactMask` instance. + + Raises: + ValueError: If the RLE payloads are malformed, are not aligned with + ``xyxy``, or their sizes/counts do not match ``image_shape``. + + Examples: + ```pycon + >>> import numpy as np + >>> from supervision.detection.compact_mask import CompactMask + >>> # 4x4 image with a 2x2 True block at the top-left corner. + >>> # Uncompressed F-order COCO counts: F=0, T=2, F=2, T=2, F=10 + >>> # (column-major: col0=[T,T,F,F], col1=[T,T,F,F], cols2-3 all F). + >>> rles = [{"size": [4, 4], "counts": [0, 2, 2, 2, 10]}] + >>> xyxy = np.array([[0, 0, 3, 3]], dtype=np.float32) + >>> cm = CompactMask.from_coco_rle(rles, xyxy, image_shape=(4, 4)) + >>> cm.shape + (1, 4, 4) + >>> cm.area.tolist() + [4] + + ``` + """ + img_h, img_w = (int(image_shape[0]), int(image_shape[1])) + if img_h <= 0 or img_w <= 0: + raise ValueError("image_shape must contain positive height and width.") + if img_h > _MAX_IMAGE_DIMENSION or img_w > _MAX_IMAGE_DIMENSION: + raise ValueError( + f"image_shape {(img_h, img_w)} exceeds the maximum allowed dimension " + f"of {_MAX_IMAGE_DIMENSION} pixels per side." + ) + + xyxy_arr = np.asarray(xyxy) + if xyxy_arr.shape != (len(rles), 4): + raise ValueError( + "xyxy must have shape (N, 4), where N matches the number of RLEs." + ) + + if len(rles) == 0: + return cls( + [], + np.empty((0, 2), dtype=np.int32), + np.empty((0, 2), dtype=np.int32), + (img_h, img_w), + ) + + crop_rles: list[npt.NDArray[np.int32]] = [] + crop_shapes_list: list[tuple[int, int]] = [] + offsets_list: list[tuple[int, int]] = [] + + for mask_idx, rle in enumerate(rles): + if not isinstance(rle, Mapping): + raise ValueError("Each RLE payload must be a mapping.") + if "size" not in rle or "counts" not in rle: + raise ValueError("Each RLE payload must contain 'size' and 'counts'.") + + try: + # COCO standard: size=[height, width] (h,w order per pycocotools spec) + rle_h, rle_w = rle["size"] + rle_h = int(rle_h) + rle_w = int(rle_w) + except (TypeError, ValueError) as exc: + raise ValueError("RLE size must be [height, width].") from exc + + if (rle_h, rle_w) != (img_h, img_w): + raise ValueError( + f"RLE size {(rle_h, rle_w)} must match image_shape " + f"{(img_h, img_w)}." + ) + + counts = _coco_rle_counts_to_array(rle["counts"]) + if int(np.sum(counts, dtype=np.int64)) != img_h * img_w: + raise ValueError( + "The sum of COCO RLE counts must match the image area." + ) + + x1, y1, x2, y2 = xyxy_arr[mask_idx] + x1i, y1i, x2i, y2i = int(x1), int(y1), int(x2), int(y2) + x1c = max(0, min(x1i, img_w - 1)) + y1c = max(0, min(y1i, img_h - 1)) + + if ( + x2i < x1i + or y2i < y1i + or x2i < 0 + or y2i < 0 + or x1i >= img_w + or y1i >= img_h + ): + crop_rles.append(np.array([1], dtype=np.int32)) + crop_shapes_list.append((1, 1)) + offsets_list.append((x1c, y1c)) + continue + + x2c = max(0, min(x2i, img_w - 1)) + y2c = max(0, min(y2i, img_h - 1)) + crop_h = y2c - y1c + 1 + crop_w = x2c - x1c + 1 + + if img_h * img_w <= _SMALL_IMAGE_DENSE_THRESHOLD: + # Small image: vectorised numpy decode avoids the O(img_w)-column + # Python loop. Decode RLE to flat F-order bool, extract crop, and + # re-encode directly. + ends = np.cumsum(counts, dtype=np.int64) + starts = ends - counts.astype(np.int64) + # Mark True runs (odd-indexed) via difference-array decode (O(R)). + true_starts = starts[1::2] + true_ends = ends[1::2] + if true_starts.size > 0: + indicator = np.zeros(img_h * img_w + 1, dtype=np.int32) + np.add.at(indicator, true_starts, 1) + np.add.at(indicator, true_ends, -1) + # cumsum in int32 avoids int8 overflow; cast to uint8 (0/1). + flat = np.cumsum(indicator[:-1], dtype=np.int32).astype(np.uint8) + else: + flat = np.zeros(img_h * img_w, dtype=np.uint8) + # Extract crop: reshape to (img_w, img_h) F-order view, slice. + flat_crop = flat.reshape(img_w, img_h)[ + x1c : x2c + 1, y1c : y2c + 1 + ].ravel() + # RLE-encode the flat crop: find value-change positions. + change_pos = np.where(np.diff(flat_crop.view(np.int8)))[0] + 1 + boundaries = np.concatenate([[0], change_pos, [len(flat_crop)]]) + run_lens = np.diff(boundaries) + if flat_crop[0]: + run_lens = np.concatenate([[0], run_lens]) + crop_rle_arr = run_lens.astype(np.int32) + else: + cols = _rle_split_cols(counts, img_h, img_w, x_start=x1c, x_stop=x2c) + selected_columns = [_rle_trim_col_runs(col, y1c, y2c) for col in cols] + crop_rle_arr = _rle_join_cols(selected_columns, crop_h * crop_w) + + crop_rles.append(crop_rle_arr) + crop_shapes_list.append((crop_h, crop_w)) + offsets_list.append((x1c, y1c)) + + crop_shapes = np.array(crop_shapes_list, dtype=np.int32) + offsets = np.array(offsets_list, dtype=np.int32) + return cls(crop_rles, crop_shapes, offsets, (img_h, img_w)) + # ------------------------------------------------------------------ # Materialisation # ------------------------------------------------------------------ @@ -745,6 +1092,12 @@ class CompactMask: def area(self) -> npt.NDArray[np.int64]: """Compute the area (``True`` pixel count) of each mask. + Note: + The implementation iterates over the N individual RLE arrays in a + Python loop (one :func:`_rle_area` call per mask). This is negligible + for typical N, but callers processing thousands of detections per + frame should be aware of the per-mask Python-level overhead. + Returns: int64 array of shape ``(N,)`` with per-mask pixel counts. diff --git a/src/supervision/detection/core.py b/src/supervision/detection/core.py index f629e96e..6ae2bad2 100644 --- a/src/supervision/detection/core.py +++ b/src/supervision/detection/core.py @@ -645,7 +645,12 @@ class Detections: ) @classmethod - def from_inference(cls, roboflow_result: dict[str, Any] | Any) -> Detections: + def from_inference( + cls, + roboflow_result: dict[str, Any] | Any, + *, + compact_masks: bool = False, + ) -> Detections: """ Create a `sv.Detections` object from the [Roboflow](https://roboflow.com/) API inference result or the [Inference](https://inference.roboflow.com/) @@ -656,6 +661,31 @@ class Detections: Args: roboflow_result: The result from the Roboflow API or Inference package containing predictions. + compact_masks: When `True`, return segmentation masks as + :class:`~supervision.detection.compact_mask.CompactMask`. + The default `False` preserves the existing dense NumPy mask + representation. + + Warning: + When `compact_masks=True`, the crop policy depends on how + each prediction encodes its mask: + + - Native size-matched COCO-RLE (the RLE `size` equals the + image size) is **cropped to the detector bounding box** + (`xyxy`). For instance-segmentation models the detector + box may not tightly bound the mask, so pixels beyond the + box boundary are silently dropped. + - Polygon-derived masks (`points`) and size-mismatched + COCO-RLE masks (decoded, then resized to the image) are + retained **full-frame** and lose no pixels. + + Because only the box-cropped path is lossy, + `from_inference(r)` and + `from_inference(r, compact_masks=True)` can return masks + with different areas and IoU **only** for native + size-matched COCO-RLE predictions. Use `compact_masks=True` + only when the memory savings outweigh the boundary loss on + that path. Returns: A Detections object containing the bounding boxes, class IDs, @@ -666,10 +696,14 @@ class Detections: or absent. `detections.tracker_id` is `None` when no predictions carry a tracker ID, or when only a subset do (mixed batch) — in that case all tracker IDs are dropped to - preserve alignment with the bounding boxes. + preserve alignment with the bounding boxes. Similarly, `detections.mask` is `None` when no predictions include mask - data, or when only a subset do (mixed batch) — in that case - all masks are dropped to preserve alignment. + data, or when only a subset carry masks — all masks are dropped + to preserve xyxy alignment. + When `compact_masks=True` and all predictions carry mask data, + `detections.mask` is a + :class:`~supervision.detection.compact_mask.CompactMask` rather + than a dense boolean array. Example: ```python @@ -682,15 +716,29 @@ class Detections: result = model.infer(image)[0] detections = sv.Detections.from_inference(result) + compact_detections = sv.Detections.from_inference( + result, compact_masks=True + ) ``` """ if hasattr(roboflow_result, "dict"): roboflow_result = roboflow_result.dict(exclude_none=True, by_alias=True) elif hasattr(roboflow_result, "json"): roboflow_result = roboflow_result.json() - xyxy, confidence, class_id, masks, trackers, data = process_roboflow_result( - roboflow_result=roboflow_result - ) + masks: npt.NDArray[np.bool_] | CompactMask | None + # Design note (ADR): the `compact_masks` flag changes the runtime type of + # `detections.mask` from `NDArray[bool_]` to `CompactMask`, so every mask + # consumer must branch on `isinstance(detections.mask, CompactMask)`. A + # typed factory / `mask_format=` enum would be cleaner but would require a + # deprecation cycle if introduced later. + if compact_masks: + xyxy, confidence, class_id, masks, trackers, data = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + else: + xyxy, confidence, class_id, masks, trackers, data = process_roboflow_result( + roboflow_result=roboflow_result + ) if np.asarray(xyxy).shape[0] == 0: empty_detection = cls.empty() @@ -2540,6 +2588,68 @@ class Detections: np.divide(widths, heights, out=aspect_ratios, where=heights != 0) return aspect_ratios + def to_compact_masks(self) -> Detections: + """Return a copy of this Detections with masks converted to CompactMask. + + The dense :attr:`mask` field (``NDArray[np.bool_]``) is converted to a + :class:`~supervision.detection.compact_mask.CompactMask` without changing + mask pixels. When :attr:`mask` is already a + :class:`~supervision.detection.compact_mask.CompactMask` or is ``None``, + the instance is returned unchanged. + + Note: + The crop boundaries are set to the **full image dimensions**, not the + detector bounding box. No bbox-crop memory savings apply: the RLE + sparsity still reduces storage versus a dense array, but the + ``O(bbox_area)`` savings available from + ``from_inference(..., compact_masks=True)`` are absent here because + every crop spans the whole frame. Call + :meth:`~supervision.detection.compact_mask.CompactMask.repack` on the + resulting mask to tighten crops to their bounding boxes, at the cost + of potential pixel loss outside those boxes. + + Returns: + A new :class:`Detections` instance with ``mask`` set to a + :class:`~supervision.detection.compact_mask.CompactMask`, or ``self`` + when conversion is not needed. + + Example: + ```python + import numpy as np + import supervision as sv + detections = sv.Detections( + xyxy=np.array([[0, 0, 10, 10]]), + mask=np.ones((1, 20, 20), dtype=bool), + ) + compact = detections.to_compact_masks() + ``` + """ + from supervision.detection.compact_mask import CompactMask + + if self.mask is None or isinstance(self.mask, CompactMask): + return self + image_shape = (int(self.mask.shape[1]), int(self.mask.shape[2])) + full_image_xyxy = np.tile( + np.array( + [[0, 0, image_shape[1] - 1, image_shape[0] - 1]], dtype=np.float64 + ), + (len(self), 1), + ) + new = self.__class__( + xyxy=self.xyxy, + mask=CompactMask.from_dense( + masks=self.mask, + xyxy=full_image_xyxy, + image_shape=image_shape, + ), + confidence=self.confidence, + class_id=self.class_id, + tracker_id=self.tracker_id, + data=self.data, + metadata=self.metadata, + ) + return new + def with_nms( self, threshold: float = 0.5, diff --git a/src/supervision/detection/tools/inference_slicer.py b/src/supervision/detection/tools/inference_slicer.py index ee40d4ab..d0a793ae 100644 --- a/src/supervision/detection/tools/inference_slicer.py +++ b/src/supervision/detection/tools/inference_slicer.py @@ -154,6 +154,11 @@ class InferenceSlicer: objects. IoU and NMS are computed directly on the RLE crops without ever materialising a full ``(N, H, W)`` array. Defaults to ``False`` for backward compatibility. + + When ``compact_masks=True``, each detection's CompactMask crop spans + the entire slice tile bbox (not the tight detection bbox). Call + :meth:`~supervision.detection.compact_mask.CompactMask.repack` on the + merged result to tighten crops to the detection bounding boxes. batch_size: Number of slices passed to the callback per call. Defaults to ``1``, which uses the single-image callback contract (``np.ndarray`` → :class:`~supervision.detection.core.Detections`). @@ -500,9 +505,13 @@ class InferenceSlicer: and isinstance(detections.mask, np.ndarray) ): slice_w, slice_h = get_image_resolution_wh(image_slice) + full_slice_xyxy = np.tile( + np.array([[0, 0, slice_w - 1, slice_h - 1]], dtype=np.float64), + (len(detections), 1), + ) detections.mask = CompactMask.from_dense( detections.mask, - detections.xyxy, + full_slice_xyxy, image_shape=(slice_h, slice_w), ) @@ -586,9 +595,13 @@ class InferenceSlicer: for det, image_slice in zip(detections_in_slices, slices): if det.mask is not None and isinstance(det.mask, np.ndarray): slice_w, slice_h = get_image_resolution_wh(image_slice) + full_slice_xyxy = np.tile( + np.array([[0, 0, slice_w - 1, slice_h - 1]], dtype=np.float64), + (len(det), 1), + ) det.mask = CompactMask.from_dense( det.mask, - det.xyxy, + full_slice_xyxy, image_shape=(slice_h, slice_w), ) diff --git a/src/supervision/detection/utils/converters.py b/src/supervision/detection/utils/converters.py index 764b9678..19d954de 100644 --- a/src/supervision/detection/utils/converters.py +++ b/src/supervision/detection/utils/converters.py @@ -434,10 +434,15 @@ def _delta_decode(values: list[int]) -> list[int]: ``` """ - counts = list(values) - for i in range(3, len(counts)): - counts[i] += counts[i - 2] - return counts + # The recurrence ``counts[i] += counts[i - 2]`` for ``i >= 3`` decomposes + # into two independent stride-2 chains: the odd indices (1, 3, 5, ...) and + # the even indices from 2 onward (2, 4, 6, ...). A cumulative sum over each + # chain recovers the absolute counts. Index 0 is absolute and untouched. + # int64 accumulation avoids overflow; ``tolist`` returns native Python ints. + counts = np.asarray(values, dtype=np.int64) + counts[1::2] = np.cumsum(counts[1::2]) + counts[2::2] = np.cumsum(counts[2::2]) + return cast("list[int]", counts.tolist()) def _delta_encode(counts: list[int]) -> list[int]: diff --git a/src/supervision/detection/utils/internal.py b/src/supervision/detection/utils/internal.py index ed84b5cc..6e303f30 100644 --- a/src/supervision/detection/utils/internal.py +++ b/src/supervision/detection/utils/internal.py @@ -1,12 +1,13 @@ import logging from itertools import chain -from typing import Any, cast +from typing import Any, Literal, cast, overload import cv2 import numpy as np import numpy.typing as npt from supervision.config import CLASS_NAME_DATA_FIELD +from supervision.detection.compact_mask import CompactMask from supervision.detection.utils._typing import _DetectionDataType, _MetadataType from supervision.detection.utils.converters import polygon_to_mask, rle_to_mask from supervision.geometry.core import Vector @@ -14,6 +15,28 @@ from supervision.geometry.core import Vector logger = logging.getLogger(__name__) +def _full_image_xyxy( + count: int, + image_height: int, + image_width: int, + dtype: npt.DTypeLike = np.float64, +) -> npt.NDArray[Any]: + """Return full-frame inclusive boxes for lossless mask compaction.""" + return np.tile( + np.array([[0, 0, image_width - 1, image_height - 1]], dtype=dtype), + (count, 1), + ) + + +def _valid_rle_payload(prediction: dict[str, Any]) -> dict[str, Any] | None: + """Return the first valid RLE payload from ``rle`` then ``rle_mask``.""" + for key in ("rle", "rle_mask"): + rle_data = prediction.get(key) + if isinstance(rle_data, dict) and {"size", "counts"}.issubset(rle_data): + return rle_data + return None + + def extract_ultralytics_masks(yolov8_results: Any) -> npt.NDArray[np.bool_] | None: if not yolov8_results.masks: return None @@ -50,6 +73,60 @@ def extract_ultralytics_masks(yolov8_results: Any) -> npt.NDArray[np.bool_] | No return cast(npt.NDArray[np.bool_], np.asarray(mask_maps, dtype=bool)) +def _resolve_rle_mask( + rle_data: dict[str, Any], + image_height: int, + image_width: int, + compact_masks: bool, +) -> tuple[npt.NDArray[np.bool_] | None, dict[str, Any] | None]: + """Decode one RLE prediction into (dense_mask, compact_pending). + + Returns ``(dense_mask, None)`` when ``compact_masks=False`` or when the + RLE size does not match the image size (fall back to dense decode). + Returns ``(None, rle_data)`` when ``compact_masks=True`` and the RLE size + matches, deferring the item to the post-loop batch call. + Returns ``(None, None)`` on decode failure (caller should skip mask). + + Args: + rle_data: Validated COCO RLE dict with ``"size"`` and ``"counts"`` keys. + image_height: Full-image height in pixels. + image_width: Full-image width in pixels. + compact_masks: Whether to return a deferred item for batch processing. + + Returns: + A 2-tuple ``(dense_mask, pending)`` where at most one element is + non-``None``. + """ + try: + h, w = rle_data["size"] + if compact_masks and (h, w) == (image_height, image_width): + # Sizes match; defer to the post-loop CompactMask.from_coco_rle call. + return None, rle_data + if compact_masks and (h, w) != (image_height, image_width): + logger.debug( + "compact_masks=True: RLE size %s does not match image " + "size (%d, %d); falling back to dense decode.", + (h, w), + image_height, + image_width, + ) + mask: npt.NDArray[np.bool_] = rle_to_mask(rle_data["counts"], (w, h)) + if (h, w) != (image_height, image_width): + mask = cv2.resize( + mask.astype(np.uint8), + (image_width, image_height), + interpolation=cv2.INTER_NEAREST, + ).astype(bool) + return mask, None + except (ValueError, AssertionError, KeyError, TypeError, OverflowError) as exc: + logger.warning( + "Failed to decode RLE mask payload; falling back to box-only " + "detection. Reason: %s", + exc, + ) + return None, None + + def _all_present_or_none( values: list[Any], label: str, @@ -67,8 +144,100 @@ def _all_present_or_none( return np.array(values, dtype=dtype) +def _decode_compact_masks( + coco_rle_pending: list[tuple[int, Any, list[float]]], + polygon_compact_map: dict[int, CompactMask], + image_height: int, + image_width: int, + n_predictions: int, +) -> CompactMask | None: + """Decode deferred COCO-RLE entries and merge with polygon compact masks. + + Attempts a single batched ``CompactMask.from_coco_rle`` call for all pending + items to eliminate per-prediction call overhead on the happy path. On any + decode failure the call is retried per-prediction so that one malformed RLE + payload does not abort the entire batch. + + Isolation note: this function isolates the *decode* step only. If the + per-prediction fallback still leaves some predictions without masks, the + mixed-modality guard drops ALL masks to preserve alignment with ``xyxy``. + + Args: + coco_rle_pending: Deferred COCO-RLE items collected during the prediction + loop, each as ``(xyxy_idx, rle_dict, bbox)``. + polygon_compact_map: Already-decoded polygon masks keyed by ``xyxy_idx``. + image_height: Frame height in pixels. + image_width: Frame width in pixels. + n_predictions: Total number of accepted predictions; used by the + mixed-modality alignment guard. + + Returns: + A merged ``CompactMask`` when all predictions that carry masks decoded + successfully, or ``None`` when no masks are present or the + mixed-modality guard triggers. + + Examples: + >>> _decode_compact_masks([], {}, 1080, 1920, 5) is None + True + """ + coco_compact_map: dict[int, CompactMask] = {} + if coco_rle_pending: + pending_indices = [t[0] for t in coco_rle_pending] + pending_rles = [t[1] for t in coco_rle_pending] + pending_xyxy = np.array([t[2] for t in coco_rle_pending], dtype=np.float64) + try: + batch_cm = CompactMask.from_coco_rle( + pending_rles, pending_xyxy, (image_height, image_width) + ) + for local_idx, global_idx in enumerate(pending_indices): + coco_compact_map[global_idx] = batch_cm[local_idx : local_idx + 1] + except (ValueError, AssertionError, KeyError, TypeError, OverflowError) as exc: + logger.warning( + "Batch compact RLE decode failed (%s); retrying " + "per-prediction for fault isolation.", + exc, + ) + for xyxy_idx, rle_dict, bbox in coco_rle_pending: + try: + single_cm = CompactMask.from_coco_rle( + [rle_dict], + np.array([bbox], dtype=np.float64), + (image_height, image_width), + ) + coco_compact_map[xyxy_idx] = single_cm[0:1] + except ( + ValueError, + AssertionError, + KeyError, + TypeError, + OverflowError, + ) as per_exc: + logger.warning( + "Compact RLE decode failed for prediction at index %d; " + "dropping that mask. Reason: %s", + xyxy_idx, + per_exc, + ) + all_compact = {**coco_compact_map, **polygon_compact_map} + compact_parts: list[CompactMask] = [ + all_compact[i] for i in sorted(all_compact.keys()) + ] + if 0 < len(compact_parts) < n_predictions: + logger.warning( + "Mixed-modality compact batch: %d of %d predictions carry masks; " + "dropping all masks to preserve alignment with xyxy.", + len(compact_parts), + n_predictions, + ) + compact_parts = [] + return CompactMask.merge(compact_parts) if compact_parts else None + + +@overload def process_roboflow_result( roboflow_result: dict[str, Any], + *, + compact_masks: Literal[False] = False, ) -> tuple[ npt.NDArray[np.floating], npt.NDArray[np.floating], @@ -76,6 +245,35 @@ def process_roboflow_result( npt.NDArray[np.bool_] | None, npt.NDArray[np.integer] | None, _DetectionDataType, +]: ... + + +@overload +def process_roboflow_result( + roboflow_result: dict[str, Any], + *, + compact_masks: Literal[True], +) -> tuple[ + npt.NDArray[np.floating], + npt.NDArray[np.floating], + npt.NDArray[np.integer], + CompactMask | None, + npt.NDArray[np.integer] | None, + _DetectionDataType, +]: ... + + +def process_roboflow_result( + roboflow_result: dict[str, Any], + *, + compact_masks: bool = False, +) -> tuple[ + npt.NDArray[np.floating], + npt.NDArray[np.floating], + npt.NDArray[np.integer], + npt.NDArray[np.bool_] | CompactMask | None, + npt.NDArray[np.integer] | None, + _DetectionDataType, ]: """Parse a Roboflow API or Inference package result into detection arrays. @@ -87,18 +285,20 @@ def process_roboflow_result( Args: roboflow_result: Raw dict from the Roboflow REST API or the Inference package (after ``.dict()`` serialisation). + compact_masks: When ``True``, return segmentation masks as + :class:`~supervision.detection.compact_mask.CompactMask` instead of + a dense boolean array when mask data is present. Returns: A 6-tuple of ``(xyxy, confidence, class_id, masks, tracker_ids, data)`` where each array is aligned with the others. ``masks`` is ``None`` when no predictions include mask data, or when only a subset do - (mixed batch) — in that case all masks are dropped to preserve - alignment with ``xyxy``. A failed RLE decode is treated identically - to a box-only prediction, so one corrupt RLE payload in an otherwise - fully-masked batch also causes all masks to be dropped. - ``tracker_ids`` is ``None`` when no predictions carry a tracker ID, - or when only a subset do (mixed batch) — in that case all tracker - IDs are dropped to preserve alignment with ``xyxy``. + (mixed-modality batch) — in that case all masks are dropped to preserve + alignment with ``xyxy``. When ``compact_masks=True`` and masks are + present, ``masks`` is a :class:`CompactMask`; otherwise it is a dense + boolean array. ``tracker_ids`` is ``None`` when no predictions carry a + tracker ID, or when only a subset do (mixed batch) — in that case all + tracker IDs are dropped to preserve alignment with ``xyxy``. Examples: >>> from supervision.detection.utils.internal import process_roboflow_result @@ -122,6 +322,12 @@ def process_roboflow_result( class_id: list[int] = [] class_name: list[str] = [] masks: list[npt.NDArray[np.bool_] | None] = [] + # Deferred COCO-RLE processing: collect validated pairs here, then after the + # loop attempt a single batched from_coco_rle call (happy path). If that batch + # call fails, fall back to decoding each pending prediction individually for + # fault isolation. + _coco_rle_pending: list[tuple[int, Any, list[float]]] = [] # (xyxy_idx, rle, bbox) + _polygon_compact_map: dict[int, CompactMask] = {} # xyxy_idx → CompactMask tracker_ids: list[int | None] = [] image_width = int(roboflow_result["image"]["width"]) @@ -137,35 +343,49 @@ def process_roboflow_result( x_max = x_min + width y_max = y_min + height - rle_data = prediction.get("rle") or prediction.get("rle_mask") - if not isinstance(rle_data, dict) or not { - "size", - "counts", - }.issubset(rle_data): - rle_data = None + rle_data = _valid_rle_payload(prediction) + mask: npt.NDArray[np.bool_] | None = None + compact_mask: CompactMask | None = None if rle_data is not None: - try: - h, w = rle_data["size"] - mask = rle_to_mask(rle_data["counts"], (w, h)) - if (h, w) != (image_height, image_width): - mask = cv2.resize( - mask.astype(np.uint8), - (image_width, image_height), - interpolation=cv2.INTER_NEAREST, - ).astype(bool) - except (ValueError, AssertionError, KeyError, TypeError) as exc: - logger.warning( - "Failed to decode RLE mask payload; falling back to box-only " - "detection. Reason: %s", - exc, - ) + _dense, _pending = _resolve_rle_mask( + rle_data, image_height, image_width, compact_masks + ) + if _dense is None and _pending is None: + # Decode failed; treat as no-mask prediction. rle_data = None + elif _pending is None: + # Dense result: compact_masks=False, or size-mismatch fallback. + mask = _dense + if compact_masks and mask is not None: + compact_mask = CompactMask.from_dense( + masks=mask[np.newaxis, ...], + xyxy=_full_image_xyxy(1, image_height, image_width), + image_shape=(image_height, image_width), + ) + # else: _pending set → deferred to batch; mask and compact_mask stay None if rle_data is not None: + xyxy_idx = len(xyxy) xyxy.append([x_min, y_min, x_max, y_max]) class_id.append(prediction["class_id"]) class_name.append(prediction["class"]) confidence.append(prediction["confidence"]) - masks.append(mask) + if compact_masks: + if compact_mask is not None: + # Fallback dense path (size mismatch): compact_mask always set. + _polygon_compact_map[xyxy_idx] = compact_mask + else: + # Main COCO-RLE path: (h, w) == image size; defer to batch. + # Pass the detector bbox so _rle_split_cols only walks + # crop columns, not the full image width. + _coco_rle_pending.append( + ( + xyxy_idx, + rle_data, + [x_min, y_min, x_max, y_max], + ) + ) + elif mask is not None: + masks.append(mask) tracker_ids.append(prediction.get("tracker_id")) elif "points" not in prediction: xyxy.append([x_min, y_min, x_max, y_max]) @@ -181,11 +401,19 @@ def process_roboflow_result( mask = polygon_to_mask( polygon, resolution_wh=(image_width, image_height) ).astype(bool) + xyxy_idx = len(xyxy) xyxy.append([x_min, y_min, x_max, y_max]) class_id.append(prediction["class_id"]) class_name.append(prediction["class"]) confidence.append(prediction["confidence"]) - masks.append(mask) + if compact_masks: + _polygon_compact_map[xyxy_idx] = CompactMask.from_dense( + masks=mask[np.newaxis, ...], + xyxy=_full_image_xyxy(1, image_height, image_width), + image_shape=(image_height, image_width), + ) + else: + masks.append(mask) tracker_ids.append(prediction.get("tracker_id")) xyxy_arr: npt.NDArray[np.floating] = ( @@ -202,9 +430,17 @@ def process_roboflow_result( class_name_arr: npt.NDArray[np.str_] = ( np.array(class_name) if len(class_name) > 0 else np.empty(0, dtype=str) ) - masks_arr: npt.NDArray[np.bool_] | None = _all_present_or_none( - masks, "mask", dtype=bool - ) + masks_arr: npt.NDArray[np.bool_] | CompactMask | None + if compact_masks: + masks_arr = _decode_compact_masks( + _coco_rle_pending, + _polygon_compact_map, + image_height, + image_width, + len(xyxy), + ) + else: + masks_arr = _all_present_or_none(masks, "mask", dtype=bool) tracker_id_arr: npt.NDArray[np.integer] | None = _all_present_or_none( tracker_ids, "tracker_id", dtype=np.int64 ) diff --git a/src/supervision/metrics/f1_score.py b/src/supervision/metrics/f1_score.py index 2f172c84..0f8b1e42 100644 --- a/src/supervision/metrics/f1_score.py +++ b/src/supervision/metrics/f1_score.py @@ -9,6 +9,7 @@ import numpy.typing as npt from matplotlib import pyplot as plt from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask from supervision.detection.core import Detections from supervision.detection.utils.iou_and_nms import ( box_iou_batch, @@ -219,12 +220,18 @@ class F1Score(Metric["F1ScoreResult"]): predictions.confidence, dtype=np.float32 ) if self._metric_target == MetricTarget.BOXES: - iou = box_iou_batch(target_contents, prediction_contents) + # BOXES target never yields CompactMask; narrow for mypy. + iou = box_iou_batch( + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), + ) elif self._metric_target == MetricTarget.MASKS: iou = mask_iou_batch(target_contents, prediction_contents) elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + # OBB target never yields CompactMask; narrow for mypy. iou = oriented_box_iou_batch( - target_contents, prediction_contents + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), ) else: raise ValueError( @@ -442,13 +449,21 @@ class F1Score(Metric["F1ScoreResult"]): result_f1_score: npt.NDArray[np.float64] = f1_score return result_f1_score - def _detections_content(self, detections: Detections) -> npt.NDArray[Any]: - """Return boxes, masks or oriented bounding boxes from detections.""" + def _detections_content( + self, detections: Detections + ) -> npt.NDArray[Any] | CompactMask: + """Return boxes, masks or oriented bounding boxes from detections. + + For the mask target this may return a + :class:`~supervision.detection.compact_mask.CompactMask` rather than a + dense boolean array when the detections carry compact masks. + """ if self._metric_target == MetricTarget.BOXES: return cast(npt.NDArray[Any], detections.xyxy) if self._metric_target == MetricTarget.MASKS: if detections.mask is not None: - return cast(npt.NDArray[Any], detections.mask) + # detections.mask is NDArray[bool] | CompactMask; return as-is. + return detections.mask return self._make_empty_content() if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: obb = detections.data.get(ORIENTED_BOX_COORDINATES) @@ -646,7 +661,7 @@ class F1ScoreResult: ensure_pandas_installed() import pandas as pd - pandas_data = { + pandas_data: dict[str, Any] = { "F1@50": self.f1_50, "F1@75": self.f1_75, } diff --git a/src/supervision/metrics/mean_average_recall.py b/src/supervision/metrics/mean_average_recall.py index c45b18f4..e00ab631 100644 --- a/src/supervision/metrics/mean_average_recall.py +++ b/src/supervision/metrics/mean_average_recall.py @@ -9,6 +9,7 @@ import numpy.typing as npt from matplotlib import pyplot as plt from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask from supervision.detection.core import Detections from supervision.detection.utils.iou_and_nms import ( box_iou_batch, @@ -162,7 +163,7 @@ class MeanAverageRecallResult: ensure_pandas_installed() import pandas as pd - pandas_data = { + pandas_data: dict[str, Any] = { "mAR @ 1": self.mAR_at_1, "mAR @ 10": self.mAR_at_10, "mAR @ 100": self.mAR_at_100, @@ -419,12 +420,18 @@ class MeanAverageRecall(Metric["MeanAverageRecallResult"]): predictions.confidence, dtype=np.float32 ) if self._metric_target == MetricTarget.BOXES: - iou = box_iou_batch(target_contents, prediction_contents) + # BOXES target never yields CompactMask; narrow for mypy. + iou = box_iou_batch( + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), + ) elif self._metric_target == MetricTarget.MASKS: iou = mask_iou_batch(target_contents, prediction_contents) elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + # OBB target never yields CompactMask; narrow for mypy. iou = oriented_box_iou_batch( - target_contents, prediction_contents + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), ) else: raise ValueError( @@ -627,13 +634,21 @@ class MeanAverageRecall(Metric["MeanAverageRecallResult"]): result_recall: npt.NDArray[np.float64] = recall return result_recall - def _detections_content(self, detections: Detections) -> npt.NDArray[Any]: - """Return boxes, masks or oriented bounding boxes from detections.""" + def _detections_content( + self, detections: Detections + ) -> npt.NDArray[Any] | CompactMask: + """Return boxes, masks or oriented bounding boxes from detections. + + For the mask target this may return a + :class:`~supervision.detection.compact_mask.CompactMask` rather than a + dense boolean array when the detections carry compact masks. + """ if self._metric_target == MetricTarget.BOXES: return cast(npt.NDArray[Any], detections.xyxy) if self._metric_target == MetricTarget.MASKS: if detections.mask is not None: - return cast(npt.NDArray[Any], detections.mask) + # detections.mask is NDArray[bool] | CompactMask; return as-is. + return detections.mask return self._make_empty_content() if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: obb = detections.data.get(ORIENTED_BOX_COORDINATES) diff --git a/src/supervision/metrics/recall.py b/src/supervision/metrics/recall.py index 7088e405..bb3e3ed1 100644 --- a/src/supervision/metrics/recall.py +++ b/src/supervision/metrics/recall.py @@ -9,6 +9,7 @@ import numpy.typing as npt from matplotlib import pyplot as plt from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask from supervision.detection.core import Detections from supervision.detection.utils.iou_and_nms import ( box_iou_batch, @@ -192,12 +193,18 @@ class Recall(Metric["RecallResult"]): predictions.confidence, dtype=np.float32 ) if self._metric_target == MetricTarget.BOXES: - iou = box_iou_batch(target_contents, prediction_contents) + # BOXES target never yields CompactMask; narrow for mypy. + iou = box_iou_batch( + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), + ) elif self._metric_target == MetricTarget.MASKS: iou = mask_iou_batch(target_contents, prediction_contents) elif self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: + # OBB target never yields CompactMask; narrow for mypy. iou = oriented_box_iou_batch( - target_contents, prediction_contents + cast(npt.NDArray[np.number], target_contents), + cast(npt.NDArray[np.number], prediction_contents), ) else: raise ValueError( @@ -397,13 +404,21 @@ class Recall(Metric["RecallResult"]): result_recall: npt.NDArray[np.float64] = recall return result_recall - def _detections_content(self, detections: Detections) -> npt.NDArray[Any]: - """Return boxes, masks or oriented bounding boxes from detections.""" + def _detections_content( + self, detections: Detections + ) -> npt.NDArray[Any] | CompactMask: + """Return boxes, masks or oriented bounding boxes from detections. + + For the mask target this may return a + :class:`~supervision.detection.compact_mask.CompactMask` rather than a + dense boolean array when the detections carry compact masks. + """ if self._metric_target == MetricTarget.BOXES: return cast(npt.NDArray[Any], detections.xyxy) if self._metric_target == MetricTarget.MASKS: if detections.mask is not None: - return cast(npt.NDArray[Any], detections.mask) + # detections.mask is NDArray[bool] | CompactMask; return as-is. + return detections.mask return self._make_empty_content() if self._metric_target == MetricTarget.ORIENTED_BOUNDING_BOXES: obb = detections.data.get(ORIENTED_BOX_COORDINATES) @@ -606,7 +621,7 @@ class RecallResult: ensure_pandas_installed() import pandas as pd - pandas_data = { + pandas_data: dict[str, Any] = { "R@50": self.recall_at_50, "R@75": self.recall_at_75, } diff --git a/tests/detection/test_compact_mask.py b/tests/detection/test_compact_mask.py index 173b55ab..5046a390 100644 --- a/tests/detection/test_compact_mask.py +++ b/tests/detection/test_compact_mask.py @@ -163,6 +163,326 @@ class TestFromDenseToDense: np.testing.assert_array_equal(cm.to_dense(), masks) +class TestFromCocoRle: + """Tests for CompactMask.from_coco_rle.""" + + def test_empty_collection_has_dense_empty_shape(self) -> None: + """Empty COCO RLE input should return an empty CompactMask.""" + compact = CompactMask.from_coco_rle( + rles=[], + xyxy=np.empty((0, 4), dtype=np.float32), + image_shape=(3, 5), + ) + + assert len(compact) == 0 + assert compact.shape == (0, 3, 5) + assert compact.area.shape == (0,) + np.testing.assert_array_equal( + compact.to_dense(), np.zeros((0, 3, 5), dtype=bool) + ) + + @pytest.mark.parametrize( + ("masks", "xyxy"), + [ + pytest.param( + np.array( + [ + [ + [False, True, False, False, False], + [False, True, True, False, False], + [False, False, False, True, False], + ] + ], + dtype=bool, + ), + np.array([[1, 0, 3, 2]], dtype=np.float32), + id="non-square-crop", + ), + pytest.param( + np.ones((1, 4, 5), dtype=bool), + np.array([[-2, 1, 8, 3]], dtype=np.float32), + id="clipped-box", + ), + pytest.param( + np.zeros((1, 4, 5), dtype=bool), + np.array([[0, 0, 4, 3]], dtype=np.float32), + id="all-false", + ), + pytest.param( + np.ones((1, 4, 5), dtype=bool), + np.array([[0, 0, 4, 3]], dtype=np.float32), + id="all-true-full-image", + ), + pytest.param( + np.ones((1, 4, 5), dtype=bool), + np.array([[1, 1, 3, 2]], dtype=np.float32), + id="all-true-crop", + ), + pytest.param( + np.ones((1, 4, 5), dtype=bool), + np.array([[3, 2, 1, 2]], dtype=np.float32), + id="invalid-box", + ), + pytest.param( + np.array([[[True]]], dtype=bool), + np.array([[0, 0, 0, 0]], dtype=np.float32), + id="single-pixel-image", + ), + ], + ) + def test_matches_dense_reference(self, masks: np.ndarray, xyxy: np.ndarray) -> None: + """COCO RLE construction should match dense decode plus from_dense.""" + image_shape = masks.shape[1:] + rles = [ + { + "size": list(image_shape), + "counts": mask_to_rle(mask, compressed=True), + } + for mask in masks + ] + + compact = CompactMask.from_coco_rle( + rles=rles, xyxy=xyxy, image_shape=image_shape + ) + + reference = CompactMask.from_dense(masks, xyxy, image_shape=image_shape) + np.testing.assert_array_equal(compact.to_dense(), reference.to_dense()) + np.testing.assert_array_equal(compact.area, reference.area) + np.testing.assert_array_equal(compact.bbox_xyxy, reference.bbox_xyxy) + + def test_matches_dense_reference_for_multiple_masks(self) -> None: + """COCO RLE construction handles N>1 batches.""" + masks = np.zeros((2, 5, 6), dtype=bool) + masks[0, 1:3, 1:4] = True + masks[1, 3:5, 4:6] = True + xyxy = np.array([[1, 1, 3, 2], [4, 3, 5, 4]], dtype=np.float32) + image_shape = masks.shape[1:] + rles = [ + {"size": list(image_shape), "counts": mask_to_rle(mask)} for mask in masks + ] + + compact = CompactMask.from_coco_rle( + rles=rles, xyxy=xyxy, image_shape=image_shape + ) + + reference = CompactMask.from_dense(masks, xyxy, image_shape=image_shape) + np.testing.assert_array_equal(compact.to_dense(), reference.to_dense()) + + def test_out_of_frame_box_returns_empty_crop(self) -> None: + """Boxes with no image intersection do not collapse onto edge pixels.""" + mask = np.zeros((4, 5), dtype=bool) + mask[2, 4] = True + rles = [{"size": [4, 5], "counts": mask_to_rle(mask)}] + xyxy = np.array([[5, 2, 6, 2]], dtype=np.float32) + + compact = CompactMask.from_coco_rle(rles=rles, xyxy=xyxy, image_shape=(4, 5)) + + assert compact.area.tolist() == [0] + np.testing.assert_array_equal(compact.to_dense(), np.zeros((1, 4, 5), bool)) + + def test_rejects_rle_size_mismatch(self) -> None: + """COCO RLE size should match the explicit image shape.""" + rles = [{"size": [2, 2], "counts": [4]}] + xyxy = np.array([[0, 0, 1, 1]], dtype=np.float32) + + with pytest.raises(ValueError, match="RLE size"): + CompactMask.from_coco_rle(rles=rles, xyxy=xyxy, image_shape=(3, 2)) + + @pytest.mark.parametrize( + ("rles", "xyxy_arr", "image_shape", "err_match"), + [ + pytest.param( + [{"size": [0, 4], "counts": [0]}], + np.array([[0, 0, 3, 3]], dtype=np.float32), + (0, 4), + "positive", + id="zero-height", + ), + pytest.param( + [{"size": [4, 0], "counts": [0]}], + np.array([[0, 0, 3, 3]], dtype=np.float32), + (4, 0), + "positive", + id="zero-width", + ), + pytest.param( + [{"size": [4, 4], "counts": [16]}], + np.array([[0, 0, 3, 3, 0]], dtype=np.float32), + (4, 4), + "shape", + id="xyxy-shape-mismatch", + ), + pytest.param( + [42], + np.array([[0, 0, 3, 3]], dtype=np.float32), + (4, 4), + "mapping", + id="non-mapping-rle-item", + ), + pytest.param( + [{"size": [4, 4]}], + np.array([[0, 0, 3, 3]], dtype=np.float32), + (4, 4), + "'size' and 'counts'", + id="missing-counts-key", + ), + pytest.param( + [{"size": [4, 4], "counts": [1, 2, 3]}], + np.array([[0, 0, 3, 3]], dtype=np.float32), + (4, 4), + "sum", + id="counts-sum-mismatch", + ), + pytest.param( + [], + np.empty((0, 4), dtype=np.float32), + (32769, 4), + "maximum", + id="max-image-dimension-exceeded", + ), + ], + ) + def test_raises_on_invalid_input( + self, + rles: list, + xyxy_arr: np.ndarray, + image_shape: tuple, + err_match: str, + ) -> None: + """from_coco_rle raises ValueError for each documented invalid-input path.""" + with pytest.raises(ValueError, match=err_match): + CompactMask.from_coco_rle(rles=rles, xyxy=xyxy_arr, image_shape=image_shape) + + def test_transcodes_without_dense_decode_helpers( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """COCO RLE construction should avoid full-mask dense decode helpers.""" + rles = [{"size": [4, 4], "counts": "52203"}] + xyxy = np.array([[0, 0, 3, 3]], dtype=np.float32) + + def fail_dense_helper(*args: object, **kwargs: object) -> None: + raise AssertionError("dense helper should not be called") + + monkeypatch.setattr( + "supervision.detection.compact_mask._mask_to_rle_counts", + fail_dense_helper, + ) + monkeypatch.setattr( + "supervision.detection.compact_mask._rle_counts_to_mask", + fail_dense_helper, + ) + + compact = CompactMask.from_coco_rle(rles=rles, xyxy=xyxy, image_shape=(4, 4)) + + assert compact.shape == (1, 4, 4) + + def test_large_image_column_split_path(self) -> None: + """from_coco_rle hits column-split path on large images (H*W > 307200).""" + H, W = 720, 1280 + assert H * W > 640 * 480, ( + "test must use image above _SMALL_IMAGE_DENSE_THRESHOLD" + ) + rng = np.random.default_rng(42) + mask = rng.integers(0, 2, (H, W), dtype=np.uint8).astype(bool) + xyxy = np.array([[0, 0, W - 1, H - 1]], dtype=np.float32) + rle = {"size": [H, W], "counts": mask_to_rle(mask, compressed=True)} + + compact = CompactMask.from_coco_rle(rles=[rle], xyxy=xyxy, image_shape=(H, W)) + reference = CompactMask.from_dense(mask[np.newaxis], xyxy, image_shape=(H, W)) + + np.testing.assert_array_equal(compact.to_dense(), reference.to_dense()) + + def test_bytes_counts_match_string_counts(self) -> None: + """from_coco_rle accepts bytes-encoded compressed counts.""" + # Both encodings of "52203" should produce identical crops. + rle_str = {"size": [4, 4], "counts": "52203"} + rle_bytes = {"size": [4, 4], "counts": b"52203"} + xyxy = np.array([[0, 0, 3, 3]], dtype=np.float32) + + cm_str = CompactMask.from_coco_rle( + rles=[rle_str], xyxy=xyxy, image_shape=(4, 4) + ) + cm_bytes = CompactMask.from_coco_rle( + rles=[rle_bytes], xyxy=xyxy, image_shape=(4, 4) + ) + + np.testing.assert_array_equal(cm_str.to_dense(), cm_bytes.to_dense()) + + +class TestCocoRleCountsToArray: + """Tests for _coco_rle_counts_to_array input-format decoding.""" + + @pytest.mark.parametrize( + "counts", + [ + pytest.param("52203", id="str-input"), + pytest.param(b"52203", id="bytes-input"), + ], + ) + def test_str_and_bytes_decode_identically(self, counts: object) -> None: + """str and bytes inputs decode to the same run-length array.""" + from supervision.detection.compact_mask import _coco_rle_counts_to_array + + result = _coco_rle_counts_to_array(counts) + assert result.dtype == np.int32 + assert result.sum() == 16 # total pixels in a 4x4 image + + @pytest.mark.parametrize( + ("counts", "err_match"), + [ + pytest.param([2**31], "Invalid", id="int32-overflow"), + pytest.param([[4, 8], [3, 5]], "one-dimensional", id="two-dimensional"), + pytest.param([4, -1, 8], "non-negative", id="negative-count"), + pytest.param(None, "Invalid", id="none"), + pytest.param("", "empty", id="empty-string"), + ], + ) + def test_invalid_counts_raise_value_error( + self, counts: object, err_match: str + ) -> None: + """Invalid COCO RLE counts raise ValueError.""" + from supervision.detection.compact_mask import _coco_rle_counts_to_array + + with pytest.raises(ValueError, match=err_match): + _coco_rle_counts_to_array(counts) + + +class TestRleTrimColRuns: + """Tests for _rle_trim_col_runs row-crop behavior.""" + + @pytest.mark.parametrize( + ("col_runs", "height", "y1", "y2"), + [ + pytest.param([0, 2, 3], 5, 0, 2, id="starts-at-row-zero"), + pytest.param([2, 1, 2], 5, 2, 2, id="single-row-crop"), + pytest.param([1, 3, 2], 6, 2, 4, id="straddles-both-bounds"), + pytest.param([3, 2, 1], 6, 4, 5, id="starts-inside-true-run"), + pytest.param([0, 6], 6, 1, 4, id="all-true-col-interior-crop"), + ], + ) + def test_matches_decode_slice_encode( + self, col_runs: list[int], height: int, y1: int, y2: int + ) -> None: + """Trimmed column runs match dense slice then encode.""" + from supervision.detection.compact_mask import _rle_trim_col_runs + + column = _rle_counts_to_mask(np.array(col_runs, dtype=np.int32), height, 1) + expected = _mask_to_rle_counts(column[y1 : y2 + 1, :]).tolist() + + result = _rle_trim_col_runs(col_runs, y1, y2) + + assert result == expected + assert sum(result) == y2 - y1 + 1 + + def test_returns_all_false_when_no_runs_reach_crop(self) -> None: + """Truncated input before y1 returns an all-False crop.""" + from supervision.detection.compact_mask import _rle_trim_col_runs + + result = _rle_trim_col_runs([2], y1=3, y2=4) + + assert result == [2] + + class TestGetItem: """Tests for CompactMask.__getitem__. diff --git a/tests/detection/test_core.py b/tests/detection/test_core.py index 69b4f76f..f2eccd99 100644 --- a/tests/detection/test_core.py +++ b/tests/detection/test_core.py @@ -5,6 +5,7 @@ import numpy as np import pytest from supervision.config import ORIENTED_BOX_COORDINATES +from supervision.detection.compact_mask import CompactMask from supervision.detection.core import ( Detections, _merge_detection_group, @@ -1102,6 +1103,199 @@ def test_from_inference_sdk_dict_path_empty_preserves_class_name_dtype() -> None assert detections["class_name"].dtype.kind == "U" +def test_from_inference_compact_masks_default_keeps_dense_mask() -> None: + """Default from_inference RLE output should remain a dense ndarray mask.""" + result = { + "predictions": [ + { + "x": 1.5, + "y": 1.5, + "width": 2.0, + "height": 2.0, + "confidence": 0.9, + "class_id": 0, + "class": "person", + "rle": {"size": [4, 4], "counts": "52203"}, + } + ], + "image": {"width": 4, "height": 4}, + } + + detections = Detections.from_inference(result) + + assert isinstance(detections.mask, np.ndarray) + assert not isinstance(detections.mask, CompactMask) + + +def test_from_inference_compact_masks_matches_dense_default() -> None: + """compact_masks=True and False agree when all True pixels are inside the bbox.""" + result = { + "predictions": [ + { + "x": 1.5, + "y": 1.5, + "width": 2.0, + "height": 2.0, + "confidence": 0.9, + "class_id": 0, + "class": "person", + "rle_mask": {"size": [4, 4], "counts": "52203"}, + "tracker_id": 5, + } + ], + "image": {"width": 4, "height": 4}, + } + dense = Detections.from_inference(result) + + compact = Detections.from_inference(result, compact_masks=True) + + assert isinstance(compact.mask, CompactMask) + assert dense.mask is not None + np.testing.assert_array_equal(compact.mask.to_dense(), dense.mask) + np.testing.assert_array_equal(compact.xyxy, dense.xyxy) + np.testing.assert_array_equal(compact.confidence, dense.confidence) + np.testing.assert_array_equal(compact.class_id, dense.class_id) + np.testing.assert_array_equal(compact.tracker_id, dense.tracker_id) + np.testing.assert_array_equal(compact["class_name"], dense["class_name"]) + + +def test_from_inference_compact_masks_crops_to_detector_bbox() -> None: + """compact_masks=True crops masks to the detector bbox; pixels outside are dropped. + + This is the documented behaviour (see Warning in Detections.from_inference): + each mask is cropped to its detector bbox, so True pixels outside that box + are not stored. Dense masks are unaffected and preserve the full mask. + """ + # Mask has True at (row=0,col=0) [inside bbox] and (row=3,col=3) [outside bbox]. + # counts=[0,1,14,1,0]: 0 False, 1 True (pos 0), 14 False, 1 True (pos 15), 0 False. + # Bbox x_min=0,y_min=0,x_max=2,y_max=2 (int-truncated) covers cols 0-2, rows 0-2. + result = { + "predictions": [ + { + "x": 1.0, + "y": 1.0, + "width": 2.0, + "height": 2.0, + "confidence": 0.8, + "class_id": 0, + "class": "cat", + "rle_mask": {"size": [4, 4], "counts": [0, 1, 14, 1, 0]}, + } + ], + "image": {"width": 4, "height": 4}, + } + dense = Detections.from_inference(result) + compact = Detections.from_inference(result, compact_masks=True) + + assert dense.mask is not None + assert isinstance(compact.mask, CompactMask) + # Dense preserves both True pixels (full-image RLE decode, no cropping). + assert dense.mask[0].sum() == 2 + assert bool(dense.mask[0, 0, 0]) + assert bool(dense.mask[0, 3, 3]) + # Compact crops to detector bbox (cols 0-2, rows 0-2): out-of-bbox pixel dropped. + compact_dense = compact.mask.to_dense() + assert bool(compact_dense[0, 0, 0]), "in-bbox pixel must be preserved" + assert not bool(compact_dense[0, 3, 3]), "out-of-bbox pixel silently dropped" + assert compact_dense[0].sum() == 1 + + +def test_from_inference_compact_masks_multiple_predictions_matches_dense() -> None: + """compact_masks=True with N>1 predictions exercises batched from_coco_rle.""" + result = { + "predictions": [ + { + "x": 1.5, + "y": 1.5, + "width": 3.0, + "height": 3.0, + "confidence": 0.9, + "class_id": 0, + "class": "person", + "rle_mask": {"size": [4, 4], "counts": "52203"}, + }, + { + "x": 1.5, + "y": 1.5, + "width": 3.0, + "height": 3.0, + "confidence": 0.8, + "class_id": 1, + "class": "car", + "rle_mask": {"size": [4, 4], "counts": [0, 16]}, + }, + ], + "image": {"width": 4, "height": 4}, + } + dense = Detections.from_inference(result) + compact = Detections.from_inference(result, compact_masks=True) + + assert isinstance(compact.mask, CompactMask) + assert len(compact) == 2 + assert dense.mask is not None + np.testing.assert_array_equal(compact.mask.to_dense(), dense.mask) + + +def test_from_inference_compact_masks_empty_preserves_data_contract() -> None: + """compact_masks=True empty results should keep class_name string dtype.""" + result = {"predictions": [], "image": {"width": 100, "height": 100}} + + detections = Detections.from_inference(result, compact_masks=True) + + assert detections.mask is None + assert detections["class_name"] is not None + assert detections["class_name"].dtype.kind == "U" + + +class TestDetectionsToCompactMasks: + """Tests for Detections.to_compact_masks.""" + + def test_dense_mask_converts_to_compact_mask(self) -> None: + """Dense masks are converted to lossless CompactMask instances.""" + mask = np.zeros((1, 4, 5), dtype=bool) + mask[0, 1:3, 1:4] = True + mask[0, 0, 0] = True + xyxy = np.array([[1, 1, 4, 3]], dtype=np.float64) + detections = Detections(xyxy=xyxy, mask=mask) + + result = detections.to_compact_masks() + + assert isinstance(result.mask, CompactMask) + np.testing.assert_array_equal(result.mask.to_dense(), mask) + np.testing.assert_array_equal(result.xyxy, detections.xyxy) + + def test_compact_mask_returns_same_instance(self) -> None: + """CompactMask input is already compact and returns the same instance.""" + mask = np.zeros((1, 4, 5), dtype=bool) + mask[0, 1:3, 1:4] = True + xyxy = np.array([[1, 1, 4, 3]], dtype=np.float64) + compact = CompactMask.from_dense(mask, xyxy=xyxy, image_shape=mask.shape[1:]) + detections = Detections(xyxy=xyxy, mask=compact) + + result = detections.to_compact_masks() + + assert result is detections + + def test_none_mask_returns_same_instance(self) -> None: + """None mask cannot be compacted and returns the same instance.""" + detections = Detections(xyxy=np.array([[1, 1, 4, 3]], dtype=np.float64)) + + result = detections.to_compact_masks() + + assert result is detections + + def test_empty_dense_mask_converts_to_empty_compact_mask(self) -> None: + """Empty dense mask (N=0) converts to an empty CompactMask.""" + xyxy = np.empty((0, 4), dtype=np.float64) + masks = np.empty((0, 10, 10), dtype=bool) + detections = Detections(xyxy=xyxy, mask=masks) + + result = detections.to_compact_masks() + + assert isinstance(result.mask, CompactMask) + assert len(result.mask) == 0 + + def _rotated_rect( cx: float, cy: float, w: float, h: float, angle_deg: float ) -> np.ndarray: diff --git a/tests/detection/test_inference_slicer_compact.py b/tests/detection/test_inference_slicer_compact.py index 0090c346..79a3d4c1 100644 --- a/tests/detection/test_inference_slicer_compact.py +++ b/tests/detection/test_inference_slicer_compact.py @@ -111,6 +111,41 @@ class TestInferenceSlicerCompactMasks: err_msg="compact_masks pipeline produced different mask pixels than dense", ) + def test_compact_masks_preserve_pixels_outside_detector_box(self) -> None: + """compact_masks=True crops to the full tile, so mask pixels outside the + detection xyxy box (but inside the tile) are preserved.""" + image = np.zeros((100, 100, 3), dtype=np.uint8) + + def callback(tile: np.ndarray) -> Detections: + h, w = tile.shape[:2] + masks = np.zeros((1, h, w), dtype=bool) + masks[0, 0, 0] = True + masks[0, h - 1, w - 1] = True + return Detections( + xyxy=np.array([[0, 0, 10, 10]], dtype=np.float32), + mask=masks, + confidence=np.array([0.9], dtype=np.float32), + class_id=np.array([0]), + ) + + dense = sv.InferenceSlicer( + callback=callback, + slice_wh=100, + overlap_wh=0, + overlap_filter=sv.OverlapFilter.NONE, + compact_masks=False, + )(image) + compact = sv.InferenceSlicer( + callback=callback, + slice_wh=100, + overlap_wh=0, + overlap_filter=sv.OverlapFilter.NONE, + compact_masks=True, + )(image) + + assert isinstance(compact.mask, CompactMask) + np.testing.assert_array_equal(compact.mask.to_dense(), dense.mask) + def test_nms_with_overlapping_tiles_uses_rle_iou(self) -> None: """With overlapping tiles, NMS must suppress duplicates using RLE IoU.""" image = np.zeros((300, 300, 3), dtype=np.uint8) diff --git a/tests/detection/utils/test_internal.py b/tests/detection/utils/test_internal.py index a2be07d3..61a0dcb4 100644 --- a/tests/detection/utils/test_internal.py +++ b/tests/detection/utils/test_internal.py @@ -5,6 +5,7 @@ import numpy as np import pytest from supervision.config import CLASS_NAME_DATA_FIELD +from supervision.detection.compact_mask import CompactMask from supervision.detection.utils.internal import ( get_data_item, merge_data, @@ -12,6 +13,46 @@ from supervision.detection.utils.internal import ( process_roboflow_result, ) + +def _pred( + yx: tuple[float, float] = (1.5, 1.5), + size: tuple[float, float] = (2.0, 2.0), + confidence: float = 0.9, + class_id: int = 0, + class_name: str = "person", + **extra: Any, +) -> dict[str, Any]: + """Build a minimal Roboflow prediction dict; `extra` adds/overrides fields.""" + pred: dict[str, Any] = { + "x": yx[1], + "y": yx[0], + "width": size[0], + "height": size[1], + "confidence": confidence, + "class_id": class_id, + "class": class_name, + } + pred.update(extra) + return pred + + +def _result( + *predictions: dict[str, Any], + img_w: int = 4, + img_h: int = 4, +) -> dict[str, Any]: + """Wrap predictions in a Roboflow result envelope.""" + return { + "predictions": list(predictions), + "image": {"width": img_w, "height": img_h}, + } + + +def _result_1k(*predictions: dict[str, Any]) -> dict[str, Any]: + """Wrap predictions in a 1000x1000 Roboflow result envelope.""" + return _result(*predictions, img_w=1000, img_h=1000) + + TEST_MASK = np.zeros((1, 1000, 1000), dtype=bool) TEST_MASK[:, 300:351, 200:251] = True @@ -39,20 +80,7 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # empty result ( - { - "predictions": [ - { - "x": 200.0, - "y": 300.0, - "width": 50.0, - "height": 50.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - } - ], - "image": {"width": 1000, "height": 1000}, - }, + _result_1k(_pred(yx=(300.0, 200.0), size=(50.0, 50.0))), ( np.array([[175.0, 275.0, 225.0, 325.0]]), np.array([0.9]), @@ -64,31 +92,17 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # single correct object detection result ( - { - "predictions": [ - { - "x": 200.0, - "y": 300.0, - "width": 50.0, - "height": 50.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "tracker_id": 1, - }, - { - "x": 500.0, - "y": 500.0, - "width": 100.0, - "height": 100.0, - "confidence": 0.8, - "class_id": 7, - "class": "truck", - "tracker_id": 2, - }, - ], - "image": {"width": 1000, "height": 1000}, - }, + _result_1k( + _pred(yx=(300.0, 200.0), size=(50.0, 50.0), tracker_id=1), + _pred( + yx=(500.0, 500.0), + size=(100.0, 100.0), + confidence=0.8, + class_id=7, + class_name="truck", + tracker_id=2, + ), + ), ( np.array([[175.0, 275.0, 225.0, 325.0], [450.0, 450.0, 550.0, 550.0]]), np.array([0.9, 0.8]), @@ -100,22 +114,14 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # two correct object detection result ( - { - "predictions": [ - { - "x": 200.0, - "y": 300.0, - "width": 50.0, - "height": 50.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "points": [], - "tracker_id": None, - } - ], - "image": {"width": 1000, "height": 1000}, - }, + _result_1k( + _pred( + yx=(300.0, 200.0), + size=(50.0, 50.0), + points=[], + tracker_id=None, + ), + ), ( np.empty((0, 4)), np.empty(0), @@ -127,21 +133,13 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # single incorrect instance segmentation result with no points ( - { - "predictions": [ - { - "x": 200.0, - "y": 300.0, - "width": 50.0, - "height": 50.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "points": [{"x": 200.0, "y": 300.0}, {"x": 250.0, "y": 300.0}], - } - ], - "image": {"width": 1000, "height": 1000}, - }, + _result_1k( + _pred( + yx=(300.0, 200.0), + size=(50.0, 50.0), + points=[{"x": 200.0, "y": 300.0}, {"x": 250.0, "y": 300.0}], + ), + ), ( np.empty((0, 4)), np.empty(0), @@ -153,26 +151,18 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # single incorrect instance segmentation result with no enough points ( - { - "predictions": [ - { - "x": 200.0, - "y": 300.0, - "width": 50.0, - "height": 50.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "points": [ - {"x": 200.0, "y": 300.0}, - {"x": 250.0, "y": 300.0}, - {"x": 250.0, "y": 350.0}, - {"x": 200.0, "y": 350.0}, - ], - } - ], - "image": {"width": 1000, "height": 1000}, - }, + _result_1k( + _pred( + yx=(300.0, 200.0), + size=(50.0, 50.0), + points=[ + {"x": 200.0, "y": 300.0}, + {"x": 250.0, "y": 300.0}, + {"x": 250.0, "y": 350.0}, + {"x": 200.0, "y": 350.0}, + ], + ), + ), ( np.array([[175.0, 275.0, 225.0, 325.0]]), np.array([0.9]), @@ -184,36 +174,26 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # single incorrect instance segmentation result with no enough points ( - { - "predictions": [ - { - "x": 200.0, - "y": 300.0, - "width": 50.0, - "height": 50.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "points": [ - {"x": 200.0, "y": 300.0}, - {"x": 250.0, "y": 300.0}, - {"x": 250.0, "y": 350.0}, - {"x": 200.0, "y": 350.0}, - ], - }, - { - "x": 500.0, - "y": 500.0, - "width": 100.0, - "height": 100.0, - "confidence": 0.8, - "class_id": 7, - "class": "truck", - "points": [], - }, - ], - "image": {"width": 1000, "height": 1000}, - }, + _result_1k( + _pred( + yx=(300.0, 200.0), + size=(50.0, 50.0), + points=[ + {"x": 200.0, "y": 300.0}, + {"x": 250.0, "y": 300.0}, + {"x": 250.0, "y": 350.0}, + {"x": 200.0, "y": 350.0}, + ], + ), + _pred( + yx=(500.0, 500.0), + size=(100.0, 100.0), + confidence=0.8, + class_id=7, + class_name="truck", + points=[], + ), + ), ( np.array([[175.0, 275.0, 225.0, 325.0]]), np.array([0.9]), @@ -225,21 +205,7 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # two instance segmentation results - one correct, one incorrect ( - { - "predictions": [ - { - "x": 1.5, - "y": 1.5, - "width": 2.0, - "height": 2.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "rle": {"size": [4, 4], "counts": "52203"}, - } - ], - "image": {"width": 4, "height": 4}, - }, + _result(_pred(rle={"size": [4, 4], "counts": "52203"})), ( np.array([[0.5, 0.5, 2.5, 2.5]]), np.array([0.9]), @@ -251,21 +217,16 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # single RLE prediction with compressed string counts ( - { - "predictions": [ - { - "x": 2.0, - "y": 2.0, - "width": 4.0, - "height": 4.0, - "confidence": 0.85, - "class_id": 1, - "class": "cat", - "rle": {"size": [4, 4], "counts": "02203ON0"}, - } - ], - "image": {"width": 4, "height": 4}, - }, + _result( + _pred( + yx=(2.0, 2.0), + size=(4.0, 4.0), + confidence=0.85, + class_id=1, + class_name="cat", + rle={"size": [4, 4], "counts": "02203ON0"}, + ) + ), ( np.array([[0.0, 0.0, 4.0, 4.0]]), np.array([0.85]), @@ -277,22 +238,7 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # single RLE prediction with non-contiguous mask ( - { - "predictions": [ - { - "x": 1.5, - "y": 1.5, - "width": 2.0, - "height": 2.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "rle": {"size": [4, 4], "counts": "52203"}, - "tracker_id": 5, - } - ], - "image": {"width": 4, "height": 4}, - }, + _result(_pred(rle={"size": [4, 4], "counts": "52203"}, tracker_id=5)), ( np.array([[0.5, 0.5, 2.5, 2.5]]), np.array([0.9]), @@ -304,21 +250,7 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # RLE prediction with tracker_id ( - { - "predictions": [ - { - "x": 1.5, - "y": 1.5, - "width": 2.0, - "height": 2.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "rle_mask": {"size": [4, 4], "counts": "52203"}, - } - ], - "image": {"width": 4, "height": 4}, - }, + _result(_pred(rle_mask={"size": [4, 4], "counts": "52203"})), ( np.array([[0.5, 0.5, 2.5, 2.5]]), np.array([0.9]), @@ -330,21 +262,7 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # single RLE prediction with compressed string counts under rle_mask key ( - { - "predictions": [ - { - "x": 1.5, - "y": 1.5, - "width": 2.0, - "height": 2.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "rle": "bad_string", - } - ], - "image": {"width": 4, "height": 4}, - }, + _result(_pred(rle="bad_string")), ( np.array([[0.5, 0.5, 2.5, 2.5]]), np.array([0.9]), @@ -356,21 +274,7 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # malformed RLE payload should fall through to box-only detection ( - { - "predictions": [ - { - "x": 1.5, - "y": 1.5, - "width": 2.0, - "height": 2.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "rle": {"size": [4, 4]}, - } - ], - "image": {"width": 4, "height": 4}, - }, + _result(_pred(rle={"size": [4, 4]})), ( np.array([[0.5, 0.5, 2.5, 2.5]]), np.array([0.9]), @@ -382,21 +286,7 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # RLE dict missing counts falls through to box-only detection ( - { - "predictions": [ - { - "x": 1.5, - "y": 1.5, - "width": 2.0, - "height": 2.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "rle": {"size": [4, 4], "counts": "!"}, - } - ], - "image": {"width": 4, "height": 4}, - }, + _result(_pred(rle={"size": [4, 4], "counts": "!"})), ( np.array([[0.5, 0.5, 2.5, 2.5]]), np.array([0.9]), @@ -408,67 +298,28 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True DoesNotRaise(), ), # malformed compressed counts falls through to box-only detection ( - { - "predictions": [ - { - "x": 1.5, - "y": 1.5, - "width": 2.0, - "height": 2.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "rle": {"size": [4, 4], "counts": "52203"}, - }, - { - "x": 3.0, - "y": 3.0, - "width": 2.0, - "height": 2.0, - "confidence": 0.8, - "class_id": 1, - "class": "car", - }, - ], - "image": {"width": 4, "height": 4}, - }, + _result( + _pred(rle={"size": [4, 4], "counts": "52203"}), + _pred(yx=(3.0, 3.0), confidence=0.8, class_id=1, class_name="car"), + ), ( np.array([[0.5, 0.5, 2.5, 2.5], [2.0, 2.0, 4.0, 4.0]]), np.array([0.9, 0.8]), np.array([0, 1]), - # When only some predictions carry a mask, all masks are dropped - # so the result stays aligned with xyxy (mirrors tracker_id). + # Mixed-modality batch: only a subset carries masks. + # All masks dropped to preserve xyxy alignment (mirrors + # the tracker_id mixed-batch handling). None, None, {CLASS_NAME_DATA_FIELD: np.array(["person", "car"])}, ), DoesNotRaise(), - ), # mixed RLE + box-only batch — masks dropped to preserve alignment + ), # mixed RLE + box-only batch — masks dropped to preserve xyxy alignment pytest.param( - { - "predictions": [ - { - "x": 1.5, - "y": 1.5, - "width": 2.0, - "height": 2.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - "tracker_id": 7, - }, - { - "x": 3.0, - "y": 3.0, - "width": 2.0, - "height": 2.0, - "confidence": 0.8, - "class_id": 1, - "class": "car", - }, - ], - "image": {"width": 4, "height": 4}, - }, + _result( + _pred(tracker_id=7), + _pred(yx=(3.0, 3.0), confidence=0.8, class_id=1, class_name="car"), + ), ( np.array([[0.5, 0.5, 2.5, 2.5], [2.0, 2.0, 4.0, 4.0]]), np.array([0.9, 0.8]), @@ -483,29 +334,10 @@ TEST_RLE_NONCONTIGUOUS_MASK[0, 3, 2:4] = True id="mixed_tracker_id_batch_drops_to_none", ), pytest.param( - { - "predictions": [ - { - "x": 1.5, - "y": 1.5, - "width": 2.0, - "height": 2.0, - "confidence": 0.9, - "class_id": 0, - "class": "person", - }, - { - "x": 3.0, - "y": 3.0, - "width": 2.0, - "height": 2.0, - "confidence": 0.8, - "class_id": 1, - "class": "car", - }, - ], - "image": {"width": 4, "height": 4}, - }, + _result( + _pred(), + _pred(yx=(3.0, 3.0), confidence=0.8, class_id=1, class_name="car"), + ), ( np.array([[0.5, 0.5, 2.5, 2.5], [2.0, 2.0, 4.0, 4.0]]), np.array([0.9, 0.8]), @@ -554,6 +386,147 @@ def test_process_roboflow_result( ) +def test_process_roboflow_result_compact_masks_returns_compact_mask() -> None: + """compact_masks=True should return CompactMask for valid RLE predictions.""" + roboflow_result = _result(_pred(rle={"size": [4, 4], "counts": "52203"})) + + result = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + + assert isinstance(result[3], CompactMask) + np.testing.assert_array_equal(result[3].to_dense(), TEST_RLE_MASK) + + +def test_process_roboflow_result_compact_masks_matches_resized_dense_rle() -> None: + """compact_masks=True should preserve current RLE resize behavior.""" + roboflow_result = _result( + _pred(yx=(2.0, 2.0), size=(4.0, 4.0), rle={"size": [2, 2], "counts": [0, 4]}) + ) + dense_result = process_roboflow_result(roboflow_result=roboflow_result) + + compact_result = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + + assert isinstance(compact_result[3], CompactMask) + np.testing.assert_array_equal(compact_result[3].to_dense(), dense_result[3]) + + +def test_process_roboflow_result_compact_masks_invalid_rle_is_box_only() -> None: + """compact_masks=True should keep malformed RLE fallback behavior.""" + roboflow_result = _result(_pred(rle={"size": [4, 4], "counts": "!"})) + + result = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + + assert result[3] is None + np.testing.assert_array_equal(result[0], np.array([[0.5, 0.5, 2.5, 2.5]])) + + +def test_process_roboflow_result_compact_masks_overflow_rle_is_box_only() -> None: + """compact_masks=True should not leak OverflowError from invalid counts.""" + roboflow_result = _result(_pred(rle={"size": [4, 4], "counts": [2**31]})) + + result = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + + assert result[3] is None + np.testing.assert_array_equal(result[0], np.array([[0.5, 0.5, 2.5, 2.5]])) + + +def test_process_roboflow_result_compact_masks_partial_failure_drops_all_masks() -> ( + None +): + """One invalid RLE in a two-prediction batch drops all masks but keeps both xyxy.""" + roboflow_result = _result( + _pred(rle={"size": [4, 4], "counts": "52203"}), # valid: sum == 16 + _pred(rle={"size": [4, 4], "counts": [1, 2, 3]}), # invalid: sum == 6, not 16 + ) + + result = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + + # Mixed-modality: one mask decoded, one failed → all masks dropped for alignment. + assert result[3] is None + # Both detections preserved in xyxy. + assert result[0].shape == (2, 4) + + +def test_process_roboflow_result_uses_rle_mask_when_rle_invalid() -> None: + """Valid rle_mask should be used when rle is present but invalid.""" + roboflow_result = _result( + _pred(rle={"foo": "bar"}, rle_mask={"size": [4, 4], "counts": "52203"}) + ) + + dense_result = process_roboflow_result(roboflow_result=roboflow_result) + compact_result = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + + assert isinstance(dense_result[3], np.ndarray) + assert isinstance(compact_result[3], CompactMask) + np.testing.assert_array_equal(compact_result[3].to_dense(), dense_result[3]) + + +def test_polygon_prediction_compact_masks_true() -> None: + """polygon prediction with compact_masks=True returns a CompactMask.""" + roboflow_result = _result( + _pred( + yx=(2.5, 2.5), + size=(4.0, 4.0), + confidence=0.75, + class_name="dog", + points=[ + {"x": 1, "y": 1}, + {"x": 4, "y": 1}, + {"x": 4, "y": 4}, + {"x": 1, "y": 4}, + ], + ), + img_w=6, + img_h=6, + ) + _, _, _, masks, _, _ = process_roboflow_result(roboflow_result, compact_masks=True) + + assert isinstance(masks, CompactMask) + assert len(masks) == 1 + + +def test_box_only_compact_masks_true_returns_none_mask() -> None: + """box-only predictions with compact_masks=True yield None mask.""" + roboflow_result = _result( + _pred(yx=(2.0, 2.0), size=(3.0, 3.0), class_name="cat"), + img_w=5, + img_h=5, + ) + _, _, _, masks, _, _ = process_roboflow_result(roboflow_result, compact_masks=True) + + assert masks is None + + +def test_rle_size_mismatch_resizes_dense_mask() -> None: + """Dense path resizes mask when RLE size differs from image dimensions.""" + # counts=[0, 4]: 0 False runs then 4 True runs — all-True 2x2 mask. + # Image is 4x4, so cv2.resize must expand the decoded 2x2 to 4x4. + roboflow_result = _result( + _pred( + yx=(2.0, 2.0), + size=(4.0, 4.0), + class_name="cat", + rle_mask={"size": [2, 2], "counts": [0, 4]}, + ) + ) + _, _, _, masks, _, _ = process_roboflow_result(roboflow_result, compact_masks=False) + + assert masks is not None + assert masks.shape == (1, 4, 4) + assert masks[0].sum() > 0 + + @pytest.mark.parametrize( ("data_list", "expected_result", "exception"), [ @@ -1109,3 +1082,46 @@ def test_merge_metadata(metadata_list, expected_result, exception) -> None: np.testing.assert_array_equal(value, expected_result[key]) else: assert value == expected_result[key] + + +def test_process_roboflow_result_compact_masks_batch_retry_logs_warning( + caplog: pytest.LogCaptureFixture, +) -> None: + """Batch RLE failure triggers per-prediction retry; mixed-modality drops masks.""" + import logging + + roboflow_result = _result( + _pred(rle={"size": [4, 4], "counts": "52203"}), + _pred(rle={"size": [4, 4], "counts": "52203"}), + # sum=6 != 16 — triggers batch failure → per-prediction retry + _pred(rle={"size": [4, 4], "counts": [1, 2, 3]}), + ) + + with caplog.at_level(logging.WARNING): + result = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + + # Batch call fails, per-prediction retry produces 2/3 decoded → mixed-modality drop. + assert "Batch compact RLE decode failed" in caplog.text + assert result[3] is None + assert result[0].shape == (3, 4) + + +def test_process_roboflow_result_compact_masks_rle_mask_size_mismatch() -> None: + """rle_mask key + size mismatch triggers resize fallback with compact_masks=True.""" + # RLE is 2x2; image is 4x4 — size mismatch triggers resize fallback. + roboflow_result = _result( + _pred( + yx=(2.0, 2.0), + size=(4.0, 4.0), + rle_mask={"size": [2, 2], "counts": [0, 4]}, + ) + ) + dense_result = process_roboflow_result(roboflow_result=roboflow_result) + compact_result = process_roboflow_result( + roboflow_result=roboflow_result, compact_masks=True + ) + + assert isinstance(compact_result[3], CompactMask) + np.testing.assert_array_equal(compact_result[3].to_dense(), dense_result[3]) diff --git a/tests/metrics/test_f1_score.py b/tests/metrics/test_f1_score.py index fa831bf4..33874494 100644 --- a/tests/metrics/test_f1_score.py +++ b/tests/metrics/test_f1_score.py @@ -1,6 +1,7 @@ import numpy as np import pytest +from supervision.detection.compact_mask import CompactMask from supervision.detection.core import Detections from supervision.metrics.core import AveragingMethod, MetricTarget from supervision.metrics.f1_score import F1Score @@ -53,6 +54,41 @@ class TestF1Score: assert metric._metric_target == MetricTarget.MASKS assert metric.averaging_method == AveragingMethod.MACRO + def test_mask_content_preserves_compact_mask(self) -> None: + """CompactMask inputs stay compact for mask IoU.""" + dense_mask = np.zeros((1, 4, 5), dtype=bool) + dense_mask[0, 1:3, 1:4] = True + xyxy = np.array([[1, 1, 4, 3]], dtype=np.float64) + compact_mask = CompactMask.from_dense( + dense_mask, xyxy=xyxy, image_shape=dense_mask.shape[1:] + ) + detections = Detections(xyxy=xyxy, mask=compact_mask) + metric = F1Score(metric_target=MetricTarget.MASKS) + + content = metric._detections_content(detections) + + assert content is compact_mask + + def test_compute_with_compact_mask_matches_dense(self) -> None: + """F1Score.compute() produces identical f1_50 for CompactMask and dense.""" + masks = np.zeros((1, 50, 50), dtype=bool) + masks[0, 10:20, 10:20] = True + xyxy = np.array([[10, 10, 19, 19]], dtype=np.float64) + cm = CompactMask.from_dense(masks, xyxy, image_shape=(50, 50)) + det_dense = Detections( + xyxy=xyxy, mask=masks, confidence=np.array([0.9]), class_id=np.array([0]) + ) + det_compact = Detections( + xyxy=xyxy, mask=cm, confidence=np.array([0.9]), class_id=np.array([0]) + ) + metric = F1Score(metric_target=MetricTarget.MASKS) + + r_dense = metric.update(det_dense, det_dense).compute() + metric.reset() + r_compact = metric.update(det_compact, det_compact).compute() + + assert r_dense.f1_50 == pytest.approx(r_compact.f1_50) + def test_reset(self, dummy_prediction): """Test that reset() clears all stored data""" metric = F1Score() diff --git a/tests/metrics/test_mean_average_recall.py b/tests/metrics/test_mean_average_recall.py index 348bb9fb..1f142e26 100644 --- a/tests/metrics/test_mean_average_recall.py +++ b/tests/metrics/test_mean_average_recall.py @@ -1,6 +1,7 @@ import numpy as np import pytest +from supervision.detection.compact_mask import CompactMask from supervision.detection.core import Detections from supervision.metrics import MeanAverageRecall, MetricTarget @@ -399,6 +400,43 @@ def test_compute_value_error_for_missing_required_fields_after_update( metric.update(predictions, targets).compute() +def test_mask_content_preserves_compact_mask() -> None: + """CompactMask inputs stay compact for mask IoU.""" + dense_mask = np.zeros((1, 4, 5), dtype=bool) + dense_mask[0, 1:3, 1:4] = True + xyxy = np.array([[1, 1, 4, 3]], dtype=np.float64) + compact_mask = CompactMask.from_dense( + dense_mask, xyxy=xyxy, image_shape=dense_mask.shape[1:] + ) + detections = Detections(xyxy=xyxy, mask=compact_mask) + metric = MeanAverageRecall(metric_target=MetricTarget.MASKS) + + content = metric._detections_content(detections) + + assert content is compact_mask + + +def test_compute_with_compact_mask_matches_dense() -> None: + """MeanAverageRecall.compute() yields same recall_scores for CompactMask.""" + masks = np.zeros((1, 50, 50), dtype=bool) + masks[0, 10:20, 10:20] = True + xyxy = np.array([[10, 10, 19, 19]], dtype=np.float64) + cm = CompactMask.from_dense(masks, xyxy, image_shape=(50, 50)) + det_dense = Detections( + xyxy=xyxy, mask=masks, confidence=np.array([0.9]), class_id=np.array([0]) + ) + det_compact = Detections( + xyxy=xyxy, mask=cm, confidence=np.array([0.9]), class_id=np.array([0]) + ) + metric = MeanAverageRecall(metric_target=MetricTarget.MASKS) + + r_dense = metric.update(det_dense, det_dense).compute() + metric.reset() + r_compact = metric.update(det_compact, det_compact).compute() + + np.testing.assert_allclose(r_dense.recall_scores, r_compact.recall_scores) + + def test_single_perfect_detection() -> None: """Test that a single perfect detection yields 1.0 recall.""" detections = Detections( diff --git a/tests/metrics/test_recall.py b/tests/metrics/test_recall.py index 2e53a9d8..225dc3e7 100644 --- a/tests/metrics/test_recall.py +++ b/tests/metrics/test_recall.py @@ -1,6 +1,7 @@ import numpy as np import pytest +from supervision.detection.compact_mask import CompactMask from supervision.detection.core import Detections from supervision.metrics.core import AveragingMethod, MetricTarget from supervision.metrics.recall import Recall @@ -53,6 +54,41 @@ class TestRecall: assert metric._metric_target == MetricTarget.MASKS assert metric.averaging_method == AveragingMethod.MACRO + def test_mask_content_preserves_compact_mask(self) -> None: + """CompactMask inputs stay compact for mask IoU.""" + dense_mask = np.zeros((1, 4, 5), dtype=bool) + dense_mask[0, 1:3, 1:4] = True + xyxy = np.array([[1, 1, 4, 3]], dtype=np.float64) + compact_mask = CompactMask.from_dense( + dense_mask, xyxy=xyxy, image_shape=dense_mask.shape[1:] + ) + detections = Detections(xyxy=xyxy, mask=compact_mask) + metric = Recall(metric_target=MetricTarget.MASKS) + + content = metric._detections_content(detections) + + assert content is compact_mask + + def test_compute_with_compact_mask_matches_dense(self) -> None: + """Recall.compute() yields same recall_at_50 for CompactMask and dense.""" + masks = np.zeros((1, 50, 50), dtype=bool) + masks[0, 10:20, 10:20] = True + xyxy = np.array([[10, 10, 19, 19]], dtype=np.float64) + cm = CompactMask.from_dense(masks, xyxy, image_shape=(50, 50)) + det_dense = Detections( + xyxy=xyxy, mask=masks, confidence=np.array([0.9]), class_id=np.array([0]) + ) + det_compact = Detections( + xyxy=xyxy, mask=cm, confidence=np.array([0.9]), class_id=np.array([0]) + ) + metric = Recall(metric_target=MetricTarget.MASKS) + + r_dense = metric.update(det_dense, det_dense).compute() + metric.reset() + r_compact = metric.update(det_compact, det_compact).compute() + + assert r_dense.recall_at_50 == pytest.approx(r_compact.recall_at_50) + def test_reset(self, dummy_prediction): """Test that reset() clears all stored data""" metric = Recall()