Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): deprecate the unused validate_boxes argument of crop_by_boxes (#6438)

Muhammad Talha88cfc1b06c93
diff --git a/changelog.d/6438.added.md b/changelog.d/6438.added.md
new file mode 100644
index 000000000..4e0d94727
--- /dev/null
+++ b/changelog.d/6438.added.md
@@ -0,0 +1 @@
+`crop_by_boxes` emits a `DeprecationWarning` when `validate_boxes` is passed as `True` or `False`; the argument will be removed in a future release. Up to kornia 0.7.1 it rejected non-rectangular boxes; since 0.7.2 it has had no effect, and results do not change.
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 3aedbf276..58eb3dd63 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -50,6 +50,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.constants import Resample
+from kornia.core._compat import _emit_deprecation_warning
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.utils import is_compiling, is_exporting
from kornia.geometry.bbox import infer_bbox_shape
@@ -316,7 +317,7 @@ def crop_by_boxes(
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
- validate_boxes: bool = True,
+ validate_boxes: Optional[bool] = None,
) -> torch.Tensor:
"""Crop images by mapping a source box onto a destination box, whose size sets the output size.
@@ -356,8 +357,10 @@ def crop_by_boxes(
padding_mode: padding mode for outside grid values
``'zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: mode for grid_generation.
- validate_boxes: has no effect: the boxes are not validated
- (`#6401 <https://github.com/kornia/kornia/issues/6401>`_).
+ validate_boxes: deprecated since kornia 0.9.1 and ignored; passing ``True`` or ``False`` emits a
+ :class:`DeprecationWarning`, and the default ``None`` does not. The boxes are not validated, whatever
+ its value: only the shapes of ``src_box`` and ``dst_box`` and the equal size of the ``dst_box`` boxes
+ are checked.
Returns:
the patches, with shape ``(B, C, h, w)`` for the size ``(h, w)`` of ``dst_box``.
@@ -389,6 +392,17 @@ def crop_by_boxes(
[ 9.0000, 10.0000]]]])
"""
+ # TorchScript cannot compile the warning helper (it formats an ``Optional[str]`` and passes ``category`` to
+ # ``warnings.warn``), so a scripted call stays silent, as in ``bbox_to_mask``.
+ if not torch.jit.is_scripting() and validate_boxes is not None:
+ _emit_deprecation_warning(
+ "crop_by_boxes(validate_boxes=...)",
+ None,
+ "0.9.1",
+ "The argument has no effect: `crop_by_boxes` does not validate the boxes, whatever its value; stop "
+ "passing it.",
+ )
+
bbox: Tuple[torch.Tensor, torch.Tensor] = infer_bbox_shape(dst_box)
if not ((bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all()):
raise AssertionError(
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index ec1f9e10d..61c0488f4 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import warnings
+
import pytest
import torch
from torch.utils._python_dispatch import TorchDispatchMode
@@ -448,6 +450,83 @@ class TestCropByBoxes(BaseTester):
patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ @pytest.mark.parametrize("validate_boxes", [True, False])
+ def test_validate_boxes_is_deprecated_and_ignored_6401(self, validate_boxes, device, dtype):
+ # `validate_boxes` is read nowhere: the boxes are not validated, whatever its value. It now warns when
+ # passed, and the result stays what the call without it returns.
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ inp = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ src = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
+ dst = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype) # 1x4x2
+ expected = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
+
+ with pytest.warns(DeprecationWarning, match="validate_boxes") as record:
+ out = kornia.geometry.transform.crop_by_boxes(inp, src, dst, validate_boxes=validate_boxes)
+
+ # The warning names the caller's line, not a line inside kornia.
+ assert [w.filename for w in record if "validate_boxes" in str(w.message)] == [__file__]
+ self.assert_close(out, expected)
+
+ def test_validate_boxes_positional_is_deprecated_6401(self, device, dtype):
+ # It is the seventh parameter, so a caller can also pass it by position.
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ inp = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ src = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
+ dst = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype) # 1x4x2
+ expected = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
+
+ with pytest.warns(DeprecationWarning, match="validate_boxes"):
+ out = kornia.geometry.transform.crop_by_boxes(inp, src, dst, "bilinear", "zeros", True, True)
+
+ self.assert_close(out, expected)
+
+ @pytest.mark.parametrize("kwargs", [{}, {"validate_boxes": None}], ids=["omitted", "none"])
+ def test_no_warning_without_validate_boxes_6401(self, kwargs, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ inp = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ src = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
+ dst = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype) # 1x4x2
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", DeprecationWarning)
+ kornia.geometry.transform.crop_by_boxes(inp, src, dst, **kwargs)
+
+ def test_scriptable_with_the_validate_boxes_deprecation_6401(self, device, dtype):
+ # The deprecation warning must not take `crop_by_boxes` out of TorchScript: it scripted before #6401, and
+ # the scripted call matches eager.
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ inp = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)
+ src = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
+ dst = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype) # 1x4x2
+
+ scripted = torch.jit.script(kornia.geometry.transform.crop_by_boxes)
+
+ self.assert_close(scripted(inp, src, dst), kornia.geometry.transform.crop_by_boxes(inp, src, dst))
+
+ @pytest.mark.parametrize("validate_boxes", [None, True, False])
+ def test_convention_boxes_are_not_validated_6401(self, validate_boxes, device, dtype):
+ # A trapezoid is not a rectangle, and `crop_by_boxes` does not require one: it maps `src_box` onto
+ # `dst_box` by a perspective transform. No value of `validate_boxes` makes it reject this box, so
+ # validating by default would change a result that works today.
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ inp = torch.arange(36.0, device=device, dtype=dtype).view(1, 1, 6, 6)
+ src = torch.tensor([[[1.0, 1.0], [4.0, 1.0], [5.0, 4.0], [0.0, 4.0]]], device=device, dtype=dtype) # 1x4x2
+ dst = torch.tensor([[[0.0, 0.0], [3.0, 0.0], [3.0, 3.0], [0.0, 3.0]]], device=device, dtype=dtype) # 1x4x2
+ expected = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ out = kornia.geometry.transform.crop_by_boxes(inp, src, dst, validate_boxes=validate_boxes)
+
+ assert out.shape == (1, 1, 4, 4)
+ assert out.isfinite().all()
+ self.assert_close(out, expected)
+
@pytest.mark.parametrize("size", [(1, 3), (3, 1), (1, 1)])
def test_convention_size_one_axis_4747(self, size, device, dtype):
# A size-1 axis makes the box vertices collinear, and solving the perspective system from them returned