π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix/morphology validation 4736 (#4744)
NiteeshGowda72520e76698430
diff --git a/changelog.d/4744.breaking.md b/changelog.d/4744.breaking.mdnew file mode 100644index 000000000..d6d581008--- /dev/null+++ b/changelog.d/4744.breaking.md@@ -0,0 +1,9 @@+Morphology operations now raise a `ValueError` naming the argument for an unknown `border_type` (PyTorch+raised `NotImplementedError: Unrecognised padding mode`) and for a `structuring_element` whose shape differs+from `kernel`'s (PyTorch raised an internal `IndexError` or `RuntimeError`; only an element with extra trailing+size-1 axes, such as `(k_h, k_w, 1)`, used to run, and only with `engine="convolution"`). On a floating-point+image, a `bool` or integer `kernel` is now a plain membership mask and gives exactly the result and dtype of+the same kernel in the image's dtype. Before, a `uint8` or `int8` kernel raised an overflow `RuntimeError`, and+a `bool` kernel stored its excluded cells as `True` instead of `-max_val`: `dilation` returned wrong values on+every engine, `erosion` did so with `engine="convolution"` and raised on the other engines, and the five+operations built on them inherited this. Non-float images behave as before.diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.pyindex 4a52d8b54..c1d1e7b05 100644--- a/kornia/morphology/morphology.py+++ b/kornia/morphology/morphology.py@@ -23,6 +23,25 @@ import torch.nn.functional as F__all__ = ["bottom_hat", "closing", "dilation", "erosion", "gradient", "opening", "top_hat"]+def _validate_morphology_inputs(+ kernel: torch.Tensor, structuring_element: Optional[torch.Tensor], border_type: str+) -> None:+ if not isinstance(kernel, torch.Tensor):+ raise TypeError(f"Kernel type is not a torch.Tensor. Got {type(kernel)}")+ if len(kernel.shape) != 2:+ raise ValueError(f"Kernel size must have 2 dimensions. Got {kernel.dim()}")+ if structuring_element is not None and structuring_element.shape != kernel.shape:+ raise ValueError(+ f"`structuring_element` shape must match `kernel` shape. "+ f"Got {structuring_element.shape} and {kernel.shape}."+ )+ if border_type not in ["geodesic", "constant", "reflect", "replicate", "circular"]:+ raise ValueError(+ f"Unknown `border_type`: {border_type}. "+ "Expected one of ['geodesic', 'constant', 'reflect', 'replicate', 'circular']."+ )++def _neight2channels_like_kernel(kernel: torch.Tensor) -> torch.Tensor:h, w = kernel.size()kernel = torch.eye(h * w, dtype=kernel.dtype, device=kernel.device)@@ -185,11 +204,7 @@ def dilation(if len(tensor.shape) != 4:raise ValueError(f"Input size must have 4 dimensions. Got {tensor.dim()}")- if not isinstance(kernel, torch.Tensor):- raise TypeError(f"Kernel type is not a torch.Tensor. Got {type(kernel)}")-- if len(kernel.shape) != 2:- raise ValueError(f"Kernel size must have 2 dimensions. Got {kernel.dim()}")+ _validate_morphology_inputs(kernel, structuring_element, border_type)# originse_h, se_w = kernel.shape@@ -206,7 +221,10 @@ def dilation(# computationif structuring_element is None:- neighborhood = torch.zeros_like(kernel)+ # ``kernel`` is only a membership mask: a bool or integer kernel cannot hold ``-max_val``, so a+ # floating-point image lends it its dtype. A float kernel keeps its own, which may widen the result.+ nb_dtype = tensor.dtype if tensor.is_floating_point() and not kernel.is_floating_point() else kernel.dtype+ neighborhood = torch.zeros_like(kernel, dtype=nb_dtype)neighborhood[kernel == 0] = -max_valelse:neighborhood = structuring_element.clone()@@ -301,11 +319,7 @@ def erosion(if len(tensor.shape) != 4:raise ValueError(f"Input size must have 4 dimensions. Got {tensor.dim()}")- if not isinstance(kernel, torch.Tensor):- raise TypeError(f"Kernel type is not a torch.Tensor. Got {type(kernel)}")-- if len(kernel.shape) != 2:- raise ValueError(f"Kernel size must have 2 dimensions. Got {kernel.dim()}")+ _validate_morphology_inputs(kernel, structuring_element, border_type)# originse_h, se_w = kernel.shape@@ -321,7 +335,10 @@ def erosion(# computationif structuring_element is None:- neighborhood = torch.zeros_like(kernel)+ # ``kernel`` is only a membership mask: a bool or integer kernel cannot hold ``-max_val``, so a+ # floating-point image lends it its dtype. A float kernel keeps its own, which may widen the result.+ nb_dtype = tensor.dtype if tensor.is_floating_point() and not kernel.is_floating_point() else kernel.dtype+ neighborhood = torch.zeros_like(kernel, dtype=nb_dtype)neighborhood[kernel == 0] = -max_valelse:neighborhood = structuring_element.clone()diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.pyindex 24e5baf9b..ebb2f998b 100644--- a/tests/morphology/test_dilation.py+++ b/tests/morphology/test_dilation.py@@ -145,6 +145,44 @@ class TestDilate(BaseTester):with pytest.raises(NotImplementedError, match="unknown"):dilation(tensor, kernel, engine="invalid_engine")+ with pytest.raises(ValueError, match="Unknown `border_type`"):+ dilation(tensor, kernel, border_type="banana")++ with pytest.raises(ValueError, match="`structuring_element` shape must match `kernel` shape"):+ dilation(tensor, kernel, structuring_element=torch.ones(3, 2, device=device, dtype=dtype))++ @pytest.mark.parametrize("kernel_dtype", [torch.bool, torch.uint8, torch.int8, torch.int64])+ @pytest.mark.parametrize("engine", ["unfold", "shift", "auto"])+ def test_non_float_kernel_matches_float_kernel(self, device, dtype, kernel_dtype, engine):+ # The kernel is only a membership mask (#4736): a bool or integer kernel must give exactly the+ # float kernel's result and dtype. The cross has zeros, so an excluded neighbor that leaks in shows.+ tensor = torch.rand(2, 3, 6, 7, device=device, dtype=dtype)+ kernel = torch.tensor([[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)+ expected = dilation(tensor, kernel, engine=engine)+ actual = dilation(tensor, kernel.to(kernel_dtype), engine=engine)+ assert actual.dtype == expected.dtype+ assert torch.equal(actual, expected)++ def test_integer_image_keeps_the_kernel_dtype(self, device):+ # Only a floating-point image lends its dtype to a non-float kernel (#4736). An integer image+ # keeps the kernel's own dtype, as before: int32 with int64 computes and returns int64.+ tensor = torch.tensor([[0, 3, 0, 0, 7]], dtype=torch.int32, device=device)[None, None]+ kernel = torch.tensor([[1, 0, 1]], dtype=torch.int64, device=device)+ actual = dilation(tensor, kernel)+ assert actual.dtype == torch.int64+ assert actual.flatten().tolist() == [3, 0, 3, 7, 0]++ @pytest.mark.parametrize("border_type", ["geodesic", "constant", "reflect", "replicate", "circular"])+ def test_accepted_border_types(self, device, dtype, border_type):+ # Every documented border_type must pass the validation (#4736).+ if border_type == "reflect" and not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):+ pytest.skip("replication_pad2d is unavailable for this device/dtype")+ tensor = torch.rand(1, 2, 5, 6, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)+ assert dilation(tensor, kernel, border_type=border_type).shape == tensor.shape+def test_custom_origin(self, device, dtype):# Custom origin shifts the structuring element anchor pointtensor = torch.zeros(1, 1, 5, 5, device=device, dtype=dtype)diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.pyindex 273f63445..9acc5e4d7 100644--- a/tests/morphology/test_erosion.py+++ b/tests/morphology/test_erosion.py@@ -145,6 +145,44 @@ class TestErode(BaseTester):test = torch.ones(2, 3, 4, device=device, dtype=dtype)assert erosion(tensor, test)+ with pytest.raises(ValueError, match="Unknown `border_type`"):+ erosion(tensor, kernel, border_type="banana")++ with pytest.raises(ValueError, match="`structuring_element` shape must match `kernel` shape"):+ erosion(tensor, kernel, structuring_element=torch.ones(3, 2, device=device, dtype=dtype))++ @pytest.mark.parametrize("kernel_dtype", [torch.bool, torch.uint8, torch.int8, torch.int64])+ @pytest.mark.parametrize("engine", ["unfold", "shift", "auto"])+ def test_non_float_kernel_matches_float_kernel(self, device, dtype, kernel_dtype, engine):+ # The kernel is only a membership mask (#4736): a bool or integer kernel must give exactly the+ # float kernel's result and dtype. The cross has zeros, so an excluded neighbor that leaks in shows.+ tensor = torch.rand(2, 3, 6, 7, device=device, dtype=dtype)+ kernel = torch.tensor([[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)+ expected = erosion(tensor, kernel, engine=engine)+ actual = erosion(tensor, kernel.to(kernel_dtype), engine=engine)+ assert actual.dtype == expected.dtype+ assert torch.equal(actual, expected)++ def test_integer_image_keeps_the_kernel_dtype(self, device):+ # Only a floating-point image lends its dtype to a non-float kernel (#4736). An integer image+ # keeps the kernel's own dtype, as before: int32 with int64 computes and returns int64.+ tensor = torch.tensor([[0, 3, 0, 0, 7]], dtype=torch.int32, device=device)[None, None]+ kernel = torch.tensor([[1, 0, 1]], dtype=torch.int64, device=device)+ actual = erosion(tensor, kernel)+ assert actual.dtype == torch.int64+ assert actual.flatten().tolist() == [3, 0, 0, 0, 0]++ @pytest.mark.parametrize("border_type", ["geodesic", "constant", "reflect", "replicate", "circular"])+ def test_accepted_border_types(self, device, dtype, border_type):+ # Every documented border_type must pass the validation (#4736).+ if border_type == "reflect" and not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):+ pytest.skip("replication_pad2d is unavailable for this device/dtype")+ tensor = torch.rand(1, 2, 5, 6, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)+ assert erosion(tensor, kernel, border_type=border_type).shape == tensor.shape+def test_jit(self, device, dtype):op = erosionop_script = torch.jit.script(op)