[Bug]: NumPy `resize` fallback picks a different source pixel than OpenCV for `INTER_NEAREST` at some sizes
Bug
Without opencv-python installed, supervision._cv2.resize(..., interpolation=INTER_NEAREST) samples a different source pixel than OpenCV for some (source, destination) size pairs. The fallback uses the exact integer ratio x * src_w // dst_w; OpenCV steps through the source with ifx = 1. / (dst_w / src_w) and takes cvFloor(x * ifx) (modules/imgproc/src/resize.cpp, resizeNN). When x * src_w / dst_w is a whole number, the double-precision reciprocal can land just below it, so OpenCV picks the previous pixel.
Smallest case: a 6-pixel ramp resized to 34 pixels wide. At x = 17, 17 * 6 / 34 = 3.0 exactly; OpenCV computes 17 * (1 / (34 / 6)) = 2.9999999999999996 and picks pixel 2, the fallback picks pixel 3.
source [0, 1, 2, 3, 4, 5]
opencv [0,0,0,0,0,0, 1,1,1,1,1,1, 2,2,2,2,2,2, 3,3,3,3,3, 4,4,4,4,4,4, 5,5,5,5,5]
fallback [0,0,0,0,0,0, 1,1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3,3, 4,4,4,4,4,4, 5,5,5,5,5]
^ x = 17
Scanning every source width ≤ 40 against every destination width ≤ 80 gives 62 differing pairs (e.g. 6→34, 9→51, 10→74, 12→34). On random color images with random sizes in that range, 24 of 600 resizes differ by at least one pixel.
Expected: the fallback picks the same source pixel as OpenCV, as it already does for the fx/fy path (#2690 uses floor(x / fx) there).
Why it matters: CompactMask.resize (#2697, #2705) derives its sampling grid from cv2.resize(ramp, …, INTER_NEAREST) through the facade, and _nearest_source_index documents that this "equals INTER_NEAREST exactly, including its floating-point rounding". With this bug a resized mask differs between an environment with OpenCV and one without. The same applies to scale_image-style helpers that pass INTER_NEAREST.
Environment
- supervision
develop@ fdc0cd97f (0.31.0.dev0) - macOS 15 arm64, Python 3.12.13, NumPy 2.2.6
- Reference: opencv-python 4.12.0
Minimal Reproducible Example
import numpy as np
import cv2
from supervision._cv2._image import _resize
ramp = np.arange(6, dtype=np.uint8).reshape(1, 6)
print(cv2.resize(ramp, (34, 1), interpolation=cv2.INTER_NEAREST)[0, 17]) # 2
print(_resize(ramp, (34, 1), interpolation=cv2.INTER_NEAREST)[0, 17]) # 3
Are you willing to submit a PR?
- [x] Yes I'd like to help by submitting a PR!