Skip to content

fix: make CompactMask.resize match dense nearest-neighbour resize - #2705

Merged
Borda merged 3 commits into
roboflow:developfrom
avanish-garg:fix/compact-mask-resize-parity
Oct 11, 2026
Merged

Borda merged 3 commits into
roboflow:developfrom
avanish-garg:fix/compact-mask-resize-parity

Conversation

@avanish-garg

Copy link
Copy Markdown
Contributor

Description

CompactMask.resize produced different masks than cv2.resize(..., INTER_NEAREST) on the dense masks: it
rounded each crop's offset and inclusive last pixel and resized the crops independently.

Minimal repro (full script in the issue):

  • Before: a 20x20 square resized 640x640 -> 1920x1920 covers 3364 px instead of 3600; a 1x80 line resized 2x
    covers 159 px instead of 320.
  • After: both equal the dense nearest-neighbour result exactly.

Motivation and Context

resize is documented as a nearest-neighbour resize, and the existing parity test could not fail (it
compares boolean arrays with a tolerance of 1).

Closes #2704

Changes Made

  • For each axis, the source index each output pixel samples is computed once (_nearest_source_index). It
    resizes an index ramp through supervision._cv2.resize(INTER_NEAREST), so it is exact under whichever
    backend is active. A formula such as floor(j * src / dst) is not enough: real cv2 samples
    floor(j * (1.0 / (dst / src))) in float64 and differs from integer floor in about 5% of (src, dst) pairs
    (e.g. 2 -> 98), while the NumPy fallback uses integer floor.
  • A crop covering source range [x1, x2+1) is sampled by a contiguous range of output pixels, found with
    searchsorted; each new crop is the old crop indexed by source_index - x1 per axis, then re-encoded.
    Crops that vanish when downscaling become a 1x1 empty crop with an in-bounds offset.
  • Removed _rle_resize, _rle_scale_col and _L3_DENSITY_THRESHOLD (dead after this change, and they
    encoded the per-crop semantics) together with their tests. The benchmark example's stale references and its
    <= 1 check are updated to exact equality.

Testing

Ran (not the whole suite, not pre-commit --all-files):

  • tests/detection/test_compact_mask.py: 280 passed with OpenCV 5.0.0 and with 4.12.0; 311 passed (tests +
    doctests) with the NumPy fallback; tests/detection: 2149 passed, 1 skipped.
  • pytest --doctest-modules src/supervision/detection/compact_mask.py: 31 passed.
  • ruff check, ruff format --check and mypy on the changed files: clean.
  • An independent 6000-case fuzz against dense nearest: 0 mismatches on OpenCV 5.0, OpenCV 4.12 and the fallback.
  • Not run: the benchmark example end to end (rich not installed), Python 3.10/3.13, pre-commit --all-files.

New exact-equality tests fail on develop (41 failed, 13 passed there; 6 of 7 parity cases and all 20
random seeds fail) and pass with this change.

Benchmark (300 masks, 480x640, best of 5, develop -> this change): ellipses 315 -> 27 ms (target 960x1280),
163 -> 18.5 ms (240x320), 307 -> 23 ms (700x900); noise masks unchanged (44.7 -> 43.6 ms at 960x1280).

  • 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 (skip for lint/type/format-only or pure doc changes)

(Tick the first box only after you run the full suite yourself.)

Additional Notes

  • The diff is mostly deletions: the sparse RLE-direct path could not be made exact without being 5-12x
    slower than decoding the crop and indexing it, so it was removed instead of patched.
  • Output crop offsets are no longer round(offset * scale); the existing offset tests still pass (they use
    a +-1 tolerance).
  • The benchmark example imports the private _nearest_source_index.

@avanish-garg
avanish-garg requested a review from SkalskiP as a code owner October 8, 2026 20:10
@CLAassistant

CLAassistant commented Oct 8, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

CompactMask.resize scaled the inclusive last pixel index with round() and
resized every crop independently, so crops came out too small and sampled
different source pixels than a full-image cv2.INTER_NEAREST resize. A 20x20
square on 640x640 resized to 1920x1920 covered 3364 px instead of 3600.

Map each axis once with the backend's own nearest-neighbour sampling, find
the output range that samples each crop with searchsorted, and gather the
crop's pixels with that map. A crop no output pixel samples becomes a 1x1
all-False crop. The RLE-direct sparse path is removed; decode-and-index is
about 10x faster on sparse masks and exact.
@avanish-garg
avanish-garg force-pushed the fix/compact-mask-resize-parity branch from a370fb2 to 3063df6 Compare October 8, 2026 20:21
@Borda
Borda requested a balanced review from Copilot October 8, 2026 22:29
@Borda Borda added the bug Something isn't working label Oct 8, 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

