Skip to content

fix(cv2): match OpenCV's nearest-neighbour sampling grid in the resize fallback - #2722

Merged
Borda merged 5 commits into
roboflow:developfrom
Lingikaushikreddy:fix/cv2-nearest-resize-rounding
Oct 15, 2026
Merged

Borda merged 5 commits into
roboflow:developfrom
Lingikaushikreddy:fix/cv2-nearest-resize-rounding

Conversation

@Lingikaushikreddy

Copy link
Copy Markdown
Contributor

Description

The NumPy resize fallback picked a different source pixel than OpenCV for INTER_NEAREST at some sizes. The fallback used the exact integer ratio x * src_w // dst_w; OpenCV steps through the source with the reciprocal of the size ratio, ifx = 1. / (dst_w / src_w), and takes cvFloor(x * ifx) (resize.cpp, resizeNN). Where x * src_w / dst_w is a whole number, that reciprocal can land just below it and OpenCV picks the previous pixel.

Smallest case: a 6-pixel ramp resized to 34 wide. At x = 17, 17 * 6 / 34 = 3.0, but 17 * (1 / (34 / 6)) = 2.9999999999999996, so OpenCV samples pixel 2 and the fallback sampled pixel 3.

ramp = np.arange(6, dtype=np.uint8).reshape(1, 6)
cv2.resize(ramp, (34, 1), interpolation=cv2.INTER_NEAREST)[0, 17]  # 2
_resize(ramp, (34, 1), interpolation=cv2.INTER_NEAREST)[0, 17]     # was 3, now 2

62 (source width ≤ 40, destination width ≤ 80) pairs were affected; on random color images at random sizes in that range, 24 of 600 resizes differed.

Motivation and Context

