Skip to content

feat(metrics): score ConfusionMatrix on masks with MetricTarget.MASKS - #2612

Merged
Borda merged 5 commits into
roboflow:developfrom
raghav-rathi:feat/confusion-matrix-masks
Sep 22, 2026
Merged

Borda merged 5 commits into
roboflow:developfrom
raghav-rathi:feat/confusion-matrix-masks

Conversation

@raghav-rathi

Copy link
Copy Markdown
Contributor

Description

sv.ConfusionMatrix raised MetricTarget.MASKS is not currently supported while Precision, Recall, F1Score, MeanAveragePrecision and MeanAverageRecall all score masks. An instance segmentation model could only be scored on its boxes, so two instances that share a box but not a shape counted as a match:

import numpy as np
import supervision as sv
from supervision.metrics import MetricTarget

tri = np.tril(np.ones((16, 16), dtype=bool))
target_mask = np.zeros((1, 32, 32), dtype=bool)
predicted_mask = np.zeros((1, 32, 32), dtype=bool)
target_mask[0, 4:20, 4:20] = tri        # lower-left triangle
predicted_mask[0, 4:20, 4:20] = ~tri    # upper-right triangle, same box
box = np.array([[4, 4, 19, 19]], dtype=np.float32)
targets = [sv.Detections(xyxy=box, mask=target_mask, class_id=np.array([0]))]
predictions = [sv.Detections(xyxy=box, mask=predicted_mask, class_id=np.array([0]), confidence=np.array([0.9]))]

sv.ConfusionMatrix.from_detections(predictions, targets, classes=["box"]).matrix
# [[1, 0], [0, 0]]   box IoU is 1.0 -> TP
sv.ConfusionMatrix.from_detections(predictions, targets, classes=["box"], metric_target=MetricTarget.MASKS).matrix
# develop:  ValueError: MetricTarget.MASKS is not currently supported for ConfusionMatrix.
# this PR:  [[0, 1], [1, 0]]   the shapes share no pixel -> FN + FP

from_detections and benchmark now accept MetricTarget.MASKS and match by mask IoU (mask_iou_batch; dense (N, H, W) or CompactMask). The validation grids from benchmark(save_directory_path=...) fill each mask, so a panel shows the geometry the outcome was decided on.

Motivation and Context

Closes #238. The direction agreed there was a single sv.ConfusionMatrix for boxes and masks; metric_target is that switch, it just did not accept masks yet.

Changes Made

  • metrics/detection.py: the greedy same-class-first, IoU-descending matching the box and OBB paths used is extracted into _confusion_matrix_from_iou and shared by all three targets; _evaluate_mask_batch scores one image from Detections.mask; _split_detections_by_outcome and the grid panels get the mask branch.
  • Validation: a non-empty Detections without mask, or predictions and targets whose masks differ in resolution, raise ValueError; Detections.empty() needs no masks. from_detections also raises when predictions and targets differ in length instead of silently scoring the shorter list.
  • from_tensors, evaluate_detection_batch and detections_to_tensor still reject masks, which have no tensor row layout; the message now points at from_detections.
  • Docstrings (with a mask doctest) and a changelog entry under Unreleased.

Testing

  • tests/metrics/test_detection.py::TestConfusionMatrixMasks, 18 cases: boxes agree / masks disagree, disjoint shapes in one box, multi-class misclassification, IoU threshold applied to mask IoU, confidence filter, empty images without masks, missing-mask and resolution-mismatch errors, length mismatch, CompactMask parity with dense, split-by-outcome on masks, benchmark grid fills. On develop they fail with the ValueError above.

  • pytest tests/metrics: 413 passed. Full suite without OpenCV: 3755 passed, 23 skipped (develop: 3737 / 23). Doctests pass; ruff, docformatter, codespell clean; mypy reports the same errors as develop.

  • Real data: yolo11n-seg on coco128-seg (128 images, 929 GT masks via DetectionDataset.from_yolo(force_masks=True), conf 0.25, IoU 0.5). BOXES: TP 476 / FP 126 / FN 439. MASKS: TP 440 / FP 164 / FN 477. The 36 box matches that fail on mask IoU are mostly person (-16), dining table (-5) and umbrella (-4): boxes that overlap while the shapes do not. Mask IoU over all 128 images took 1.4 s on CPU.

  • Added/updated tests, and the full suite passes locally

  • Updated docs (docstrings / mkdocs entry) for new or changed public API

  • Added a changelog entry in docs/changelog.md under Unreleased

