Skip to content

Commit a7e292e

Browse files
committed
Fix bounding box center overflow
1 parent bdd0154 commit a7e292e

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

test/test_transforms_v2.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4477,6 +4477,27 @@ def test_cxcywh_to_xyxy_odd_dimensions(self):
44774477
assert (actual >= 0).all()
44784478
torch.testing.assert_close(actual, expected)
44794479

4480+
@pytest.mark.parametrize("inplace", [False, True])
4481+
@pytest.mark.parametrize(
4482+
("dtype", "box", "expected_box"),
4483+
[
4484+
(torch.uint8, [200, 10, 220, 30], [210, 20, 20, 20]),
4485+
(torch.float16, [32768, 0, 49152, 32], [40960, 16, 16384, 32]),
4486+
],
4487+
)
4488+
def test_xyxy_to_cxcywh_narrow_dtype_overflow(self, inplace, dtype, box, expected_box):
4489+
bounding_boxes = torch.tensor([box], dtype=dtype)
4490+
4491+
actual = F.convert_bounding_box_format(
4492+
bounding_boxes,
4493+
old_format=tv_tensors.BoundingBoxFormat.XYXY,
4494+
new_format=tv_tensors.BoundingBoxFormat.CXCYWH,
4495+
inplace=inplace,
4496+
)
4497+
expected = torch.tensor([expected_box], dtype=dtype)
4498+
4499+
torch.testing.assert_close(actual, expected)
4500+
44804501

44814502
class TestResizedCrop:
44824503
INPUT_SIZE = (17, 11)

torchvision/transforms/v2/functional/_meta.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,8 @@ def _xyxy_to_cxcywh(xyxy: torch.Tensor, inplace: bool) -> torch.Tensor:
228228

229229
# (x2 - x1) = width, same for height
230230
xyxy[..., 2:].sub_(xyxy[..., :2])
231-
# (x1 * 2 + width) / 2 = x1 + width / 2 = x1 + (x2-x1)/2 = (x1 + x2)/2 = cx, same for cy
232-
xyxy[..., :2].mul_(2).add_(xyxy[..., 2:]).div_(2, rounding_mode=None if xyxy.is_floating_point() else "floor")
231+
# x1 + width / 2 = (x1 + x2) / 2 = cx, same for cy
232+
xyxy[..., :2].add_(xyxy[..., 2:].div(2, rounding_mode=None if xyxy.is_floating_point() else "floor"))
233233

234234
return xyxy
235235

0 commit comments

Comments
 (0)