CompactMask.resize (#2697, #2705) derives its sampling grid from cv2.resize(ramp, …, INTER_NEAREST) through the facade and documents that the map "equals INTER_NEAREST exactly, including its floating-point rounding", so resized masks differed between environments with and without OpenCV. The fx/fy path already used OpenCV's floor(x / fx) since #2690; this makes the dsize path consistent with it.

Closes #2721

Changes Made

  • _resize: compute the sampling step for the dsize path as 1 / (dst / src) like OpenCV, and use the same floor(x * step) indexing for both nearest paths. The linear path is unaffected in practice (the uint8 branch goes through Pillow; the generic branch changes only in the last floating-point bit).
  • Tests: four 1-D ramp cases at the first affected widths, and one color image resized on both axes.
  • Changelog entry under Unreleased.

Testing

New tests on develop (with opencv-python):

$ uv run --with opencv-python pytest tests/cv2/test_image.py -k nearest_resize -q
FAILED tests/cv2/test_image.py::test_fallback_nearest_resize_matches_opencv_at_whole_sample_positions[six-to-thirty-four]
FAILED tests/cv2/test_image.py::test_fallback_nearest_resize_matches_opencv_at_whole_sample_positions[nine-to-fifty-one]
FAILED tests/cv2/test_image.py::test_fallback_nearest_resize_matches_opencv_at_whole_sample_positions[ten-to-seventy-four]
FAILED tests/cv2/test_image.py::test_fallback_nearest_resize_matches_opencv_at_whole_sample_positions[twelve-to-thirty-four]
FAILED tests/cv2/test_image.py::test_fallback_nearest_resize_matches_opencv_on_both_axes
5 failed, 101 deselected

With this change:

$ uv run --with opencv-python pytest tests/cv2 -q              # 467 passed, 6 skipped
$ uv run --with opencv-python pytest tests/detection tests/annotators -q   # 2486 passed, 1 skipped
$ uv run pytest -q                                              # 5385 passed, 79 skipped
$ uv run pre-commit run --all-files                             # all hooks passed

A randomized sweep of 600 nearest resizes against OpenCV 4.12 (random 1–40 px sources, 1–80 px destinations) goes from 24 mismatches to 0.

  • 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

Additional Notes

The equivalent rounding exists for INTER_LINEAR in OpenCV (scale_x = 1. / inv_scale_x), but the fallback's uint8 linear path is Pillow-based and already tested at atol=1, so this PR leaves it alone.

@CLAassistant

CLAassistant commented Oct 12, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@Lingikaushikreddy

Copy link
Copy Markdown
Contributor Author

recheck

Borda and others added 2 commits October 15, 2026 13:05
Changes:
- Merge develop at e2c958f and preserve both sides of the changelog insertion conflict.
- Retain the PR's reciprocal nearest-neighbor sampling and regression tests alongside upstream docstring corrections.
- Incorporate upstream label separation, oriented-box precision, configurable mAP limits, integer-area overflow, keypoint indexing, CompactMask copy handling, and CSV array serialization fixes.
- Incorporate upstream keypoint parity tests and dependency, API documentation links and examples, review guidance, and documentation publishing improvements.

Impact:
- Bring the PR branch onto the fetched target implementation without discarding either changelog history or the resize fix.
- Preserve the upstream behavior and tooling updates in the local integration.

Verification:
- Focused CompactMask and image tests: 318 passed, 2 skipped, 1 warning.
- Configured Markdown formatter and git diff --cached --check passed.
- Entire staged tree checked against fetched target; the three PR files match their independently constructed expected contents, with no unresolved index entries.

Residual limits:
- OpenCV is absent; native parity tests remain unverified.
- Review findings await scope selection; independent review and the canonical full gates remain pending.

---

Co-authored-by: Codex <[email protected]>
Changes:
- Limit the PR roboflow#2722 changelog claim to some whole-number positions where reciprocal multiplication rounds below the integer.
- Preserve the 6-to-34 example and its CompactMask impact.

Impact:
- Explain the backend mismatch without implying every integer boundary differs.

Verification:
- Full configured pre-commit and targeted mdformat passed.
- Full suite: 5566 passed, 79 skipped, 39 warnings; 94% coverage.
- Native OpenCV resize checks: 35 passed; four before/after oracle cases verified the correction.
- Four independent role assessments and the snapshot evidence gate passed.

Residual limits:
- Native parity exercised OpenCV 5.0.0.93 on macOS ARM64; other versions and platforms remain unverified.
- Full-suite skips and warnings remain recorded; historical review provenance is unchanged.

---

Co-authored-by: Codex <[email protected]>
@Borda
Borda requested a balanced review from Copilot October 15, 2026 12:02
@Borda Borda added the bug Something isn't working label Oct 15, 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.

🟢 Approval recommended

The localized arithmetic correction addresses the reported mismatch with focused regression coverage and no identified blocking issues.

0 open findings

What changed in this PR

Aligns the NumPy resize fallback with OpenCV’s nearest-neighbour sampling, keeping resized masks consistent across backends.

Changes:

  • Uses reciprocal scale arithmetic for explicit destination sizes.
  • Adds four ramp regression cases and a two-axis color-image test.
  • Documents the fix in the changelog.

Scores: Code quality 5/5 · Testing 5/5 · Documentation 5/5

File Description
tests/​cv2/​test_image.py Adds exact OpenCV parity regression tests.
src/​supervision/​_cv2/​_image.py Corrects nearest-neighbour sampling arithmetic.
docs/​changelog.md Records the fix and its effect on compact masks.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@codecov

codecov Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94%. Comparing base (c92f8cf) to head (c975429).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2722   +/-   ##
=======================================
- Coverage       94%     94%   -0%     
=======================================
  Files           83      83           
  Lines        13129   13127    -2     
=======================================
- Hits         12322   12320    -2     
  Misses         807     807           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Borda
Borda merged commit 8185496 into roboflow:develop Oct 15, 2026
36 checks passed
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]: NumPy resize fallback picks a different source pixel than OpenCV for INTER_NEAREST at some sizes

4 participants