Additional Notes

#240 (2023) implemented this against the pre-metric_target API and has been in conflict since; this PR does not build on it.

@CLAassistant

CLAassistant commented Sep 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@Borda
Borda requested a balanced review from Copilot September 21, 2026 20:36
@Borda Borda added the enhancement New feature or request label Sep 21, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Mask validation can be bypassed by filtering or empty-side paths, and repository documentation conventions remain unmet.

Get a fresh assessment by requesting another Copilot review.

Review effort: Balanced
Findings: 2 Medium severity · 8 Low severity

Open (10)
What changed in this PR

Adds mask-IoU scoring to ConfusionMatrix for instance segmentation.

Changes:

  • Supports dense and compact masks in detection and benchmark paths.
  • Shares greedy IoU matching across boxes, OBBs, and masks.
  • Adds mask-focused tests, visualization, documentation, and changelog coverage.
File Description
src/​supervision/​metrics/​detection.py Implements mask scoring and visualization.
tests/​metrics/​test_detection.py Adds mask confusion-matrix tests.
docs/​changelog.md Documents the feature.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/supervision/metrics/detection.py Resolved
Comment thread src/supervision/metrics/detection.py Resolved
Comment thread docs/changelog.md Resolved
Comment thread tests/metrics/test_detection.py Resolved
Comment thread tests/metrics/test_detection.py Resolved
Comment thread tests/metrics/test_detection.py Resolved
Comment thread tests/metrics/test_detection.py Resolved
Comment thread tests/metrics/test_detection.py Resolved
Comment thread tests/metrics/test_detection.py Resolved
Comment thread tests/metrics/test_detection.py Resolved
raghav-rathi added a commit to raghav-rathi/supervision that referenced this pull request Sep 22, 2026
Review follow-up for roboflow#2612. _evaluate_mask_batch and
_split_detections_by_outcome checked for masks and matching
resolution only after the confidence filter and the empty-side
returns, so a prediction dropped by the threshold, or an empty
other side, hid a missing mask or a resolution mismatch and the
image scored silently. Validate the unfiltered inputs first.

Also: changelog links the PR instead of the issue, and the new
test helpers carry docstrings and type hints.
raghav-rathi and others added 3 commits September 22, 2026 04:22
ConfusionMatrix raised "MetricTarget.MASKS is not currently supported"
while Precision, Recall, F1Score, MeanAveragePrecision and
MeanAverageRecall all accept masks. from_detections and benchmark now
match predictions to targets by mask IoU (mask_iou_batch, dense or
CompactMask) through the same greedy same-class-first matching the box
and OBB paths use, which is extracted into a shared helper. Validation
grids written by benchmark(save_directory_path=...) fill each mask.

Masks have no tensor row layout, so from_tensors,
evaluate_detection_batch and detections_to_tensor keep rejecting them
and now point at from_detections. from_detections also raises when
predictions and targets differ in length instead of scoring the shorter
list.

Refs roboflow#238
Review follow-up for roboflow#2612. _evaluate_mask_batch and
_split_detections_by_outcome checked for masks and matching
resolution only after the confidence filter and the empty-side
returns, so a prediction dropped by the threshold, or an empty
other side, hid a missing mask or a resolution mismatch and the
image scored silently. Validate the unfiltered inputs first.

Also: changelog links the PR instead of the issue, and the new
test helpers carry docstrings and type hints.
@raghav-rathi
raghav-rathi force-pushed the feat/confusion-matrix-masks branch from 180b393 to f73f725 Compare September 22, 2026 08:25
@codecov

codecov Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.80220% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 92%. Comparing base (6deb6e2) to head (1a1df83).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2612   +/-   ##
=======================================
  Coverage       92%     92%           
=======================================
  Files           78      78           
  Lines        11603   11662   +59     
=======================================
+ Hits         10617   10674   +57     
- Misses         986     988    +2     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread src/supervision/metrics/detection.py Resolved
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@Borda Borda changed the title feat(metrics): score ConfusionMatrix on masks with MetricTarget.MASKS feat(metrics): score ConfusionMatrix on masks with MetricTarget.MASKS Sep 22, 2026
@Borda
Borda merged commit f132aa0 into roboflow:develop Sep 22, 2026
36 checks passed
@Borda Borda mentioned this pull request Sep 22, 2026
1 of 3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Instance Segmentation Confusion Matrix

4 participants