π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): return second order derivatives with the standard sign in spatial_gradient and spatial_gradient3d (#4683)
εΊζ’ηbde7c1dd084b
diff --git a/changelog.d/4683.breaking.md b/changelog.d/4683.breaking.mdnew file mode 100644index 000000000..e0cbaeb03--- /dev/null+++ b/changelog.d/4683.breaking.md@@ -0,0 +1,10 @@+`spatial_gradient(..., order=2)` and `spatial_gradient3d(..., order=2)` return second derivatives with the+standard sign: on `x**2` the `dxx` channel is positive and on `x*y` the `dxy` channel is positive, matching the+OpenCV `Sobel(dx=2)` and `Sobel(dx=1, dy=1)` kernels. Previously `mode="sobel"` returned `-dxx`, `-dxy` and `-dyy`,+the 2D `mode="diff"` returned `-dxy` next to a correctly signed `dxx`/`dyy`, and the 3D `mode="diff"` returned+`-dyz` and `-dxz` next to a correctly signed `dxy`. Code that compensated for the old signs, for example `-dxx` as a+Sobel Laplacian, now gets the opposite result without a warning. The exported kernel getters+`get_spatial_gradient_kernel2d("sobel", 2)` and `get_spatial_gradient_kernel2d("diff", 2)` return the negated+kernels accordingly, while `get_spatial_gradient_kernel3d("diff", 2)` is unchanged because the fix removes the+flip in `spatial_gradient3d` instead of editing the kernel. `hessian_response` is unchanged. The docstrings now+list the channel layout, `(dxx, dxy, dyy)` in 2D and `(dxx, dyy, dzz, dxy, dyz, dxz)` in 3D.diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex de0392706..041ae2544 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -386,11 +386,11 @@ def get_sobel_kernel_5x5_2nd_order("""Return a 2nd order sobel kernel of 5x5."""return torch.tensor([- [-1.0, 0.0, 2.0, 0.0, -1.0],- [-4.0, 0.0, 8.0, 0.0, -4.0],- [-6.0, 0.0, 12.0, 0.0, -6.0],- [-4.0, 0.0, 8.0, 0.0, -4.0],- [-1.0, 0.0, 2.0, 0.0, -1.0],+ [1.0, 0.0, -2.0, 0.0, 1.0],+ [4.0, 0.0, -8.0, 0.0, 4.0],+ [6.0, 0.0, -12.0, 0.0, 6.0],+ [4.0, 0.0, -8.0, 0.0, 4.0],+ [1.0, 0.0, -2.0, 0.0, 1.0],],device=device,dtype=dtype,@@ -403,11 +403,11 @@ def _get_sobel_kernel_5x5_2nd_order_xy("""Return a 2nd order sobel kernel of 5x5."""return torch.tensor([- [-1.0, -2.0, 0.0, 2.0, 1.0],- [-2.0, -4.0, 0.0, 4.0, 2.0],- [0.0, 0.0, 0.0, 0.0, 0.0],- [2.0, 4.0, 0.0, -4.0, -2.0],[1.0, 2.0, 0.0, -2.0, -1.0],+ [2.0, 4.0, 0.0, -4.0, -2.0],+ [0.0, 0.0, 0.0, 0.0, 0.0],+ [-2.0, -4.0, 0.0, 4.0, 2.0],+ [-1.0, -2.0, 0.0, 2.0, 1.0],],device=device,dtype=dtype,@@ -518,7 +518,7 @@ def get_diff_kernel2d_2nd_order("""Return 2nd order gradient for diff operator."""gxx = torch.tensor([[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype)gyy = gxx.transpose(0, 1)- gxy = torch.tensor([[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]], device=device, dtype=dtype)+ gxy = torch.tensor([[1.0, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, 1.0]], device=device, dtype=dtype)return torch.stack([gxx, gxy, gyy])diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex 51cdb9199..793c0f5a6 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -29,7 +29,7 @@ from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, normalized: bool = True) -> torch.Tensor:- r"""Compute the first order image derivative in both x and y using a Sobel operator.+ r"""Compute the first or second order image derivative in x and y using a Sobel or diff operator... image:: _static/img/spatial_gradient.png@@ -40,7 +40,9 @@ def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, nnormalized: whether the output is normalized.Return:- the derivatives of the input feature map. with shape :math:`(B, C, 2, H, W)`.+ the derivatives of the input feature map. with shape :math:`(B, C, 2, H, W)` holding+ :math:`(dx, dy)` for ``order=1`` and :math:`(B, C, 3, H, W)` holding :math:`(dxx, dxy, dyy)`+ for ``order=2``... note::See a working example `here <https://www.kornia.org/tutorials/nbs/filtering_edges.html>`__.@@ -104,8 +106,9 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1)order: the order of the derivatives.Return:- the spatial gradients of the input feature map with shape math:`(B, C, 3, D, H, W)`- or :math:`(B, C, 6, D, H, W)`.+ the spatial gradients of the input feature map with shape :math:`(B, C, 3, D, H, W)` holding+ :math:`(dx, dy, dz)` for ``order=1`` or :math:`(B, C, 6, D, H, W)` holding+ :math:`(dxx, dyy, dzz, dxy, dyz, dxz)` for ``order=2``.Examples:>>> input = torch.rand(1, 4, 2, 4, 4)@@ -138,9 +141,6 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1)tmp_kernel = kernel.repeat(c, 1, 1, 1, 1)- # convolve input torch.Tensor with grad kernel- kernel_flip = tmp_kernel.flip(-3)-# Pad with "replicate for spatial dims, but with torch.zeros for channelspatial_pad = [kernel.size(2) // 2,@@ -151,7 +151,7 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1)kernel.size(4) // 2,]out_ch: int = 6 if order == 2 else 3- out = F.conv3d(F.pad(input, spatial_pad, "replicate"), kernel_flip, padding=0, groups=c).view(+ out = F.conv3d(F.pad(input, spatial_pad, "replicate"), tmp_kernel, padding=0, groups=c).view(b, c, out_ch, d, h, w)return outdiff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.pyindex 788b4106d..2df8123f9 100644--- a/tests/filters/test_sobel.py+++ b/tests/filters/test_sobel.py@@ -254,6 +254,23 @@ class TestSpatialGradient(BaseTester):edges = spatial_gradient(inp, "diff", normalized=True)self.assert_close(edges, expected)+ @pytest.mark.parametrize("mode", ["sobel", "diff"])+ def test_second_order_quadratics(self, mode, device, dtype):+ coords = torch.arange(7, device=device, dtype=dtype)+ y, x = torch.meshgrid(coords, coords, indexing="ij")+ # one image per quadratic surface: x^2, x*y, y^2+ inp = torch.stack([x * x, x * y, y * y])[:, None]+ # the unnormalized (dxx, dxy, dyy) response of each surface is constant away from the border+ if mode == "sobel":+ expected = torch.tensor(+ [[128.0, 0.0, 0.0], [0.0, 64.0, 0.0], [0.0, 0.0, 128.0]], device=device, dtype=dtype+ )+ else:+ expected = torch.tensor([[2.0, 0.0, 0.0], [0.0, 4.0, 0.0], [0.0, 0.0, 2.0]], device=device, dtype=dtype)++ actual = spatial_gradient(inp, mode, order=2, normalized=False)[:, 0, :, 2:-2, 2:-2]+ self.assert_close(actual, expected[..., None, None].expand_as(actual))+def test_noncontiguous(self, device, dtype):batch_size = 3inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)@@ -434,6 +451,16 @@ class TestSpatialGradient3d(BaseTester):edges = spatial_gradient3d(inp)self.assert_close(edges, expected)+ def test_second_order_quadratics(self, device, dtype):+ coords = torch.arange(5, device=device, dtype=dtype)+ z, y, x = torch.meshgrid(coords, coords, coords, indexing="ij")+ # one volume per quadratic surface, in the order of the output channels (dxx, dyy, dzz, dxy, dyz, dxz)+ inp = torch.stack([x * x, y * y, z * z, x * y, y * z, x * z])[:, None]+ expected = torch.diag(torch.tensor([2.0, 2.0, 2.0, 4.0, 4.0, 4.0], device=device, dtype=dtype))++ actual = spatial_gradient3d(inp, "diff", order=2)[:, 0, :, 1:-1, 1:-1, 1:-1]+ self.assert_close(actual, expected[..., None, None, None].expand_as(actual))+def test_gradcheck(self, device):img = torch.rand(1, 1, 1, 3, 4, device=device, dtype=torch.float64)fast_mode = "cpu" in str(device) # disable fast mode on gpu