π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix: compute integer and bool boxes in float32 in mean_iou_bbox (#5417)
Muhammad Talha722ee1fe63cd
diff --git a/changelog.d/5417.fixed.md b/changelog.d/5417.fixed.mdnew file mode 100644index 000000000..32b4011cf--- /dev/null+++ b/changelog.d/5417.fixed.md@@ -0,0 +1 @@+`kornia.metrics.mean_iou_bbox` now computes integer and bool boxes in `float32`, so `uint8`, `int8` and `int16` boxes no longer wrap around in widths, areas and the union (which gave IoUs outside [0, 1] or NaN, accepted inverted `uint8` boxes and rejected wide `int8` ones). The result is still `float32`. An integer box set paired with a float16 or bfloat16 one in `xyxy` or `xywh` format now returns `float32`, as `cxcywh` already did, instead of the half dtype.diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.pyindex 5bce258d7..79c44565a 100644--- a/kornia/metrics/mean_iou.py+++ b/kornia/metrics/mean_iou.py@@ -105,6 +105,11 @@ def _convert_boxes_to_xyxy(boxes: torch.Tensor, box_format: str) -> torch.Tensorraise ValueError(f"Unsupported box format: {box_format}. Must be one of 'xyxy', 'xywh', or 'cxcywh'.")+def _promote_integer_boxes(boxes: torch.Tensor) -> torch.Tensor:+ """Return integer and bool boxes as float32; floating point boxes are returned unchanged."""+ return boxes if boxes.is_floating_point() else boxes.to(torch.float32)++def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str = "xyxy") -> torch.Tensor:"""Compute the IoU of the cartesian product of two sets of boxes.@@ -121,6 +126,10 @@ def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: stra tensor in dimensions :math:`(B1, B2)`, representing theintersection of each of the boxes in set 1 with respect to each of the boxes in set 2.+ .. note::+ Integer (and bool) boxes are computed in ``float32``, so the result is ``float32`` and widths, areas and the+ union do not wrap around in a narrow integer dtype such as ``uint8``, ``int8`` or ``int16``.+Example:>>> # XYXY format>>> boxes_1 = torch.tensor([[40, 40, 60, 60], [30, 40, 50, 60]])@@ -142,6 +151,12 @@ def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str[0.1429, 0.2500]])"""+ # Integer boxes would otherwise form every width, area and the union in their own dtype, where uint8, int8 and+ # int16 wrap around. Promote them before the format conversion too, because 'xywh' adds x + w in the box dtype.+ # Bool boxes are covered as well (they cannot be subtracted). The result is float32 for integer input either way.+ boxes_1 = _promote_integer_boxes(boxes_1)+ boxes_2 = _promote_integer_boxes(boxes_2)+# Convert boxes to xyxy formatboxes_1_xyxy = _convert_boxes_to_xyxy(boxes_1, box_format)boxes_2_xyxy = _convert_boxes_to_xyxy(boxes_2, box_format)diff --git a/tests/metrics/test_mean_iou.py b/tests/metrics/test_mean_iou.pyindex d0758f738..f2cbf0af3 100644--- a/tests/metrics/test_mean_iou.py+++ b/tests/metrics/test_mean_iou.py@@ -239,3 +239,64 @@ class TestMeanIoUBBox(BaseTester):iou_explicit = kornia.metrics.mean_iou_bbox(boxes_1, boxes_2, box_format="xyxy")self.assert_close(iou_default, iou_explicit)++ @pytest.mark.parametrize("box_format", ["xyxy", "xywh", "cxcywh"])+ @pytest.mark.parametrize(+ "int_dtype,side",+ [+ # The area side**2 is outside the dtype's range in every case: 400 > 255 and 127, 40000 > 32767, and+ # 512**2 is a multiple of 2**16, which wrapped the area, the intersection and the union to 0 (NaN IoU).+ (torch.uint8, 20),+ (torch.int8, 20),+ (torch.int16, 200),+ (torch.int16, 512),+ (torch.int32, 200),+ (torch.int64, 200),+ ],+ )+ def test_integer_boxes_do_not_overflow(self, int_dtype, side, box_format, device):+ half = side // 2+ coordinates = {+ "xyxy": [[0, 0, side, side], [half, 0, side + half, side]],+ "xywh": [[0, 0, side, side], [half, 0, side, side]],+ "cxcywh": [[half, half, side, side], [side, half, side, side]],+ }[box_format]+ boxes = torch.tensor(coordinates, device=device, dtype=int_dtype)+ original = boxes.clone()+ actual = kornia.metrics.mean_iou_bbox(boxes, boxes, box_format)+ # The same boxes held as int64 never wrap, so they are the reference for every narrower integer dtype.+ reference = kornia.metrics.mean_iou_bbox(boxes.to(torch.int64), boxes.to(torch.int64), box_format)+ expected = torch.tensor([[1.0, 1.0 / 3.0], [1.0 / 3.0, 1.0]], device=device)+ self.assert_close(actual, reference, atol=0.0, rtol=0.0)+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)+ self.assert_close(boxes, original, atol=0.0, rtol=0.0)+ assert actual.dtype == torch.float32+ assert actual.device == device++ def test_uint8_xywh_corner_does_not_wrap_during_conversion(self, device):+ # x + w is 300 and 300, past the uint8 maximum. The overflow is in the xywh -> xyxy conversion itself, so the+ # integer boxes have to be promoted before it. The true IoU is 500 / 1000.+ boxes_1 = torch.tensor([[200, 0, 100, 10]], device=device, dtype=torch.uint8)+ boxes_2 = torch.tensor([[250, 0, 50, 10]], device=device, dtype=torch.uint8)+ actual = kornia.metrics.mean_iou_bbox(boxes_1, boxes_2, "xywh")+ self.assert_close(actual, torch.tensor([[0.5]], device=device), atol=0.0, rtol=0.0)++ def test_integer_boxes_are_validated_without_wraparound(self, device):+ # 5 - 10 wraps to 251 in uint8, so an inverted box used to pass the validation and return a plausible IoU.+ inverted = torch.tensor([[10, 10, 5, 5]], device=device, dtype=torch.uint8)+ valid = torch.tensor([[0, 0, 4, 4]], device=device, dtype=torch.uint8)+ with pytest.raises(AssertionError, match="Boxes_1 contains invalid boxes"):+ kornia.metrics.mean_iou_bbox(inverted, valid)+ with pytest.raises(AssertionError, match="Boxes_2 contains invalid boxes"):+ kornia.metrics.mean_iou_bbox(valid, inverted)+ # 100 - (-100) wraps to -56 in int8, so a valid wide box used to be rejected as invalid.+ wide = torch.tensor([[-100, 0, 100, 10]], device=device, dtype=torch.int8)+ self.assert_close(kornia.metrics.mean_iou_bbox(wide, wide), torch.tensor([[1.0]], device=device))++ def test_bool_boxes(self, device):+ # Subtracting bool tensors raises in torch, so bool boxes used to fail. They are 0/1 coordinates.+ boxes_1 = torch.tensor([[False, False, True, True]], device=device)+ boxes_2 = torch.tensor([[False, False, True, True]], device=device)+ actual = kornia.metrics.mean_iou_bbox(boxes_1, boxes_2)+ assert actual.dtype == torch.float32+ self.assert_close(actual, torch.tensor([[1.0]], device=device))