π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix: preserve fractional bounds in in_range (#5434)
Mohamed Zakkariad5c918be03ba
diff --git a/changelog.d/5434.fixed.md b/changelog.d/5434.fixed.mdnew file mode 100644index 000000000..3fab41fe9--- /dev/null+++ b/changelog.d/5434.fixed.md@@ -0,0 +1 @@+`in_range` and `InRange` now respect fractional and out-of-range bounds on integer images without truncating bounds or overflowing the image dtype.diff --git a/kornia/filters/in_range.py b/kornia/filters/in_range.pyindex 29dee3d91..43d1c25c3 100644--- a/kornia/filters/in_range.py+++ b/kornia/filters/in_range.py@@ -25,6 +25,36 @@ from torch import nnfrom kornia.image.utils import perform_keep_shape_image+def _tuple_bound(bound: tuple[Any, ...], input: torch.Tensor) -> torch.Tensor:+ if input.is_floating_point() or input.is_complex():+ return torch.tensor(bound, device=input.device, dtype=input.dtype)+ # Preserve Python float precision and exact integer bounds. Normalize on CPU before moving to devices+ # such as MPS, which do not support float64.+ dtype = torch.int64 if all(isinstance(value, int) for value in bound) else torch.float64+ return torch.tensor(bound, dtype=dtype)+++def _compare_bound(input: torch.Tensor, bound: torch.Tensor, lower: bool) -> torch.Tensor:+ if input.is_floating_point() or input.is_complex():+ bound = bound.to(input)+ elif bound.is_floating_point():+ # Round the bound, not the image: promoting large integer pixels to float can change the comparison.+ bound = bound.ceil() if lower else bound.floor()+ minimum = 0 if input.dtype == torch.bool else torch.iinfo(input.dtype).min+ maximum = 1 if input.dtype == torch.bool else torch.iinfo(input.dtype).max+ below = bound < minimum+ above = bound >= maximum + 1+ # max + 1 is an exact power of two even when max itself rounds up in the bound's floating dtype.+ safe_bound = torch.where((bound >= minimum) & (bound < maximum + 1), bound, 0).to(input)+ below, above = below.to(input.device), above.to(input.device)+ if lower:+ return ((input >= safe_bound) | below) & ~above & ~bound.isnan().to(input.device)+ return ((input <= safe_bound) | above) & ~below & ~bound.isnan().to(input.device)+ else:+ bound = bound.to(device=input.device)+ return input >= bound if lower else input <= bound++def _as_bchw_bound(name: str, bound: torch.Tensor, input_shape: torch.Size) -> torch.Tensor:"""Validate a Tensor bound against the ``(B, C, H, W)`` input and return it as a 4-D Tensor.@@ -68,7 +98,9 @@ def in_range(\text{out}(I) = \bigwedge_{c=0}^{C-1}\left( \text{lower}_c(I) \leq \text{input}_c(I) \leq \text{upper}_c(I) \right)- where `C` is the number of channels. Both comparisons are inclusive.+ where `C` is the number of channels. Both comparisons are inclusive. For integer inputs, fractional lower+ bounds are rounded up and fractional upper bounds down. Bounds outside the input dtype's range do not+ wrap or overflow; a range containing no representable input value produces an empty mask.Args:input: The input torch.Tensor to be filtered in the shape of :math:`(*, *, H, W)`.@@ -154,26 +186,18 @@ def in_range(if len(lower) != input_shape[1] or len(upper) != input_shape[1]:raise ValueError("Shape of `lower`, `upper` and `input` image channels must have same shape.")- lower = (- torch.tensor(lower, device=input.device, dtype=input.dtype)- .reshape(1, -1, 1, 1)- .repeat(input_shape[0], 1, 1, 1)- )- upper = (- torch.tensor(upper, device=input.device, dtype=input.dtype)- .reshape(1, -1, 1, 1)- .repeat(input_shape[0], 1, 1, 1)- )+ lower = _tuple_bound(lower, input).reshape(1, -1, 1, 1).repeat(input_shape[0], 1, 1, 1)+ upper = _tuple_bound(upper, input).reshape(1, -1, 1, 1).repeat(input_shape[0], 1, 1, 1)elif isinstance(lower, torch.Tensor) and isinstance(upper, torch.Tensor):- lower = _as_bchw_bound("lower", lower, input_shape).to(input)- upper = _as_bchw_bound("upper", upper, input_shape).to(input)+ lower = _as_bchw_bound("lower", lower, input_shape)+ upper = _as_bchw_bound("upper", upper, input_shape)else:raise TypeError("Invalid `lower` and `upper` format. Both should be tuples or both torch.Tensor.")# Apply lower and upper bounds. Combine masks with logical_and.- mask = torch.logical_and(input >= lower, input <= upper)+ mask = torch.logical_and(_compare_bound(input, lower, lower=True), _compare_bound(input, upper, lower=False))mask = mask.all(dim=(1), keepdim=True).to(input.dtype)if return_mask:diff --git a/tests/filters/test_in_range.py b/tests/filters/test_in_range.pyindex e390796c7..de09891f2 100644--- a/tests/filters/test_in_range.py+++ b/tests/filters/test_in_range.py@@ -266,6 +266,70 @@ class TestInRange(BaseTester):self.assert_close(by_tuple, expected)self.assert_close(by_tensor, expected)+ @pytest.mark.parametrize("tensor_bounds", [False, True])+ @pytest.mark.parametrize("return_mask", [False, True])+ @pytest.mark.parametrize(+ "image_dtype, values, lower, upper, expected",+ [+ (torch.uint8, [99, 100, 101, 200, 201], 100.7, 200.5, [0, 0, 1, 1, 0]),+ (torch.int16, [-5, -4, -3, -2], -10.0, -3.5, [1, 1, 0, 0]),+ (torch.int16, [-5, -4, -3, -2], -3.5, -2.5, [0, 0, 1, 0]),+ (torch.uint8, [100, 101], 100.2, 100.8, [0, 0]),+ (torch.uint8, [0, 100, 255], -1, 256, [1, 1, 1]),+ (torch.uint8, [0, 100, 255], -10.0, -0.5, [0, 0, 0]),+ (torch.uint8, [0, 100, 255], 255.5, 300.0, [0, 0, 0]),+ (torch.int16, [-32768, 0, 32767], -40000.0, 40000.0, [1, 1, 1]),+ (torch.int16, [-32768, 0, 32767], float("-inf"), float("inf"), [1, 1, 1]),+ (torch.int16, [-1, 0, 1], float("nan"), 1.0, [0, 0, 0]),+ (torch.int16, [-1, 0, 1], -1.0, float("nan"), [0, 0, 0]),+ (torch.int64, [2**60, 2**60 + 1, 2**60 + 2], 2**60 + 1, 2**60 + 1, [0, 1, 0]),+ (torch.int64, [-(2**63), 0, 2**63 - 1], float("-inf"), float(2**63), [1, 1, 1]),+ (torch.int64, [-(2**63), 0, 2**63 - 1], float(2**63), float("inf"), [0, 0, 0]),+ ],+ )+ def test_integer_bounds(self, image_dtype, values, lower, upper, expected, tensor_bounds, return_mask, device):+ # Expected masks follow the inclusive inequalities using the original bounds, before any dtype conversion.+ img = torch.tensor(values, device=device, dtype=image_dtype).reshape(1, 1, 1, -1)+ lower, upper = (lower,), (upper,)+ if tensor_bounds:+ lower, upper = torch.tensor(lower), torch.tensor(upper)+ expected = torch.tensor(expected, device=device, dtype=image_dtype).reshape_as(img)+ if not return_mask:+ expected = img * expected+ actual = in_range(img, lower, upper, return_mask=return_mask)+ assert actual.dtype == img.dtype+ assert actual.device == img.device+ self.assert_close(actual, expected, rtol=0, atol=0)+ self.assert_close(InRange(lower, upper, return_mask=return_mask)(img), expected, rtol=0, atol=0)++ def test_integer_input_is_not_rounded_to_bound_dtype(self, device):+ img = torch.tensor([2**24, 2**24 + 1], device=device, dtype=torch.int32).reshape(1, 1, 1, 2)+ bound = torch.tensor([2**24], dtype=torch.float32)+ expected = torch.tensor([[[[1, 0]]]], device=device, dtype=img.dtype)+ self.assert_close(in_range(img, bound, bound, return_mask=True), expected, rtol=0, atol=0)++ def test_integer_tuple_bound_preserves_python_precision(self, device):+ img = torch.tensor([100, 101], device=device, dtype=torch.uint8).reshape(1, 1, 1, 2)+ expected = torch.tensor([[[[0, 1]]]], device=device, dtype=img.dtype)+ self.assert_close(in_range(img, (100.0000001,), (101.0,), return_mask=True), expected)++ def test_integer_tensor_bounds_broadcast_per_batch_and_channel(self, device):+ img = torch.tensor([100, 101, -4, -3, 200, 201, -2, -1], device=device, dtype=torch.int16).reshape(2, 2, 1, 2)+ lower = torch.tensor([[100.7, -5.0], [199.5, -2.5]], device=device).reshape(2, 2, 1, 1)+ upper = torch.tensor([[200.5, -3.5], [200.5, -0.5]], device=device).reshape(2, 2, 1, 1)+ expected = torch.tensor([0, 0, 1, 0], device=device, dtype=img.dtype).reshape(2, 1, 1, 2)+ self.assert_close(in_range(img, lower, upper, return_mask=True), expected)++ @pytest.mark.parametrize("tensor_bounds", [False, True])+ def test_dynamo_integer_bounds(self, device, tensor_bounds, torch_optimizer):+ img = torch.tensor([0, 100, 101, 200, 255], device=device, dtype=torch.uint8).reshape(1, 1, 1, 5)+ lower, upper = (100.7,), (256.0,)+ if tensor_bounds:+ lower, upper = torch.tensor(lower, device=device), torch.tensor(upper, device=device)+ op = InRange(lower, upper, return_mask=True)+ expected = torch.tensor([[[[0, 0, 1, 1, 1]]]], device=device, dtype=img.dtype)+ self.assert_close(torch_optimizer(op, fullgraph=True)(img), expected)+def test_multi_channel_mask_requires_every_channel(self, device, dtype):# The conjunction runs over the C channels: one channel out of range clears the pixel.img = torch.tensor([0.5, 0.5, 0.5, 0.5, 0.5, 0.95], device=device, dtype=dtype).reshape(1, 3, 1, 2)