π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
added docstrings
Dmytro Mishkin2a8e0fb64415
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex f4798a286..1efacaa53 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -6,23 +6,39 @@ import mathfrom kornia.filters import get_gaussian_kernel2dfrom kornia.filters import SpatialGradientfrom kornia.feature.laf import (ellipse_to_laf,- make_upright,get_laf_scale,raise_error_if_laf_is_not_valid,- scale_laf)+ scale_laf, make_upright)from kornia.feature import extract_patches_from_pyramidclass PatchAffineShapeEstimator(nn.Module):- def __init__(self, patch_size: int = 19):+ def __init__(self, patch_size: int = 19, eps: float = 1e-10):+ """Module, which estimates the second moment matrix of the patch gradients in order to determine the+ affine shape of the local feature as in+ A. Baumberg (2000). "Reliable feature matching across widely separated views".+ In Proc.of CVPR. pp. I:1774--1781.+ Args:+ patch_size: int, default = 19+ eps: float, for safe division, default is 1e-10"""super(PatchAffineShapeEstimator, self).__init__()self.patch_size: int = patch_sizeself.gradient: nn.Module = SpatialGradient('sobel', 1)+ self.eps: float = epssigma: float = float(self.patch_size) / math.sqrt(2.0)self.weighting: torch.Tensor = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True)return+ def __repr__(self):+ return self.__class__.__name__ + '('\+ 'patch_size=' + str(self.patch_size) + ', ' + \+ 'eps=' + str(self.eps) + ')'+def forward(self, patch: torch.Tensor) -> torch.Tensor: # type: ignore+ """Args:+ patch: 4d tensor, shape [Bx1xHxW]+ Returns:+ ellipse_shape: 3d tensor, shape [Bx1x5] """if not torch.is_tensor(patch):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patch)))@@ -39,21 +55,45 @@ class PatchAffineShapeEstimator(nn.Module):# unpack the edgesgx: torch.Tensor = grads[:, :, 0]gy: torch.Tensor = grads[:, :, 1]+ # abc == 1st axis, mixture, 2nd axis. Ellipse_shape is a 2nd moment matrix.ellipse_shape = torch.cat([gx.pow(2).mean(dim=2).mean(dim=2, keepdim=True),(gx * gy).mean(dim=2).mean(dim=2, keepdim=True),gy.pow(2).mean(dim=2).mean(dim=2, keepdim=True)], dim=2)++ # Now lets detect degenerate cases: when 2 or 3 elements are close to zero (e.g. if patch is completely black+ bad_mask = ((ellipse_shape < self.eps).float().sum(dim=2, keepdim=True) >= 2).to(ellipse_shape.dtype)+ # We will replace degenerate shape with circular shapes.+ circular_shape = torch.tensor([1.0, 0., 1.0]).to(ellipse_shape.device).to(ellipse_shape.dtype).view(1, 1, 3)+ ellipse_shape = ellipse_shape * (1.0 - bad_mask) + circular_shape * bad_mask # type: ignore+ # normalization+ ellipse_shape = ellipse_shape / ellipse_shape.max(dim=2, keepdim=True)[0]return ellipse_shapeclass LAFAffineShapeEstimator(nn.Module):+ """Module, which extracts patches using input images and local affine frames (LAFs),+ then runs PatchAffineShapeEstimator on patches to estimate LAFs shape.+ Then original LAF shape is replaced with estimated one. The original LAF orientation is not preserved,+ so it is recommended to first run LAFAffineShapeEstimator and then LAFOrienter+ Args:+ patch_size: int, default = 32"""def __init__(self,- patch_size: int = 32):+ patch_size: int = 32) -> None:super(LAFAffineShapeEstimator, self).__init__()self.patch_size = patch_sizeself.affine_shape_detector = PatchAffineShapeEstimator(self.patch_size)return+ def __repr__(self):+ return self.__class__.__name__ + '('\+ 'patch_size=' + str(self.patch_size) + ')'+def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: # type: ignore+ """Args:+ laf: 4d tensor, shape [BxNx2x3]+ img: 4d tensor, shape [Bx1xHxW]+ Returns:+ laf_out: 4d tensor, shape [BxNx2x3] """raise_error_if_laf_is_not_valid(laf)img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)if not torch.is_tensor(img):@@ -65,10 +105,10 @@ class LAFAffineShapeEstimator(nn.Module):raise ValueError("Batch size of laf and img should be the same. Got {}, {}".format(img.size(0), laf.size(0)))B, N = laf.shape[:2]- patches: torch.Tensor = extract_patches_from_pyramid(img, laf, PS=self.patch_size).view(-1,- 1,- self.patch_size,- self.patch_size)+ PS: int = self.patch_size+ patches: torch.Tensor = extract_patches_from_pyramid(img,+ make_upright(laf),+ PS, True).view(-1, 1, PS, PS)ellipse_shape: torch.Tensor = self.affine_shape_detector(patches)ellipses = torch.cat([laf.view(-1, 2, 3)[..., 2].unsqueeze(1), ellipse_shape], dim=2).view(B, N, 5)scale_orig = get_laf_scale(laf)diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex 9af6dedc4..9c94f0508 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -27,6 +27,12 @@ class PassLAF(nn.Module):class PatchDominantGradientOrientation(nn.Module):+ """Module, which estimates the dominant gradient orientation of the given patches, in radians.+ Zero angle points towards right.+ Args:+ patch_size: int, default = 32+ num_angular_bins: int, default is 36+ eps: float, for safe division, and arctan, default is 1e-8"""def __init__(self,patch_size: int = 32,num_angular_bins: int = 36, eps: float = 1e-8):@@ -35,14 +41,24 @@ class PatchDominantGradientOrientation(nn.Module):self.num_ang_bins = num_angular_binsself.gradient = SpatialGradient('sobel', 1)self.eps = eps- self.angular_smooth = nn.Conv1d(1, 1, kernel_size=3, padding=1, bias=False)+ self.angular_smooth = nn.Conv1d(1, 1, kernel_size=3, padding=2, bias=False, padding_mode="circular")with torch.no_grad():self.angular_smooth.weight[:] = torch.tensor([[[0.33, 0.34, 0.33]]])sigma: float = float(self.patch_size) / math.sqrt(2.0)self.weighting = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True)return+ def __repr__(self):+ return self.__class__.__name__ + '('\+ 'patch_size=' + str(self.patch_size) + ', ' + \+ 'num_ang_bins=' + str(self.num_ang_bins) + ', ' + \+ 'eps=' + str(self.eps) + ')'+def forward(self, patch: torch.Tensor) -> torch.Tensor: # type: ignore+ """Args:+ patch: 4d tensor, shape [Bx1xHxW]+ Returns:+ patch: 4d tensor, shape [Bx1] """if not torch.is_tensor(patch):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patch)))@@ -83,16 +99,31 @@ class PatchDominantGradientOrientation(nn.Module):class LAFOrienter(nn.Module):+ """Module, which extracts patches using input images and local affine frames (LAFs),+ then runs PatchDominantGradientOrientation on patches and then rotates the LAFs by the estimated angles+ Args:+ patch_size: int, default = 32+ num_angular_bins: int, default is 36"""def __init__(self,- num_angular_bins: int = 36,- patch_size: int = 32):+ patch_size: int = 32,+ num_angular_bins: int = 36):super(LAFOrienter, self).__init__()self.patch_size = patch_sizeself.num_ang_bins = num_angular_binsself.angle_detector = PatchDominantGradientOrientation(self.patch_size, self.num_ang_bins)return+ def __repr__(self):+ return self.__class__.__name__ + '('\+ 'patch_size=' + str(self.patch_size) + ', ' + \+ 'num_ang_bins=' + str(self.num_ang_bins) + ')'+def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: # type: ignore+ """Args:+ laf: 4d tensor, shape [BxNx2x3]+ img: 4d tensor, shape [Bx1xHxW]+ Returns:+ laf_out: 4d tensor, shape [BxNx2x3] """raise_error_if_laf_is_not_valid(laf)img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)if not torch.is_tensor(img):diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex dce25da98..a73cc2104 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -23,7 +23,6 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor) -> torReturns:torch.Tensor: tensor [BxNx3].-"""# depth (scale) in coord_max is represented as (float) index, not the scale yet.# we will interpolate the scale using pytorch.grid_sample function@@ -53,13 +52,36 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor) -> torclass ScaleSpaceDetector(nn.Module):+ """Module for differentiable local feature detection, as close as possible to classical+ local feature detectors like Harris, Hessian-Affine or SIFT (DoG).+ It has 5 modules inside: scale pyramid generator, responce ("cornerness") function,+ soft nms function, affine shape estimator and patch orientation estimator.+ Each of those modules could be replaced with learned custom one, as long, as+ they respect output shape.++ Args:+ num_features: int, default = 500. Number of features to detect. In order to keep everything batchable,+ output would always have num_features outputed, even for completely homogeneous images.++ mr_size: float, default 6.0. Multiplier for local feature scale compared to the detection scale. 6.0 is+ matching OpenCV 12.0 convention for SIFT.+ scale_pyr_module: nn.Module, which generates scale pyramid. See :class:`~kornia.geometry.ScalePyramid`+ for details. Default is ScalePyramid(3, 1.6, 10)+ resp_module: nn.Module, which calculates 'cornerness' of the pixel. Default is BlobHessian(),+ nms_module: nn.Module, which outputs per-patch coordinates of the responce maxima.+ See :class:`~kornia.geometry.ConvSoftArgmax3d` for details.+ ori_module: nn.Module for local feature orientation estimation.+ See :class:`~kornia.feature.LAFOrienter` for details. Default is PassLAF, which does nothing+ aff_module: nn.Module for local feature affine shape estimation.+ See :class:`~kornia.feature.LAFAffineShapeEstimator` for details. Default is PassLAF, which does nothing+ """def __init__(self,num_features: int = 500,- mr_size: float = 5.192,+ mr_size: float = 6.0,scale_pyr_module: nn.Module = ScalePyramid(3, 1.6, 10),resp_module: nn.Module = BlobHessian(),nms_module: nn.Module = ConvSoftArgmax3d((3, 3, 3),- (2, 2, 2),+ (1, 1, 1),(1, 1, 1),normalized_coordinates=False,output_value=True),@@ -135,6 +157,14 @@ class ScaleSpaceDetector(nn.Module):return responses, denormalize_laf(lafs, img)def forward(self, img: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore+ """+ Three stage local feature detection. First the location and scale of interest points are determined by+ detect function. Then affine shape and orientation.+ Args:+ img: 4d tensor, shape [BxCxHxW]+ Returns:+ lafs: 4d tensor, shape [BxNx2x3]. Detected local affine frames.+ responses: 3d tensor, shape [BxNx1]. Response function values for corresponding lafs """responses, lafs = self.detect(img, self.num_features)lafs = self.aff(lafs, img)lafs = self.ori(lafs, img)diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.pyindex a2de7816d..aac46e050 100644--- a/test/feature/test_affine_shape_estimator.py+++ b/test/feature/test_affine_shape_estimator.py@@ -29,7 +29,7 @@ class TestPatchAffineShapeEstimator:inp = torch.zeros(1, 1, 19, 19)inp[:, :, 5:-5, 1:-1] = 1abc = aff(inp)- expected = torch.tensor([[[0.0229, 0.0000, 0.0450]]])+ expected = torch.tensor([[[0.4146, 0.0000, 1.0000]]])assert_allclose(abc, expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self):@@ -66,16 +66,14 @@ class TestLAFAffineShapeEstimator:inp[:, :, 15:-15, 9:-9] = 1laf = torch.tensor([[[[20., 0., 16.], [0., 20., 16.]]]])new_laf = aff(laf, inp)- expected = torch.tensor([[[[36.246, 0., 16.], [0., 11.036, 16.]]]])+ expected = torch.tensor([[[[36.643, 0., 16.], [0., 10.916, 16.]]]])assert_allclose(new_laf, expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self):- batch_size, channels, height, width = 1, 1, 21, 21- patches = torch.rand(batch_size, channels, height, width).float()+ batch_size, channels, height, width = 1, 1, 100, 100+ patches = torch.rand(batch_size, channels, height, width)patches = utils.tensor_to_gradcheck_var(patches) # to var- laf = 0.5 * torch.ones(batch_size, 2, 2, 3).float()- laf[:, :, 0, 1] = 0- laf[:, :, 1, 0] = 0+ laf = torch.tensor([[[[20., 0., 56.], [0., 20., 56.]]]])laf = utils.tensor_to_gradcheck_var(laf) # to var- assert gradcheck(LAFAffineShapeEstimator(12), (laf, patches),+ assert gradcheck(LAFAffineShapeEstimator(11), (laf, patches),raise_exception=True, rtol=1e-3, atol=1e-3)