Skip to content

fix(detection): anchor empty masks at box center for CENTER_OF_MASS - #2976

Merged
Borda merged 8 commits into
roboflow:developfrom
avanish-garg:fix/empty-mask-anchor
Nov 24, 2026
Merged

Borda merged 8 commits into
roboflow:developfrom
avanish-garg:fix/empty-mask-anchor

Conversation

@avanish-garg

Copy link
Copy Markdown
Contributor

Description

Detections.get_anchors_coordinates(Position.CENTER_OF_MASS) now anchors a detection whose mask has no pixels at the center of its xyxy box, instead of the frame's top-left corner (0, 0). It works for dense masks and CompactMask. Centroids of non-empty masks are unchanged. sv.calculate_masks_centroids is untouched.

Motivation and Context

A mask with no pixels has no centroid. calculate_masks_centroids guards its division by zero and reports (0, 0), so every consumer of the CENTER_OF_MASS anchor acts on the top-left corner. A segmentation detection can easily end up with an empty mask (a small object lost to thresholding or resizing; see #2631 and #2741 for other empty-mask handling). Visible effects on develop:

  • A stationary object whose mask is empty in one frame makes LineZone count a phantom crossing (in=1, out=1, expected 0/0).
  • PolygonZone reports it in the zone when the zone contains the corner.
  • DotAnnotator, LabelAnnotator and TraceAnnotator draw at (0, 0).
import numpy as np
import supervision as sv

H, W = 120, 160


def make(empty):
    mask = np.zeros((1, H, W), bool)
    if not empty:
        mask[0, 80:100, 90:110] = True
    return sv.Detections(
        xyxy=np.array([[90.0, 80.0, 110.0, 100.0]]), mask=mask, tracker_id=np.array([7])
    )


line = sv.LineZone(sv.Point(0, 50), sv.Point(W, 50), triggering_anchors=[sv.Position.CENTER_OF_MASS])
for empty in [False, False, True, False, False]:
    line.trigger(make(empty))
print(line.in_count, line.out_count)  # develop: 1 1, expected 0 0

Closes #2975

Changes Made

  • Detections.get_anchors_coordinates: for CENTER_OF_MASS, detections with area == 0 use the box centre (truncated to int like the centroids). The docstring is updated. For CompactMask the area comes from the RLE, with no decode.
  • Tests: TestGetAnchorsCenterOfMassEmptyMask (dense and CompactMask, mixed batch, all-empty batch, integer dtype, oriented-box data present, non-empty centroids unchanged, other anchors unchanged, detections without a mask still raise) and a LineZone end-to-end test (a stationary object with an empty mask gives in=0 / out=0).
  • Changelog entry under Unreleased.
  • Out of scope: calculate_masks_centroids itself still returns (0, 0) for an empty mask.

Testing

  • pytest tests/detection/test_core.py tests/detection/test_line_counter.py -k EmptyMask

    • on develop (the fix reverted): 9 failed, 5 passed (the 5 are regression guards: dtype, non-empty unchanged, other anchors, no-mask still raises). The LineZone test fails with assert (1, 1) == (0, 0).
    • with this change: 14 passed
  • pytest tests/detection tests/annotators: 3035 passed, 12 skipped

  • The reproduction above now prints 0 0; the anchor is [[100, 90]], PolygonZone no longer reports the object in the zone and the dot is drawn at (100, 90).

  • ruff check, ruff format and docformatter on the changed files: clean.

  • Added/updated tests. tests/detection and tests/annotators pass locally; the full suite was not run because tests/metrics needs optional extras that are not installed here.

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

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

Additional Notes

  • I kept the fallback in Detections and left calculate_masks_centroids alone, because existing tests pin its (0, 0) result for the standalone helper (TestCalculateMasksCentroidsCompact and the all-zeros case in test_masks.py), and the helper has no box to fall back to. Happy to move it into the helper, or return NaN / drop empty masks instead, if you prefer; that changes a public function's contract and 2 to 3 existing tests.
  • Detections without any mask still raise ValueError for CENTER_OF_MASS, as before.
  • With oriented-box data present and an empty mask, the fallback uses the xyxy centre, consistent with CENTER_OF_MASS ignoring OBB corners.
  • Cost: one extra area read, which for dense masks is a pixel count comparable to the centroid helper's own work, and for CompactMask is read from the RLE.

`Detections.get_anchors_coordinates(Position.CENTER_OF_MASS)` returned
(0, 0) for a detection whose mask has no pixels, because
`calculate_masks_centroids` guards its division by zero and reports the
frame's top-left corner. A stationary object with one empty mask then made
`LineZone` count a phantom in+out crossing, `PolygonZone` report it inside a
zone containing the corner, and the dot, label and trace annotators draw at
the corner.

Fall back to the center of the `xyxy` box for detections whose mask is empty,
for dense masks and `CompactMask` alike. Centroids of non-empty masks are
unchanged and `calculate_masks_centroids` still returns (0, 0) for an empty
mask.
# Conflicts:
#	docs/changelog.md
#	tests/detection/test_line_counter.py
@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95%. Comparing base (1e2ac13) to head (fee129d).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2976   +/-   ##
=======================================
  Coverage       95%     95%           
=======================================
  Files           84      84           
  Lines        15607   15612    +5     
=======================================
+ Hits         14897   14902    +5     
  Misses         710     710           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Borda
Borda requested a balanced review from Copilot November 13, 2026 09:35
@Borda Borda added the bug Something isn't working label Nov 13, 2026
@Borda Borda changed the title fix(detection): anchor empty masks at the box center for CENTER_OF_MASS fix(detection): anchor empty masks at box center for CENTER_OF_MASS Nov 13, 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.

🟡 Changes recommended

Empty masks with large supported uint64 box coordinates can produce incorrect center anchors because the integer cast exceeds the signed range, requiring range-aware conversion and a regression test.

1 open issue
What changed in this PR

This PR addresses #2975 by anchoring detections with empty masks at their bounding-box centers instead of (0, 0), preventing false zone events and misplaced annotations.

Changes:

  • Adds the CENTER_OF_MASS fallback for dense masks and CompactMask, leaving non-empty centroids and the standalone helper unchanged.
  • Adds anchor regression tests and a LineZone test for a stationary object with an intermittently empty mask.
  • Updates the method documentation and changelog.
File Description
tests/​detection/​test_line_counter.py Tests that empty-mask frames do not cause phantom crossings.
tests/​detection/​test_core.py Tests fallback coordinates and existing anchor behavior.
src/​supervision/​detection/​core.py Implements and documents the box-center fallback.
docs/​changelog.md Adds anchor-fallback and label-positioning changelog entries.

Review effort: Balanced

Comment on lines +2363 to +2370
if np.any(is_empty_mask):
box_centers = coordinates(
_box_midpoint(xyxy[:, 0], xyxy[:, 2]),
_box_midpoint(xyxy[:, 1], xyxy[:, 3]),
).astype(centroids.dtype)
centroids = np.where(
is_empty_mask[:, np.newaxis], box_centers, centroids
)

@YusefSyed YusefSyed left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Checked at c249045 on Python 3.12.13 with NumPy 2.5.4 and opencv-python-headless 5.0.0.

  • pytest tests/detection/test_core.py tests/detection/test_line_counter.py -k EmptyMask: 14 passed. With detection/core.py reverted to the merge base (f0767b1): 9 failed, 5 passed, the LineZone test with assert (1, 1) == (0, 0), as the description says.
  • I changed the new block eight ways in a copy (for example any to all, top-left instead of center, no CompactMask fallback, swapped np.where branches). Each change fails at least two of the new tests.
  • pytest tests/detection tests/annotators: 3223 passed, 12 skipped. Merged locally into today's develop (5f9e21e): 3309 passed, 12 skipped.
  • ruff, docformatter, codespell, mdformat and mypy on the changed files: clean.
  • I also tried empty batches, uint8 masks, strided and Fortran-order masks, integer and float16 boxes, boxes partly or fully outside the frame, zero-area boxes, and Detections indexed by int, slice, list and boolean mask, dense and CompactMask. Empty masks get the box center and the other centroids are unchanged.
  • The extra area read measured 3 to 5 ms, next to 80 to 120 ms for the whole call, with 30 dense 1080p masks.

Two things.

1. Changelog. The diff adds a second entry besides this PR's: the sv.LabelAnnotator / sv.RichLabelAnnotator smart_position=True line for #2940. That change shipped in 0.31.7 and is already listed under ### 0.31.7 further down the file, so after this merges it appears twice, once under Unreleased. It seems to have come back with the merge of develop (c249045); the first commit only adds the #2976 line. Dropping that line from this PR fixes it.

2. Two inputs where the anchor still jumps. Not blockers, but they bear on the box center versus NaN or drop question in the notes.

Box derived from the mask: sv.mask_to_xyxy gives [0, 0, 0, 0] for an empty mask, so the box center is the corner again. from_transformers derives its boxes this way for segmentation results that carry no boxes.

masks = np.zeros((1, 120, 160), dtype=bool)
detections = sv.Detections(xyxy=sv.mask_to_xyxy(masks), mask=masks)
detections.get_anchors_coordinates(sv.Position.CENTER_OF_MASS)  # [[0, 0]]

With the reproduction from the description and xyxy=sv.mask_to_xyxy(mask), LineZone still prints 1 1 on this branch, and a PolygonZone over the top-left corner still reports the object inside.

Mask that does not fill its box: the fallback moves the anchor from the centroid to the box center, so a line between the two is crossed. Box [90, 20, 110, 100] with the mask on rows 80 to 99 has its centroid at (100, 90) and its empty-mask anchor at (100, 60). With frames full, full, empty, full, full and the line at y=75 I get in=1, out=1 on this branch, the same as on develop. At y=50 it is 0/0 on this branch and 1/1 on develop.

If the box center stays, a sentence in the docstring that an empty mask's anchor can differ from the centroid in the frames before and after would cover the second case.

…nchor jump

The smart_position entry for roboflow#2940 already ships under 0.31.7; remove its copy from Unreleased. Document that an empty mask's box-center anchor can differ from the centroid in neighbouring frames.
@avanish-garg

Copy link
Copy Markdown
Contributor Author

Thank you for the careful one @YusefSyed. you're right about the changelog: the smart_position bullet came back with my merge of develop and is already under 0.31.7. I removed it, so the PR adds only the #2976 entry.

On the two inputs: mask_to_xyxy gives [0, 0, 0, 0] for an empty mask, so the box center is the corner again, and I'd treat that as a separate limitation of from_transformers-style boxes rather than widen this fix. I added a sentence to the docstring that an empty mask's anchor can differ from the centroid in the frames before and after. In for opening a follow-up issue for the mask_to_xyxy case if you think it's worth tracking.

@YusefSyed YusefSyed left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks @avanish-garg. Checked at 9766b4a: the Unreleased section now has only the #2976 entry, and pytest tests/detection/test_core.py tests/detection/test_line_counter.py -k EmptyMask gives 14 passed.

Agreed on keeping the mask_to_xyxy case out of this PR. The new docstring sentence covers the mask that does not fill its box. A follow-up issue for the [0, 0, 0, 0] box that mask_to_xyxy returns for an empty mask is worth having, so please go ahead.

One more thing: develop has moved since, and docs/changelog.md now conflicts in the Unreleased section, where both sides added bullets. Keeping both sides resolves it.

Copilot's comment on the new cast also still has no reply, and it reproduces at 9766b4a: an empty mask with the uint64 box [2**63, 0, 2**63 + 2**20, 2] (the uint64-overflow case in tests/detection/test_core.py) gets a saturated CENTER_OF_MASS anchor ([[9223372036854775807, 1]] on my arm64 Mac, with NumPy's "invalid value encountered in cast" warning), while Position.CENTER on the same box keeps the 2**63 + 2**19 center. The .astype(centroids.dtype) on the box centers cannot hold that value. Promoting only when a center does not fit, as Copilot suggests, would keep it in line with CENTER. Otherwise this looks good to me.

