Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): reject non-finite bbox coordinates (#4243)

Blackdrome217b92e60039
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dea433c5d..1b89f0af3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -477,6 +477,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
branch, used to raise: `_compute_zero_padding3d` defined a `(k - 1) // 2` helper and then returned the
full kernel sizes, so the padded volume did not match the kernel it was convolved with. (#4241, #4242)
+* Eager bbox validation now rejects NaN and infinite coordinates: `validate_bbox` returns `False` and
+ `Boxes.from_tensor(..., validate_boxes=True)` raises `ValueError` for the `xyxy`, `xyxy_plus` and `xywh`
+ modes, instead of accepting them as valid geometry (closes #4238). (#4243)
+
* `HyNet` and `SOSNet` now run in half precision, on CPU and on GPU, and no longer return NaN for a
degenerate patch (closes #4224). Two defects sat on the same line. On CPU both raised
`NotImplementedError: "avg_pool3d_out_frame" not implemented for 'Half'` (and the `'BFloat16'` spelling):
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index b29013b29..8cc2ded42 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -70,6 +70,9 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
if not (len(boxes.shape) in [3, 4] and boxes.shape[-2:] == torch.Size([4, 2])):
return False
+ if not torch.isfinite(boxes).all():
+ return False
+
if len(boxes.shape) == 4:
boxes = boxes.reshape(-1, 4, 2)
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index b6f747cac..d03532b1e 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -139,6 +139,8 @@ def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_b
# Value validation reads the data, which graph capture cannot do; skip it under export.
if validate_boxes and not is_exporting():
+ if not torch.isfinite(boxes).all():
+ raise ValueError("Some boxes have non-finite coordinates.")
if (width <= 0).any():
raise ValueError("Some boxes have negative widths or 0.")
if (height <= 0).any():
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index b8919670c..6e2f0f201 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -123,6 +123,23 @@ class TestBbox2D(BaseTester):
assert expanded.stride(0) == 0
assert validate_bbox(expanded) is True
+ def test_convention_validate_bbox_rejects_non_finite_coordinates_4238(self, device, dtype):
+ # Pin kornia#4238: NaN and infinite coordinates must not pass validation,
+ # including when an invalid row is mixed with a valid row.
+ boxes = torch.tensor(
+ [
+ [[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]],
+ [[1.0, 1.0], [5.0, 1.0], [5.0, 5.0], [1.0, 5.0]],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ for coordinate_index in range(8):
+ for non_finite in [float("nan"), float("inf"), float("-inf")]:
+ invalid_boxes = boxes.clone()
+ invalid_boxes[1].reshape(-1)[coordinate_index] = non_finite
+ assert validate_bbox(invalid_boxes) is False
+
def test_convention_validate_bbox_invariance_is_exact_arithmetic_only(self, device):
# In float16 the inclusive +1 rounds distinct sub-unit spans to the same
# value, although the exclusive span difference exceeds the 1e-4 threshold.
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 1b42e42f4..0482a33b6 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -48,6 +48,24 @@ class TestBoxes2D(BaseTester):
expected = torch.tensor([[[[1.0, 2.0], [4.0, 2.0], [4.0, 3.0], [1.0, 3.0]]]], device=device, dtype=dtype)
self.assert_close(boxes.data, expected, atol=0.0, rtol=0.0)
+ @pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh"])
+ def test_convention_from_tensor_rejects_non_finite_coordinates_4238(self, mode, device, dtype):
+ # Pin kornia#4238: eager validation rejects non-finite values in both
+ # unbatched and batched inputs, even when valid rows are present too.
+ source = torch.tensor([[0.0, 0.0, 4.0, 4.0], [1.0, 1.0, 5.0, 5.0]], device=device, dtype=dtype)
+ for source_layout in [source, source.unsqueeze(0)]:
+ for coordinate_index in range(4):
+ for non_finite in [float("nan"), float("inf"), float("-inf")]:
+ invalid_source = source_layout.clone()
+ invalid_source.reshape(-1, 4)[1, coordinate_index] = non_finite
+ with pytest.raises(ValueError, match="non-finite coordinates"):
+ Boxes.from_tensor(invalid_source, mode=mode, validate_boxes=True)
+
+ def test_convention_from_tensor_opt_out_preserves_non_finite_input_4238(self, device, dtype):
+ source = torch.tensor([[0.0, 0.0, float("nan"), 4.0]], device=device, dtype=dtype)
+ boxes = Boxes.from_tensor(source, mode="xyxy", validate_boxes=False)
+ assert torch.isnan(boxes.data).any()
+
@pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])
def test_convention_axis_aligned_box_round_trips_in_each_mode(self, mode, device, dtype):
# Convention pin: an axis-aligned rectangle whose extent is at least one unit