The int32 sampling ramp is unsupported by native OpenCV and breaks non-identity resizing.

3 open findings
What changed in this PR

Fixes CompactMask.resize to match dense nearest-neighbor resizing exactly.

Changes:

  • Reworks crop sampling using backend-specific source indices.
  • Adds exact parity and edge-case tests.
  • Updates benchmark validation and changelog.
File Description
compact_mask.py Implements source-index-based resizing.
test_compact_mask.py Adds parity and crop tests.
benchmark.py Checks exact resize equality.
changelog.md Documents the fix.

🧠 Review effort: Balanced


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

Comment thread tests/detection/test_compact_mask.py Resolved
Comment thread tests/detection/test_compact_mask.py Resolved
Borda and others added 2 commits October 11, 2026 21:00
Changes:
- Merge develop at 8b94622 into PR roboflow#2705.
- Preserve the PR's decode-and-gather resize implementation and retain the target's 22 public grid-sampling regression cases.
- Reconcile the changelog to describe the replacement of the previously merged sparse resize path.
- Import target depth containers, annotation, clip ranges, distance measurement and model/file loaders with their documentation and tests.
- Import target COCO keypoint mAP, exact perfect-prediction mAP and per-class detection limits for mAR.
- Import target mask-hole export preservation, NumPy-backed Ultralytics support and pre-commit/link-check updates.

Impact:
- Resolve target conflicts while retaining the implementation chosen for PR roboflow#2705.
- Preserve target features and fixes, public exports, documentation and regression coverage.
- Keep the sparse-mask speed claim pending separate review-finding remediation.

Verification:
- Full merged pytest suite with coverage: 5385 passed, 79 skipped, 39 warnings; 93% coverage.
- Repository-wide pre-commit hooks: all passed.
- Staged diff whitespace check passed; no unmerged paths remain.
- Production compact-mask source equals the reviewed PR head; clean imported paths match fetched target blobs.

Residual limits:
- Independent reviewer evidence remains unadmitted because of the host receipt-format mismatch.
- Merged suite uses the NumPy fallback on macOS Python 3.12; native OpenCV checks cover the unchanged PR production code before integration.
- Comparative speed and memory against the newly merged target remain unverified.

---

Co-authored-by: Codex <[email protected]>
Changes:
- Remove the unqualified 10× speed claim from the CompactMask.resize changelog entry; retain the implementation and parity description.

Impact:
- Readers no longer interpret the author’s workload-specific measurement as a general performance guarantee.

Verification:
- Changelog diff confirms the numeric speed claim is absent.
- Repository suite: 5,385 passed, 79 skipped; pre-commit all files passed in this remediation run.

Residual limits:
- G1 remains open: native OpenCV and platform coverage beyond OpenCV 5.0.0 on macOS Python 3.12 lacks evidence.

---

Co-authored-by: Codex <[email protected]>
@codecov

codecov Bot commented Oct 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93%. Comparing base (8b94622) to head (1da4a61).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2705   +/-   ##
=======================================
  Coverage       93%     93%           
=======================================
  Files           83      83           
  Lines        13109   13064   -45     
=======================================
- Hits         12253   12211   -42     
+ Misses         856     853    -3     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Borda Borda changed the title fix: make CompactMask.resize match dense nearest-neighbour resize fix: make CompactMask.resize match dense nearest-neighbour resize Oct 11, 2026
@Borda
Borda merged commit fdc0cd9 into roboflow:develop Oct 11, 2026
36 checks passed
Borda added a commit that referenced this pull request Oct 12, 2026
Changes:
- Merge fetched develop commit 1dad30d into the verified PR branch.
- Preserve the target\x27s nearest-neighbor CompactMask resize implementation and retain valid PR cross-references.

Impact:
- Brings the local remediation branch up to the current target before review-item fixes.
- Keeps compact-mask behavior aligned with target PR #2705 while preserving documentation links for surviving APIs.

Verification:
- `git diff --cached --check` passed with no unresolved paths.
- `tests/detection/test_compact_mask.py -p no:xdist`: 318 passed; one OpenCV fallback warning.

Residual limits:
- Requested review report remains incomplete; review-item scope is still pending.
- The OpenCV warning indicates tests used the project\x27s NumPy fallback backend.

---

Co-authored-by: Codex <[email protected]>
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]: CompactMask.resize returns different masks than resizing the dense masks with cv2.INTER_NEAREST

4 participants