Borda and others added 2 commits November 24, 2026 12:35
Changes:
- Integrate the current develop branch and preserve the PR's unreleased changelog entry above the 0.32.1 release notes.

Impact:
- Keep the PR compatible with the latest target changes and retain both sets of release notes.

Verification:
- Empty-mask detection and LineZone tests: 14 passed.
- Staged diff whitespace check: passed.

Residual limits:
- Tests used the NumPy fallback backend; OpenCV was not installed in the local environment.

---

Co-authored-by: Codex <[email protected]>
Changes:
- Preserve fractional and large box centers when an empty mask supplies the center-of-mass fallback.
- Add zone-boundary and large-coordinate regressions and document the floating-point result for batches containing empty masks.

Impact:
- Prevent false border-zone hits and invalid large-coordinate anchors while retaining nonempty mask centroids.

Verification:
- Full project test gate: 7786 passed, 298 skipped, 95% coverage.
- All-files pre-commit checks: passed.
- Focused detection tests: 701 passed, 3 skipped.

Residual limits:
- Local tests used the NumPy fallback backend; OpenCV-specific behavior was not exercised locally.

---

Co-authored-by: Codex <[email protected]>
@Borda
Borda merged commit 375f49c into roboflow:develop Nov 24, 2026
37 checks passed
@Borda Borda mentioned this pull request Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: A detection with an empty mask is anchored at (0, 0) for Position.CENTER_OF_MASS, giving phantom LineZone crossings and zone hits

4 participants