[Bug]: CompactMask.resize returns different masks than resizing the dense masks with cv2.INTER_NEAREST
Search before asking
- [x] I have searched the issues and discussions and found no similar bug report.
Bug
What's the bug? CompactMask.resize scales each crop's offset and its inclusive last pixel with round(), then resizes every crop on its own. The sampling phase therefore differs from a nearest-neighbour resize of the full mask, and crops come out a pixel or more too small. The existing "dense parity" test asserts np.abs(a.astype(int) - b.astype(int)).max() <= 1 on boolean arrays, which is always true, so it cannot catch this.
Expected behavior: resize(...).to_dense() equals cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST) on the dense mask.
Actual behavior: A 20x20 square on a 640x640 image resized to 1920x1920 covers 3364 px instead of 3600 (bounding box 58x58 instead of 60x60, IoU 0.934). A 1-px-wide, 80-px-long line resized 2x covers 159 px instead of 320. In a fuzz of 1500 random cases every case differed. Same result on OpenCV 4.12.0 and 5.0.0.
Error/Traceback (if any):
# No error: the masks are silently wrong.
Environment
- Supervision: 0.31.0.dev0 (develop @ 69cb843)
- Python: 3.11
- OS: macOS 15 (arm64)
Minimal Reproducible Example
import cv2
import numpy as np
import supervision as sv
def check(name, mask, new_shape):
h, w = mask.shape
ys, xs = np.nonzero(mask)
xyxy = np.array([[xs.min(), ys.min(), xs.max(), ys.max()]], dtype=np.float32)
cm = sv.CompactMask.from_dense(mask[None], xyxy, (h, w))
got = cm.resize(new_shape).to_dense()[0]
new_h, new_w = new_shape
want = cv2.resize(mask.astype(np.uint8), (new_w, new_h), interpolation=cv2.INTER_NEAREST).astype(bool)
print(f"{name}: dense={int(want.sum())} px, CompactMask.resize={int(got.sum())} px, equal={np.array_equal(got, want)}")
square = np.zeros((640, 640), dtype=bool); square[100:120, 100:120] = True
check("20x20 square, 640x640 -> 1920x1920", square, (1920, 1920))
line = np.zeros((100, 100), dtype=bool); line[10, 10:90] = True
check("1x80 line, 100x100 -> 200x200", line, (200, 200))
# develop: dense=3600 / resize=3364 equal=False; dense=320 / resize=159 equal=False
Are you willing to submit a PR?
- [x] Yes I'd like to help by submitting a PR!