π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Enhancement] Local feature fixes and nms improvements (#545)
Dmytro Mishkin2592ef552035
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex 53a5a4771..582f9383b 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -222,11 +222,24 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:raise TypeError("ellipse shape should be must be [BxNx5]. ""Got {}".format(ells.size()))-- ell_shape = torch.cat([torch.cat([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),- torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)- out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2)- out = torch.cat([out, ells[..., :2].view(B, N, 2, 1)], dim=3)+ # Previous implementation was incorrectly using Cholesky decomp as matrix sqrt+ # ell_shape = torch.cat([torch.cat([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),+ # torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)+ # out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2)++ # We will calculate 2x2 matrix square root via special case formula+ # https://en.wikipedia.org/wiki/Square_root_of_a_matrix+ # "The Cholesky factorization provides another particular example of square root+ # which should not be confused with the unique non-negative square root."+ # https://en.wikipedia.org/wiki/Square_root_of_a_2_by_2_matrix+ # M = (A 0; C D)+ # R = (sqrt(A) 0; C / (sqrt(A)+sqrt(D)) sqrt(D))+ a11 = ells[..., 2:3].abs().sqrt()+ a12 = torch.zeros_like(a11)+ a22 = ells[..., 4:5].abs().sqrt()+ a21 = ells[..., 3:4] / (a11 + a22).clamp(1e-9)+ A = torch.stack([a11, a12, a21, a22], dim=-1).view(B, N, 2, 2).inverse()+ out = torch.cat([A, ells[..., :2].view(B, N, 2, 1)], dim=3)return out@@ -311,10 +324,12 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:"""raise_error_if_laf_is_not_valid(LAF)n, ch, h, w = images.size()- min_size: float = 1. * min(h, w)+ wf = float(w)+ hf = float(h)+ min_size = min(hf, wf)coef = torch.ones(1, 1, 2, 3).to(LAF.dtype).to(LAF.device) * min_size- coef[0, 0, 0, 2] = float(w)- coef[0, 0, 1, 2] = float(h)+ coef[0, 0, 0, 2] = wf+ coef[0, 0, 1, 2] = hfreturn coef.expand_as(LAF) * LAF@@ -341,10 +356,12 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:"""raise_error_if_laf_is_not_valid(LAF)n, ch, h, w = images.size()- min_size: float = 1. * min(h, w)+ wf: float = float(w)+ hf: float = float(h)+ min_size = min(hf, wf)coef = torch.ones(1, 1, 2, 3).to(LAF.dtype).to(LAF.device) / min_size- coef[0, 0, 0, 2] = 1.0 / w- coef[0, 0, 1, 2] = 1.0 / h+ coef[0, 0, 0, 2] = 1.0 / wf+ coef[0, 0, 1, 2] = 1.0 / hfreturn coef.expand_as(LAF) * LAFdiff --git a/kornia/feature/nms.py b/kornia/feature/nms.pyindex 9acd0b522..77f6aa05b 100644--- a/kornia/feature/nms.py+++ b/kornia/feature/nms.py@@ -2,6 +2,25 @@ from typing import Tuple, Unionimport torchimport torch.nn as nn+import torch.nn.functional as F+++def _get_nms_kernel2d(kx: int, ky: int) -> torch.Tensor:+ """Utility function, which returns neigh2channels conv kernel"""+ numel: int = ky * kx+ center: int = numel // 2+ weight = torch.eye(numel)+ weight[center, center] = 0+ return weight.view(numel, 1, ky, kx)+++def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> torch.Tensor:+ """Utility function, which returns neigh2channels conv kernel"""+ numel: int = kd * ky * kx+ center: int = numel // 2+ weight = torch.eye(numel)+ weight[center, center] = 0+ return weight.view(numel, 1, kd, ky, kx)class NonMaximaSuppression2d(nn.Module):@@ -13,8 +32,7 @@ class NonMaximaSuppression2d(nn.Module):self.kernel_size: Tuple[int, int] = kernel_sizeself.padding: Tuple[int,int] = self._compute_zero_padding2d(kernel_size)- self.max_pool2d = nn.MaxPool2d(kernel_size, stride=1,- padding=self.padding)+ self.kernel = _get_nms_kernel2d(*kernel_size)@staticmethoddef _compute_zero_padding2d(@@ -30,10 +48,16 @@ class NonMaximaSuppression2d(nn.Module):def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignoreassert len(x.shape) == 4, x.shape+ B, CH, H, W = x.size()# find local maximum values+ max_non_center = F.conv2d(x, self.kernel.repeat(CH, 1, 1, 1).to(x.device, x.dtype),+ stride=1,+ padding=self.padding,+ groups=CH).view(B, CH, -1, H, W).max(dim=2)[0]+ mask = x > max_non_centerif mask_only:- return x == self.max_pool2d(x)- return x * (x == self.max_pool2d(x)).to(x.dtype)+ return mask+ return x * (mask.to(x.dtype))class NonMaximaSuppression3d(nn.Module):@@ -46,8 +70,7 @@ class NonMaximaSuppression3d(nn.Module):self.padding: Tuple[int,int,int] = self._compute_zero_padding3d(kernel_size)- self.max_pool3d = nn.MaxPool3d(kernel_size, stride=1,- padding=self.padding)+ self.kernel = _get_nms_kernel3d(*kernel_size)@staticmethoddef _compute_zero_padding3d(@@ -64,9 +87,16 @@ class NonMaximaSuppression3d(nn.Module):def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignoreassert len(x.shape) == 5, x.shape# find local maximum values+ B, CH, D, H, W = x.size()+ max_non_center = F.conv3d(x, self.kernel.repeat(CH, 1, 1, 1, 1).to(x.device, x.dtype),+ stride=1,+ padding=self.padding,+ groups=CH).view(B, CH, -1, D, H, W).max(dim=2, keepdim=False)[0]+ mask = x > max_non_centerif mask_only:- return x == self.max_pool3d(x)- return x * (x == self.max_pool3d(x)).to(x.dtype)+ return mask+ return x * (mask.to(x.dtype))+# functiona apidiff --git a/test/feature/test_nms.py b/test/feature/test_nms.pyindex 6e0bfb566..2bf2b1a9d 100644--- a/test/feature/test_nms.py+++ b/test/feature/test_nms.py@@ -24,15 +24,15 @@ class TestNMS2d:inp = torch.tensor([[[[0., 0., 0., 0., 0., 0., 0.],[0., 0.1, 1., 0., 1., 1., 0.],- [0., 0.7, 1.1, 0., 1., 1., 0.],+ [0., 0.7, 1.1, 0., 1., 2., 0.],[0., 0.8, 1., 0., 1., 1., 0.],]]], device=device).float()expected = torch.tensor([[[[0., 0., 0., 0., 0., 0., 0.],- [0., 0, 0, 0., 1, 1., 0.],- [0., 0, 1.1, 0., 1., 1., 0.],- [0., 0, 0, 0., 1., 1., 0.],+ [0., 0, 0, 0., 0, 0., 0.],+ [0., 0, 1.1, 0., 0., 2., 0.],+ [0., 0, 0, 0., 0., 0., 0.],]]], device=device).float()nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)scores = nms(inp)