π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): scale normalized second order kernels to derivative estimates (#4767)
εΊζ’ηba1c45c02d2a
diff --git a/changelog.d/4767.breaking.md b/changelog.d/4767.breaking.mdnew file mode 100644index 000000000..1ae15c450--- /dev/null+++ b/changelog.d/4767.breaking.md@@ -0,0 +1,20 @@+`spatial_gradient(..., order=2, normalized=True)` and `SpatialGradient(order=2)` now scale every second order+kernel by its response to the quadratic it estimates, so `dxx`, `dxy` and `dyy` come out in the same units: on+`x**2 / 2`, `x * y` and `y**2 / 2` each channel returns 1 in both modes. Previously each kernel was divided by its+own absolute sum, which gave the mixed channel a scale of its own: `mode="sobel"` returned `dxy` too large by+`64 / 36`, `mode="diff"` returned `dxx` and `dyy` too small by 4. `order=1` and `normalized=False` are unchanged.++`hessian_response` and `BlobHessian` use the normalized default, so their values change: the determinant is now+`fxx * fyy - fxy**2` instead of `fxx * fyy - (64 / 36)**2 * fxy**2` (sobel) or `fxx * fyy / 16 - fxy**2` (diff).+At the centre of a 9x9 grid:++| surface (true determinant) | sobel before | sobel after | diff before | diff after |+|---|---|---|---|---|+| `x**2 + y**2` (4) | 4.0 | 4.0 | 0.25 | 4.0 |+| `x * y` (-1) | -3.1605 | -1.0 | -1.0 | -1.0 |+| `(x + y)**2 / 2` (0) | -2.1605 | 0.0 | -0.9375 | 0.0 |++With the default `grads_mode="sobel"` responses without a mixed term keep their value and the `fxy**2` term+shrinks; with `grads_mode="diff"` the `fxx * fyy` term grows 16 times. The detections of `ScaleSpaceDetector`+(whose default response is `BlobHessian`), `HesAffNetHardNet`, and `MultiResolutionDetector` with `BlobHessian`+can therefore change. Refs #4710.diff --git a/kornia/feature/responses.py b/kornia/feature/responses.pyindex f1c5ad672..e9f33328b 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -248,13 +248,13 @@ def hessian_response(... ]]]) # 1x1x7x7>>> # compute the response map; rounded for a platform-stable display>>> hessian_response(input).round(decimals=4) + 0.0- tensor([[[[-0.0564, -0.0759, -0.0253, 0.0000, -0.0253, -0.0759, -0.0564],- [-0.0759, -0.0330, 0.0333, 0.0000, 0.0333, -0.0330, -0.0759],- [-0.0253, 0.0333, 0.0542, 0.0000, 0.0542, 0.0333, -0.0253],+ tensor([[[[-0.0137, -0.0332, -0.0205, 0.0000, -0.0205, -0.0332, -0.0137],+ [-0.0332, 0.0098, 0.0381, 0.0000, 0.0381, 0.0098, -0.0332],+ [-0.0205, 0.0381, 0.0547, 0.0000, 0.0547, 0.0381, -0.0205],[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [-0.0253, 0.0333, 0.0542, 0.0000, 0.0542, 0.0333, -0.0253],- [-0.0759, -0.0330, 0.0333, 0.0000, 0.0333, -0.0330, -0.0759],- [-0.0564, -0.0759, -0.0253, 0.0000, -0.0253, -0.0759, -0.0564]]]])+ [-0.0205, 0.0381, 0.0547, 0.0000, 0.0547, 0.0381, -0.0205],+ [-0.0332, 0.0098, 0.0381, 0.0000, 0.0381, 0.0098, -0.0332],+ [-0.0137, -0.0332, -0.0205, 0.0000, -0.0205, -0.0332, -0.0137]]]])"""KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 1d98423e7..990ef00ac 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -74,6 +74,27 @@ def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:return input / (norm[..., None, None])+def _normalize_kernel2d_2nd_order(input: torch.Tensor) -> torch.Tensor:+ r"""Scale a stack of second order derivative kernels ``(dxx, dxy, dyy)`` to derivative estimates.++ Each kernel is divided by the magnitude of its response to the quadratic whose second derivative it+ estimates, ``x**2 / 2`` for ``dxx``, ``x * y`` for ``dxy`` and ``y**2 / 2`` for ``dyy``, so the three+ channels come out in the same units. Dividing every kernel by its own absolute sum instead, as+ :func:`normalize_kernel2d` does, scales the mixed kernel differently from the pure ones.+ """+ KORNIA_CHECK_SHAPE(input, ["3", "H", "W"])++ h, w = input.shape[-2:]+ y = torch.arange(h, device=input.device, dtype=torch.float32) - (h - 1) / 2+ x = torch.arange(w, device=input.device, dtype=torch.float32) - (w - 1) / 2+ y, x = torch.meshgrid(y, x, indexing="ij")+ quadratics = torch.stack([x * x / 2, x * y, y * y / 2])++ norm = (input * quadratics).sum(dim=(-2, -1)).abs().to(input.dtype)++ return input / norm[:, None, None]++def gaussian(window_size: int,sigma: torch.Tensor | float,diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex 793c0f5a6..c3e794512 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -25,7 +25,12 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE-from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d+from .kernels import (+ _normalize_kernel2d_2nd_order,+ get_spatial_gradient_kernel2d,+ get_spatial_gradient_kernel3d,+ normalize_kernel2d,+)def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, normalized: bool = True) -> torch.Tensor:@@ -37,7 +42,9 @@ def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, ninput: input image torch.Tensor with shape :math:`(B, C, H, W)`.mode: derivatives modality, can be: `sobel` or `diff`.order: the order of the derivatives.- normalized: whether the output is normalized.+ normalized: if ``True``, scale the kernels so that every output channel estimates the derivative+ itself, exact on linear surfaces for ``order=1`` and on quadratic surfaces for ``order=2``. If+ ``False``, return the raw kernel responses.Return:the derivatives of the input feature map. with shape :math:`(B, C, 2, H, W)` holding@@ -83,7 +90,7 @@ def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, nelse:kernel = get_spatial_gradient_kernel2d(mode, order, device=input.device, dtype=input.dtype)if normalized:- kernel = normalize_kernel2d(kernel)+ kernel = normalize_kernel2d(kernel) if order == 1 else _normalize_kernel2d_2nd_order(kernel)# prepare kernelb, c, h, w = input.shapediff --git a/tests/feature/test_responces_local_features.py b/tests/feature/test_responces_local_features.pyindex f0e87db82..ceb9acfb7 100644--- a/tests/feature/test_responces_local_features.py+++ b/tests/feature/test_responces_local_features.py@@ -303,22 +303,22 @@ class TestBlobHessian(BaseTester):expected = torch.tensor([[- [-0.0564, -0.0759, -0.0342, -0.0759, -0.0564, -0.0057, 0.0000],- [-0.0759, -0.0330, 0.0752, -0.0330, -0.0759, -0.0096, 0.0000],+ [-0.0137, -0.0332, -0.0342, -0.0332, -0.0137, -0.0010, 0.0000],+ [-0.0332, 0.0098, 0.0752, 0.0098, -0.0332, -0.0049, 0.0000],[-0.0342, 0.0752, 0.1914, 0.0752, -0.0342, -0.0068, 0.0000],- [-0.0759, -0.0330, 0.0752, -0.0330, -0.0759, -0.0096, 0.0000],- [-0.0564, -0.0759, -0.0342, -0.0759, -0.0564, -0.0057, 0.0000],- [-0.0057, -0.0096, -0.0068, -0.0096, -0.0057, -0.0005, 0.0000],+ [-0.0332, 0.0098, 0.0752, 0.0098, -0.0332, -0.0049, 0.0000],+ [-0.0137, -0.0332, -0.0342, -0.0332, -0.0137, -0.0010, 0.0000],+ [-0.0010, -0.0049, -0.0068, -0.0049, -0.0010, 0.0000, 0.0000],[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],],[- [-0.0564, -0.0522, -0.0522, -0.0564, -0.0057, 0.0000, 0.0000],- [-0.0522, 0.0688, 0.0688, -0.0123, 0.0033, -0.0057, -0.0005],- [-0.0522, 0.0688, -0.0755, -0.1111, -0.0123, -0.0564, -0.0057],- [-0.0564, -0.0123, -0.1111, -0.0755, 0.0688, -0.0522, -0.0080],- [-0.0057, 0.0033, -0.0123, 0.0688, 0.0688, -0.0522, -0.0080],- [0.0000, -0.0057, -0.0564, -0.0522, -0.0522, -0.0564, -0.0057],- [0.0000, -0.0005, -0.0057, -0.0080, -0.0080, -0.0057, -0.0005],+ [-0.0137, -0.0332, -0.0332, -0.0137, -0.0010, 0.0000, 0.0000],+ [-0.0332, 0.0820, 0.0693, -0.0039, 0.0117, -0.0010, 0.0000],+ [-0.0332, 0.0693, 0.0137, -0.0352, -0.0039, -0.0137, -0.0010],+ [-0.0137, -0.0039, -0.0352, 0.0137, 0.0693, -0.0332, -0.0059],+ [-0.0010, 0.0117, -0.0039, 0.0693, 0.0820, -0.0332, -0.0059],+ [0.0000, -0.0010, -0.0137, -0.0332, -0.0332, -0.0137, -0.0010],+ [0.0000, 0.0000, -0.0010, -0.0059, -0.0059, -0.0010, 0.0000],],],device=device,diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex 9667a01e8..8af677706 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -256,8 +256,16 @@ class TestScaleSpaceDetector(BaseTester):if dtype in (torch.float16, torch.bfloat16):# The shifted response is flat at half precision and yields no maxima at all.pytest.skip("a Hessian response offset by 1.0 has no resolution left in half precision")- torch.manual_seed(0)- inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ # Gaussian blobs of increasing size give the Hessian one scale-space maximum per blob. Random noise+ # left one or two maxima whose survival depended on the exact response scale and on the dtype.+ # Built in float64 on the CPU so every device sees the same input: MPS has no float64.+ coords = torch.arange(96, dtype=torch.float64)+ yy, xx = torch.meshgrid(coords, coords, indexing="ij")+ inp = torch.zeros(96, 96, dtype=torch.float64)+ for i, sigma in enumerate((1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 5.0, 6.0, 7.0)):+ cy, cx = 16 + 32 * (i // 3), 16 + 32 * (i % 3)+ inp += torch.exp(-((yy - cy) ** 2 + (xx - cx) ** 2) / (2 * sigma**2))+ inp = inp[None, None].to(device=device, dtype=dtype)det = ScaleSpaceDetector(50, resp_module=NegatedHessian()).to(device, dtype)lafs, resps = det(inp)filled = lafs[0].ne(0).any(dim=-1).any(dim=-1)diff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.pyindex 2df8123f9..8f3e5fa1f 100644--- a/tests/filters/test_sobel.py+++ b/tests/filters/test_sobel.py@@ -281,6 +281,27 @@ class TestSpatialGradient(BaseTester):assert actual.is_contiguous()assert actual.shape == (3, 3, 2, 5, 5)+ @pytest.mark.parametrize("mode", ["sobel", "diff"])+ def test_second_order_normalized_quadratics(self, mode, device, dtype):+ # With normalized=True every second order channel estimates the derivative itself, so on a quadratic+ # surface the channels are the exact second derivatives and dxx * dyy - dxy**2 is the exact determinant+ # of the Hessian. Before, dxy had a scale of its own.+ coords = torch.arange(9, device=device, dtype=dtype)+ y, x = torch.meshgrid(coords, coords, indexing="ij")+ surfaces = torch.stack([x * x, x * y, y * y, x * x + y * y, (x + y) ** 2 / 2])[:, None]+ out = spatial_gradient(surfaces, mode, order=2, normalized=True)[..., 3:-3, 3:-3]++ expected = torch.tensor(+ [[2.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 2.0], [2.0, 0.0, 2.0], [1.0, 1.0, 1.0]],+ device=device,+ dtype=dtype,+ )+ self.assert_close(out, expected[:, None, :, None, None].expand_as(out))++ det = out[:, :, 0] * out[:, :, 2] - out[:, :, 1] ** 2+ expected_det = torch.tensor([0.0, -1.0, 0.0, 4.0, 0.0], device=device, dtype=dtype)+ self.assert_close(det, expected_det[:, None, None, None].expand_as(det))+def test_gradcheck(self, device):batch_size, channels, height, width = 1, 1, 3, 4img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)