Skip to content

Instance Segmentation Confusion Matrix - #240

Closed
mayankagarwals wants to merge 1 commit into
roboflow:developfrom
mayankagarwals:segmentationConfusionMat
Closed

mayankagarwals wants to merge 1 commit into
roboflow:developfrom
mayankagarwals:segmentationConfusionMat

Conversation

@mayankagarwals

@mayankagarwals mayankagarwals commented Jul 25, 2023 •

Copy link
Copy Markdown
Contributor

Description

Solves for #238

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • This change requires a documentation update

How has this change been tested, please provide a testcase or example of how you tested the change?

Please use this colab for testing: https://colab.research.google.com/drive/1OKjyH8JmFMROJ97447DUn13p-GDP6dXl
Test cases have been added

Comment thread supervision/detection/utils.py Outdated
return area_inter / (area_true[:, None] + area_detection - area_inter)


def mask_iou_batch(masks_true: np.ndarray, masks_detection: np.ndarray) -> np.ndarray:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@mayankagarwals let's add unit tests

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hey! Yep, waiting for some discussion to happen with respect to API here #238 before completing the feature

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added!

@SkalskiP

SkalskiP commented Aug 1, 2023

Copy link
Copy Markdown
Collaborator

Hi @mayankagarwals 👋🏻! Is that code ready for review? It is still marked as draft.

@SkalskiP SkalskiP added the enhancement New feature or request label Aug 1, 2023
@SkalskiP SkalskiP added this to the version: 0.13.0 milestone Aug 1, 2023
@SkalskiP SkalskiP added the version: 0.13.0 Feature to be added in `0.13.0` release label Aug 1, 2023
@mayankagarwals

Copy link
Copy Markdown
Contributor Author

Hey @SkalskiP. No, the code is still not complete as I'm waiting for your input on #238. There are two different ways we can design the API.

@SkalskiP SkalskiP added the version 0.14.0 Feature to be added in `0.14.0` release label Aug 7, 2023
@SkalskiP

SkalskiP commented Aug 7, 2023

Copy link
Copy Markdown
Collaborator

@mayankagarwals okey I'm rolling that PR over to supervision-0.14.0

@CLAassistant

CLAassistant commented Aug 11, 2023 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@mayankagarwals

mayankagarwals commented Aug 15, 2023 •

Copy link
Copy Markdown
Contributor Author

Hi @kirilllzaitsev @hardikdava @SkalskiP

While the code here is functional, I wanted to ask your opinion on force_masks

Right now I'm assuming if force_masks is passed we will enforce that every detection in the from_detections is accompanied by a mask.
The segmentation confusion matrix is computed only when force_masks is passed

@kirilllzaitsev

Copy link
Copy Markdown
Contributor

@mayankagarwals hey, this PR should be relevant. force_masks=True refers to the case when the masks are enforced, while if force_masks=False, but the masks are present in annotations ('segmentation' field), they will be parsed since now

@mayankagarwals

mayankagarwals commented Aug 16, 2023 •

Copy link
Copy Markdown
Contributor Author

hi @kirilllzaitsev!

Cool! I guess then it makes sense to provide a segmentation matrix only if force_masks = true.

@kirilllzaitsev @hardikdava
Before I wrap up the documentation and tests, can you please go through the PR and let me know if you have any queries or concerns?

@mayankagarwals
mayankagarwals marked this pull request as ready for review August 18, 2023 12:29
@mayankagarwals

Copy link
Copy Markdown
Contributor Author

@SkalskiP @hardikdava
PR is ready for review. Have added a colab link for testing.

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.

Pull request overview

This PR extends the existing ConfusionMatrix metric to optionally compute an additional confusion matrix based on instance-segmentation mask IoU, addressing the request in issue #238 while keeping the existing box-based confusion matrix behavior.

Changes:

  • Added mask_iou_batch utility for computing pairwise IoU between sets of boolean masks.
  • Extended ConfusionMatrix to optionally compute and return a segmentation-based confusion matrix alongside the box-based one.
  • Added/updated tests to cover mask IoU and the new segmentation confusion matrix behavior.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 10 comments.

File Description
supervision/detection/utils.py Adds mask_iou_batch for mask IoU computation (used by metrics).
supervision/metrics/detection.py Extends ConfusionMatrix to compute segmentation confusion matrix and adds force_masks plumbing.
test/metrics/test_detection.py Adds test coverage for mask IoU and segmentation confusion matrix cases.

