Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(geometry): bbox_to_mask takes size=(height, width) and deprecates the pair (#6343)

Adarsh Mishra41d7c0e65630
diff --git a/changelog.d/6343.added.md b/changelog.d/6343.added.md
new file mode 100644
index 000000000..3fff233be
--- /dev/null
+++ b/changelog.d/6343.added.md
@@ -0,0 +1 @@
+`kornia.geometry.bbox.bbox_to_mask` takes `size=(height, width)`, the order of `bbox_to_mask3d` and `Boxes.to_mask`. Passing `width` and `height` still works but emits a `DeprecationWarning`; those arguments will be removed in a future release.
diff --git a/docs/export_support/cases_geomA.py b/docs/export_support/cases_geomA.py
index 0dd7be7c9..343733d85 100644
--- a/docs/export_support/cases_geomA.py
+++ b/docs/export_support/cases_geomA.py
@@ -613,7 +613,7 @@ CASES += [
G,
bbox_to_mask,
[boxes_quad[0]],
- {"width": W, "height": H},
+ {"size": (H, W)},
note="H,W baked; input (N,4,2)",
),
case(
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.py
index 69dbb402f..e8f40ca0f 100644
--- a/kornia/augmentation/_2d/intensity/erasing.py
+++ b/kornia/augmentation/_2d/intensity/erasing.py
@@ -140,7 +140,7 @@ class RandomErasing(IntensityAugmentationBase2D):
# The (B, 4, 2) boxes cross to the device, not the (B, H, W) mask: a large pageable copy stalls the host while
# the driver stages it. The mask is 0 or 1 by exact comparisons, so it is the same on either device.
bboxes = _to_device_nonblocking(bboxes, input.device)
- mask = bbox_to_mask(bboxes, w, h).unsqueeze(1).to(input.dtype) # (B, 1, H, W)
+ mask = bbox_to_mask(bboxes, size=(h, w)).unsqueeze(1).to(input.dtype) # (B, 1, H, W)
return torch.where(mask == 1.0, values, input)
def apply_transform_mask(
@@ -161,5 +161,5 @@ class RandomErasing(IntensityAugmentationBase2D):
# The (B, 4, 2) boxes cross to the device, not the (B, H, W) mask: a large pageable copy stalls the host while
# the driver stages it. The mask is 0 or 1 by exact comparisons, so it is the same on either device.
bboxes = _to_device_nonblocking(bboxes, input.device)
- mask = bbox_to_mask(bboxes, w, h).unsqueeze(1).to(input.dtype) # (B, 1, H, W)
+ mask = bbox_to_mask(bboxes, size=(h, w)).unsqueeze(1).to(input.dtype) # (B, 1, H, W)
return torch.where(mask == 1.0, values, input)
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 8e53cdca0..935c11283 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -192,7 +192,7 @@ class RandomCutMixV2(MixAugmentationBaseV2):
for pair, crop in zip(params["mix_pairs"], params["crop_src"]):
input_permute = input.index_select(dim=0, index=_to_device_nonblocking(pair, input.device))
# compute mask to match input shape
- mask = bbox_to_mask(crop, width, height).bool().unsqueeze(dim=1).repeat(1, input.size(1), 1, 1)
+ mask = bbox_to_mask(crop, size=(height, width)).bool().unsqueeze(dim=1).repeat(1, input.size(1), 1, 1)
out_inputs[mask] = input_permute[mask]
return out_inputs
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 0ea9cdd7a..045bee835 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -23,6 +23,7 @@ from typing import Optional
import torch
+from kornia.core._compat import _emit_deprecation_warning
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.utils import is_compiling
@@ -305,19 +306,26 @@ def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor,
return depths, heights, widths
-def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
+def bbox_to_mask(
+ boxes: torch.Tensor,
+ width: Optional[int] = None,
+ height: Optional[int] = None,
+ size: Optional[tuple[int, int]] = None,
+) -> torch.Tensor:
"""Convert 2D bounding boxes to masks. Covered area is 1. and the remaining is 0.
Convention:
- The size is ``(width, height)`` and the mask :math:`(B, height, width)`;
- :meth:`kornia.geometry.boxes.Boxes.to_mask` takes ``(height, width)``. Only vertices 0 (top-left) and 2
+ The size is ``size=(height, width)``, as for :func:`bbox_to_mask3d` and
+ :meth:`~kornia.geometry.boxes.Boxes.to_mask`; the deprecated ``width, height`` arguments come in the
+ opposite order. The mask is :math:`(B, height, width)`. Only vertices 0 (top-left) and 2
(bottom-right) are read. A pixel is covered when ``xmin <= x <= xmax`` and ``ymin <= y <= ymax`` on the
unrounded values, i.e. inclusively: pass the ``'vertices_plus'`` export of
:class:`~kornia.geometry.boxes.Boxes`. The mask has the input dtype and no gradient path.
:math:`(B, N, 4, 2)` raises :class:`~kornia.core.exceptions.ShapeError`.
.. warning::
- The ``(width, height)`` order is `#4014 <https://github.com/kornia/kornia/issues/4014>`_. For fractional
+ The ``(width, height)`` form is deprecated in favour of ``size=(height, width)``:
+ `#4014 <https://github.com/kornia/kornia/issues/4014>`_. For fractional
coordinates the raw comparison differs from the rounding of :meth:`~kornia.geometry.boxes.Boxes.to_mask`
and the truncation of :func:`bbox_to_mask3d`: `#4015 <https://github.com/kornia/kornia/issues/4015>`_.
The exclusive-export trap is `#4009 <https://github.com/kornia/kornia/issues/4009>`_.
@@ -326,14 +334,17 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
of :math:`(B, 4, 2)`, where each box is defined in the following ``clockwise`` order: top-left, top-right,
bottom-right and bottom-left. The coordinates must be in the x, y order.
- width: width of the masked image.
- height: height of the masked image.
+ width: deprecated since 0.9.1; pass ``size=(height, width)`` instead. Width of the masked image.
+ height: deprecated since 0.9.1; pass ``size=(height, width)`` instead. Height of the masked image.
+ size: (height, width) of the masked image.
Returns:
the output mask tensor, shape of :math:`(B, height, width)` and dtype of ``boxes``.
Raises:
ShapeError: if ``boxes`` does not have shape :math:`(B, 4, 2)`.
+ ValueError: if ``size`` is passed together with ``width`` or ``height``.
+ TypeError: if neither ``size`` nor both ``width`` and ``height`` are given.
Note:
It is currently non-differentiable.
@@ -351,7 +362,7 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
... [3., 2.],
... [1., 2.],
... ]]) # 1x4x2
- >>> bbox_to_mask(boxes, 5, 5)
+ >>> bbox_to_mask(boxes, size=(5, 5))
tensor([[[0., 0., 0., 0., 0.],
[0., 1., 1., 1., 0.],
[0., 1., 1., 1., 0.],
@@ -359,6 +370,26 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
[0., 0., 0., 0., 0.]]])
"""
+ # `size` carries the canonical (height, width) order; `width`/`height` stay in place for one
+ # release cycle in the opposite order, which is exactly the trap #4014 records, so the
+ # deprecated form is resolved here, with a warning on every eager call, rather than silently transposing.
+ if size is not None:
+ if width is not None or height is not None:
+ raise ValueError("Pass either size=(height, width) or the deprecated width and height, not both.")
+ mask_height, mask_width = size
+ elif width is not None and height is not None:
+ if not torch.jit.is_scripting():
+ _emit_deprecation_warning(
+ "bbox_to_mask(boxes, width, height)",
+ "bbox_to_mask(boxes, size=(height, width))",
+ "0.9.1",
+ "The `width` and `height` arguments will be removed in a future release; note that `size` is "
+ "`(height, width)`, the order of `bbox_to_mask3d` and `Boxes.to_mask`.",
+ )
+ mask_height, mask_width = height, width
+ else:
+ raise TypeError("bbox_to_mask() missing required argument 'size' (height, width).")
+
KORNIA_CHECK_SHAPE(boxes, ["B", "4", "2"])
# NOTE: `validate_bbox`'s boolean result was previously computed here and discarded β€” it
@@ -374,8 +405,8 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
# promote to the wider of the two dtypes (float32 for float16/bfloat16/
# float32 boxes, float64 for float64 boxes), so nothing downstream loses
# precision; the returned mask still casts back to boxes.dtype as documented.
- yy = torch.arange(height, device=boxes.device, dtype=torch.float32).view(height, 1)
- xx = torch.arange(width, device=boxes.device, dtype=torch.float32).view(1, width)
+ yy = torch.arange(mask_height, device=boxes.device, dtype=torch.float32).view(mask_height, 1)
+ xx = torch.arange(mask_width, device=boxes.device, dtype=torch.float32).view(1, mask_width)
x_min = boxes[:, 0, 0].view(-1, 1, 1)
y_min = boxes[:, 0, 1].view(-1, 1, 1)
x_max = boxes[:, 2, 0].view(-1, 1, 1)
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 9cb425b8d..7ac829e0e 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -252,7 +252,8 @@ class Boxes:
stored inclusive vertices, ``(width - 1) * (height - 1)``:
`#4010 <https://github.com/kornia/kornia/issues/4010>`_. :func:`~kornia.geometry.bbox.nms` is exclusive:
`#4008 <https://github.com/kornia/kornia/issues/4008>`_. :meth:`to_mask` and
- :func:`~kornia.geometry.bbox.bbox_to_mask` take opposite size orders:
+ :func:`~kornia.geometry.bbox.bbox_to_mask` agree on ``(height, width)`` once that function is called with
+ ``size``; its deprecated ``width, height`` form takes the opposite order:
`#4014 <https://github.com/kornia/kornia/issues/4014>`_. The integer-input split is
`#4012 <https://github.com/kornia/kornia/issues/4012>`_. ``'vertices'`` subtracts the inclusive offset at
fixed vertex slots, so it deforms a quadrilateral that is not an axis-aligned rectangle in clockwise order:
@@ -830,8 +831,9 @@ class Boxes:
``RuntimeError``.
.. warning::
- :func:`~kornia.geometry.bbox.bbox_to_mask` takes ``(width, height)``
- (`#4014 <https://github.com/kornia/kornia/issues/4014>`_) and does not round, so a fractional box can
+ :func:`~kornia.geometry.bbox.bbox_to_mask` takes ``(height, width)`` through its ``size`` argument,
+ like this method (`#4014 <https://github.com/kornia/kornia/issues/4014>`_); its deprecated
+ ``width, height`` form takes the opposite order. It also does not round, so a fractional box can
fill a different area (`#4015 <https://github.com/kornia/kornia/issues/4015>`_).
Args:
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 9b4c93936..b71bd764b 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -1000,7 +1000,7 @@ class TestAugmentationSequential:
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
- torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 500, 1000
+ torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), size=(1000, 500)
)[:, None]
aug = K.AugmentationSequential(
K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
@@ -1038,7 +1038,7 @@ class TestAugmentationSequential:
bbox = torch.tensor([[[[355, 10], [660, 10], [660, 250], [355, 250]]]], device=device, dtype=dtype)
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
- torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 500, 1000
+ torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), size=(1000, 500)
)[:, None]
crop_size = (200, 200)
@@ -1083,7 +1083,7 @@ class TestAugmentationSequential:
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
- torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 500, 1000
+ torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), size=(1000, 500)
)[:, None]
aug = K.AugmentationSequential(
K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
@@ -1128,7 +1128,7 @@ class TestAugmentationSequential:
]
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
- torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 500, 1000
+ torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), size=(1000, 500)
)[:, None]
aug = K.AugmentationSequential(
K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
diff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.py
index 4e65fc8e0..951604cf3 100644
--- a/tests/augmentation/test_auto_operation.py
+++ b/tests/augmentation/test_auto_operation.py
@@ -46,7 +46,7 @@ def _test_sequential(augment_method, device, dtype):
bbox = torch.tensor([[[35.5, 1], [66, 1], [66, 25], [35.5, 25]]], device=device, dtype=dtype)
keypoints = torch.tensor([[[46.5, 11.5], [54.5, 11.6]]], device=device, dtype=dtype)
mask = bbox_to_mask(
- torch.tensor([[[15.5, 0], [90, 0], [90, 40], [15.5, 40]]], device=device, dtype=dtype), width, height
+ torch.tensor([[[15.5, 0], [90, 0], [90, 40], [15.5, 40]]], device=device, dtype=dtype), size=(height, width)
)[:, None]
aug = AugmentationSequential(augment_method, data_keys=["input", "mask", "bbox", "keypoints"])
out = aug(inp, mask, bbox, keypoints)
diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.py
index a0f10251e..d940918dc 100644
--- a/tests/augmentation/test_conventions_mix.py
+++ b/tests/augmentation/test_conventions_mix.py
@@ -570,7 +570,7 @@ class TestMixConventions(BaseTester):
expected_lambda = 1 - width * height / 64
self.assert_close(mixed[mix, :, 2], expected_lambda.expand(4))
# each mix pastes its own cut from the original image, a later mix over an earlier one
- cut = bbox_to_mask(crops[mix], 8, 8).bool().unsqueeze(1)
+ cut = bbox_to_mask(crops[mix], size=(8, 8)).bool().unsqueeze(1)
expected_image = torch.where(cut, image[pairs[mix]], expected_image)
self.assert_close(output, expected_image, rtol=0, atol=0)
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index 5d5deca17..455ac70eb 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -87,7 +87,7 @@ class TestBbox2D(BaseTester):
boxes = torch.zeros(1, num_boxes, 4, 2, device=device, dtype=dtype)
with pytest.raises(ShapeError, match="expected 3 dimensions, got 4"):
- bbox_to_mask(boxes, width=5, height=5)
+ bbox_to_mask(boxes, size=(5, 5))
def test_convention_validate_bbox_checks_parallelograms_and_accepts_contiguous_batched_boxes(self, device, dtype):
# The validator only compares the top and bottom edge vectors at fixed vertex
@@ -272,12 +272,12 @@ class TestBbox2D(BaseTester):
assert scripted_fn(boxes_non_rectangle) is False
def test_convention_bbox_to_mask_takes_width_then_height_and_reads_two_vertices_4014(self, device, dtype):
- # Convention pin (kornia#4014 records the argument-order split with Boxes.to_mask):
- # bbox_to_mask(boxes, width, height) returns (B, height, width), fills through the
+ # Convention pin (kornia#4014 records the argument-order split with Boxes.to_mask, now repaired through
+ # `size`): bbox_to_mask(boxes, size=(height, width)) returns (B, height, width), fills through the
# top-left (index 0) and bottom-right (index 2) vertices inclusively, ignores the two
# other vertices, keeps the input dtype, and carries no gradient path.
boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
- mask = bbox_to_mask(boxes, 5, 3)
+ mask = bbox_to_mask(boxes, size=(3, 5))
assert mask.shape == (1, 3, 5)
assert mask.dtype == dtype
expected = torch.tensor(
@@ -286,15 +286,76 @@ class TestBbox2D(BaseTester):
dtype=dtype,
)
self.assert_close(mask, expected, atol=0.0, rtol=0.0)
- assert bbox_to_mask(boxes, 3, 5).shape == (1, 5, 3)
+ assert bbox_to_mask(boxes, size=(5, 3)).shape == (1, 5, 3)
corrupted = boxes.clone()
corrupted[0, 1] = 9.0
corrupted[0, 3] = -9.0
- self.assert_close(bbox_to_mask(corrupted, 5, 3), expected, atol=0.0, rtol=0.0)
+ self.assert_close(bbox_to_mask(corrupted, size=(3, 5)), expected, atol=0.0, rtol=0.0)
+
+ assert bbox_to_mask(boxes.to(torch.int64), size=(3, 5)).dtype == torch.int64
+ assert not bbox_to_mask(boxes.clone().requires_grad_(), size=(3, 5)).requires_grad
+
+ # One deprecated call stays in the pin, because the opposite order is what #4014 was filed about.
+ with pytest.warns(DeprecationWarning, match=r"size=\(height, width\)"):
+ self.assert_close(bbox_to_mask(boxes, 5, 3), expected, atol=0.0, rtol=0.0)
+
+ def test_bbox_to_mask_size_matches_the_deprecated_pair_bitwise_4014(self, device, dtype):
+ # The repair must not move a single pixel: on a non-square size the new form has to be
+ # bitwise equal to what the deprecated pair produced before.
+ boxes = torch.tensor([[[1.0, 1.0], [4.0, 1.0], [4.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)
+ with pytest.warns(DeprecationWarning, match=r"size=\(height, width\)"):
+ deprecated = bbox_to_mask(boxes, 7, 4) # width 7, height 4
+ canonical = bbox_to_mask(boxes, size=(4, 7))
+ assert canonical.shape == deprecated.shape == (1, 4, 7)
+ assert torch.equal(canonical, deprecated)
+
+ def test_bbox_to_mask_size_form_warns_nothing_4014(self, device, dtype):
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ bbox_to_mask(boxes, size=(3, 5))
+
+ @pytest.mark.parametrize("form", ["positional", "keyword"])
+ def test_bbox_to_mask_deprecated_forms_warn_and_agree_4014(self, device, dtype, form):
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ expected = bbox_to_mask(boxes, size=(3, 5))
+ with pytest.warns(DeprecationWarning, match=r"size=\(height, width\)") as record:
+ got = bbox_to_mask(boxes, 5, 3) if form == "positional" else bbox_to_mask(boxes, width=5, height=3)
+ assert torch.equal(got, expected)
+ # The warning names the caller's line, not a line inside kornia.
+ assert [w.filename for w in record] == [__file__]
- assert bbox_to_mask(boxes.to(torch.int64), 5, 3).dtype == torch.int64
- assert not bbox_to_mask(boxes.clone().requires_grad_(), 5, 3).requires_grad
+ def test_bbox_to_mask_rejects_both_forms_and_neither_4014(self, device, dtype):
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Pass either size=\\(height, width\\) or the deprecated width"):
+ bbox_to_mask(boxes, 5, 3, (3, 5))
+ with pytest.raises(ValueError, match="not both"):
+ bbox_to_mask(boxes, height=3, size=(3, 5))
+ with pytest.raises(TypeError, match="missing required argument 'size'"):
+ bbox_to_mask(boxes)
+ with pytest.raises(TypeError, match="missing required argument 'size'"):
+ bbox_to_mask(boxes, 5)
+
+ def test_bbox_to_mask_stays_scriptable_for_both_size_forms_4014(self, device, dtype):
+ # `size` is an ordinary fourth parameter, not a keyword-only one, precisely because
+ # torch.jit.script(bbox_to_mask) works today and TorchScript rejects keyword-only defaults.
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ scripted = torch.jit.script(bbox_to_mask)
+ assert torch.equal(scripted(boxes, size=(3, 5)), bbox_to_mask(boxes, size=(3, 5)))
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ assert torch.equal(scripted(boxes, 5, 3), bbox_to_mask(boxes, 5, 3))
+
+ def test_dynamo_bbox_to_mask_is_fullgraph_for_both_forms_4014(self, device, dtype, torch_optimizer):
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ eager = bbox_to_mask(boxes, size=(3, 5))
+ assert torch.equal(torch_optimizer(bbox_to_mask, fullgraph=True)(boxes, size=(3, 5)), eager)
+ # The deprecated path must compile without a graph break too: the warning is suppressed
+ # while capturing, so nothing here raises a Python-level call into `warnings`.
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ assert torch.equal(torch_optimizer(bbox_to_mask, fullgraph=True)(boxes, 5, 3), eager)
def test_wart_bbox_to_mask_compares_raw_floats_inclusively_4015(self, device, dtype):
# Wart pin for kornia#4015: the fractional box [1.4, 3.0] x [2.0, 2.6] covers the integer
@@ -304,9 +365,9 @@ class TestBbox2D(BaseTester):
boxes = torch.tensor([[[1.4, 2.0], [3.0, 2.0], [3.0, 2.6], [1.4, 2.6]]], device=device, dtype=dtype)
expected = torch.zeros(1, 5, 6, device=device, dtype=dtype)
expected[0, 2, 2:4] = 1.0
- self.assert_close(bbox_to_mask(boxes, 6, 5), expected, atol=0.0, rtol=0.0)
+ self.assert_close(bbox_to_mask(boxes, size=(5, 6)), expected, atol=0.0, rtol=0.0)
fractional = torch.tensor([[[1.4, 1.4], [3.6, 1.4], [3.6, 2.6], [1.4, 2.6]]], device=device, dtype=dtype)
- assert bbox_to_mask(fractional, 6, 5).sum().item() == 2.0
+ assert bbox_to_mask(fractional, size=(5, 6)).sum().item() == 2.0
@pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
def test_bbox_to_mask_position_grid_is_exact_for_half_boxes_on_a_large_image(self, device, half_dtype):
@@ -322,8 +383,8 @@ class TestBbox2D(BaseTester):
[[[1000.0, 1000.0], [4080.0, 1000.0], [4080.0, 3072.0], [1000.0, 3072.0]]], device=device
)
boxes_half = boxes32.to(half_dtype)
- mask32 = bbox_to_mask(boxes32, width=4096, height=4096)
- mask_half = bbox_to_mask(boxes_half, width=4096, height=4096)
+ mask32 = bbox_to_mask(boxes32, size=(4096, 4096))
+ mask_half = bbox_to_mask(boxes_half, size=(4096, 4096))
assert mask_half.dtype == half_dtype
assert torch.equal(mask_half.bool(), mask32.bool())
@@ -882,7 +943,7 @@ class TestBbox3D(BaseTester):
assert bbox_to_mask3d(cuboid.to(torch.int64), (4, 5, 6)).dtype == torch.int64
assert not bbox_to_mask3d(cuboid.clone().requires_grad_(), (4, 5, 6)).requires_grad
square = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
- assert bbox_to_mask(square, 6, 5).dtype == dtype
+ assert bbox_to_mask(square, size=(5, 6)).dtype == dtype
@pytest.mark.parametrize("case", ["full_width", "full_height", "full_depth", "overhang"])
def test_convention_bbox_to_mask3d_intersects_the_axis_ranges_for_a_full_or_overhanging_axis_box_4255(
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 42546735c..93030f76c 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -1259,15 +1259,18 @@ class TestBoxes2D(BaseTester):
assert transformed.data.shape == original.shape
def test_wart_to_mask_and_bbox_to_mask_take_opposite_size_orders_4014(self, device, dtype):
- # Wart pin for kornia#4014: Boxes.to_mask(height, width) and bbox_to_mask(boxes, width, height)
- # are the same call, and both return (N, height, width) in the box dtype.
+ # Wart pin for kornia#4014: Boxes.to_mask(height, width) and bbox_to_mask(boxes, size=(height, width))
+ # are the same call, and both return (N, height, width) in the box dtype. The deprecated pair stays
+ # wrapped at the bottom, because the opposite order it implied is the wart that was reported.
vertices = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
method = Boxes(vertices).to_mask(3, 5)
assert method.shape == (1, 3, 5)
assert method.dtype == dtype
- self.assert_close(method, bbox_to_mask(vertices, 5, 3), atol=0.0, rtol=0.0)
+ self.assert_close(method, bbox_to_mask(vertices, size=(3, 5)), atol=0.0, rtol=0.0)
assert Boxes(vertices).to_mask(5, 3).shape == (1, 5, 3)
assert Boxes(vertices[None]).to_mask(3, 5).shape == (1, 1, 3, 5)
+ with pytest.warns(DeprecationWarning, match=r"size=\(height, width\)"):
+ self.assert_close(method, bbox_to_mask(vertices, 5, 3), atol=0.0, rtol=0.0)
def test_wart_to_mask_rounds_the_exclusive_export_half_open_4015(self, device, dtype):
# Wart pin for kornia#4015: the fractional box [1.4, 3.6] x [1.4, 2.6] exports as xyxy
@@ -1278,7 +1281,7 @@ class TestBoxes2D(BaseTester):
expected = torch.zeros(1, 5, 6, device=device, dtype=dtype)
expected[0, 1:4, 1:5] = 1.0
self.assert_close(Boxes(boxes).to_mask(5, 6), expected, atol=0.0, rtol=0.0)
- assert bbox_to_mask(boxes, 6, 5).sum().item() == 2.0
+ assert bbox_to_mask(boxes, size=(5, 6)).sum().item() == 2.0
outside = torch.tensor([[[6.0, 6.0], [9.0, 6.0], [9.0, 9.0], [6.0, 9.0]]], device=device, dtype=dtype)
assert Boxes(outside).to_mask(5, 5).sum().item() == 0.0