π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fixe DoG accuracy, add `upscale_double` (#2105)
Vaclav Vavra2c04cd55728f
diff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rstindex 901d1f7d0..f3e98045b 100644--- a/docs/source/geometry.transform.rst+++ b/docs/source/geometry.transform.rst@@ -35,6 +35,7 @@ Image 2d transforms.. autofunction:: pyrup.. autofunction:: build_pyramid.. autofunction:: build_laplacian_pyramid+.. autofunction:: upscale_doubleMatrix transformations----------------------diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex 9f550b95a..9e9dc0f86 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -7,7 +7,7 @@ from kornia.core import Device, Module, Tensor, concatenate, eyefrom kornia.geometry.subpix import ConvSoftArgmax3dfrom kornia.geometry.transform import ScalePyramid-from .laf import denormalize_laf, laf_is_inside_image, normalize_laf+from .laf import laf_is_inside_imagefrom .orientation import PassLAFfrom .responses import BlobHessian@@ -132,6 +132,7 @@ class ScaleSpaceDetector(Module):sp, sigmas, _ = self.scale_pyr(img)all_responses: List[Tensor] = []all_lafs: List[Tensor] = []+ px_size = 0.5 if self.scale_pyr.double_image else 1.0for oct_idx, octave in enumerate(sp):sigmas_oct = sigmas[oct_idx]B, CH, L, H, W = octave.size()@@ -203,17 +204,18 @@ class ScaleSpaceDetector(Module):resp_flat_best = resp_flat_best * good_mask.to(dev, dtype)# Normalize LAFs- current_lafs = normalize_laf(current_lafs, octave[:, 0]) # We don`t need # of scale levels, only shape+ current_lafs *= px_sizeall_responses.append(resp_flat_best)all_lafs.append(current_lafs)+ px_size *= 2# Sort and keep best nresponses = concatenate(all_responses, 1)lafs = concatenate(all_lafs, 1)responses, idxs = torch.topk(responses, k=num_feats, dim=1)lafs = torch.gather(lafs, 1, idxs.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 2, 3))- return responses, denormalize_laf(lafs, img)+ return responses, lafsdef forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:"""Three stage local feature detection. First the location and scale of interest points are determined bydiff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex 8650ec787..2ab7eb969 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -3,7 +3,7 @@ from typing import Tuple, Unionimport torchimport torch.nn.functional as F-from kornia.core import Module, Tensor, concatenate, stack, tensor, zeros+from kornia.core import Module, Tensor, concatenate, stack, tensor, where, zerosfrom kornia.filters.sobel import spatial_gradient3dfrom kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3dfrom kornia.utils import create_meshgrid, create_meshgrid3d@@ -620,7 +620,8 @@ def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: fl# Kill those points, where we cannot solvenew_nms_mask = nms_mask.masked_scatter(nms_mask, solved_correctly)- x_solved.masked_scatter_(new_nms_mask.view(-1, 1, 1), x_solved_masked[solved_correctly])+ x_solved[where(new_nms_mask.view(-1, 1, 1))[0]] = x_solved_masked[solved_correctly]+dx: Tensor = -x_solved# Ignore ones, which are far from window center@@ -632,6 +633,8 @@ def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: fly_max += strict_maxima_bonus * new_nms_mask.to(input.dtype)dx_res: Tensor = dx.flip(1).reshape(B, CH, D, H, W, 3).permute(0, 1, 5, 2, 3, 4)+ dx_res[:, :, (1, 2)] = dx_res[:, :, (2, 1)]+coords_max: Tensor = grid_global.repeat(B, 1, 1, 1, 1).unsqueeze(1)coords_max = coords_max + dx_resdiff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.pyindex 1e41218ea..d0e3373b9 100644--- a/kornia/geometry/transform/pyramid.py+++ b/kornia/geometry/transform/pyramid.py@@ -6,9 +6,18 @@ import torch.nn.functional as Ffrom kornia.core import Module, Tensor, pad, stack, tensorfrom kornia.filters import filter2d, gaussian_blur2d-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE-__all__ = ["PyrDown", "PyrUp", "ScalePyramid", "pyrdown", "pyrup", "build_pyramid", "build_laplacian_pyramid"]+__all__ = [+ "PyrDown",+ "PyrUp",+ "ScalePyramid",+ "pyrdown",+ "pyrup",+ "build_pyramid",+ "build_laplacian_pyramid",+ "upscale_double",+]def _get_pyramid_gaussian_kernel() -> Tensor:@@ -171,7 +180,7 @@ class ScalePyramid(Module):cur_sigma = 0.5# Same as in OpenCV up to interpolation differenceif self.double_image:- x = F.interpolate(input, scale_factor=2.0, mode='bilinear', align_corners=False)+ x = upscale_double(input)pixel_distance = 0.5cur_sigma *= 2.0else:@@ -213,9 +222,8 @@ class ScalePyramid(Module):sigmas[-1][:, level_idx] = cur_sigmapixel_dists[-1][:, level_idx] = pixel_distance_pyr = pyr[-1][-self.extra_levels]- nextOctaveFirstLevel = F.interpolate(- _pyr, size=(_pyr.size(-2) // 2, _pyr.size(-1) // 2), mode='nearest'- ) # Nearest matches OpenCV SIFT+ nextOctaveFirstLevel = _pyr[:, :, ::2, ::2]+pixel_distance *= 2.0cur_sigma = self.init_sigmaif min(nextOctaveFirstLevel.size(2), nextOctaveFirstLevel.size(3)) <= self.min_size:@@ -410,3 +418,27 @@ def build_laplacian_pyramid(laplacian_pyramid.append(laplacian)laplacian_pyramid.append(gaussian_pyramid[-1])return laplacian_pyramid+++def upscale_double(x: Tensor) -> Tensor:+ r"""Upscale image by the factor of 2, even indices maps to original indices.++ Odd indices are linearly interpolated from the even ones.++ Args:+ x: input image.++ Shape:+ - Input: :math:`(*, H, W)`+ - Output :math:`(*, H, W)`+ """+ KORNIA_CHECK_IS_TENSOR(x)+ KORNIA_CHECK_SHAPE(x, ["*", "H", "W"])+ double_shape = x.shape[:-2] + (x.shape[-2] * 2, x.shape[-1] * 2)+ upscaled = torch.zeros(double_shape, device=x.device, dtype=x.dtype)+ upscaled[..., ::2, ::2] = x+ upscaled[..., ::2, 1::2][..., :-1] = (upscaled[..., ::2, ::2][..., :-1] + upscaled[..., ::2, 2::2]) / 2+ upscaled[..., ::2, -1] = upscaled[..., ::2, -2]+ upscaled[..., 1::2, :][..., :-1, :] = (upscaled[..., ::2, :][..., :-1, :] + upscaled[..., 2::2, :]) / 2+ upscaled[..., -1, :] = upscaled[..., -2, :]+ return upscaleddiff --git a/test/geometry/subpix/test_spatial_softargmax.py b/test/geometry/subpix/test_spatial_softargmax.pyindex c4f8f3c06..321486476 100644--- a/test/geometry/subpix/test_spatial_softargmax.py+++ b/test/geometry/subpix/test_spatial_softargmax.py@@ -575,7 +575,7 @@ class TestConvQuadInterp3d:[[0.0, 1.0, 2.0, 3.0, 4.0],[0.0, 1.0, 2.0, 3.0, 4.0],- [0.0, 1.0, 2.0, 3.0, 4.0],+ [0.0, 1.0, 2.0495, 3.0, 4.0],[0.0, 1.0, 2.0, 3.0, 4.0],[0.0, 1.0, 2.0, 3.0, 4.0],],@@ -598,7 +598,7 @@ class TestConvQuadInterp3d:[[0.0, 0.0, 0.0, 0.0, 0.0],[1.0, 1.0, 1.0, 1.0, 1.0],- [2.0, 2.0, 2.0495, 2.0, 2.0],+ [2.0, 2.0, 2.0, 2.0, 2.0],[3.0, 3.0, 3.0, 3.0, 3.0],[4.0, 4.0, 4.0, 4.0, 4.0],],diff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.pyindex 1d1b4ee22..25a934600 100644--- a/test/geometry/transform/test_pyramid.py+++ b/test/geometry/transform/test_pyramid.py@@ -4,7 +4,7 @@ from torch.autograd import gradcheckimport korniaimport kornia.testing as utils # test utils-from kornia.testing import assert_close+from kornia.testing import BaseTester, assert_closeclass TestPyrUp:@@ -192,3 +192,106 @@ class TestBuildLaplacianPyramid:raise_exception=True,fast_mode=True,)+++class TestUpscaleDouble(BaseTester):+ @pytest.mark.parametrize("shape", ((5, 5), (2, 5, 5), (1, 2, 5, 5)))+ def test_smoke(self, shape, device, dtype):+ x = self.prepare_data(shape, device, dtype)+ assert kornia.geometry.transform.upscale_double(x) is not None++ def test_exception(self, device, dtype):+ with pytest.raises(TypeError):+ assert kornia.geometry.transform.upscale_double(None)++ def test_cardinality(self, device, dtype):+ with pytest.raises(TypeError):+ img = torch.rand(10)+ assert kornia.geometry.transform.upscale_double(img)++ @pytest.mark.jit+ def test_jit(self, device, dtype):+ img = self.prepare_data((1, 2, 5, 5), device, dtype)+ op = kornia.geometry.transform.upscale_double+ op_jit = torch.jit.script(op)+ assert_close(op(img), op_jit(img))++ @pytest.mark.grad+ def test_gradcheck(self, device, dtype):+ x = self.prepare_data((1, 2, 5, 5), device, dtype, requires_grad=True)+ assert gradcheck(+ kornia.geometry.transform.upscale_double, (x,), rtol=5e-2, raise_exception=True, fast_mode=False+ )++ @pytest.mark.skip(reason="not implemented yet")+ def test_module(self, device, dtype):+ pass++ @pytest.mark.parametrize("shape", ((5, 5), (2, 5, 5), (1, 2, 5, 5)))+ def test_upscale_double_and_back(self, shape, device, dtype):+ x = self.prepare_data(shape, device, dtype)+ upscaled = kornia.geometry.transform.upscale_double(x)++ expected = torch.tensor(+ [+ [+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],+ [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],+ [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],+ [1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5],+ [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0],+ [2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5],+ [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0],+ [3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5],+ [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0],+ [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0],+ ],+ [+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],+ ],+ ],+ device=device,+ dtype=dtype,+ )++ if len(shape) == 2:+ expected = expected[0]+ elif len(shape) == 4:+ expected = expected[None]++ assert_close(upscaled, expected)+ assert torch.all(upscaled == expected)+ downscaled_back = upscaled[..., ::2, ::2]+ assert torch.all(x == downscaled_back)++ @staticmethod+ def prepare_data(shape, device, dtype, requires_grad=False):+ xm = torch.tensor(+ [[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]],+ device=device,+ dtype=dtype,+ )+ ym = torch.tensor(+ [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]],+ device=device,+ dtype=dtype,+ )++ x = torch.zeros(shape, device=device, dtype=dtype)+ if len(shape) == 2:+ x = xm+ else:+ x[..., 0, :, :] = xm+ x[..., 1, :, :] = ym+ if requires_grad:+ x.requires_grad_()+ return x