Comment thread test/metrics/test_detection.py Outdated
max_x = int(np.max(detection_tensors[0][:, [0, 2]]))
max_x = max(max_x, int(np.max(target_tensors[0][:, [0, 2]])))
max_y = int(np.max(detection_tensors[0][:, [1, 3]]))
max_y = max(max_x, int(np.max(target_tensors[0][:, [1, 3]])))
Comment thread supervision/metrics/detection.py Outdated
classes: List[str],
conf_threshold: float = 0.3,
iou_threshold: float = 0.5,
force_masks=True,
Comment thread supervision/metrics/detection.py Outdated
Comment on lines +115 to +119
force_masks (bool, default=True):
If True, the ConfusionMatrix.segmentationMatrix is computed.
Otherwise, it is None
If this value is set to True and masks
are not present for some images, error will be thrown.
Comment thread supervision/metrics/detection.py Outdated
Comment on lines +166 to +171
if force_masks:
if prediction.mask is None or target.mask is None:
raise Exception(
"Please make sure all images have corresponding mask"
" annotations"
)
Comment thread supervision/metrics/detection.py Outdated
iou_threshold: float,
prediction_mask: Optional[np.ndarray] = None,
target_mask: Optional[np.ndarray] = None,
) -> np.ndarray:
Comment thread supervision/metrics/detection.py Outdated
Comment on lines 427 to 433
iou_mask = (
target_mask
if target_mask is None
else mask_iou_batch(
masks_true=target_mask, masks_detection=detection_mask_batch_filtered
)
matches = ConfusionMatrix._drop_extra_matches(matches=matches)
else:
matches = np.zeros((0, 3))

matched_true_idx, matched_detection_idx, _ = matches.transpose().astype(
np.int16
)
Comment thread supervision/metrics/detection.py Outdated
Comment on lines 470 to 474
callback: Callable[[np.ndarray], Detections],
conf_threshold: float = 0.3,
iou_threshold: float = 0.5,
force_masks=True,
) -> ConfusionMatrix:
Comment thread supervision/detection/utils.py Outdated
Comment on lines +58 to +78
def mask_iou_batch(masks_true: np.ndarray, masks_detection: np.ndarray) -> np.ndarray:
"""
Compute Intersection over Union (IoU) of two sets of masks - `masks_true`
and `masks_detection`. Both sets of masks are expected to be of type np.ndarray

Args:
masks_true (np.ndarray): 3D `np.ndarray` representing ground-truth
segmentation mask. `shape = (N, W, H)` where `N` is number of true objects.
masks_detection (np.ndarray): 3D `np.ndarray` representing detection
segmentation mask. `shape = (M, W, H)` where `M` is number of detected objects.

Returns:
np.ndarray: Pairwise IoU of masks from `masks_true` and
`masks_detection`. `shape = (N, M)`
where `N` is number of true objects and `M` is number of detected objects.
"""

intersection = np.logical_and(masks_true[:, None], masks_detection).sum((2, 3))
union = np.logical_or(masks_true[:, None], masks_detection).sum((2, 3))

return intersection / union
Comment thread supervision/metrics/detection.py Outdated
Comment on lines 89 to 93
classes: List[str]
conf_threshold: float
iou_threshold: float
segmentationMatrix: Optional[np.ndarray] = None

Comment thread supervision/metrics/detection.py Outdated
Comment on lines +275 to +279
segmentation_matrix = (
prediction_masks
if prediction_masks is None
else (np.zeros((num_classes + 1, num_classes + 1)))
)
Adds segmentation confusion-matrix support by mirroring the existing
ORIENTED_BOUNDING_BOXES dispatch pattern: masks are threaded as a parallel
optional argument (they can't flatten into the tensor row like OBB
coordinates), and evaluate_detection_batch/_split_detections_by_outcome
dispatch to mask_iou_batch. Reuses the existing vectorized mask_iou_batch
(matmul-based, chunked, zero-guarded) rather than introducing a new one.

Removes _assert_supported_target, which previously rejected MASKS
unconditionally at every entry point. Converts the 3 rejection tests to
assert ValueError only when masks are actually missing, and adds
positive coverage for perfect overlap, mask-IoU-vs-box-IoU divergence,
and IoU-threshold sensitivity.

Supersedes PR roboflow#240's force_masks/segmentationMatrix approach, which
targeted the pre-src/ layout and predates this metric_target axis.
@codecov

codecov Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.20690% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 87%. Comparing base (937ed4a) to head (ace6129).
⚠️ Report is 164 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff           @@
##           develop    #240   +/-   ##
=======================================
- Coverage       87%     87%   -0%     
=======================================
  Files           84      84           
  Lines        11797   11816   +19     
=======================================
+ Hits         10209   10224   +15     
- Misses        1588    1592    +4     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@kemo04

kemo04 commented Jul 22, 2026

Copy link
Copy Markdown

AI Code Review (PR Review Agent)

  • [Logic & Correctness · High] — supervision/metrics/detection.py (diff line 53): Removing the f-string prefix while keeping f-string interpolation syntax results in a literal string containing unparsed braces instead of the intended values.

@Borda

Borda commented Sep 22, 2026

Copy link
Copy Markdown
Member

Hi @mayankagarwals — thanks for the work here, and sorry this sat for so long without a real answer.

Instance-segmentation support for ConfusionMatrix landed in #2612, merged just now. It closes the same issue (#238) but takes a different shape than this PR: instead of a separate force_masks flag and a parallel segmentation matrix, it plugs masks into the MetricTarget axis that boxes and OBB already dispatch through, so ConfusionMatrix.from_detections(..., metric_target=MetricTarget.MASKS) scores by mask IoU using the existing mask_iou_batch. That API didn't exist yet back when this PR was opened in 2023, which is why the two approaches diverged and this one never found a clean way to rebase.

Given that, I'm closing this PR — the functionality it targeted is now covered by #2612. I know that's a frustrating outcome for work that was otherwise sound; the review discussion here (the force_masks semantics in particular) was genuinely useful context. Thank you for pushing on this early and for your patience.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request has conflicts version: 0.13.0 Feature to be added in `0.13.0` release version 0.14.0 Feature to be added in `0.14.0` release

Projects

Status: Current Release: Done

Development

Successfully merging this pull request may close these issues.

7 participants