Repository navigation
feat(metrics): score ConfusionMatrix on masks with MetricTarget.MASKS - #2612
Conversation
There was a problem hiding this comment.
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
Open (10)
Validate masks and resolutions before filtering and early returns · New Validate masks before empty-side branches · New Link the changelog entry to the pull request · New Add a docstring to the new helper · New Type the call parameter as a zero-argument callable · New Add a docstring to the new helper method · New Add scenario docstrings to parametrized tests · New Add a Path type annotation to tmp_path · New Add a docstring to the local class · New Annotate and document the new iterator helper · New
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.
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.
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.
180b393 to
f73f725
Compare
Codecov Report❌ Patch coverage is 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:
|
There was a problem hiding this comment.
Copilot review overview
🟢 Approval recommended
The implementation and tests are comprehensive; only minor non-blocking example wording remains.
Review effort: Balanced
Findings: 1
Resolved since last review (10)
Validate masks before empty-side branches Validate masks and resolutions before filtering and early returns Annotate and document the new iterator helper Add a docstring to the local class Add a Path type annotation to tmp_path Add scenario docstrings to parametrized tests Add a docstring to the new helper method Type the call parameter as a zero-argument callable Add a docstring to the new helper Link the changelog entry to the pull request
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
ConfusionMatrix on masks with MetricTarget.MASKS


Description
sv.ConfusionMatrixraisedMetricTarget.MASKS is not currently supportedwhilePrecision,Recall,F1Score,MeanAveragePrecisionandMeanAverageRecallall 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:from_detectionsandbenchmarknow acceptMetricTarget.MASKSand match by mask IoU (mask_iou_batch; dense(N, H, W)orCompactMask). The validation grids frombenchmark(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.ConfusionMatrixfor boxes and masks;metric_targetis 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_iouand shared by all three targets;_evaluate_mask_batchscores one image fromDetections.mask;_split_detections_by_outcomeand the grid panels get the mask branch.Detectionswithoutmask, or predictions and targets whose masks differ in resolution, raiseValueError;Detections.empty()needs no masks.from_detectionsalso raises whenpredictionsandtargetsdiffer in length instead of silently scoring the shorter list.from_tensors,evaluate_detection_batchanddetections_to_tensorstill reject masks, which have no tensor row layout; the message now points atfrom_detections.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,CompactMaskparity with dense, split-by-outcome on masks,benchmarkgrid fills. Ondevelopthey fail with theValueErrorabove.pytest tests/metrics: 413 passed. Full suite without OpenCV: 3755 passed, 23 skipped (develop: 3737 / 23). Doctests pass;ruff,docformatter,codespellclean;mypyreports the same errors asdevelop.Real data:
yolo11n-segoncoco128-seg(128 images, 929 GT masks viaDetectionDataset.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 mostlyperson(-16),dining table(-5) andumbrella(-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.mdunderUnreleasedAdditional Notes
#240 (2023) implemented this against the pre-
metric_targetAPI and has been in conflict since; this PR does not build on it.