🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
nicify docstrings
Dmytro Mishkinb2c2e6e69624
diff --git a/docs/Makefile b/docs/Makefileindex 316e362da..b9abfd215 100644--- a/docs/Makefile+++ b/docs/Makefile@@ -3,7 +3,7 @@# You can set these variables from the command line.SPHINXOPTS =-SPHINXBUILD = sphinx-build+SPHINXBUILD = /home/old-ufo/anaconda3/envs/fastai1/bin/./sphinx-buildSPHINXPROJ = korniaSOURCEDIR = sourceBUILDDIR = builddiff --git a/docs/source/contrib.rst b/docs/source/contrib.rstindex 3deff654f..bb6624b3e 100644--- a/docs/source/contrib.rst+++ b/docs/source/contrib.rst@@ -3,11 +3,9 @@ kornia.contrib.. currentmodule:: kornia.contrib-.. autofunction:: spatial_soft_argmax2d.. autofunction:: extract_tensor_patches.. autofunction:: max_blur_pool2d-.. autoclass:: SpatialSoftArgmax2d.. autoclass:: ExtractTensorPatches.. autoclass:: MaxBlurPool2ddiff --git a/docs/source/feature.rst b/docs/source/feature.rstindex 46da1f63a..a6b43a93c 100644--- a/docs/source/feature.rst+++ b/docs/source/feature.rst@@ -3,8 +3,35 @@ kornia.feature.. currentmodule:: kornia.feature-.. autofunction:: corner_harris.. autofunction:: non_maxima_suppression2d+.. autofunction:: gftt_response+.. autofunction:: harris_response+.. autofunction:: hessian_response+.. autofunction:: extract_patches_from_pyramid+.. autofunction:: extract_patches_simple+.. autofunction:: normalize_laf+.. autofunction:: denormalize_laf+.. autofunction:: laf_to_boundary_points+.. autofunction:: ellipse_to_laf+.. autofunction:: make_upright+.. autofunction:: scale_laf+.. autofunction:: get_laf_scale+.. autofunction:: raise_error_if_laf_is_not_valid-.. autoclass:: CornerHarris.. autoclass:: NonMaximaSuppression2d+.. autoclass:: BlobHessian+.. autoclass:: CornerGFTT+.. autoclass:: CornerHarris+.. autoclass:: SIFTDescriptor+.. autoclass:: ScaleSpaceDetector+ :members: forward+.. autoclass:: PassLAF+ :members: forward+.. autoclass:: PatchAffineShapeEstimator+ :members: forward+.. autoclass:: LAFAffineShapeEstimator+ :members: forward+.. autoclass:: LAFOrienter+ :members: forward+.. autoclass:: PatchDominantGradientOrientation+ :members: forwarddiff --git a/docs/source/geometry.conversions.rst b/docs/source/geometry.conversions.rstindex 567096528..03cfabe33 100644--- a/docs/source/geometry.conversions.rst+++ b/docs/source/geometry.conversions.rst@@ -17,4 +17,7 @@ kornia.geometry.conversions.. autofunction:: angle_axis_to_rotation_matrix.. autofunction:: denormalize_pixel_coordinates.. autofunction:: normalize_pixel_coordinates+.. autofunction:: denormalize_pixel_coordinates3d+.. autofunction:: normalize_pixel_coordinates3d.. autofunction:: normalize_quaternion+diff --git a/docs/source/geometry.rst b/docs/source/geometry.rstindex 186cf2081..6406f923a 100644--- a/docs/source/geometry.rst+++ b/docs/source/geometry.rst@@ -3,6 +3,19 @@ kornia.geometry.. currentmodule:: kornia.geometry+.. autofunction:: spatial_softmax_2d+.. autofunction:: spatial_softargmax_2d+.. autofunction:: render_gaussian_2d+.. autofunction:: conv_soft_argmax2d+.. autofunction:: conv_soft_argmax3d+.. autofunction:: spatial_softmax_2d+.. autofunction:: spatial_softmax_2d++.. autoclass:: SpatialSoftArgmax2d+.. autoclass:: ConvSoftArgmax2d+.. autoclass:: ConvSoftArgmax3d++.. toctree:::maxdepth: 2@@ -12,3 +25,4 @@ kornia.geometrygeometry.linalggeometry.transformgeometry.warp+diff --git a/docs/source/references.bib b/docs/source/references.bibindex 6adc23bcd..c664af9d0 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -4,3 +4,9 @@booktitle={ICML},year={2019}}+@inproceedings{baumberg2000,+ author={A. {Baumberg}},+ booktitle={CVPR},+ title={Reliable feature matching across widely separated views},+ year={2000}+}\ No newline at end of filediff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.pyindex 0aa6a1e5b..514c09b04 100644--- a/kornia/contrib/__init__.py+++ b/kornia/contrib/__init__.py@@ -1,12 +1,9 @@-from kornia.geometry.spatial_soft_argmax import SpatialSoftArgmax2d, spatial_soft_argmax2dfrom .extract_patches import ExtractTensorPatches, extract_tensor_patchesfrom .max_blur_pool import MaxBlurPool2d, max_blur_pool2d__all__ = [- "spatial_soft_argmax2d","extract_tensor_patches","max_blur_pool2d",- "SpatialSoftArgmax2d","ExtractTensorPatches","MaxBlurPool2d",]diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex 232eb7a71..fbee8e688 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -1,4 +1,3 @@-from kornia.geometry import angle_to_rotation_matrixfrom .responses import (CornerHarris,CornerGFTT,BlobHessian,@@ -21,7 +20,6 @@ from .scale_space_detector import ScaleSpaceDetector, PassLAFfrom .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimatorfrom .orientation import LAFOrienter, PatchDominantGradientOrientation-__all__ = ["non_maxima_suppression2d","harris_response",diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 1efacaa53..dff3f96d0 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -13,14 +13,12 @@ from kornia.feature import extract_patches_from_pyramidclass PatchAffineShapeEstimator(nn.Module):+ """Module, which estimates the second moment matrix of the patch gradients in order to determine the+ affine shape of the local feature as in :cite:`baumberg2000`.+ Args:+ patch_size: int, default = 19+ eps: float, for safe division, default is 1e-10"""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)@@ -36,7 +34,7 @@ class PatchAffineShapeEstimator(nn.Module):def forward(self, patch: torch.Tensor) -> torch.Tensor: # type: ignore"""Args:- patch: 4d tensor, shape [Bx1xHxW]+ patch: (torch.Tensor) shape [Bx1xHxW]Returns:ellipse_shape: 3d tensor, shape [Bx1x5] """if not torch.is_tensor(patch):@@ -72,9 +70,10 @@ class PatchAffineShapeEstimator(nn.Module):class 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 runs :class:`~kornia.feature.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+ so it is recommended to first run LAFAffineShapeEstimator and then LAFOrienter.+Args:patch_size: int, default = 32"""def __init__(self,@@ -89,11 +88,13 @@ class LAFAffineShapeEstimator(nn.Module):'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] """+ """+ Args:+ laf: (torch.Tensor) shape [BxNx2x3]+ img: (torch.Tensor) shape [Bx1xHxW]++ Returns:+ laf_out: (torch.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/laf.py b/kornia/feature/laf.pyindex 7b4cf3f89..bde101106 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -6,10 +6,10 @@ import torch.nn.functional as Fdef raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:- """- Auxilary function, which verifies that input is a torch.tensor of [BxNx2x3] shape- Args:- laf+ """Auxilary function, which verifies that input is a torch.tensor of [BxNx2x3] shape++ Args:+ laf"""laf_message: str = "Invalid laf shape, we expect BxNx2x3. Got: {}".format(laf.shape)if not torch.is_tensor(laf):@@ -23,8 +23,8 @@ def raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:- """- Returns a scale of the LAFs+ """Returns a scale of the LAFs+Args:LAF: (torch.Tensor): tensor [BxNx2x3] or [BxNx2x2].@@ -80,6 +80,7 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torcdef make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:"""Rectifies the affine matrix, so that it becomes upright+Args:laf: (torch.Tensor): tensor of LAFs.eps (float): for safe division, (default 1e-9)@@ -90,6 +91,7 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:Shape:- Input: :math:`(B, N, 2, 3)`- Output: :math:`(B, N, 2, 3)`+Example:>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3>>> output = kornia.make_upright(input) # BxNx2x3@@ -126,6 +128,7 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:Shape:- Input: :math:`(B, N, 5)`- Output: :math:`(B, N, 2, 3)`+Example:>>> input = torch.ones(1, 10, 5) # BxNx5>>> output = kornia.ellipse_to_laf(input) # BxNx2x3@@ -152,6 +155,7 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:"""Converts LAFs to boundary points of the regions + center.Used for local features visualization, see visualize_laf function+Args:LAF: (torch.Tensor).n_pts: number of points to output@@ -179,14 +183,7 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:def get_laf_pts_to_draw(LAF: torch.Tensor,img_idx: int = 0):- """- Returns numpy array for drawing LAFs (local features).- To draw:- x, y = kornia.feature.laf.get_laf_pts_to_draw(LAF, img_idx)- plt.figure()- plt.imshow(kornia.utils.tensor_to_image(img[img_idx]))- plt.plot(x, y, 'r')- plt.show()+ """Returns numpy array for drawing LAFs (local features).Args:LAF: (torch.Tensor).@@ -198,6 +195,13 @@ def get_laf_pts_to_draw(LAF: torch.Tensor,Shape:- Input: :math:`(B, N, 2, 3)`- Output: :math:`(B, N, n_pts, 2)`++ Examples:+ >>> x, y = kornia.feature.laf.get_laf_pts_to_draw(LAF, img_idx)+ >>> plt.figure()+ >>> plt.imshow(kornia.utils.tensor_to_image(img[img_idx]))+ >>> plt.plot(x, y, 'r')+ >>> plt.show()"""raise_error_if_laf_is_not_valid(LAF)pts = laf_to_boundary_points(LAF[img_idx:img_idx + 1])[0]@@ -206,8 +210,7 @@ def get_laf_pts_to_draw(LAF: torch.Tensor,def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:- """- De-normalizes LAFs from scale to image scale.+ """De-normalizes LAFs from scale to image scale.B,N,H,W = images.size()MIN_SIZE = min(H,W)[a11 a21 x]@@ -240,8 +243,7 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:- """- Normalizes LAFs to [0,1] scale from pixel scale.+ """Normalizes LAFs to [0,1] scale from pixel scale.See below:B,N,H,W = images.size()MIN_SIZE = min(H,W)@@ -250,6 +252,7 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:becomes[a11/MIN_SIZE a21/MIN_SIZE x/W][a21/MIN_SIZE a22/MIN_SIZE y/H]+Args:LAF: (torch.Tensor).images: (torch.Tensor) images, LAFs are detected in@@ -276,8 +279,7 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:def generate_patch_grid_from_normalized_LAF(img: torch.Tensor,LAF: torch.Tensor,PS: int = 32) -> torch.Tensor:- """- Helper function for affine grid generation.+ """Helper function for affine grid generation.Args:img: (torch.Tensor) images, LAFs are detected in@@ -310,16 +312,17 @@ def extract_patches_simple(img: torch.Tensor,laf: torch.Tensor,PS: int = 32,normalize_lafs_before_extraction: bool = True) -> torch.Tensor:- """- Extract patches defined by LAFs from image tensor.+ """Extract patches defined by LAFs from image tensor.No smoothing applied, huge aliasing (better use extract_patches_from_pyramid)+Args:img: (torch.Tensor) images, LAFs are detected inlaf: (torch.Tensor).PS: (int) patch size, default = 32- normalize_lafs_before_extraction (bool) - if True, lafs are normalized to image size, default = True+ normalize_lafs_before_extraction (bool): if True, lafs are normalized to image size, default = True+Returns:- patches: (torch.Tensor), :math:`(B, N, CH, PS,PS)`+ patches: (torch.Tensor) :math:`(B, N, CH, PS,PS)`"""raise_error_if_laf_is_not_valid(laf)if normalize_lafs_before_extraction:@@ -340,16 +343,17 @@ def extract_patches_from_pyramid(img: torch.Tensor,laf: torch.Tensor,PS: int = 32,normalize_lafs_before_extraction: bool = True) -> torch.Tensor:- """- Extract patches defined by LAFs from image tensor.+ """Extract patches defined by LAFs from image tensor.Patches are extracted from appropriate pyramid level+Args:laf: (torch.Tensor).images: (torch.Tensor) images, LAFs are detected inPS: (int) patch size, default = 32- normalize_lafs_before_extraction (bool) - if True, lafs are normalized to image size, default = True+ normalize_lafs_before_extraction (bool): if True, lafs are normalized to image size, default = True+Returns:- patches: (torch.Tensor), :math:`(B, N, CH, PS,PS)`+ patches: (torch.Tensor) :math:`(B, N, CH, PS,PS)`"""raise_error_if_laf_is_not_valid(laf)if normalize_lafs_before_extraction:diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex 9c94f0508..cfaf6893f 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -13,8 +13,7 @@ from kornia.geometry import rad2degclass PassLAF(nn.Module):- """Dummy module to use instead of local feature orientation or affine shape estimator- """+ """Dummy module to use instead of local feature orientation or affine shape estimator"""def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: # type: ignore"""Args:@@ -29,6 +28,7 @@ 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 = 32num_angular_bins: int, default is 36@@ -56,9 +56,9 @@ class PatchDominantGradientOrientation(nn.Module):def forward(self, patch: torch.Tensor) -> torch.Tensor: # type: ignore"""Args:- patch: 4d tensor, shape [Bx1xHxW]+ patch: (torch.Tensor) shape [Bx1xHxW]Returns:- patch: 4d tensor, shape [Bx1] """+ patch: (torch.Tensor) shape [Bx1] """if not torch.is_tensor(patch):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patch)))@@ -100,7 +100,9 @@ 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+ then runs :class:`~kornia.feature.PatchDominantGradientOrientation`+ on patches and then rotates the LAFs by the estimated angles+Args:patch_size: int, default = 32num_angular_bins: int, default is 36"""@@ -119,11 +121,13 @@ class LAFOrienter(nn.Module):'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]+ """+ Args:+ laf: (torch.Tensor), shape [BxNx2x3]+ img: (torch.Tensor), shape [Bx1xHxW]+Returns:- laf_out: 4d tensor, shape [BxNx2x3] """+ laf_out: (torch.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/responses.py b/kornia/feature/responses.pyindex 029479087..2974e7e5b 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -1,4 +1,4 @@-from typing import Tuple, Union+from typing import Tuple, Union, Optionalimport torchimport torch.nn as nn@@ -9,11 +9,9 @@ from kornia.filters import spatial_gradient, gaussian_blur2ddef harris_response(input: torch.Tensor,k: Union[torch.Tensor, float] = 0.04,grads_mode: str = 'sobel',- sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:+ sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:r"""Computes the Harris cornerness function. Function does not do- any normalization or nms.-- The response map is computed according the following formulation:+ any normalization or nms.The response map is computed according the following formulation:.. math::R = max(0, det(M) - k \cdot trace(M)^2)@@ -34,10 +32,11 @@ def harris_response(input: torch.Tensor,input: torch.Tensor: 4d tensork (torch.Tensor): the Harris detector free parameter.grads_mode (string): can be 'sobel' for standalone use or 'diff' for use on Gaussian pyramid- sigmas (torch.Tensor or None): coefficients to be multiplied by multichannel response.- Should be shape of (B)- It is necessary for performing non-maxima-suppression across different scale pyramid levels.- See also https://github.com/vlfeat/vlfeat/blob/1b9075fc42fe54b42f0e937f8b9a230d8e2c7701/vl/covdet.c#L874+ sigmas (optional, torch.Tensor): coefficients to be multiplied by multichannel response. \n+ Should be shape of (B)+ It is necessary for performing non-maxima-suppression+ across different scale pyramid levels.\+ See `vlfeat <https://github.com/vlfeat/vlfeat/blob/master/vl/covdet.c#L874>`_Return:torch.Tensor: the response map per channel.@@ -100,10 +99,8 @@ def harris_response(input: torch.Tensor,def gftt_response(input: torch.Tensor,grads_mode: str = 'sobel',- sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:- r"""Computes the Shi-Tomasi cornerness function. Function does not do- any normalization or nms.-+ sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:+ r"""Computes the Shi-Tomasi cornerness function. Function does not do any normalization or nms.The response map is computed according the following formulation:.. math::@@ -121,10 +118,11 @@ def gftt_response(input: torch.Tensor,Args:input (torch.Tensor): 4d tensorgrads_mode (string): can be 'sobel' for standalone use or 'diff' for use on Gaussian pyramid- sigmas (torch.Tensor or None): coefficients to be multiplied by multichannel response.- Should be shape of (B)- It is necessary for performing non-maxima-suppression across different scale pyramid levels.- See also https://github.com/vlfeat/vlfeat/blob/1b9075fc42fe54b42f0e937f8b9a230d8e2c7701/vl/covdet.c#L874+ sigmas (optional, torch.Tensor): coefficients to be multiplied by multichannel response. \n+ Should be shape of (B)+ It is necessary for performing non-maxima-suppression+ across different scale pyramid levels.\+ See `vlfeat <https://github.com/vlfeat/vlfeat/blob/master/vl/covdet.c#L874>`_Return:torch.Tensor: the response map per channel.@@ -185,40 +183,39 @@ def gftt_response(input: torch.Tensor,def hessian_response(input: torch.Tensor,grads_mode: str = 'sobel',- sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:- r"""Computes the absolute of determinant of the Hessian matrix. Function does not do- any normalization or nms.-- The response map is computed according the following formulation:+ sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:+ r"""Computes the absolute of determinant of the Hessian matrix. Function does not do any normalization or nms.+ The response map is computed according the following formulation:.. math::R = det(H)+where:.. math::M = \sum_{(x,y) \in W}\begin{bmatrix}I_{xx} & I_{xy} \\- I_{xy} & I_yy \\+ I_{xy} & I_{yy} \\\end{bmatrix}-- Args:+ Args:input: torch.Tensor: 4d tensorgrads_mode (string): can be 'sobel' for standalone use or 'diff' for use on Gaussian pyramid- sigmas (torch.Tensor or None): coefficients to be multiplied by multichannel response.- Should be shape of (B)- It is necessary for performing non-maxima-suppression across different scale pyramid levels.- See also https://github.com/vlfeat/vlfeat/blob/1b9075fc42fe54b42f0e937f8b9a230d8e2c7701/vl/covdet.c#L874+ sigmas (optional, torch.Tensor): coefficients to be multiplied by multichannel response. \n+ Should be shape of (B)+ It is necessary for performing non-maxima-suppression+ across different scale pyramid levels.\+ See `vlfeat <https://github.com/vlfeat/vlfeat/blob/master/vl/covdet.c#L874>`_- Return:+ Return:torch.Tensor: the response map per channel.- Shape:+ Shape:- Input: :math:`(B, C, H, W)`- Output: :math:`(B, C, H, W)`- Examples:+ Examples:>>> input = torch.tensor([[[[0., 0., 0., 0., 0., 0., 0.],[0., 1., 1., 1., 1., 1., 0.],@@ -237,7 +234,7 @@ def hessian_response(input: torch.Tensor,[0.0194, 0.0339, 0.0497, 0.0000, 0.0497, 0.0339, 0.0194],[0.0334, 0.0575, 0.0339, 0.0000, 0.0339, 0.0575, 0.0334],[0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155]]]])- """+ """if not torch.is_tensor(input):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))@@ -263,6 +260,9 @@ def hessian_response(input: torch.Tensor,class CornerHarris(nn.Module):+ r"""nn.Module that calculates Harris corners+ See :func:`~kornia.feature.harris_response` for details.+ """def __init__(self, k: Union[float, torch.Tensor],grads_mode='sobel') -> None:super(CornerHarris, self).__init__()@@ -279,11 +279,14 @@ class CornerHarris(nn.Module):'grads_mode=' + self.grads_mode + ')'def forward(self, input: torch.Tensor, # type: ignore- sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:+ sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:return harris_response(input, self.k, self.grads_mode, sigmas) # type: ignoreclass CornerGFTT(nn.Module):+ r"""nn.Module that calculates Shi-Tomasi corners+ See :func:`~kornia.feature.gfft_response` for details.+ """def __init__(self, grads_mode='sobel') -> None:super(CornerGFTT, self).__init__()self.grads_mode: str = grads_mode@@ -294,11 +297,14 @@ class CornerGFTT(nn.Module):'grads_mode=' + self.grads_mode + ')'def forward(self, input: torch.Tensor, # type: ignore- sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:+ sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:return gftt_response(input, self.grads_mode, sigmas)class BlobHessian(nn.Module):+ r"""nn.Module that calculates Hessian blobs+ See :func:`~kornia.feature.hessian_response` for details.+ """def __init__(self, grads_mode='sobel') -> None:super(BlobHessian, self).__init__()self.grads_mode: str = grads_mode@@ -309,5 +315,5 @@ class BlobHessian(nn.Module):'grads_mode=' + self.grads_mode + ')'def forward(self, input: torch.Tensor, # type: ignore- sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:+ sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:return hessian_response(input, self.grads_mode, sigmas)diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex b25519478..89cb8e073 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -54,23 +54,26 @@ 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 classicallocal feature detectors like Harris, Hessian-Affine or SIFT (DoG).- It has 5 modules inside: scale pyramid generator, responce ("cornerness") function,+ It has 5 modules inside: scale pyramid generator, response ("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, asthey 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- """+ Args:+ num_features: (int) Number of features to detect. default = 500. 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. Default is :class:`~kornia.feature.PassLAF`,+ which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.+ aff_module: (nn.Module) for local feature affine shape estimation. Default is :class:`~kornia.feature.PassLAF`,+ which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.+ """def __init__(self,num_features: int = 500,mr_size: float = 6.0,@@ -153,14 +156,15 @@ 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+ """Three stage local feature detection. First the location and scale of interest points are determined bydetect function. Then affine shape and orientation.+Args:- img: 4d tensor, shape [BxCxHxW]+ img: (torch.Tensor), shape [BxCxHxW]+Returns:- lafs: 4d tensor, shape [BxNx2x3]. Detected local affine frames.- responses: 3d tensor, shape [BxNx1]. Response function values for corresponding lafs """+ lafs (torch.Tensor): shape [BxNx2x3]. Detected local affine frames.+ responses (torch.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/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 5f090199b..651c3b75e 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -9,8 +9,8 @@ from kornia.geometry import pidef get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:- """- Returns a weighted pooling kernel for SIFT descriptor+ """Returns a weighted pooling kernel for SIFT descriptor+Args:ksize: (int): kernel_size@@ -18,7 +18,7 @@ def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:torch.Tensor: kernelShape:- - Output: :math: `(ksize,ksize)`+ Output: :math: `(ksize,ksize)`"""ks_2: float = float(ksize) / 2.0xc2: torch.Tensor = ks_2 - (torch.arange(ksize).float() + 0.5 - ks_2).abs() # type: ignore # noqa@@ -28,9 +28,9 @@ def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:def get_sift_bin_ksize_stride_pad(patch_size: int,num_spatial_bins: int) -> Tuple:- """- Returns a tuple with SIFT parameters, given the patch size+ """Returns a tuple with SIFT parameters, given the patch sizeand number of spatial bins.+Args:patch_size: (int)num_spatial_bins: (int)@@ -47,23 +47,21 @@ def get_sift_bin_ksize_stride_pad(patch_size: int,class SIFTDescriptor(nn.Module):"""Module, which computes SIFT descriptors of given patches+Args:- patch_size: (int): Input patch size in pixels- (41 is default)- num_ang_bins: (int): Number of angular bins.- (8 is default)- num_spatial_bins: (int): Number of spatial bins- (4 is default)- clipval: (float): default 0.2- rootsift: (bool): if True, RootSIFT (Arandjelović et. al, 2012)+ patch_size: (int) Input patch size in pixels (41 is default)+ num_ang_bins: (int) Number of angular bins. (8 is default)+ num_spatial_bins: (int) Number of spatial bins (4 is default)+ clipval: (float) default 0.2+ rootsift: (bool) if True, RootSIFT (Arandjelović et. al, 2012)is computedReturns:Tensor: SIFT descriptor of the patchesShape:- - Input: :math:`(B, 1, num_spatial_bins, num_spatial_bins)`- - Output: :math:`(B, num_ang_bins * num_spatial_bins ** 2)`+ - Input: (B, 1, num_spatial_bins, num_spatial_bins)+ - Output: (B, num_ang_bins * num_spatial_bins ** 2)Examples::>>> input = torch.rand(23, 1, 32, 32)diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex fe80d5770..3405edf11 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -600,16 +600,18 @@ def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor:def normalize_pixel_coordinates(pixel_coordinates: torch.Tensor,height: int,- width: int) -> torch.Tensor:+ width: int,+ eps: float = 1e-8) -> torch.Tensor:r"""Normalize pixel coordinates between -1 and 1.Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).Args:- pixel_coordinate (torch.Tensor): the grid with pixel coordinates.+ pixel_coordinates (torch.Tensor): the grid with pixel coordinates.Shape can be :math:`(*, 2)`.width (int): the maximum width in the x-axis.height (int): the maximum height in the y-axis.+ eps (float): safe division by zero. (default 1e-8).Return:torch.Tensor: the normalized pixel coordinates.@@ -622,7 +624,7 @@ def normalize_pixel_coordinates(torch.tensor(width), torch.tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)- factor: torch.Tensor = torch.tensor(2.) / (hw - 1).clamp(1e-8)+ factor: torch.Tensor = torch.tensor(2.) / (hw - 1).clamp(eps)return factor * pixel_coordinates - 1@@ -630,17 +632,19 @@ def normalize_pixel_coordinates(def denormalize_pixel_coordinates(pixel_coordinates: torch.Tensor,height: int,- width: int) -> torch.Tensor:+ width: int,+ eps: float = 1e-8) -> torch.Tensor:r"""Denormalize pixel coordinates.The input is assumed to be -1 if on extreme left, 1 if onextreme right (x = w-1).Args:- pixel_coordinate (torch.Tensor): the normalized grid coordinates.+ pixel_coordinates (torch.Tensor): the normalized grid coordinates.Shape can be :math:`(*, 2)`.width (int): the maximum width in the x-axis.height (int): the maximum height in the y-axis.+ eps (float): safe division by zero. (default 1e-8).Return:torch.Tensor: the denormalized pixel coordinates.@@ -653,7 +657,7 @@ def denormalize_pixel_coordinates(torch.tensor(width), torch.tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)- factor: torch.Tensor = torch.tensor(2.) / (hw - 1).clamp(1e-8)+ factor: torch.Tensor = torch.tensor(2.) / (hw - 1).clamp(eps)return torch.tensor(1.) / factor * (pixel_coordinates + 1)@@ -662,17 +666,19 @@ def normalize_pixel_coordinates3d(pixel_coordinates: torch.Tensor,depth: int,height: int,- width: int) -> torch.Tensor:+ width: int,+ eps: float = 1e-8) -> torch.Tensor:r"""Normalize pixel coordinates between -1 and 1.Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).Args:- pixel_coordinate (torch.Tensor): the grid with pixel coordinates.+ pixel_coordinates (torch.Tensor): the grid with pixel coordinates.Shape can be :math:`(*, 3)`.depth (int): the maximum depth in the z-axis.height (int): the maximum height in the y-axis.width (int): the maximum width in the x-axis.+ eps (float): safe division by zero. (default 1e-8).Return:torch.Tensor: the normalized pixel coordinates.@@ -685,7 +691,7 @@ def normalize_pixel_coordinates3d(torch.tensor(depth), torch.tensor(width), torch.tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)- factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(1e-8)+ factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(eps)return factor * pixel_coordinates - 1@@ -694,18 +700,21 @@ def denormalize_pixel_coordinates3d(pixel_coordinates: torch.Tensor,depth: int,height: int,- width: int) -> torch.Tensor:+ width: int,+ eps: float = 1e-8) -> torch.Tensor:r"""Denormalize pixel coordinates.The input is assumed to be -1 if on extreme left, 1 if onextreme right (x = w-1).Args:- pixel_coordinate (torch.Tensor): the normalized grid coordinates.+ pixel_coordinates (torch.Tensor): the normalized grid coordinates.Shape can be :math:`(*, 3)`.depth (int): the maximum depth in the x-axis.height (int): the maximum height in the y-axis.width (int): the maximum width in the x-axis.+ eps (float): safe division by zero. (default 1e-8).+Return:torch.Tensor: the denormalized pixel coordinates.@@ -718,6 +727,6 @@ def denormalize_pixel_coordinates3d(torch.tensor(depth), torch.tensor(width), torch.tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)- factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(1e-8)+ factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(eps)return torch.tensor(1.) / factor * (pixel_coordinates + 1)diff --git a/kornia/geometry/spatial_soft_argmax.py b/kornia/geometry/spatial_soft_argmax.pyindex fa975e9c8..25d4bc955 100644--- a/kornia/geometry/spatial_soft_argmax.py+++ b/kornia/geometry/spatial_soft_argmax.py@@ -76,6 +76,9 @@ def _get_window_grid_kernel3d(d: int, h: int, w: int) -> torch.Tensor:class ConvSoftArgmax2d(nn.Module):+ r"""Module that calculates soft argmax 2d per window+ See :func:`~kornia.geometry.conv_soft_argmax2d` for details.+ """def __init__(self,kernel_size: Tuple[int, int] = (3, 3),stride: Tuple[int, int] = (1, 1),@@ -116,6 +119,9 @@ class ConvSoftArgmax2d(nn.Module):class ConvSoftArgmax3d(nn.Module):+ r"""Module that calculates soft argmax 3d per window+ See :func:`~kornia.geometry.conv_soft_argmax3d` for details.+ """def __init__(self,kernel_size: Tuple[int, int, int] = (3, 3, 3),stride: Tuple[int, int, int] = (1, 1, 1),@@ -164,46 +170,41 @@ def conv_soft_argmax2d(input: torch.Tensor,eps: float = 1e-8,output_value: bool = False) -> Union[torch.Tensor,Tuple[torch.Tensor, torch.Tensor]]:- """- Function that computes the convolutional spatial Soft-Argmax 2D over the windows+ r"""Function that computes the convolutional spatial Soft-Argmax 2D over the windowsof a given input heatmap. Function has two outputs: argmax coordinates and the softmaxpooled heatmap values- themselves.+ themselves. On each window, the function computed is- On each window, the function computed is:+ .. math::+ ij(X) = \frac{\sum{(i,j)} * exp(x / T) \in X} {\sum{exp(x / T) \in X}}.. math::- ij(X) = \frac{\sum_{(i,j) * exp(x / T) \in X}} {\sum_{exp(x / T) \in X}}- val(X) = \frac{\sum_{x * exp(x / T) \in X}} {\sum_{exp(x / T) \in X}}+ val(X) = \frac{\sum{x * exp(x / T) \in X}} {\sum{exp(x / T) \in X}}- - where T is temperature.+ where T is temperature.Args:- kernel_size (Tuple([int,int])): the size of the window- stride (Tuple([int,int])): the stride of the window.- padding (Tuple([int,int])): input zero padding+ kernel_size (Tuple[int,int]): the size of the window+ stride (Tuple[int,int]): the stride of the window.+ padding (Tuple[int,int]): input zero paddingtemperature (torch.Tensor): factor to apply to input. Default is 1.- normalized_coordinates (bool): whether to return the- coordinates normalized in the range of [-1, 1]. Otherwise,- it will return the coordinates in the range of the input shape.- Default is True.+ normalized_coordinates (bool): whether to return the coordinates normalized in the range of [-1, 1]. Otherwise,+ it will return the coordinates in the range of the input shape. Default is True.eps (float): small value to avoid zero division. Default is 1e-8.- output_value(bool): if True, val is outputed, if False, only ij-+ output_value (bool): if True, val is outputed, if False, only ijShape:- Input: :math:`(N, C, H_{in}, W_{in})`- - Output: math:`(N, C, 2, H_{out}, W_{out})`, :math:`(N, C, H_{out}, W_{out})`, where+ - Output: :math:`(N, C, 2, H_{out}, W_{out})`, :math:`(N, C, H_{out}, W_{out})`, where- .. math::- H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] -- (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor+ .. math::+ H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] -+ (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor- .. math::- W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] -- (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor+ .. math::+ W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] -+ (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloorExamples::->>> input = torch.randn(20, 16, 50, 32)>>> nms_coords, nms_val = conv_soft_argmax2d(input, (3,3), (2,2), (1,1))"""@@ -284,54 +285,46 @@ def conv_soft_argmax3d(input: torch.Tensor,eps: float = 1e-8,output_value: bool = True) -> Union[torch.Tensor,Tuple[torch.Tensor, torch.Tensor]]:- """- Function that computes the convolutional spatial Soft-Argmax 3D over the windows+ r"""Function that computes the convolutional spatial Soft-Argmax 3D over the windowsof a given input heatmap. Function has two outputs: argmax coordinates and the softmaxpooled heatmap valuesthemselves.-On each window, the function computed is:.. math::- ijk(X) = \frac{\sum_{(i,j,k) * exp(x / T) \in X}} {\sum_{exp(x / T) \in X}}+ ijk(X) = \frac{\sum{(i,j,k)} * exp(x / T) \in X} {\sum{exp(x / T) \in X}}- val(X) = \frac{\sum_{x * exp(x / T) \in X}} {\sum_{exp(x / T) \in X}}+ .. math::+ val(X) = \frac{\sum{x * exp(x / T) \in X}} {\sum{exp(x / T) \in X}}- - where T is temperature.- [:,:, 0, ...] is i == depth (scale)- [:,:, 1, ...] is j == x- [:,:, 2, ...] is k == y+ where T is temperature.Args:- kernel_size (Tuple([int,int,int])): the size of the window- stride (Tuple([int,int,int])): the stride of the window.- padding (Tuple([int,int,int])): input zero padding+ kernel_size (Tuple[int,int,int]): size of the window+ stride (Tuple[int,int,int]): stride of the window.+ padding (Tuple[int,int,int]): input zero paddingtemperature (torch.Tensor): factor to apply to input. Default is 1.- normalized_coordinates (bool): whether to return the- coordinates normalized in the range of [-1, 1]. Otherwise,- it will return the coordinates in the range of the input shape.- Default is False.+ normalized_coordinates (bool): whether to return the coordinates normalized in the range of [-1, 1]. Otherwise,+ it will return the coordinates in the range of the input shape. Default is False.eps (float): small value to avoid zero division. Default is 1e-8.- output_value(bool): if True, val is outputed, if False, only ij-+ output_value (bool): if True, val is outputed, if False, only ijShape:- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})`- - Output: math:`(N, C, 3, D_{out}, H_{out}, W_{out})`, :math:`(N, C, D_{out}, H_{out}, W_{out})`, where-- .. math::- D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -- (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor+ - Output: :math:`(N, C, 3, D_{out}, H_{out}, W_{out})`, :math:`(N, C, D_{out}, H_{out}, W_{out})`, where- .. math::- H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] -- (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor+ .. math::+ D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -+ (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor- .. math::- W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] -- (\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor+ .. math::+ H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] -+ (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor- Examples::+ .. math::+ W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] -+ (\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor+ Examples:>>> input = torch.randn(20, 16, 3, 50, 32)>>> nms_coords, nms_val = conv_soft_argmax2d(input, (3, 3, 3), (1, 2, 2), (0, 1, 1))"""@@ -444,11 +437,10 @@ def spatial_soft_argmax2d(class SpatialSoftArgmax2d(nn.Module):- r"""Function that computes the Spatial Soft-Argmax 2D of a given heatmap.+ r"""Module that computes the Spatial Soft-Argmax 2D of a given heatmap.- See :class:`~kornia.contrib.spatial_soft_argmax2d` for details.+ See :func:`~kornia.contrib.spatial_soft_argmax2d` for details."""-def __init__(self,temperature: torch.Tensor = torch.tensor(1.0),normalized_coordinates: bool = True,diff --git a/test/integration/test_soft_argmax2d.py b/test/integration/test_soft_argmax2d.pyindex d6a69e47c..36462915a 100644--- a/test/integration/test_soft_argmax2d.py+++ b/test/integration/test_soft_argmax2d.py@@ -42,7 +42,7 @@ class TestIntegrationSoftArgmax2d:criterion = nn.MSELoss()# spatial soft-argmax2d module- soft_argmax2d = kornia.contrib.SpatialSoftArgmax2d(+ soft_argmax2d = kornia.geometry.SpatialSoftArgmax2d(normalized_coordinates=False)# NOTE: check where this comes from