π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(morphology): subtract integer structuring elements in the compute dtype; accept non-contiguous kernels (#6150)
Prateekshit Jaiswalc0ba9e101416
diff --git a/changelog.d/6150.fixed.md b/changelog.d/6150.fixed.mdnew file mode 100644index 000000000..d5e6f2682--- /dev/null+++ b/changelog.d/6150.fixed.md@@ -0,0 +1,7 @@+`kornia.morphology.dilation`, `erosion` and the operations built on them (`opening`, `closing`, `gradient`,+`top_hat`, `bottom_hat`) give the same result for a bool or integer `structuring_element` as for the equal float+one, on every engine. In 0.9.0rc1 a `uint8` or `int8` structuring element raised an overflow `RuntimeError`, a+bool one raised `NotImplementedError` in `erosion` and gave wrong values in `dilation` when `kernel` excluded a+cell, and every integer or bool one raised under `engine="convolution"`. The same functions also accept a+non-contiguous `kernel`, such as a transposed view, under `engine="convolution"`, which used to raise+`RuntimeError: view size is not compatible with input tensor's size and stride`. Other calls are not affected.diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.pyindex 88c6bd026..9ca756a93 100644--- a/kornia/morphology/morphology.py+++ b/kornia/morphology/morphology.py@@ -438,7 +438,7 @@ def dilation(output = output.masked_fill(special == 3, float("nan"))output = output.masked_fill(- kernel.view(-1).flip(0).view(1, -1, 1, 1) == 0,+ kernel.reshape(-1).flip(0).view(1, -1, 1, 1) == 0,reduction_min,)@@ -591,7 +591,8 @@ def erosion(# As in :func:`dilation`; subtracting the zero offsets changes no value, not even a ``-0.0``.output = torch.where(excluded, reduction_max, output).amin((-2, -1)).to(compute_dtype)else:- output = output - neighborhood+ # A bool structuring element has no subtraction; the cast changes no other value.+ output = output - neighborhood.to(dtype=compute_dtype)output.masked_fill_(excluded, reduction_max)output, _ = torch.min(output, 4)output, _ = torch.min(output, 4)@@ -627,7 +628,7 @@ def erosion(output = output.masked_fill(special == 3, float("nan"))output = output.masked_fill(- kernel.view(-1).view(1, -1, 1, 1) == 0,+ kernel.reshape(-1).view(1, -1, 1, 1) == 0,reduction_max,)@@ -640,7 +641,9 @@ def erosion(output = output.min(dim=1).valuesoutput = output.view(B, C, H, W)elif engine == "shift":- offsets = -neighborhood+ # Negate in the compute dtype, as ``unfold`` and ``convolution`` subtract: an unsigned structuring+ # element would wrap (``-uint8(2) == 254``), and a bool one has no negation.+ offsets = -neighborhood.to(dtype=compute_dtype)inplace = Falseif not torch.jit.is_scripting():inplace = not recording_grad and _can_reduce_in_place(output, offsets)diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.pyindex feff8154f..c5bf0027f 100644--- a/tests/morphology/test_dilation.py+++ b/tests/morphology/test_dilation.py@@ -162,6 +162,46 @@ class TestDilate(BaseTester):assert actual.dtype == expected.dtypeassert torch.equal(actual, expected)+ @pytest.mark.parametrize("se_dtype", [torch.bool, torch.uint8, torch.int8, torch.int64])+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution", "auto"])+ def test_non_float_structuring_element_matches_float(self, device, dtype, se_dtype, engine):+ # Every engine adds a bool or integer structuring element in the compute dtype, so it gives the float+ # structuring element's result, as in :func:`erosion`.+ tensor = torch.rand(2, 3, 6, 7, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)+ values = [[0, 1, 0], [1, 2, 1], [0, 1, 0]]+ if se_dtype in (torch.int8, torch.int64):+ values[0][0] = -128+ structuring_element = torch.tensor(values, device=device).to(se_dtype)++ expected = dilation(tensor, kernel, structuring_element=structuring_element.to(dtype), engine=engine)+ actual = dilation(tensor, kernel, structuring_element=structuring_element, engine=engine)++ assert actual.dtype == tensor.dtype+ assert torch.equal(actual, expected)++ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])+ @pytest.mark.parametrize("non_flat", [False, True])+ def test_non_contiguous_kernel(self, device, dtype, engine, non_flat):+ # A transposed kernel or structuring element is a strided view, which every engine must read by its+ # values. ``convolution`` flattened the kernel with ``view`` and raised on one.+ tensor = torch.rand(2, 3, 6, 7, device=device, dtype=dtype)+ kernel = torch.tensor([[1.0, 0.0, 0.0], [1.0, 1.0, 1.0]], device=device, dtype=dtype).T+ structuring_element = None+ if non_flat:+ structuring_element = torch.tensor([[0.0, 1.0, 0.0], [2.0, 0.0, 3.0]], device=device, dtype=dtype).T+ assert not kernel.is_contiguous()++ expected = dilation(+ tensor,+ kernel.contiguous(),+ structuring_element=structuring_element.contiguous() if structuring_element is not None else None,+ engine=engine,+ )+ actual = dilation(tensor, kernel, structuring_element=structuring_element, engine=engine)++ assert torch.equal(actual, expected)+@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).diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.pyindex 91688154a..ed50f9625 100644--- a/tests/morphology/test_erosion.py+++ b/tests/morphology/test_erosion.py@@ -159,6 +159,47 @@ class TestErode(BaseTester):assert actual.dtype == expected.dtypeassert torch.equal(actual, expected)+ @pytest.mark.parametrize("se_dtype", [torch.bool, torch.uint8, torch.int8, torch.int64])+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution", "auto"])+ def test_non_float_structuring_element_matches_float(self, device, dtype, se_dtype, engine):+ # Every engine subtracts a bool or integer structuring element in the compute dtype, so it gives the+ # float structuring element's result. ``shift`` used to negate it in its own dtype, which wrapped+ # ``-uint8(2)`` to 254 and ``-int8(-128)`` to -128 and raised for bool, as ``unfold`` also did.+ tensor = torch.rand(2, 3, 6, 7, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)+ values = [[0, 1, 0], [1, 2, 1], [0, 1, 0]]+ if se_dtype in (torch.int8, torch.int64):+ values[0][0] = -128+ structuring_element = torch.tensor(values, device=device).to(se_dtype)++ expected = erosion(tensor, kernel, structuring_element=structuring_element.to(dtype), engine=engine)+ actual = erosion(tensor, kernel, structuring_element=structuring_element, engine=engine)++ assert actual.dtype == tensor.dtype+ assert torch.equal(actual, expected)++ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])+ @pytest.mark.parametrize("non_flat", [False, True])+ def test_non_contiguous_kernel(self, device, dtype, engine, non_flat):+ # A transposed kernel or structuring element is a strided view, which every engine must read by its+ # values. ``convolution`` flattened the kernel with ``view`` and raised on one.+ tensor = torch.rand(2, 3, 6, 7, device=device, dtype=dtype)+ kernel = torch.tensor([[1.0, 0.0, 0.0], [1.0, 1.0, 1.0]], device=device, dtype=dtype).T+ structuring_element = None+ if non_flat:+ structuring_element = torch.tensor([[0.0, 1.0, 0.0], [2.0, 0.0, 3.0]], device=device, dtype=dtype).T+ assert not kernel.is_contiguous()++ expected = erosion(+ tensor,+ kernel.contiguous(),+ structuring_element=structuring_element.contiguous() if structuring_element is not None else None,+ engine=engine,+ )+ actual = erosion(tensor, kernel, structuring_element=structuring_element, engine=engine)++ assert torch.equal(actual, expected)+@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).