Repository navigation
fix(detection): anchor empty masks at box center for CENTER_OF_MASS - #2976
Conversation
`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 Report✅ All modified and coverable lines are covered by tests. 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:
|
CENTER_OF_MASS
There was a problem hiding this comment.
🟡 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_MASSfallback for dense masks andCompactMask, 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
| 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
left a comment
There was a problem hiding this comment.
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. Withdetection/core.pyreverted to the merge base (f0767b1): 9 failed, 5 passed, theLineZonetest withassert (1, 1) == (0, 0), as the description says.- I changed the new block eight ways in a copy (for example
anytoall, top-left instead of center, noCompactMaskfallback, swappednp.wherebranches). Each change fails at least two of the new tests. pytest tests/detection tests/annotators: 3223 passed, 12 skipped. Merged locally into today'sdevelop(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
Detectionsindexed by int, slice, list and boolean mask, dense andCompactMask. Empty masks get the box center and the other centroids are unchanged. - The extra
arearead 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.
…nchor # Conflicts: # docs/changelog.md
|
Thank you for the careful one @YusefSyed. you're right about the changelog: the On the two inputs: |
YusefSyed
left a comment
There was a problem hiding this comment.
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.
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]>

Description
Detections.get_anchors_coordinates(Position.CENTER_OF_MASS)now anchors a detection whose mask has no pixels at the center of itsxyxybox, instead of the frame's top-left corner (0, 0). It works for dense masks andCompactMask. Centroids of non-empty masks are unchanged.sv.calculate_masks_centroidsis untouched.Motivation and Context
A mask with no pixels has no centroid.
calculate_masks_centroidsguards its division by zero and reports (0, 0), so every consumer of theCENTER_OF_MASSanchor 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 ondevelop:LineZonecount a phantom crossing (in=1, out=1, expected 0/0).PolygonZonereports it in the zone when the zone contains the corner.DotAnnotator,LabelAnnotatorandTraceAnnotatordraw at (0, 0).Closes #2975
Changes Made
Detections.get_anchors_coordinates: forCENTER_OF_MASS, detections witharea == 0use the box centre (truncated to int like the centroids). The docstring is updated. ForCompactMaskthe area comes from the RLE, with no decode.TestGetAnchorsCenterOfMassEmptyMask(dense andCompactMask, 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 aLineZoneend-to-end test (a stationary object with an empty mask gives in=0 / out=0).calculate_masks_centroidsitself still returns (0, 0) for an empty mask.Testing
pytest tests/detection/test_core.py tests/detection/test_line_counter.py -k EmptyMaskdevelop(the fix reverted): 9 failed, 5 passed (the 5 are regression guards: dtype, non-empty unchanged, other anchors, no-mask still raises). TheLineZonetest fails withassert (1, 1) == (0, 0).pytest tests/detection tests/annotators: 3035 passed, 12 skippedThe reproduction above now prints
0 0; the anchor is[[100, 90]],PolygonZoneno 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/detectionandtests/annotatorspass locally; the full suite was not run becausetests/metricsneeds optional extras that are not installed here.Updated docs (docstrings / mkdocs entry) for new or changed public API (the
get_anchors_coordinatesdocstring)Added a changelog entry in
docs/changelog.mdunderUnreleasedAdditional Notes
Detectionsand leftcalculate_masks_centroidsalone, because existing tests pin its (0, 0) result for the standalone helper (TestCalculateMasksCentroidsCompactand the all-zeros case intest_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.ValueErrorforCENTER_OF_MASS, as before.xyxycentre, consistent withCENTER_OF_MASSignoring OBB corners.arearead, which for dense masks is a pixel count comparable to the centroid helper's own work, and forCompactMaskis read from the RLE.