Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix/jit/validate box (#3202)

Jian Shi1a6876878c87
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 3ea4c6574..ce6057c31 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -63,10 +63,15 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
width_t, width_b = x_tr - x_tl + 1, x_br - x_bl + 1
height_t, height_b = y_tr - y_tl + 1, y_br - y_bl + 1
- if not torch.allclose(width_t, width_b, atol=1e-4):
+ # Replace torch.allclose with exportable operations
+ width_diff = torch.abs(width_t - width_b)
+ height_diff = torch.abs(height_t - height_b)
+
+ # Check if differences are within tolerance (1e-4)
+ if torch.any(width_diff > 1e-4):
return False
- if not torch.allclose(height_t, height_b, atol=1e-4):
+ if torch.any(height_diff > 1e-4):
return False
return True
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index c34e6aef3..2b1f16ae9 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -15,18 +15,26 @@
# limitations under the License.
#
-from typing import Optional, Tuple
+from typing import Optional, Tuple, Union
import torch
-from kornia.core import Tensor, as_tensor, pad, tensor
+from kornia.constants import Resample
+from kornia.core import Module, Tensor, as_tensor, pad, tensor
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.bbox import infer_bbox_shape, validate_bbox
from .affwarp import resize
from .imgwarp import get_perspective_transform, warp_affine
-__all__ = ["center_crop", "crop_and_resize", "crop_by_boxes", "crop_by_indices", "crop_by_transform_mat"]
+__all__ = [
+ "CenterCrop2D",
+ "center_crop",
+ "crop_and_resize",
+ "crop_by_boxes",
+ "crop_by_indices",
+ "crop_by_transform_mat",
+]
def crop_and_resize(
@@ -378,3 +386,89 @@ def crop_by_indices(
else:
out[i] = _out
return out
+
+
+class CenterCrop2D(Module):
+ """Center crop the input tensor.
+
+ Args:
+ size: Size (h, w) in pixels of the resized region or just one side.
+ align_corners: interpolation flag.
+ resample: Resampling mode.
+ cropping_mode: Cropping mode, "resample" or "slice".
+
+ Note:
+ For JIT, the cropping mode must be "resample".
+ """
+
+ def __init__(
+ self,
+ size: Union[int, Tuple[int, int]],
+ align_corners: bool = True,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ cropping_mode: str = "slice",
+ ) -> None:
+ super().__init__()
+ if isinstance(size, tuple):
+ self.size = (size[0], size[1])
+ elif isinstance(size, int):
+ self.size = (size, size)
+ else:
+ raise Exception(f"Invalid size type. Expected (int, tuple(int, int). Got: {type(size)}.")
+
+ dst_h, dst_w = self.size
+ points_dst = torch.tensor([[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]], dtype=torch.long)
+ self.register_buffer("points_src", points_dst.clone())
+ self.register_buffer("points_dst", points_dst)
+
+ self.flags = {
+ "resample": Resample.get(resample),
+ "cropping_mode": cropping_mode,
+ "align_corners": align_corners,
+ "size": self.size,
+ "padding_mode": "zeros",
+ }
+
+ def forward(self, input: Tensor) -> Tensor:
+ batch_size = input.shape[0]
+
+ dst_h, dst_w = self.size
+ src_h, src_w = input.shape[-2:]
+
+ dst_h_half, dst_w_half = dst_h / 2, dst_w / 2
+ src_h_half, src_w_half = src_h / 2, src_w / 2
+
+ start_x, start_y = int(src_w_half - dst_w_half), int(src_h_half - dst_h_half)
+ end_x, end_y = start_x + dst_w - 1, start_y + dst_h - 1
+
+ # [y, x] origin
+ # top-left, top-right, bottom-right, bottom-left
+ self.points_src[0, 0, 0] = start_x
+ self.points_src[0, 0, 1] = start_y
+ self.points_src[0, 1, 0] = end_x
+ self.points_src[0, 1, 1] = start_y
+ self.points_src[0, 2, 0] = end_x
+ self.points_src[0, 2, 1] = end_y
+ self.points_src[0, 3, 0] = start_x
+ self.points_src[0, 3, 1] = end_y
+
+ if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
+ transform = get_perspective_transform(
+ self.points_src.expand(batch_size, -1, -1).to(input),
+ self.points_dst.expand(batch_size, -1, -1).to(input),
+ )
+ transform = transform.expand(batch_size, -1, -1)
+
+ return crop_by_transform_mat(
+ input,
+ transform[:, :2, :],
+ self.size,
+ self.flags["resample"].name.lower(), # type:ignore
+ "zeros",
+ self.flags["align_corners"], # type:ignore
+ )
+
+ if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
+ return crop_by_indices(input, self.points_src.expand(batch_size, -1, -1).to(input), self.flags["size"]) # type:ignore
+
+ raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index 59987337d..6a94452cf 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -77,6 +77,24 @@ class TestBbox2D(BaseTester):
# Compare
self.assert_close(actual, expected)
+ def test_jit(self, device, dtype):
+ # Test with valid rectangular box
+ boxes = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype)
+
+ # JIT compile the validate_bbox function
+ scripted_fn = torch.jit.script(validate_bbox)
+
+ # Test with valid box
+ self.assert_close(scripted_fn(boxes), validate_bbox(boxes))
+
+ # Test with non-rectangular box
+ boxes_invalid = torch.tensor([[[0.0, 0.0], [2.0, 0.0], [3.0, 1.0], [1.0, 1.0]]], device=device, dtype=dtype)
+ self.assert_close(scripted_fn(boxes_invalid), validate_bbox(boxes_invalid))
+
+ # Test with invalid shape
+ boxes_wrong_shape = torch.rand(1, 3, 2, device=device, dtype=dtype)
+ self.assert_close(scripted_fn(boxes_wrong_shape), validate_bbox(boxes_wrong_shape))
+
class TestTransformBoxes2D(BaseTester):
def test_transform_boxes(self, device, dtype):
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index 008d8225b..3591a6941 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -136,6 +136,7 @@ class TestCenterCrop(BaseTester):
out_crop = kornia.geometry.transform.center_crop(inp, (2, 4))
self.assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(kornia.geometry.transform.CenterCrop2D((2, 4))(inp), expected, rtol=1e-4, atol=1e-4)
def test_center_crop_h4_w2(self, device, dtype):
inp = torch.tensor(
@@ -149,6 +150,7 @@ class TestCenterCrop(BaseTester):
out_crop = kornia.geometry.transform.center_crop(inp, (height, width))
self.assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(kornia.geometry.transform.CenterCrop2D((height, width))(inp), expected, rtol=1e-4, atol=1e-4)
def test_center_crop_h4_w2_batch(self, device, dtype):
inp = torch.tensor(
@@ -171,11 +173,13 @@ class TestCenterCrop(BaseTester):
out_crop = kornia.geometry.transform.center_crop(inp, (4, 2))
self.assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(kornia.geometry.transform.CenterCrop2D((4, 2))(inp), expected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device):
img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
self.gradcheck(kornia.geometry.transform.center_crop, (img, (4, 2)))
+ self.gradcheck(kornia.geometry.transform.CenterCrop2D((4, 2)), (img))
def test_dynamo(self, device, dtype, torch_optimizer):
# Define script