🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
improve typing in docs (#1137)
Edgar Ribabfb66c82dc1b
diff --git a/docs/source/feature.rst b/docs/source/feature.rstindex 04807f320..6b8c81fad 100644--- a/docs/source/feature.rst+++ b/docs/source/feature.rst@@ -3,14 +3,6 @@ kornia.feature.. currentmodule:: kornia.feature-Non Maxima Suppression-------------------------.. autofunction:: non_maxima_suppression2d-.. autofunction:: non_maxima_suppression3d-.. autofunction:: nms2d-.. autofunction:: nms3d-Detectors---------@@ -60,6 +52,13 @@ Local Affine Frames (LAF).. autofunction:: laf_from_three_points.. autofunction:: raise_error_if_laf_is_not_valid+Non Maxima Suppression+----------------------++.. autofunction:: non_maxima_suppression2d+.. autofunction:: non_maxima_suppression3d+.. autofunction:: nms2d+.. autofunction:: nms3dModule------diff --git a/docs/source/geometry.subpix.rst b/docs/source/geometry.subpix.rstindex ed990d165..0327f0bbd 100644--- a/docs/source/geometry.subpix.rst+++ b/docs/source/geometry.subpix.rst@@ -3,14 +3,21 @@ kornia.geometry.subpix.. currentmodule:: kornia.geometry.subpix-Module with useful functionalities to extract coordinates sub=pixel accuracy.+Module with useful functionalities to extract coordinates sub-pixel accuracy.++Convolutional+--------------.. autofunction:: spatial_soft_argmax2d.. autofunction:: conv_soft_argmax2d.. autofunction:: conv_soft_argmax3d.. autofunction:: conv_quad_interp3d++Spatial+-------+.. autofunction:: spatial_softmax2d.. autofunction:: spatial_expectation2d+.. autofunction:: spatial_soft_argmax2d.. autofunction:: render_gaussian2dModulediff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.pyindex 701709545..8361adac4 100644--- a/kornia/augmentation/augmentation3d.py+++ b/kornia/augmentation/augmentation3d.py@@ -27,13 +27,13 @@ class RandomHorizontalFlip3D(AugmentationBase3D):r"""Apply random horizontal flip to 3D volumes (5D tensor).Args:- p (float): probability of the image being flipped. Default value is 0.5.- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability of the image being flipped.+ return_transform: if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated.+ same_on_batch: apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it+ to the batch form ``False``.Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`@@ -97,13 +97,13 @@ class RandomVerticalFlip3D(AugmentationBase3D):previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.Args:- p (float): probability of the image being flipped. Default value is 0.5.- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability of the image being flipped.+ return_transform: if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated.+ same_on_batch: apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it+ to the batch form ``False``.Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`@@ -167,13 +167,13 @@ class RandomDepthicalFlip3D(AugmentationBase3D):previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.Args:- p (float): probability of the image being flipped. Default value is 0.5.- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability of the image being flipped.+ return_transform: if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated.+ same_on_batch: apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it+ to the batch form ``False``.Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`@@ -234,7 +234,7 @@ class RandomAffine3D(AugmentationBase3D):The transformation is computed so that the center is kept invariant.Args:- degrees (float or tuple or list): Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)@@ -242,30 +242,30 @@ class RandomAffine3D(AugmentationBase3D):If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from(a, b), (m, n) and (x, y).Set to 0 to deactivate rotations.- translate (tuple, optional): tuple of maximum absolute fraction for horizontal, vertical and+ translate: tuple of maximum absolute fraction for horizontal, vertical anddepthical translations (dx,dy,dz). For example translate=(a, b, c), thenhorizontal shift will be randomly sampled in the range -img_width * a < dx < img_width * avertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b.depthical shift will be randomly sampled in the range -img_depth * c < dz < img_depth * c.Will not translate by default.- scale (tuple, optional): scaling factor interval.+ scale: scaling factor interval.If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.If ((a, b), (c, d), (e, f)), the scale is randomly sampled from the range a <= scale_x <= b,c <= scale_y <= d, e <= scale_z <= f. Will keep original scale by default.- shear (sequence or float, optional): Range of degrees to select from.+ shear: Range of degrees to select from.If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be applied.If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])will be applied.If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])will be applied.- resample (int, str or kornia.Resample): Default: Resample.BILINEAR.- return_transform (bool): if ``True`` return the matrix describing the transformation- applied to each. Default: False.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- align_corners(bool): interpolation flag. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ resample:+ return_transform: if ``True`` return the matrix describing the transformation+ applied to each.+ same_on_batch: apply the same transformation across the batch.+ align_corners: interpolation flag.+ keepdim: whether to keep the output shape the same as input (True) or broadcast it+ to the batch form (False). Default: False.Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`@@ -430,7 +430,7 @@ class RandomRotation3D(AugmentationBase3D):previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.Args:- degrees (float or tuple or list): Range of degrees to select from.+ degrees: Range of degrees to select from.If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)@@ -438,14 +438,13 @@ class RandomRotation3D(AugmentationBase3D):If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from(a, b), (m, n) and (x, y).Set to 0 to deactivate rotations.- resample (int, str or kornia.Resample): Default: Resample.BILINEAR- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- align_corners(bool): interpolation flag. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ resample:+ return_transform: if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch: apply the same transformation across the batch.+ align_corners: interpolation flag.+ keepdim: whether to keep the output shape the same as input (True) or broadcast it+ to the batch form (False).Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`@@ -538,11 +537,11 @@ class RandomMotionBlur3D(AugmentationBase3D):r"""Apply random motion blur on 3D volumes (5D tensor).Args:- p (float): probability of applying the transformation. Default value is 0.5.- kernel_size (int or Tuple[int, int]): motion kernel size (odd and positive).+ p: probability of applying the transformation.+ kernel_size: motion kernel size (odd and positive).If int, the kernel will have a fixed size.If Tuple[int, int], it will randomly generate the value from the range batch-wisely.- angle (float or tuple or list): Range of degrees to select from.+ angle: Range of degrees to select from.If angle is a number, then yaw, pitch, roll will be generated from the range of (-angle, +angle).If angle is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).If angle is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)@@ -550,18 +549,16 @@ class RandomMotionBlur3D(AugmentationBase3D):If angle is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from(a, b), (m, n) and (x, y).Set to 0 to deactivate rotations.- direction (float or Tuple[float, float]): forward/backward direction of the motion blur.+ direction: forward/backward direction of the motion blur.Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to auniformly (but still angled) motion blur.If float, it will generate the value from (-direction, direction).If Tuple[int, int], it will randomly generate the value from the range.- border_type (int, str or kornia.BorderType): the padding mode to be applied before convolving.+ border_type: the padding mode to be applied before convolving.CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.- resample (int, str or kornia.Resample): resample mode from "nearest" (0) or "bilinear" (1).- Default: Resample.NEAREST.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ resample: resample mode from "nearest" (0) or "bilinear" (1).+ keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False).Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`@@ -661,17 +658,16 @@ class CenterCrop3D(AugmentationBase3D):r"""Apply center crop on 3D volumes (5D tensor).Args:- p (float): probability of applying the transformation for the whole batch. Default value is 1.+ p: probability of applying the transformation for the whole batch.size (Tuple[int, int, int] or int): Desired output size (out_d, out_h, out_w) of the crop.If integer, out_d = out_h = out_w = size.If Tuple[int, int, int], out_d = size[0], out_h = size[1], out_w = size[2].- resample (int, str or kornia.Resample): Default: Resample.BILINEAR- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- align_corners(bool): interpolation flag. Default: True.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ resample:+ return_transform: if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ align_corners: interpolation flag.+ keepdim: whether to keep the output shape the same as input (True) or broadcast it+ to the batch form (False).Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`@@ -759,29 +755,28 @@ class RandomCrop3D(AugmentationBase3D):Crops random sub-volumes on a given size.Args:- p (float): probability of applying the transformation for the whole batch. Default value is 1.0.- size (Tuple[int, int, int]): Desired output size (out_d, out_h, out_w) of the crop.+ p: probability of applying the transformation for the whole batch.+ size: Desired output size (out_d, out_h, out_w) of the crop.Must be Tuple[int, int, int], then out_d = size[0], out_h = size[1], out_w = size[2].- padding (int or sequence, optional): Optional padding on each border of the image.+ padding: Optional padding on each border of the image.Default is None, i.e no padding. If a sequence of length 6 is provided, it is used to padleft, top, right, bottom, front, back borders respectively.If a sequence of length 3 is provided, it is used to pad left/right,top/bottom, front/back borders, respectively.- pad_if_needed (boolean): It will pad the image if smaller than the+ pad_if_needed: It will pad the image if smaller than thedesired size to avoid raising an exception. Since cropping is doneafter padding, the padding seems to be done at a random offset.fill: Pixel fill value for constant fill. Default is 0. If a tuple oflength 3, it is used to fill R, G, B channels respectively.This value is only used when the padding_mode is constant.padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.- resample (int, str or kornia.Resample): Default: Resample.BILINEAR- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated- same_on_batch (bool): apply the same transformation across the batch. Default: False.- align_corners(bool): interpolation flag. Default: True.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ resample:+ return_transform: if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated+ same_on_batch: apply the same transformation across the batch.+ align_corners: interpolation flag.+ keepdim: whether to keep the output shape the same as input (True) or broadcast it+ to the batch form (False).Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`@@ -920,15 +915,14 @@ class RandomPerspective3D(AugmentationBase3D):r"""Apply andom perspective transformation to 3D volumes (5D tensor).Args:- p (float): probability of the image being perspectively transformed. Default value is 0.5.- distortion_scale(float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.- resample (int, str or kornia.Resample): Default: Resample.BILINEAR.- return_transform (bool): if ``True`` return the matrix describing the transformation- applied to each. Default: False.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- align_corners(bool): interpolation flag. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability of the image being perspectively transformed.+ distortion_scale: it controls the degree of distortion and ranges from 0 to 1.+ resample:+ return_transform: if ``True`` return the matrix describing the transformation applied to each.+ same_on_batch: apply the same transformation across the batch.+ align_corners: interpolation flag.+ keepdim: whether to keep the output shape the same as input (True) or broadcast it+ to the batch form (False).Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`@@ -1028,14 +1022,12 @@ class RandomEqualize3D(AugmentationBase3D):r"""Apply random equalization to 3D volumes (5D tensor).Args:- p (float): probability of the image being equalized. Default value is 0.5.-- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability of the image being equalized.+ return_transform: if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch): apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input (True) or broadcast it+ to the batch form (False).Shape:- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 96b215e49..508548fb2 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -25,13 +25,12 @@ class _BasicAugmentationBase(nn.Module):To change this behaviour, please use ``set_rng_device_and_dtype``.Args:- p (float): probability for applying an augmentation. This param controls the augmentation- probabilities element-wisely.- p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wisely.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability for applying an augmentation. This param controls the augmentation probabilities element-wise.+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation+ probabilities batch-wise.+ same_on_batch: apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to+ the batch form ``False``."""def __init__(@@ -139,16 +138,15 @@ class _AugmentationBase(_BasicAugmentationBase):Advanced augmentation base class with the functionality of transformation matrix calculations.Args:- p (float): probability for applying an augmentation. This param controls the augmentation probabilities- element-wisely for a batch.- p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wisely.- return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ pprobability for applying an augmentation. This param controls the augmentation probabilities+ element-wise for a batch.+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation+ probabilities batch-wise.+ return_transform: if ``True`` return the matrix describing the geometric transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch: apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it+ to the batch form ``False``."""def __init__(@@ -255,16 +253,15 @@ class AugmentationBase2D(_AugmentationBase):"compute_transformation" is only required when passing "return_transform" as True.Args:- p (float): probability for applying an augmentation. This param controls the augmentation probabilities- element-wisely for a batch.- p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wisely.- return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability for applying an augmentation. This param controls the augmentation probabilities+ element-wise for a batch.+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation+ probabilities batch-wise.+ return_transform: if ``True`` return the matrix describing the geometric transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch: apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch+ form ``False``."""def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):@@ -297,16 +294,15 @@ class IntensityAugmentationBase2D(AugmentationBase2D):"compute_transformation" is only required when passing "return_transform" as True.Args:- p (float): probability for applying an augmentation. This param controls the augmentation probabilities- element-wisely for a batch.- p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wisely.- return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability for applying an augmentation. This param controls the augmentation probabilities+ element-wise for a batch.+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation+ probabilities batch-wise.+ return_transform: if ``True`` return the matrix describing the geometric transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch: apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it+ to the batch form ``False``."""def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:@@ -320,16 +316,15 @@ class GeometricAugmentationBase2D(AugmentationBase2D):"compute_transformation" is only required when passing "return_transform" as True.Args:- p (float): probability for applying an augmentation. This param controls the augmentation probabilities- element-wisely for a batch.- p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wisely.- return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability for applying an augmentation. This param controls the augmentation probabilities+ element-wise for a batch.+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation+ probabilities batch-wise.+ return_transform: if ``True`` return the matrix describing the geometric transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch: apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it+ to the batch form ``False``."""def inverse_transform(@@ -410,14 +405,13 @@ class AugmentationBase3D(_AugmentationBase):"compute_transformation" is only required when passing "return_transform" as True.Args:- p (float): probability for applying an augmentation. This param controls the augmentation probabilities- element-wisely for a batch.- p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wisely.- return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each- input tensor. If ``False`` and the input is a tuple the applied transformation- wont be concatenated.- same_on_batch (bool): apply the same transformation across the batch. Default: False.+ p: probability for applying an augmentation. This param controls the augmentation probabilities+ element-wise for a batch.+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation+ probabilities batch-wise.+ return_transform: if ``True`` return the matrix describing the geometric transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch: apply the same transformation across the batch."""def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):@@ -450,13 +444,12 @@ class MixAugmentationBase(_BasicAugmentationBase):"apply_transform" will need to handle the probabilities internally.Args:- p (float): probability for applying an augmentation.- This param controls if to apply the augmentation for the batch.- p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wisely.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False.+ p: probability for applying an augmentation. This param controls if to apply the augmentation for the batch.+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation+ probabilities batch-wise.+ same_on_batch: apply the same transformation across the batch.+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it+ to the batch form ``False``."""def __init__(self, p: float, p_batch: float, same_on_batch: bool = False, keepdim: bool = False) -> None:diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 1ef0942ec..116236fc1 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -43,8 +43,7 @@ class AugmentationSequential(ImageSequential):If False, the whole list of args will be processed as a sequence in original order.Return:- List[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]: the tensor (, and the transformation matrix)- has been sequentially modified by the args.+ the tensor (, and the transformation matrix) has been sequentially modified by the args.Examples:>>> import korniadiff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 197f4e444..50f9662f4 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -35,8 +35,7 @@ class ImageSequential(nn.Sequential):If False, the whole list of args will be processed as a sequence in original order.Returns:- Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: the tensor (, and the transformation matrix)- has been sequentially modified by the args.+ the tensor (, and the transformation matrix) has been sequentially modified by the args.Examples:>>> import korniadiff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.pyindex eeceabb24..889981c4c 100644--- a/kornia/augmentation/container/patch.py+++ b/kornia/augmentation/container/patch.py@@ -42,8 +42,7 @@ class PatchSequential(ImageSequential):If ``False``, the whole list of args will be processed in original order.Return:- List[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]: the tensor (, and the transformation matrix)- has been sequentially modified by the args.+ the tensor (, and the transformation matrix) has been sequentially modified by the args.Examples:>>> import kornia.augmentation as Kdiff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 31bb35db2..98dc10368 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -19,12 +19,14 @@ urls["affnet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/Affclass 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`.+ r"""Module, which estimates the second moment matrix of the patch gradients.++ The method determines 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"""+ patch_size: the input image patch size.+ eps: for safe division.+ """def __init__(self, patch_size: int = 19, eps: float = 1e-10):super(PatchAffineShapeEstimator, self).__init__()@@ -78,15 +80,17 @@ class PatchAffineShapeEstimator(nn.Module):class LAFAffineShapeEstimator(nn.Module):- """Module, which extracts patches using input images and local affine frames (LAFs),- then runs :class:`~kornia.feature.PatchAffineShapeEstimator`- on patches to estimate LAFs shape.+ """Module, which extracts patches using input images and local affine frames (LAFs).++ 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.Args:- patch_size: int, default = 32- affine_shape_detector: nn.Module. Patch affine shape estimator, e.g. PatchAffineShapeEstimator. Default: None""" # noqa pylint: disable+ patch_size: the input image patch size.+ affine_shape_detector: Patch affine shape estimator, :class:`~kornia.feature.PatchAffineShapeEstimator`.+ """ # noqa pylint: disabledef __init__(self, patch_size: int = 32, affine_shape_detector: Optional[nn.Module] = None) -> None:super(LAFAffineShapeEstimator, self).__init__()@@ -136,16 +140,17 @@ class LAFAffineShapeEstimator(nn.Module):class LAFAffNetShapeEstimator(nn.Module):- """Module, which extracts patches using input images and local affine frames (LAFs),- then runs AffNet on patches to estimate LAFs shape.- This is based on the original code from paper "Repeatability Is Not Enough:- Learning Discriminative Affine Regions via Discriminability"".+ """Module, which extracts patches using input images and local affine frames (LAFs).++ Then runs AffNet on patches to estimate LAFs shape. This is based on the original code from paper+ "Repeatability Is Not Enough: Learning Discriminative Affine Regions via Discriminability"".See :cite:`AffNet2018` for more details.+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:- pretrained: (bool) Download and set pretrained weights to the model. Default: false.+ pretrained: Download and set pretrained weights to the model."""def __init__(self, pretrained: bool = False):@@ -194,11 +199,12 @@ class LAFAffNetShapeEstimator(nn.Module):def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:"""Args:- laf: (torch.Tensor) shape [BxNx2x3]- img: (torch.Tensor) shape [Bx1xHxW]+ laf: shape [BxNx2x3]+ img: shape [Bx1xHxW]Returns:- torch.Tensor: laf_out shape [BxNx2x3]"""+ laf_out 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/hardnet.py b/kornia/feature/hardnet.pyindex 557779d5b..84b43fd68 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -13,17 +13,16 @@ urls["hardnet8v2"] = "http://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt" # noqa pclass HardNet(nn.Module):- """- Module, which computes HardNet descriptors of given grayscale patches of 32x32.+ r"""Module, which computes HardNet descriptors of given grayscale patches of 32x32.This is based on the original code from paper "Working hard to know your neighbor'smargins: Local descriptor learning loss". See :cite:`HardNet2017` for more details.Args:- pretrained: (bool) Download and set pretrained weights to the model. Default: false.+ pretrained: Download and set pretrained weights to the model.Returns:- torch.Tensor: HardNet descriptor of the patches.+ HardNet descriptor of the patches.Shape:- Input: (B, 1, 32, 32)@@ -85,17 +84,16 @@ class HardNet(nn.Module):class HardNet8(nn.Module):- """- Module, which computes HardNet8 descriptors of given grayscale patches of 32x32.+ r"""Module, which computes HardNet8 descriptors of given grayscale patches of 32x32.This is based on the original code from paper "Improving the HardNet Descriptor".See :cite:`HardNet2020` for more details.Args:- pretrained: (bool) Download and set pretrained weights to the model. Default: false.+ pretrained: Download and set pretrained weights to the model.Returns:- torch.Tensor: HardNet8 descriptor of the patches.+ HardNet8 descriptor of the patches.Shape:- Input: (B, 1, 32, 32)diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex cefd794cb..7c5fa988d 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -9,10 +9,10 @@ from kornia.geometry import angle_to_rotation_matrixdef raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:- """Auxilary function, which verifies that input is a torch.tensor of [BxNx2x3] shape+ """Auxilary function, which verifies that input.Args:- laf+ laf: [BxNx2x3] shape."""laf_message: str = "Invalid laf shape, we expect BxNx2x3. Got: {}".format(laf.shape)if not isinstance(laf, torch.Tensor):@@ -25,13 +25,13 @@ 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].+ LAF: tensor [BxNx2x3] or [BxNx2x2].Returns:- torch.Tensor: tensor BxNx1x1 .+ tensor BxNx1x1.Shape:- Input: :math: `(B, N, 2, 3)`@@ -48,13 +48,13 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:- """Returns a center (keypoint) of the LAFs+ """Returns a center (keypoint) of the LAFs.Args:- LAF: (torch.Tensor): tensor [BxNx2x3].+ LAF: tensor [BxNx2x3].Returns:- torch.Tensor: tensor BxNx2 .+ tensor BxNx2.Shape:- Input: :math: `(B, N, 2, 3)`@@ -95,11 +95,11 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torc"""Changes the orientation of the LAFs.Args:- LAF: (torch.Tensor): tensor [BxNx2x3].- angles: (torch.Tensor): tensor BxNx1, in degrees .+ LAF: tensor [BxNx2x3].+ angles: tensor BxNx1, in degrees.Returns:- torch.Tensor: tensor [BxNx2x3] .+ tensor [BxNx2x3].Shape:- Input: :math: `(B, N, 2, 3)`, `(B, N, 1)`@@ -116,15 +116,15 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torcdef laf_from_center_scale_ori(xy: torch.Tensor, scale: torch.Tensor, ori: torch.Tensor) -> torch.Tensor:- """Returns orientation of the LAFs, in radians. Useful to create kornia LAFs from OpenCV keypoints+ """Returns orientation of the LAFs, in radians. Useful to create kornia LAFs from OpenCV keypoints.Args:- xy: (torch.Tensor): tensor [BxNx2].- scale: (torch.Tensor): tensor [BxNx1x1].- ori: (torch.Tensor): tensor [BxNx1].+ xy: tensor [BxNx2].+ scale: tensor [BxNx1x1].+ ori: tensor [BxNx1].Returns:- torch.Tensor: tensor BxNx2x3 .+ tensor BxNx2x3."""names = ['xy', 'scale', 'ori']for var_name, var, req_shape in zip(names, [xy, scale, ori], [("B", "N", 2), ("B", "N", 1, 1), ("B", "N", 1)]):@@ -145,22 +145,21 @@ def laf_from_center_scale_ori(xy: torch.Tensor, scale: torch.Tensor, ori: torch.def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torch.Tensor:- """- Multiplies region part of LAF ([:, :, :2, :2]) by a scale_coefficient.+ """Multiplies region part of LAF ([:, :, :2, :2]) by a scale_coefficient.+So the center, shape and orientation of the local feature stays the same, but the region area changes.Args:- laf: (torch.Tensor): tensor [BxNx2x3] or [BxNx2x2].- scale_coef: (torch.Tensor): broadcastable tensor or float.-+ laf: tensor [BxNx2x3] or [BxNx2x2].+ scale_coef: broadcastable tensor or float.Returns:- torch.Tensor: tensor BxNx2x3 .+ tensor BxNx2x3.Shape:- - Input: :math: `(B, N, 2, 3)`- - Input: :math: `(B, N,)` or ()- - Output: :math: `(B, N, 1, 1)`+ - Input: :math:`(B, N, 2, 3)`+ - Input: :math:`(B, N,)` or ()+ - Output: :math:`(B, N, 1, 1)`Example:>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3@@ -175,15 +174,14 @@ 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+ """Rectifies the affine matrix, so that it becomes upright.Args:- laf: (torch.Tensor): tensor of LAFs.- eps (float): for safe division, (default 1e-9)+ laf: tensor of LAFs.+ eps : for safe division.Returns:- torch.Tensor: tensor of same shape.+ tensor of same shape.Shape:- Input: :math:`(B, N, 2, 3)`@@ -212,18 +210,18 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:- """- Converts ellipse regions to LAF format. Ellipse (a, b, c)- and upright covariance matrix [a11 a12; 0 a22] are connected- by inverse matrix square root:- A = invsqrt([a b; b c])+ """Converts ellipse regions to LAF format.++ Ellipse (a, b, c) and upright covariance matrix [a11 a12; 0 a22] are connected+ by inverse matrix square root: A = invsqrt([a b; b c]).+See also https://github.com/vlfeat/vlfeat/blob/master/toolbox/sift/vl_frame2oell.mArgs:- ells: (torch.Tensor): tensor of ellipses in Oxford format [x y a b c].+ ells: tensor of ellipses in Oxford format [x y a b c].Returns:- LAF: (torch.Tensor) tensor of ellipses in LAF format.+ tensor of ellipses in LAF format.Shape:- Input: :math:`(B, N, 5)`@@ -261,16 +259,16 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor: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+ """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+ LAF:+ n_pts: number of points to output.Returns:- pts: (torch.Tensor) tensor of boundary points+ tensor of boundary points.Shape:- Input: :math:`(B, N, 2, 3)`@@ -299,11 +297,11 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0):"""Returns numpy array for drawing LAFs (local features).Args:- LAF: (torch.Tensor).- n_pts: number of boundary points to output+ LAF:+ n_pts: number of boundary points to output.Returns:- pts: (torch.Tensor) tensor of boundary points+ tensor of boundary points.Shape:- Input: :math:`(B, N, 2, 3)`@@ -325,6 +323,7 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0):def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:"""De-normalizes LAFs from scale to image scale.+B,N,H,W = images.size()MIN_SIZE = min(H,W)[a11 a21 x]@@ -334,11 +333,11 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:[a21*MIN_SIZE a22*MIN_SIZE y*H]Args:- LAF: (torch.Tensor).- images: (torch.Tensor) images, LAFs are detected in+ LAF:+ images: images, LAFs are detected in.Returns:- LAF: (torch.Tensor).+ the denormalized lafs.Shape:- Input: :math:`(B, N, 2, 3)`@@ -391,16 +390,13 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor"""Helper function for affine grid generation.Args:- img: (torch.Tensor) images, LAFs are detected in- LAF: (torch.Tensor).- PS (int) -- patch size to be extracted+ img: image tensor of shape :math:`(B, CH, H, W)`.+ LAF: laf with shape :math:`(B, N, 2, 3)`.+ PS: patch size to be extracted.Returns:- grid: (torch.Tensor).+ grid- Shape:- - Input: :math:`(B, CH, H, W)`, :math:`(B, N, 2, 3)`- - Output: :math:`(B, N, PS, PS)`"""raise_error_if_laf_is_not_valid(LAF)B, N, _, _ = LAF.size()@@ -420,16 +416,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.- No smoothing applied, huge aliasing (better use extract_patches_from_pyramid)++ No smoothing applied, huge aliasing (better use extract_patches_from_pyramid).Args:- img: (torch.Tensor) images, LAFs are detected in- laf: (torch.Tensor).- PS: (int) patch size, default = 32- normalize_lafs_before_extraction (bool): if True, lafs are normalized to image size, default = True+ img: images, LAFs are detected in.+ laf:+ PS: patch size.+ normalize_lafs_before_extraction: if True, lafs are normalized to image size.Returns:- patches: (torch.Tensor) :math:`(B, N, CH, PS,PS)`+ patches with shape :math:`(B, N, CH, PS,PS)`."""raise_error_if_laf_is_not_valid(laf)if normalize_lafs_before_extraction:@@ -457,16 +454,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.- Patches are extracted from appropriate pyramid level++ Patches are extracted from appropriate pyramid level.Args:- laf: (torch.Tensor).- images: (torch.Tensor) images, LAFs are detected in- PS: (int) patch size, default = 32- normalize_lafs_before_extraction (bool): if True, lafs are normalized to image size, default = True+ laf:+ images: images, LAFs are detected in.+ PS: patch size.+ normalize_lafs_before_extraction: if True, lafs are normalized to image size.Returns:- patches: (torch.Tensor) :math:`(B, N, CH, PS,PS)`+ patches with shape :math:`(B, N, CH, PS,PS)`."""raise_error_if_laf_is_not_valid(laf)if normalize_lafs_before_extraction:@@ -503,16 +501,17 @@ def extract_patches_from_pyramid(def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0) -> torch.Tensor:- """Checks if the LAF is touching or partly outside the image boundary. Returns the mask- of LAFs, which are fully inside the image, i.e. valid.+ """Checks if the LAF is touching or partly outside the image boundary.++ Returns the mask of LAFs, which are fully inside the image, i.e. valid.Args:- laf (torch.Tensor): :math:`(B, N, 2, 3)`- images (torch.Tensor): images, lafs are detected in :math:`(B, CH, H, W)`- border (int): additional border+ laf: :math:`(B, N, 2, 3)`.+ images: images, lafs are detected in :math:`(B, CH, H, W)`.+ border: additional border.Returns:- mask (torch.Tensor): :math:`(B, N)`+ mask with shape :math:`(B, N)`."""raise_error_if_laf_is_not_valid(laf)n, ch, h, w = images.size()@@ -529,10 +528,10 @@ def laf_to_three_points(laf: torch.Tensor):LAF center, LAF-x unit vector, LAF-y unit vector.Args:- laf (torch.Tensor): :math:`(B, N, 2, 3)`+ laf: :math:`(B, N, 2, 3)`.Returns:- threepts (torch.Tensor): :math:`(B, N, 2, 3)`+ threepts :math:`(B, N, 2, 3)`."""raise_error_if_laf_is_not_valid(laf)three_pts: torch.Tensor = torch.stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)@@ -541,13 +540,14 @@ def laf_to_three_points(laf: torch.Tensor):def laf_from_three_points(threepts: torch.Tensor):"""Converts three points to local affine frame.+Order is (0,0), (0, 1), (1, 0).Args:- threepts (torch.Tensor): :math:`(B, N, 2, 3)`+ threepts: :math:`(B, N, 2, 3)`.Returns:- laf (torch.Tensor): :math:`(B, N, 2, 3)`+ laf :math:`(B, N, 2, 3)`."""laf: torch.Tensor = torch.stack([threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1diff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex c0f0c2984..453895f02 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -8,16 +8,15 @@ def match_nn() -> Tuple[torch.Tensor, torch.Tensor]:r"""Function, which finds nearest neighbors in desc2 for each vector in desc1.- If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.+ If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.Args:- desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.- desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.- dm (torch.Tensor, optional): Tensor containing the distances from each descriptor in desc1+ desc1: Batch of descriptors of a shape :math:`(B1, D)`.+ desc2: Batch of descriptors of a shape :math:`(B2, D)`.+ dm: Tensor containing the distances from each descriptor in desc1to each descriptor in desc2, shape of :math:`(B1, B2)`.Returns:- Tuple[torch.Tensor, torch.Tensor]:- Descriptor distance of matching descriptors, shape of :math:`(B1, 1)`.- Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`."""@@ -40,16 +39,15 @@ def match_mnn() -> Tuple[torch.Tensor, torch.Tensor]:"""Function, which finds mutual nearest neighbors in desc2 for each vector in desc1.- If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.+ If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.Args:- desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.- desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.- dm (torch.Tensor, optional): Tensor containing the distances from each descriptor in desc1+ desc1: Batch of descriptors of a shape :math:`(B1, D)`.+ desc2: Batch of descriptors of a shape :math:`(B2, D)`.+ dm: Tensor containing the distances from each descriptor in desc1to each descriptor in desc2, shape of :math:`(B1, B2)`.Return:- Tuple[torch.Tensor, torch.Tensor]:- Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.- Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,where 0 <= B3 <= min(B1, B2)@@ -82,19 +80,19 @@ def match_snn(desc1: torch.Tensor, desc2: torch.Tensor, th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:"""Function, which finds nearest neighbors in desc2 for each vector in desc1.- which satisfy first to second nearest neighbor distance <= th.- If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.+ The method satisfies first to second nearest neighbor distance <= th.++ If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.Args:- desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.- desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.- th (float): distance ratio threshold.- dm (torch.Tensor, optional): Tensor containing the distances from each descriptor in desc1+ desc1: Batch of descriptors of a shape :math:`(B1, D)`.+ desc2: Batch of descriptors of a shape :math:`(B2, D)`.+ th: distance ratio threshold.+ dm: Tensor containing the distances from each descriptor in desc1to each descriptor in desc2, shape of :math:`(B1, B2)`.Return:- Tuple[torch.Tensor, torch.Tensor]:- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.- Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,where 0 <= B3 <= B1.@@ -122,19 +120,19 @@ def match_smnn(desc1: torch.Tensor, desc2: torch.Tensor, th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:"""Function, which finds mutual nearest neighbors in desc2 for each vector in desc1.- which satisfy first to second nearest neighbor distance <= th.- If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.+ the method satisfies first to second nearest neighbor distance <= th.++ If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.Args:- desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.- desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.- th (float): distance ratio threshold.- dm (torch.Tensor, optional): Tensor containing the distances from each descriptor in desc1+ desc1: Batch of descriptors of a shape :math:`(B1, D)`.+ desc2: Batch of descriptors of a shape :math:`(B2, D)`.+ th: distance ratio threshold.+ dm: Tensor containing the distances from each descriptor in desc1to each descriptor in desc2, shape of :math:`(B1, B2)`.Return:- Tuple[torch.Tensor, torch.Tensor]:- Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.- Long tensor indexes of matching descriptors in desc1 and desc2,shape of :math:`(B3, 2)` where 0 <= B3 <= B1.diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex 8b51ed209..dbcaad67b 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -23,7 +23,7 @@ urls: Dict[str, str] = {def get_grid_dict(patch_size: int = 32) -> Dict[str, torch.Tensor]:- """Gets cartesian and polar parametrizations of grid."""+ r"""Gets cartesian and polar parametrizations of grid."""kgrid = create_meshgrid(height=patch_size, width=patch_size, normalized_coordinates=True)x = kgrid[0, :, :, 0]y = kgrid[0, :, :, 1]@@ -33,7 +33,7 @@ def get_grid_dict(patch_size: int = 32) -> Dict[str, torch.Tensor]:def get_kron_order(d1: int, d2: int) -> torch.Tensor:- """Gets order for doing kronecker product."""+ r"""Gets order for doing kronecker product."""kron_order = torch.zeros([d1 * d2, 2], dtype=torch.int64)for i in range(d1):for j in range(d2):@@ -43,20 +43,23 @@ def get_kron_order(d1: int, d2: int) -> torch.Tensor:class MKDGradients(nn.Module):- r"""- Module, which computes gradients of given patches,- stacked as [magnitudes, orientations].+ r"""Module, which computes gradients of given patches, stacked as [magnitudes, orientations].+Given gradients $g_x$, $g_y$ with respect to $x$, $y$ respectively,- $\mathbox{mags} = $\sqrt{g_x^2 + g_y^2 + eps}$- $\mathbox{oris} = $\mbox{tan}^{-1}(\nicefrac{g_y}{g_x})$.+Args:- patch_size: (int) Input patch size in pixels (32 is default)+ patch_size: Input patch size in pixels.+Returns:- Tensor: gradients of given patches+ gradients of given patches.+Shape:- Input: (B, 1, patch_size, patch_size)- Output: (B, 2, patch_size, patch_size)- Examples::++ Example:>>> patches = torch.rand(23, 1, 32, 32)>>> gradient = MKDGradients()>>> g = gradient(patches) # 23x2x32x32@@ -85,19 +88,20 @@ class MKDGradients(nn.Module):class VonMisesKernel(nn.Module):- """- Module, which computes parameters of Von Mises kernel given coefficients,- and embeds given patches.+ r"""Module, which computes parameters of Von Mises kernel given coefficients, and embeds given patches.+Args:- patch_size: (int) Input patch size in pixels (32 is default)- coeffs: (list) List of coefficients- Some examples are hardcoded in COEFFS+ patch_size: Input patch size in pixels.+ coeffs: List of coefficients. Some examples are hardcoded in COEFFS,+Returns:- Tensor: Von Mises embedding of given parametrization+ Von Mises embedding of given parametrization.+Shape:- Input: (B, 1, patch_size, patch_size)- Output: (B, d, patch_size, patch_size)- Examples::++ Examples:>>> oris = torch.rand(23, 1, 32, 32)>>> vm = VonMisesKernel(patch_size=32,... coeffs=[0.14343168,@@ -167,18 +171,20 @@ class VonMisesKernel(nn.Module):class EmbedGradients(nn.Module):- """- Module that computes gradient embedding,- weighted by sqrt of magnitudes of given patches.+ r"""Module that computes gradient embedding, weighted by sqrt of magnitudes of given patches.+Args:- patch_size: (int) Input patch size in pixels (32 is default)- relative: (bool) absolute or relative gradients (False is default)+ patch_size: Input patch size in pixels.+ relative: absolute or relative gradients.+Returns:- torch.Tensor: Gradient embedding+ Gradient embedding.+Shape:- Input: (B, 2, patch_size, patch_size)- Output: (B, 7, patch_size, patch_size)- Examples::++ Examples:>>> grads = torch.rand(23, 2, 32, 32)>>> emb_grads = EmbedGradients(patch_size=32,... relative=False)@@ -230,7 +236,7 @@ class EmbedGradients(nn.Module):def spatial_kernel_embedding(kernel_type, grids: dict) -> torch.Tensor:- """Compute embeddings for cartesian and polar parametrizations."""+ r"""Compute embeddings for cartesian and polar parametrizations."""factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2}if kernel_type == 'cart':coeffs_ = 'xy'@@ -261,21 +267,23 @@ def spatial_kernel_embedding(kernel_type, grids: dict) -> torch.Tensor:class ExplicitSpacialEncoding(nn.Module):- """- Module that computes explicit cartesian or polar embedding.+ r"""Module that computes explicit cartesian or polar embedding.+Args:- kernel_type: (str) Parametrization of kernel.- 'polar', 'cart' ('polar' is default)- fmap_size: (int) Input feature map size in pixels (32 is default)- in_dims: (int) Dimensionality of input feature map (7 is default)- do_gmask: (bool) Apply gaussian mask (True is default)- do_l2: (bool) Apply l2-normalization (True is default)+ kernel_type: Parametrization of kernel ``'polar'`` or ``'cart'``.+ fmap_size: Input feature map size in pixels.+ in_dims: Dimensionality of input feature map.+ do_gmask: Apply gaussian mask.+ do_l2: Apply l2-normalization.+Returns:- Tensor: Explicit cartesian or polar embedding+ Explicit cartesian or polar embedding.+Shape:- Input: (B, in_dims, fmap_size, fmap_size)- Output: (B, out_dims, fmap_size, fmap_size)- Examples::++ Example:>>> emb_ori = torch.rand(23, 7, 32, 32)>>> ese = ExplicitSpacialEncoding(kernel_type='polar',... fmap_size=32,@@ -377,27 +385,27 @@ class ExplicitSpacialEncoding(nn.Module):class Whitening(nn.Module):- """- Module, performs supervised or unsupervised whitening.+ r"""Module, performs supervised or unsupervised whitening.This is based on the paper "Understanding and Improving Kernel Local Descriptors".See :cite:`mukundan2019understanding` for more details.Args:- xform: (str) Variant of whitening to use.- None, 'lw', 'pca', 'pcaws', 'pcawt'- whitening_model: (dict) Dictionary with keys- 'mean', 'eigvecs', 'eigvals' holding torch.Tensors- in_dims: (int) Dimensionality of input descriptors- output_dims: (int) Dimensionality reduction (128 is default)- keval: (int) Shrinkage parameter (40 is default)- t: (float) Attenuation parameter (0.7 is default)+ xform: Variant of whitening to use. None, 'lw', 'pca', 'pcaws', 'pcawt'.+ whitening_model: Dictionary with keys 'mean', 'eigvecs', 'eigvals' holding torch.Tensors.+ in_dims: Dimensionality of input descriptors.+ output_dims: (int) Dimensionality reduction.+ keval: Shrinkage parameter.+ t: Attenuation parameter.+Returns:- Tensor: l2-normalized, whitened descriptors+ l2-normalized, whitened descriptors.+Shape:- Input: (B, in_dims, fmap_size, fmap_size)- Output: (B, out_dims, fmap_size, fmap_size)- Examples::++ Examples:>>> descs = torch.rand(23, 238)>>> whitening_model = {'pca': {'mean': torch.zeros(238),... 'eigvecs': torch.eye(238),@@ -508,21 +516,18 @@ class MKDDescriptor(nn.Module):See :cite:`mukundan2019understanding` for more details.Args:- patch_size: (int) Input patch size in pixels (32 is default).- kernel_type: (str) Parametrization of kernel- 'concat', 'cart', 'polar' ('concat' is default).- whitening: (str) Whitening transform to apply- None, 'lw', 'pca', 'pcawt', 'pcaws' ('pcawt' is default).- training_set: (str) Set that model was trained on- 'liberty', 'notredame', 'yosemite' ('liberty' is default).- output_dims: (int) Dimensionality reduction (128 is default).+ patch_size: Input patch size in pixels.+ kernel_type: Parametrization of kernel ``'concat'``, ``'cart'``, ``'polar'``.+ whitening: Whitening transform to apply ``None``, ``'lw'``, ``'pca'``, ``'pcawt'``, ``'pcaws'``.+ training_set: Set that model was trained on ``'liberty'``, ``'notredame'``, ``'yosemite'``.+ output_dims: Dimensionality reduction.Returns:- torch.Tensor: Explicit cartesian or polar embedding.+ Explicit cartesian or polar embedding.Shape:- - Input: :math:`(B, in_dims, fmap_size, fmap_size)`.- - Output: :math:`(B, out_dims, fmap_size, fmap_size)`,+ - Input: :math:`(B, in_{dims}, fmap_{size}, fmap_{size})`.+ - Output: :math:`(B, out_{dims}, fmap_{size}, fmap_{size})`,Examples:>>> patches = torch.rand(23, 1, 32, 32)diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex ed5cf4ab1..81b9ac1ed 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -25,8 +25,8 @@ class PassLAF(nn.Module):def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:"""Args:- laf: torch.Tensor: 4d tensor- img (torch.Tensor): the input image tensor+ laf: 4d tensor.+ img: the input image tensor.Return:torch.Tensor: unchanged laf from the input."""@@ -35,12 +35,14 @@ 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"""+ patch_size:+ num_angular_bins:+ eps: for safe division, and arctan.+ """def __init__(self, patch_size: int = 32, num_angular_bins: int = 36, eps: float = 1e-8):super(PatchDominantGradientOrientation, self).__init__()@@ -115,17 +117,17 @@ class PatchDominantGradientOrientation(nn.Module):class OriNet(nn.Module):"""Network, which estimates the canonical orientation of the given 32x32 patches, in radians.- Zero angle points towards right.- This is based on the original code from paper "Repeatability Is Not Enough:- Learning Discriminative Affine Regions via Discriminability"".++ Zero angle points towards right. This is based on the original code from paper+ "Repeatability Is Not Enough: Learning Discriminative Affine Regions via Discriminability"".See :cite:`AffNet2018` for more details.Args:- pretrained: (bool) Download and set pretrained weights to the model. Default: false.- eps: (float) to avoid division by zero in atan2. Default: 1e-6.+ pretrained: Download and set pretrained weights to the model.+ eps: to avoid division by zero in atan2.Returns:- torch.Tensor: Angle in radians.+ Angle in radians.Shape:- Input: (B, 1, 32, 32)@@ -191,14 +193,17 @@ class OriNet(nn.Module):class LAFOrienter(nn.Module):- """Module, which extracts patches using input images and local affine frames (LAFs),- then runs :class:`~kornia.feature.PatchDominantGradientOrientation` or+ """Module, which extracts patches using input images and local affine frames (LAFs).++ Then runs :class:`~kornia.feature.PatchDominantGradientOrientation` or:class:`~kornia.feature.OriNet` on patches and then rotates the LAFs by the estimated anglesArgs:- patch_size: int, default = 32- num_angular_bins: int, default is 36- angle_detector: nn.Module. Patch orientation estimator, e.g. PatchDominantGradientOrientation or OriNet. Default: None""" # noqa pylint: disable+ patch_size:+ num_angular_bins:+ angle_detector: Patch orientation estimator, e.g. :class:`~kornia.feature.PatchDominantGradientOrientation`+ or OriNet.+ """ # noqa pylint: disabledef __init__(self, patch_size: int = 32, num_angular_bins: int = 36, angle_detector: Optional[nn.Module] = None):super(LAFOrienter, self).__init__()@@ -219,11 +224,12 @@ class LAFOrienter(nn.Module):def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:"""Args:- laf: (torch.Tensor), shape [BxNx2x3]- img: (torch.Tensor), shape [Bx1xHxW]+ laf: shape [BxNx2x3]+ img: shape [Bx1xHxW]Returns:- torch.Tensor: laf_out, shape [BxNx2x3]"""+ laf_out, 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 isinstance(img, torch.Tensor):diff --git a/kornia/feature/responses.py b/kornia/feature/responses.pyindex 0d0c1956c..1b16d2a8f 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -12,8 +12,9 @@ def harris_response(grads_mode: str = 'sobel',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:+ r"""Computes the Harris cornerness function.++ Function does not do any normalization or nms. The response map is computed according the following formulation:.. math::R = max(0, det(M) - k \cdot trace(M)^2)@@ -31,23 +32,17 @@ def harris_response(:math:`k ∈ [ 0.04 , 0.06 ]`Args:- input: torch.Tensor: 4d tensor- k (torch.Tensor): the Harris detector free parameter.- grads_mode (string): can be 'sobel' for standalone use or 'diff' for use on Gaussian pyramid- 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>`_+ input: input image with shape :math:`(B, C, H, W)`.+ k: the Harris detector free parameter.+ grads_mode: can be ``'sobel'`` for standalone use or ``'diff'`` for use on Gaussian pyramid.+ sigmas: coefficients to be multiplied by multichannel response. Should be shape of :math:`(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.-- Shape:- - Input: :math:`(B, C, H, W)`- - Output: :math:`(B, C, H, W)`+ the response map per channel with shape :math:`(B, C, H, W)`.- Examples:+ Example:>>> input = torch.tensor([[[... [0., 0., 0., 0., 0., 0., 0.],... [0., 1., 1., 1., 1., 1., 0.],@@ -70,13 +65,16 @@ def harris_response(# TODO: Recompute doctestif not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))+if not len(input.shape) == 4:raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))+if sigmas is not None:if not isinstance(sigmas, torch.Tensor):raise TypeError("sigmas type is not a torch.Tensor. Got {}".format(type(sigmas)))if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):raise ValueError("Invalid sigmas shape, we expect B == input.size(0). Got: {}".format(sigmas.shape))+gradients: torch.Tensor = spatial_gradient(input, grads_mode)dx: torch.Tensor = gradients[:, :, 0]dy: torch.Tensor = gradients[:, :, 1]@@ -89,18 +87,22 @@ def harris_response(det_m: torch.Tensor = dx2 * dy2 - dxy * dxytrace_m: torch.Tensor = dx2 + dy2+# compute the response mapscores: torch.Tensor = det_m - k * (trace_m ** 2)+if sigmas is not None:scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)+return scoresdef gftt_response(input: torch.Tensor, grads_mode: str = 'sobel', 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:+ 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::R = min(eig(M))@@ -115,22 +117,16 @@ def gftt_response(\end{bmatrix}Args:- input (torch.Tensor): 4d tensor- grads_mode (string): can be 'sobel' for standalone use or 'diff' for use on Gaussian pyramid- 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>`_+ input: input image with shape :math:`(B, C, H, W)`.+ grads_mode: can be ``'sobel'`` for standalone use or ``'diff'`` for use on Gaussian pyramid.+ sigmas: coefficients to be multiplied by multichannel response. Should be shape of :math:`(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.-- Shape:- - Input: :math:`(B, C, H, W)`- - Output: :math:`(B, C, H, W)`+ the response map per channel with shape :math:`(B, C, H, W)`.- Examples:+ Example:>>> input = torch.tensor([[[... [0., 0., 0., 0., 0., 0., 0.],... [0., 1., 1., 1., 1., 1., 0.],@@ -153,8 +149,10 @@ def gftt_response(# TODO: Recompute doctestif not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))+if not len(input.shape) == 4:raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))+gradients: torch.Tensor = spatial_gradient(input, grads_mode)dx: torch.Tensor = gradients[:, :, 0]dy: torch.Tensor = gradients[:, :, 1]@@ -170,16 +168,19 @@ def gftt_response(e2: torch.Tensor = 0.5 * (trace_m - torch.sqrt((trace_m ** 2 - 4 * det_m).abs()))scores: torch.Tensor = torch.min(e1, e2)+if sigmas is not None:scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)+return scoresdef hessian_response(input: torch.Tensor, grads_mode: str = 'sobel', 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:+ 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)@@ -194,16 +195,14 @@ def hessian_response(\end{bmatrix}Args:- input: torch.Tensor: 4d tensor- grads_mode (string): can be 'sobel' for standalone use or 'diff' for use on Gaussian pyramid- 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>`_+ input: input image with shape :math:`(B, C, H, W)`.+ grads_mode: can be ``'sobel'`` for standalone use or ``'diff'`` for use on Gaussian pyramid.+ sigmas: coefficients to be multiplied by multichannel response. Should be shape of :math:`(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.+ the response map per channel with shape :math:`(B, C, H, W)`.Shape:- Input: :math:`(B, C, H, W)`@@ -232,48 +231,52 @@ def hessian_response(# TODO: Recompute doctestif not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))+if not len(input.shape) == 4:raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))+if sigmas is not None:if not isinstance(sigmas, torch.Tensor):raise TypeError("sigmas type is not a torch.Tensor. Got {}".format(type(sigmas)))+if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):raise ValueError("Invalid sigmas shape, we expect B == input.size(0). Got: {}".format(sigmas.shape))+gradients: torch.Tensor = spatial_gradient(input, grads_mode, 2)dxx: torch.Tensor = gradients[:, :, 0]dxy: torch.Tensor = gradients[:, :, 1]dyy: torch.Tensor = gradients[:, :, 2]scores: torch.Tensor = dxx * dyy - dxy ** 2+if sigmas is not None:scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)+return scoresdef dog_response(input: torch.Tensor) -> torch.Tensor:- r"""Computes the Difference-of-Gaussian response given the Gaussian 5d input:-+ r"""Computes the Difference-of-Gaussian response.Args:- input: torch.Tensor: 5d tensor+ input: a given the gaussian 5d tensor :math:`(B, C, D, H, W)`.Return:- torch.Tensor: the response map per channel.-- Shape:- - Input: :math:`(B, C, D, H, W)`- - Output: :math:`(B, C, D-1, H, W)`+ the response map per channel with shape :math:`(B, C, D-1, H, W)`."""if not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))+if not len(input.shape) == 5:raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}".format(input.shape))+return input[:, :, 1:] - input[:, :, :-1]class BlobDoG(nn.Module):- r"""nn.Module that calculates Difference-of-Gaussians blobs+ r"""Module that calculates Difference-of-Gaussians blobs.+See :func:`~kornia.feature.dog_response` for details."""@@ -289,7 +292,8 @@ class BlobDoG(nn.Module):class CornerHarris(nn.Module):- r"""nn.Module that calculates Harris corners+ r"""Module that calculates Harris corners.+See :func:`~kornia.feature.harris_response` for details."""@@ -310,7 +314,8 @@ class CornerHarris(nn.Module):class CornerGFTT(nn.Module):- r"""nn.Module that calculates Shi-Tomasi corners+ r"""Module that calculates Shi-Tomasi corners.+See :func:`~kornia.feature.gfft_response` for details."""@@ -327,7 +332,8 @@ class CornerGFTT(nn.Module):class BlobHessian(nn.Module):- r"""nn.Module that calculates Hessian blobs+ r"""Module that calculates Hessian blobs.+See :func:`~kornia.feature.hessian_response` for details."""diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex 1022143b5..ba11a1657 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -12,14 +12,15 @@ from kornia.geometry.transform import ScalePyramiddef _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_levels: int) -> torch.Tensor:- """Auxiliary function for ScaleSpaceDetector. Converts scale level index from ConvSoftArgmax3d- to the actual scale, using the sigmas from the ScalePyramid output+ r"""Auxiliary function for ScaleSpaceDetector. Converts scale level index from ConvSoftArgmax3d+ to the actual scale, using the sigmas from the ScalePyramid output.+Args:- max_coords: (torch.Tensor): tensor [BxNx3].- sigmas: (torch.Tensor): tensor [BxNxD], D >= 1+ max_coords: tensor [BxNx3].+ sigmas: tensor [BxNxD], D >= 1Returns:- torch.Tensor: tensor [BxNx3].+ 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@@ -38,36 +39,37 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_ledef _create_octave_mask(mask: torch.Tensor, octave_shape: List[int]) -> torch.Tensor:- """Downsamples a mask based on the given octave shape."""+ r"""Downsamples a mask based on the given octave shape."""mask_shape = octave_shape[-2:]mask_octave = F.interpolate(mask, mask_shape, mode='bilinear', align_corners=False) # type: ignorereturn mask_octave.unsqueeze(1)class 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, 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, as- they respect output shape.+ r"""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, 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, as+ they respect output shape.Args:- num_features: (int) Number of features to detect. default = 500. In order to keep everything batchable,- output would always have num_features output, 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 response 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.- minima_are_also_good: (bool) if True, then both response function minima and maxima are detected- Useful for symmetric response functions like DoG or Hessian. Default is False+ num_features: Number of features to detect. In order to keep everything batchable,+ output would always have num_features output, even for completely homogeneous images.+ mr_size: multiplier for local feature scale compared to the detection scale.+ 6.0 is matching OpenCV 12.0 convention for SIFT.+ scale_pyr_module: generates scale pyramid. See :class:`~kornia.geometry.ScalePyramid` for details.+ Default: ScalePyramid(3, 1.6, 10).+ resp_module: calculates ``'cornerness'`` of the pixel.+ nms_module: outputs per-patch coordinates of the response maxima.+ See :class:`~kornia.geometry.ConvSoftArgmax3d` for details.+ ori_module: for local feature orientation estimation. Default:class:`~kornia.feature.PassLAF`,+ which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.+ aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,+ which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.+ minima_are_also_good: if True, then both response function minima and maxima are detected+ Useful for symmetric response functions like DoG or Hessian. Default is False"""def __init__(@@ -212,13 +214,14 @@ class ScaleSpaceDetector(nn.Module):detect function. Then affine shape and orientation.Args:- img (torch.Tensor): image to extract features with shape [BxCxHxW]- mask (torch.Tensor, optional): a mask with weights where to apply the- response function. The shape must be the same as the input image.+ img: image to extract features with shape [BxCxHxW]+ mask: a mask with weights where to apply the response function. The shape must be the same as+ the input image.Returns:- lafs (torch.Tensor): shape [BxNx2x3]. Detected local affine frames.- responses (torch.Tensor): shape [BxNx1]. Response function values for corresponding lafs"""+ lafs: shape [BxNx2x3]. Detected local affine frames.+ responses: shape [BxNx1]. Response function values for corresponding lafs+ """responses, lafs = self.detect(img, self.num_features, mask)lafs = self.aff(lafs, img)lafs = self.ori(lafs, img)diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 50c22c8b3..205290707 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -10,16 +10,13 @@ from kornia.geometry.conversions import pidef get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:- """Returns a weighted pooling kernel for SIFT descriptor+ r"""Returns a weighted pooling kernel for SIFT descriptor.Args:- ksize: (int): kernel_size+ ksize: kernel_size.Returns:- torch.Tensor: kernel-- Shape:- Output: :math: `(ksize,ksize)`+ the pooling kernel with shape :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,15 +25,14 @@ 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- and number of spatial bins.+ r"""Returns a tuple with SIFT parameters.Args:- patch_size: (int)- num_spatial_bins: (int)+ patch_size: the given patch size.+ num_spatial_bins: the ggiven number of spatial bins.Returns:- ksize, stride, pad: ints+ ksize, stride, pad."""ksize: int = 2 * int(patch_size / (num_spatial_bins + 1))stride: int = patch_size // num_spatial_bins@@ -53,25 +49,23 @@ def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tupclass SIFTDescriptor(nn.Module):- """- Module, which computes SIFT descriptors of given patches+ r"""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)- is computed+ patch_size: Input patch size in pixels.+ num_ang_bins: Number of angular bins.+ num_spatial_bins: Number of spatial bins.+ clipval:+ rootsift: if ``True``, RootSIFT (Arandjelović et. al, 2012) is computed.Returns:- torch.Tensor: SIFT descriptor of the patches+ SIFT descriptor of the patches with shape.Shape:- Input: (B, 1, num_spatial_bins, num_spatial_bins)- Output: (B, num_ang_bins * num_spatial_bins ** 2)- Examples::+ Example:>>> input = torch.rand(23, 1, 32, 32)>>> SIFT = SIFTDescriptor(32, 8, 4)>>> descs = SIFT(input) # 23x128@@ -194,5 +188,4 @@ def sift_describe(See :class:`~kornia.feature.SIFTDescriptor` for details."""-return SIFTDescriptor(patch_size, num_ang_bins, num_spatial_bins, rootsift, clipval)(input)diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex 6430c8aeb..ad5c3f73f 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -9,13 +9,13 @@ urls["hp_a"] = "https://github.com/yuruntian/SOSNet/raw/master/sosnet-weights/soclass SOSNet(nn.Module):- """128-dimensional SOSNet model definition for 32x32 patches.+ r"""128-dimensional SOSNet model definition for 32x32 patches.This is based on the original code from paper"SOSNet:Second Order Similarity Regularization for Local Descriptor Learning".Args:- pretrained (bool): Download and set pretrained weights to the model. Default: false.+ pretrained: Download and set pretrained weights to the model.Shape:- Input: (B, 1, 32, 32)diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.pyindex 338ad679a..0474af3c0 100644--- a/kornia/feature/tfeat.py+++ b/kornia/feature/tfeat.py@@ -16,18 +16,17 @@ urls[class TFeat(nn.Module):- """- Module, which computes TFeat descriptors of given grayscale patches of 32x32.+ r"""Module, which computes TFeat descriptors of given grayscale patches of 32x32.This is based on the original code from paper "Learning local feature descriptorswith triplets and shallow convolutional neural networks".See :cite:`TFeat2016` for more detailsArgs:- pretrained: (bool) Download and set pretrained weights to the model. Default: false.+ pretrained: Download and set pretrained weights to the model.Returns:- torch.Tensor: TFeat descriptor of the patches.+ TFeat descriptor of the patches.Shape:- Input: (B, 1, 32, 32)diff --git a/kornia/filters/canny.py b/kornia/filters/canny.pyindex 4f1a61252..59311b2de 100644--- a/kornia/filters/canny.py+++ b/kornia/filters/canny.py@@ -166,7 +166,6 @@ class Canny(nn.Module):eps: regularization number to avoid NaN during backprop.Returns:- Tuple[torch.Tensor, torch.Tensor]:- the canny edge magnitudes map, shape of :math:`(B,1,H,W)`.- the canny edge detection filtered by thresholds and hysteresis, shape of :math:`(B,1,H,W)`.diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.pyindex 3aa698af0..982006321 100644--- a/kornia/geometry/calibration/undistort.py+++ b/kornia/geometry/calibration/undistort.py@@ -44,19 +44,21 @@ def inverseTiltProjection(taux: torch.Tensor, tauy: torch.Tensor) -> torch.Tenso# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) -> torch.Tensor:- r"""Compensate for lens distortion a set of 2D image points. Radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`,+ r"""Compensate for lens distortion a set of 2D image points.++ Radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`,tangential :math:`(p_1, p_2)`, thin prism :math:`(s_1, s_2, s_3, s_4)`, and tilt :math:`(\tau_x, \tau_y)`distortion models are considered in this function.Args:- points (torch.Tensor): Input image points with shape :math:`(*, N, 2)`.- K (torch.Tensor): Intrinsic camera matrix with shape :math:`(*, 3, 3)`.- dist (torch.Tensor): Distortion coefficients+ points: Input image points with shape :math:`(*, N, 2)`.+ K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.+ dist: Distortion coefficients:math:`(k_1,k_2,p_1,p_2[,k_3[,k_4,k_5,k_6[,s_1,s_2,s_3,s_4[,\tau_x,\tau_y]]]])`. This isa vector with 4, 5, 8, 12 or 14 elements with shape :math:`(*, n)`Returns:- torch.Tensor: Undistorted 2D points with shape :math:`(*, N, 2)`.+ Undistorted 2D points with shape :math:`(*, N, 2)`."""assert points.dim() >= 2 and points.shape[-1] == 2assert K.shape[-2:] == (3, 3)diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.pyindex d1b3ce9b0..7ab8538f8 100644--- a/kornia/geometry/camera/perspective.py+++ b/kornia/geometry/camera/perspective.py@@ -8,13 +8,13 @@ def project_points(point_3d: torch.Tensor, camera_matrix: torch.Tensor) -> torchr"""Projects a 3d point onto the 2d camera plane.Args:- point3d (torch.Tensor): tensor containing the 3d points to be projected+ point3d: tensor containing the 3d points to be projectedto the camera plane. The shape of the tensor can be :math:`(*, 3)`.- camera_matrix (torch.Tensor): tensor containing the intrinsics camera+ camera_matrix: tensor containing the intrinsics cameramatrix. The tensor shape must be :math:`(*, 3, 3)`.Returns:- torch.Tensor: array of (u, v) cam coordinates with shape :math:`(*, 2)`.+ tensor of (u, v) cam coordinates with shape :math:`(*, 2)`."""if not isinstance(point_3d, torch.Tensor):raise TypeError("Input point_3d type is not a torch.Tensor. Got {}".format(type(point_3d)))@@ -61,19 +61,18 @@ def unproject_points(Transform coordinates in the pixel frame to the camera frame.Args:- point2d (torch.Tensor): tensor containing the 2d to be projected to+ point2d: tensor containing the 2d to be projected toworld coordinates. The shape of the tensor can be :math:`(*, 2)`.- depth (torch.Tensor): tensor containing the depth value of each 2d+ depth: tensor containing the depth value of each 2dpoints. The tensor shape must be equal to point2d :math:`(*, 1)`.- camera_matrix (torch.Tensor): tensor containing the intrinsics camera+ camera_matrix: tensor containing the intrinsics cameramatrix. The tensor shape must be :math:`(*, 3, 3)`.- normalize (bool, optional): whether to normalize the pointcloud. This+ normalize: whether to normalize the pointcloud. Thismust be set to `True` when the depth is represented as the Euclidean- ray length from the camera position. Default is `False`.+ ray length from the camera position.Returns:- torch.Tensor: tensor of (x, y, z) world coordinates with shape- :math:`(*, 3)`.+ tensor of (x, y, z) world coordinates with shape :math:`(*, 3)`."""if not isinstance(point_2d, torch.Tensor):raise TypeError("Input point_2d type is not a torch.Tensor. Got {}".format(type(point_2d)))diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex 97fe30631..b7ebf7d8c 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -9,14 +9,12 @@ class PinholeCamera:r"""Class that represents a Pinhole Camera model.Args:- intrinsics (torch.Tensor): tensor with shape :math:`(B, 4, 4)`+ intrinsics: tensor with shape :math:`(B, 4, 4)`containing the full 4x4 camera calibration matrix.- extrinsics (torch.Tensor): tensor with shape :math:`(B, 4, 4)`+ extrinsics: tensor with shape :math:`(B, 4, 4)`containing the full 4x4 rotation-translation matrix.- height (torch.Tensor): tensor with shape :math:`(B)` containing the- image height.- width (torch.Tensor): tensor with shape :math:`(B)` containing the image- width.+ height: tensor with shape :math:`(B)` containing the image height.+ width: tensor with shape :math:`(B)` containing the image width... note::We assume that the class attributes are in batch form in order to take@@ -66,7 +64,7 @@ class PinholeCamera:r"""The full 4x4 intrinsics matrix.Returns:- torch.Tensor: tensor of shape :math:`(B, 4, 4)`+ tensor of shape :math:`(B, 4, 4)`."""assert self._check_valid_params(self._intrinsics, "intrinsics")return self._intrinsics@@ -76,7 +74,7 @@ class PinholeCamera:r"""The full 4x4 extrinsics matrix.Returns:- torch.Tensor: tensor of shape :math:`(B, 4, 4)`+ tensor of shape :math:`(B, 4, 4)`."""assert self._check_valid_params(self._extrinsics, "extrinsics")return self._extrinsics@@ -86,7 +84,7 @@ class PinholeCamera:r"""Returns the batch size of the storage.Returns:- int: scalar with the batch size+ scalar with the batch size."""return self.intrinsics.shape[0]@@ -95,7 +93,7 @@ class PinholeCamera:r"""Returns the focal lenght in the x-direction.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`."""return self.intrinsics[..., 0, 0]@@ -104,7 +102,7 @@ class PinholeCamera:r"""Returns the focal length in the y-direction.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`."""return self.intrinsics[..., 1, 1]@@ -113,7 +111,7 @@ class PinholeCamera:r"""Returns the x-coordinate of the principal point.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`."""return self.intrinsics[..., 0, 2]@@ -122,7 +120,7 @@ class PinholeCamera:r"""Returns the y-coordinate of the principal point.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`."""return self.intrinsics[..., 1, 2]@@ -131,15 +129,13 @@ class PinholeCamera:r"""Returns the x-coordinate of the translation vector.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`."""return self.extrinsics[..., 0, -1]@tx.setterdef tx(self, value) -> 'PinholeCamera':- r"""Set the x-coordinate of the translation vector with the given- value.- """+ r"""Set the x-coordinate of the translation vector with the given value."""self.extrinsics[..., 0, -1] = valuereturn self@@ -148,15 +144,13 @@ class PinholeCamera:r"""Returns the y-coordinate of the translation vector.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`."""return self.extrinsics[..., 1, -1]@ty.setterdef ty(self, value) -> 'PinholeCamera':- r"""Set the y-coordinate of the translation vector with the given- value.- """+ r"""Set the y-coordinate of the translation vector with the given value."""self.extrinsics[..., 1, -1] = valuereturn self@@ -165,15 +159,13 @@ class PinholeCamera:r"""Returns the z-coordinate of the translation vector.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`."""return self.extrinsics[..., 2, -1]@tz.setterdef tz(self, value) -> 'PinholeCamera':- r"""Set the y-coordinate of the translation vector with the given- value.- """+ r"""Set the y-coordinate of the translation vector with the given value."""self.extrinsics[..., 2, -1] = valuereturn self@@ -182,7 +174,7 @@ class PinholeCamera:r"""Returns the 3x4 rotation-translation matrix.Returns:- torch.Tensor: tensor of shape :math:`(B, 3, 4)`+ tensor of shape :math:`(B, 3, 4)`."""return self.extrinsics[..., :3, :4]@@ -191,7 +183,7 @@ class PinholeCamera:r"""Returns the 3x3 camera matrix containing the intrinsics.Returns:- torch.Tensor: tensor of shape :math:`(B, 3, 3)`+ tensor of shape :math:`(B, 3, 3)`."""return self.intrinsics[..., :3, :3]@@ -200,7 +192,7 @@ class PinholeCamera:r"""Returns the 3x3 rotation matrix from the extrinsics.Returns:- torch.Tensor: tensor of shape :math:`(B, 3, 3)`+ tensor of shape :math:`(B, 3, 3)`."""return self.extrinsics[..., :3, :3]@@ -209,7 +201,7 @@ class PinholeCamera:r"""Returns the translation vector from the extrinsics.Returns:- torch.Tensor: tensor of shape :math:`(B, 3, 1)`+ tensor of shape :math:`(B, 3, 1)`."""return self.extrinsics[..., :3, -1:]@@ -225,7 +217,7 @@ class PinholeCamera:r"""Returns the inverse of the 4x4 instrisics matrix.Returns:- torch.Tensor: tensor of shape :math:`(B, 4, 4)`+ tensor of shape :math:`(B, 4, 4)`."""return self.intrinsics.inverse()@@ -233,12 +225,12 @@ class PinholeCamera:r"""Scales the pinhole model.Args:- scale_factor (torch.Tensor): a tensor with the scale factor. It has+ scale_factor: a tensor with the scale factor. It hasto be broadcastable with class members. The expected shape is:math:`(B)` or :math:`(1)`.Returns:- PinholeCamera: the camera model with scaled parameters.+ the camera model with scaled parameters."""# scale the intrinsic parametersintrinsics: torch.Tensor = self.intrinsics.clone()@@ -255,12 +247,12 @@ class PinholeCamera:r"""Scales the pinhole model in-place.Args:- scale_factor (torch.Tensor): a tensor with the scale factor. It has+ scale_factor: a tensor with the scale factor. It hasto be broadcastable with class members. The expected shape is:math:`(B)` or :math:`(1)`.Returns:- PinholeCamera: the camera model with scaled parameters.+ the camera model with scaled parameters."""# scale the intrinsic parametersself.intrinsics[..., 0, 0] *= scale_factor@@ -323,8 +315,7 @@ class PinholeCamerasList(PinholeCamera):size and :math:`N` is the numbers of cameras (in this case two).Args:- pinholes_list (Iterable[PinholeCamera]): a python tuple or list- containg a set of `PinholeCamera` instances.+ pinholes_list: a python tuple or list containg a set of `PinholeCamera` instances."""def __init__(self, pinholes_list: Iterable[PinholeCamera]) -> None:@@ -367,7 +358,7 @@ class PinholeCamerasList(PinholeCamera):return PinholeCamera(intrinsics, extrinsics, height, width)-def pinhole_matrix(pinholes, eps=1e-6):+def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:r"""Function that returns the pinhole matrix from a pinhole model.. note::@@ -375,10 +366,10 @@ def pinhole_matrix(pinholes, eps=1e-6)::attr:`kornia.PinholeCamera.camera_matrix`.Args:- pinholes (Tensor): tensor of pinhole models.+ pinholes: tensor of pinhole models.Returns:- Tensor: tensor of pinhole matrices.+ tensor of pinhole matrices.Shape:- Input: :math:`(N, 12)`@@ -410,7 +401,7 @@ def pinhole_matrix(pinholes, eps=1e-6):return k-def inverse_pinhole_matrix(pinhole, eps=1e-6):+def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:r"""Returns the inverted pinhole matrix from a pinhole model.. note::@@ -418,10 +409,10 @@ def inverse_pinhole_matrix(pinhole, eps=1e-6)::attr:`kornia.PinholeCamera.intrinsics_inverse()`.Args:- pinholes (Tensor): tensor with pinhole models.+ pinholes: tensor with pinhole models.Returns:- Tensor: tensor of inverted pinhole matrices.+ tensor of inverted pinhole matrices.Shape:- Input: :math:`(N, 12)`@@ -453,7 +444,7 @@ def inverse_pinhole_matrix(pinhole, eps=1e-6):return k-def scale_pinhole(pinholes, scale):+def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:r"""Scales the pinhole matrix for each pinhole model... note::@@ -461,11 +452,11 @@ def scale_pinhole(pinholes, scale)::attr:`kornia.PinholeCamera.scale()`.Args:- pinholes (Tensor): tensor with the pinhole model.- scale (Tensor): tensor of scales.+ pinholes: tensor with the pinhole model.+ scale: tensor of scales.Returns:- Tensor: tensor of scaled pinholes.+ tensor of scaled pinholes.Shape:- Input: :math:`(N, 12)` and :math:`(N, 1)`@@ -489,24 +480,24 @@ def scale_pinhole(pinholes, scale):return pinholes_scaled-def get_optical_pose_base(pinholes):+def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:"""Get extrinsic transformation matrices for pinholesArgs:- pinholes (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz]+ pinholes: tensor of form [fx fy cx cy h w rx ry rz tx ty tz]of size (N, 12).Returns:- Tensor: tensor of extrinsic transformation matrices of size (N, 4, 4).+ tensor of extrinsic transformation matrices of size (N, 4, 4)."""assert len(pinholes.shape) == 2 and pinholes.shape[1] == 12, pinholes.shapeoptical_pose_parent = pinholes[..., 6:]# TODO: where is rtvec_to_pose?- return rtvec_to_pose(optical_pose_parent)+ return rtvec_to_pose(optical_pose_parent) # type: ignore-def homography_i_H_ref(pinhole_i, pinhole_ref):+def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> torch.Tensor:r"""Homography from reference to ith pinhole.. note::@@ -527,12 +518,11 @@ def homography_i_H_ref(pinhole_i, pinhole_ref):H_{ref}^{i} = K_{i} * T_{ref}^{i} * K_{ref}^{-1}Args:- pinhole_i (Tensor): tensor with pinhole model for ith frame.- pinhole_ref (Tensor): tensor with pinhole model for reference frame.+ pinhole_i: tensor with pinhole model for ith frame.+ pinhole_ref: tensor with pinhole model for reference frame.Returns:- Tensor: tensors that convert depth points (u, v, d) from- pinhole_ref to pinhole_i.+ tensors that convert depth points (u, v, d) from pinhole_ref to pinhole_i.Shape:- Input: :math:`(N, 12)` and :math:`(N, 12)`@@ -544,7 +534,7 @@ def homography_i_H_ref(pinhole_i, pinhole_ref):homography_i_H_ref(pinhole_i, pinhole_ref) # Nx4x4"""# TODO: Add doctest once having `rtvec_to_pose`.- assert len(pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12, pinhole.shape+ assert len(pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12, pinhole_i.shapeassert pinhole_i.shape == pinhole_ref.shape, pinhole_ref.shapei_pose_base = get_optical_pose_base(pinhole_i)ref_pose_base = get_optical_pose_base(pinhole_ref)@@ -560,14 +550,12 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: tr"""Transform coordinates in the pixel frame to the camera frame.Args:- depth (torch.Tensor): the source depth maps. Shape must be Bx1xHxW.- intrinsics_inv (torch.Tensor): the inverse intrinsics camera matrix.- Shape must be Bx4x4.- pixel_coords (torch.Tensor): the grid with the homogeneous camera- coordinates. Shape must be BxHxWx3.+ depth: the source depth maps. Shape must be Bx1xHxW.+ intrinsics_inv: the inverse intrinsics camera matrix. Shape must be Bx4x4.+ pixel_coords: the grid with the homogeneous camera coordinates. Shape must be BxHxWx3.Returns:- torch.Tensor: array of (u, v, 1) cam coordinates with shape BxHxWx3.+ tensor of (u, v, 1) cam coordinates with shape BxHxWx3."""if not len(depth.shape) == 4 and depth.shape[1] == 1:raise ValueError("Input depth has to be in the shape of " "Bx1xHxW. Got {}".format(depth.shape))@@ -583,17 +571,16 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: t# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L43-def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: Optional[float] = 1e-6) -> torch.Tensor:+def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:r"""Transform coordinates in the camera frame to the pixel frame.Args:- cam_coords (torch.Tensor): pixel coordinates defined in the first- camera coordinates system. Shape must be BxHxWx3.- dst_proj_src (torch.Tensor): the projection matrix between the+ cam_coords: pixel coordinates defined in the first camera coordinates system. Shape must be BxHxWx3.+ dst_proj_src: the projection matrix between thereference and the non reference camera frame. Shape must be Bx4x4.Returns:- torch.Tensor: array of [-1, 1] coordinates of shape BxHxWx2.+ tensor of [-1, 1] coordinates of shape BxHxWx2."""if not len(cam_coords_src.shape) == 4 and cam_coords_src.shape[3] == 3:raise ValueError(diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.pyindex 469417847..66f703635 100644--- a/kornia/geometry/camera/stereo.py+++ b/kornia/geometry/camera/stereo.py@@ -7,11 +7,12 @@ from kornia.utils.grid import create_meshgridclass StereoException(Exception):def __init__(self, msg: str, *args, **kwargs):- """- Custom exception for the :module:`~kornia.geometry.camera.stereo` module. Adds a general helper module- redirecting the user to the proper documentation site.+ r"""Custom exception for the :module:`~kornia.geometry.camera.stereo` module.++ Adds a general helper module redirecting the user to the proper documentation site.+Args:- msg (str): Custom message to add to the general message.+ msg: Custom message to add to the general message.*args:**kwargs:"""@@ -27,14 +28,13 @@ class StereoException(Exception):class StereoCamera:def __init__(self, rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor):- """- Class representing a horizontal stereo camera setup.+ r"""Class representing a horizontal stereo camera setup.Args:- rectified_left_camera (torch.Tensor): The rectified left camera projection matrix- of shape :math:`(B, 3, 4)`- rectified_right_camera (torch.Tensor): The rectified right camera projection matrix- of shape :math:`(B, 3, 4)`+ rectified_left_camera: The rectified left camera projection matrix+ of shape :math:`(B, 3, 4)`+ rectified_right_camera: The rectified right camera projection matrix+ of shape :math:`(B, 3, 4)`"""self._check_stereo_camera(rectified_left_camera, rectified_right_camera)self.rectified_left_camera: torch.Tensor = rectified_left_camera@@ -47,13 +47,13 @@ class StereoCamera:@staticmethoddef _check_stereo_camera(rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor):- """- Utility function to ensure user specified correct camera matrices.+ r"""Utility function to ensure user specified correct camera matrices.+Args:- rectified_left_camera (torch.Tensor): The rectified left camera projection matrix- of shape :math:`(B, 3, 4)`- rectified_right_camera (torch.Tensor): The rectified right camera projection matrix- of shape :math:`(B, 3, 4)`+ rectified_left_camera: The rectified left camera projection matrix+ of shape :math:`(B, 3, 4)`+ rectified_right_camera: The rectified right camera projection matrix+ of shape :math:`(B, 3, 4)`"""# Ensure correct shapesif len(rectified_left_camera.shape) != 3:@@ -112,27 +112,31 @@ class StereoCamera:r"""Returns the batch size of the storage.Returns:- int: scalar with the batch size+ scalar with the batch size"""return self.rectified_left_camera.shape[0]@propertydef fx(self) -> torch.Tensor:- r"""Returns the focal length in the x-direction. Note that the focal lengths of the rectified left and right+ r"""Returns the focal length in the x-direction.++ Note that the focal lengths of the rectified left and rightcamera are assumed to be equal.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`"""return self.rectified_left_camera[..., 0, 0]@propertydef fy(self) -> torch.Tensor:- r"""Returns the focal length in the y-direction. Note that the focal lengths of the rectified left and right+ r"""Returns the focal length in the y-direction.++ Note that the focal lengths of the rectified left and rightcamera are assumed to be equal.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`"""return self.rectified_left_camera[..., 1, 1]@@ -141,7 +145,7 @@ class StereoCamera:r"""Returns the x-coordinate of the principal point for the left camera.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`"""return self.rectified_left_camera[..., 0, 2]@@ -150,50 +154,50 @@ class StereoCamera:r"""Returns the x-coordinate of the principal point for the right camera.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`"""return self.rectified_right_camera[..., 0, 2]@propertydef cy(self) -> torch.Tensor:- r"""Returns the y-coordinate of the principal point. Note that the y-coordinate of the principal points+ r"""Returns the y-coordinate of the principal point.++ Note that the y-coordinate of the principal pointsis assumed to be equal for the left and right camera.Returns:- torch.Tensor: tensor of shape :math:`(B)`+ tensor of shape :math:`(B)`"""return self.rectified_left_camera[..., 1, 2]@propertydef tx(self) -> torch.Tensor:- """- The horizontal baseline between the two cameras.+ r"""The horizontal baseline between the two cameras.Returns:- torch.tensor: Tensor of shape :math:`(B)`+ Tensor of shape :math:`(B)`"""return -self.rectified_right_camera[..., 0, 3] / self.fx@propertydef Q(self) -> torch.Tensor:- """- The Q matrix of the horizontal stereo setup. This matrix is used for reprojecting a disparity tensor to+ r"""The Q matrix of the horizontal stereo setup.++ This matrix is used for reprojecting a disparity tensor tothe corresponding point cloud. Note that this is in a general form that allows different focallengths in the x and y direction.Return:- torch.Tensor: The Q matrix of shape :math:`(B, 4, 4)`.+ The Q matrix of shape :math:`(B, 4, 4)`."""return self._Q_matrixdef _init_Q_matrix(self) -> torch.Tensor:- """- Initialized the Q matrix of the horizontal stereo setup. See the Q property.+ r"""Initialized the Q matrix of the horizontal stereo setup. See the Q property.Returns:- torch.Tensor: The Q matrix of shape :math:`(B, 4, 4)`.-+ The Q matrix of shape :math:`(B, 4, 4)`."""Q = torch.zeros((self.batch_size, 4, 4), device=self.device, dtype=self.dtype)baseline: torch.Tensor = -self.tx@@ -207,24 +211,22 @@ class StereoCamera:return Qdef reproject_disparity_to_3D(self, disparity_tensor: torch.Tensor) -> torch.Tensor:- """- Reproject the disparity tensor to a 3D point cloud.+ r"""Reproject the disparity tensor to a 3D point cloud.Args:- disparity_tensor (torch.Tensor): Disparity tensor of shape :math:`(B, 1, H, W)`.+ disparity_tensor: Disparity tensor of shape :math:`(B, 1, H, W)`.Returns:- torch.Tensor: The 3D point cloud of shape :math:`(B, H, W, 3)`+ The 3D point cloud of shape :math:`(B, H, W, 3)`"""return reproject_disparity_to_3D(disparity_tensor, self.Q)def _check_disparity_tensor(disparity_tensor: torch.Tensor):- """- Utility function to ensure correct user provided correct disparity tensor.+ r"""Utility function to ensure correct user provided correct disparity tensor.Args:- disparity_tensor (torch.Tensor): The disparity tensor of shape :math:`(B, 1, H, W)`.+ disparity_tensor: The disparity tensor of shape :math:`(B, 1, H, W)`."""if not isinstance(disparity_tensor, torch.Tensor):raise StereoException(@@ -248,10 +250,10 @@ def _check_disparity_tensor(disparity_tensor: torch.Tensor):def _check_Q_matrix(Q_matrix: torch.Tensor):- """- Utility function to ensure Q matrix is of correct form.+ r"""Utility function to ensure Q matrix is of correct form.+Args:- Q_matrix (torch.Tensor): The Q matrix for reprojecting disparity to a point cloud of shape :math:`(B, 4, 4)`+ Q_matrix: The Q matrix for reprojecting disparity to a point cloud of shape :math:`(B, 4, 4)`"""if not isinstance(Q_matrix, torch.Tensor):@@ -272,15 +274,14 @@ def _check_Q_matrix(Q_matrix: torch.Tensor):def reproject_disparity_to_3D(disparity_tensor: torch.Tensor, Q_matrix: torch.Tensor) -> torch.Tensor:- """- Reproject the disparity tensor to a 3D point cloud.+ r"""Reproject the disparity tensor to a 3D point cloud.Args:- disparity_tensor (torch.Tensor): Disparity tensor of shape :math:`(B, 1, H, W)`.- Q_matrix (torch.Tensor): Tensor of Q matrices of shapes :math:`(B, 4, 4)`.+ disparity_tensor: Disparity tensor of shape :math:`(B, 1, H, W)`.+ Q_matrix: Tensor of Q matrices of shapes :math:`(B, 4, 4)`.Returns:- torch.Tensor: The 3D point cloud of shape :math:`(B, H, W, 3)`+ The 3D point cloud of shape :math:`(B, H, W, 3)`"""_check_Q_matrix(Q_matrix)_check_disparity_tensor(disparity_tensor)diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 341aa49cc..22dca74cd 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -42,10 +42,10 @@ def rad2deg(tensor: torch.Tensor) -> torch.Tensor:r"""Function that converts angles from radians to degrees.Args:- tensor (torch.Tensor): Tensor of arbitrary shape.+ tensor: Tensor of arbitrary shape.Returns:- torch.Tensor: Tensor with same shape as input.+ Tensor with same shape as input.Example:>>> input = torch.tensor(3.1415926535) * torch.rand(1, 3, 3)@@ -61,13 +61,12 @@ def deg2rad(tensor: torch.Tensor) -> torch.Tensor:r"""Function that converts angles from degrees to radians.Args:- tensor (torch.Tensor): Tensor of arbitrary shape.+ tensor: Tensor of arbitrary shape.Returns:- torch.Tensor: tensor with same shape as input.-- Examples::+ tensor with same shape as input.+ Examples:>>> input = 360. * torch.rand(1, 3, 3)>>> output = deg2rad(input)"""@@ -81,11 +80,11 @@ def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> Tuple[torch.Tensor, torch.r"""Function that converts polar coordinates to cartesian coordinates.Args:- rho (torch.Tensor): Tensor of arbitrary shape.- phi (torch.Tensor): Tensor of same arbitrary shape.+ rho: Tensor of arbitrary shape.+ phi: Tensor of same arbitrary shape.Returns:- torch.Tensor, torch.Tensor: Tensor with same shape as input.+ Tensor with same shape as input.Example:>>> rho = torch.rand(1, 3, 3)@@ -104,12 +103,12 @@ def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1.0e-8) -> Tuple[tor"""Function that converts cartesian coordinates to polar coordinates.Args:- rho (torch.Tensor): Tensor of arbitrary shape.- phi (torch.Tensor): Tensor of same arbitrary shape.- eps (float): To avoid division by zero. Default is 1e-8+ rho: Tensor of arbitrary shape.+ phi: Tensor of same arbitrary shape.+ eps: To avoid division by zero.Returns:- torch.Tensor, torch.Tensor: Tensor with same shape as input.+ Tensor with same shape as input.Example:>>> x = torch.rand(1, 3, 3)@@ -127,8 +126,14 @@ def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1.0e-8) -> Tuple[tordef convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:r"""Function that converts points from homogeneous to Euclidean space.- Examples::+ Args:+ points: the points to be transformed.+ eps: to avoid division by zero.++ Returns:+ the points in Euclidean space.+ Examples:>>> input = torch.rand(2, 4, 3) # BxNx3>>> output = convert_points_from_homogeneous(input) # BxNx2"""@@ -153,8 +158,13 @@ def convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) ->def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:r"""Function that converts points from Euclidean to homogeneous space.- Examples::+ Args:+ points: the points to be transformed.++ Returns:+ the points in homogeneous coordinates.+ Examples:>>> input = torch.rand(2, 4, 3) # BxNx3>>> output = convert_points_to_homogeneous(input) # BxNx4"""@@ -173,10 +183,15 @@ def _convert_affinematrix_to_homography_impl(A: torch.Tensor) -> torch.Tensor:def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:- r"""Function that converts batch of affine matrices from [Bx2x3] to [Bx3x3].+ r"""Function that converts batch of affine matrices.- Examples::+ Args:+ A: the affine matrix with shape :math:`(B,2,3)`.++ Returns:+ the homography matrix with shape of :math:`(B,3,3)`.+ Examples:>>> input = torch.rand(2, 2, 3) # Bx2x3>>> output = convert_affinematrix_to_homography(input) # Bx3x3"""@@ -188,10 +203,15 @@ def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:- r"""Function that converts batch of affine matrices from [Bx3x4] to [Bx4x4].+ r"""Function that converts batch of 3d affine matrices.- Examples::+ Args:+ A: the affine matrix with shape :math:`(B,3,4)`.+ Returns:+ the homography matrix with shape of :math:`(B,4,4)`.++ Examples:>>> input = torch.rand(2, 3, 4) # Bx3x4>>> output = convert_affinematrix_to_homography3d(input) # Bx4x4"""@@ -203,13 +223,13 @@ def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:- r"""Convert 3d vector of axis-angle rotation to 3x3 rotation matrix+ r"""Convert 3d vector of axis-angle rotation to 3x3 rotation matrix.Args:- angle_axis (torch.Tensor): tensor of 3d vector of axis-angle rotations.+ angle_axis: tensor of 3d vector of axis-angle rotations.Returns:- torch.Tensor: tensor of 3x3 rotation matrices.+ tensor of 3x3 rotation matrices.Shape:- Input: :math:`(N, 3)`@@ -283,10 +303,10 @@ def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor) -> torch.Tensorr"""Convert 3x3 rotation matrix to Rodrigues vector.Args:- rotation_matrix (torch.Tensor): rotation matrix.+ rotation_matrix: rotation matrix.Returns:- torch.Tensor: Rodrigues vector transformation.+ Rodrigues vector transformation.Shape:- Input: :math:`(N, 3, 3)`@@ -316,13 +336,12 @@ def rotation_matrix_to_quaternion(The (x, y, z, w) order is going to be deprecated in favor of efficiency.Args:- rotation_matrix (torch.Tensor): the rotation matrix to convert.- eps (float): small value to avoid zero division. Default: 1e-8.- order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.- Note: 'xyzw' will be deprecated in favor of 'wxyz'.+ rotation_matrix: the rotation matrix to convert.+ eps: small value to avoid zero division.+ order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.Return:- torch.Tensor: the rotation in quaternion.+ the rotation in quaternion.Shape:- Input: :math:`(*, 3, 3)`@@ -413,13 +432,12 @@ def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.0e-12) -> torcThe quaternion should be in (x, y, z, w) format.Args:- quaternion (torch.Tensor): a tensor containing a quaternion to be- normalized. The tensor can be of shape :math:`(*, 4)`.- eps (Optional[bool]): small value to avoid division by zero.- Default: 1e-12.+ quaternion: a tensor containing a quaternion to be normalized.+ The tensor can be of shape :math:`(*, 4)`.+ eps: small value to avoid division by zero.Return:- torch.Tensor: the normalized quaternion of shape :math:`(*, 4)`.+ the normalized quaternion of shape :math:`(*, 4)`.Example:>>> quaternion = torch.tensor((1., 0., 1., 0.))@@ -447,13 +465,12 @@ def quaternion_to_rotation_matrix(The quaternion should be in (x, y, z, w) or (w, x, y, z) format.Args:- quaternion (torch.Tensor): a tensor containing a quaternion to be- converted. The tensor can be of shape :math:`(*, 4)`.- order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.- Note: 'xyzw' will be deprecated in favor of 'wxyz'.+ quaternion: a tensor containing a quaternion to be converted.+ The tensor can be of shape :math:`(*, 4)`.+ order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.Return:- torch.Tensor: the rotation matrix of shape :math:`(*, 3, 3)`.+ the rotation matrix of shape :math:`(*, 3, 3)`.Example:>>> quaternion = torch.tensor((0., 0., 0., 1.))@@ -533,12 +550,11 @@ def quaternion_to_angle_axis(Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.hArgs:- quaternion (torch.Tensor): tensor with quaternions.- order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.- Note: 'xyzw' will be deprecated in favor of 'wxyz'.+ quaternion: tensor with quaternions.+ order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.Return:- torch.Tensor: tensor with angle axis of rotation.+ tensor with angle axis of rotation.Shape:- Input: :math:`(*, 4)` where `*` means, any number of dimensions@@ -607,13 +623,12 @@ def quaternion_log_to_exp(The quaternion should be in (x, y, z, w) or (w, x, y, z) format.Args:- quaternion (torch.Tensor): a tensor containing a quaternion to be- converted. The tensor can be of shape :math:`(*, 3)`.- order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.- Note: 'xyzw' will be deprecated in favor of 'wxyz'.+ quaternion: a tensor containing a quaternion to be converted.+ The tensor can be of shape :math:`(*, 3)`.+ order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.Return:- torch.Tensor: the quaternion exponential map of shape :math:`(*, 4)`.+ the quaternion exponential map of shape :math:`(*, 4)`.Example:>>> quaternion = torch.tensor((0., 0., 0.))@@ -663,14 +678,13 @@ def quaternion_exp_to_log(The quaternion should be in (x, y, z, w) format.Args:- quaternion (torch.Tensor): a tensor containing a quaternion to be- converted. The tensor can be of shape :math:`(*, 4)`.- eps (float): A small number for clamping.- order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.- Note: 'xyzw' will be deprecated in favor of 'wxyz'.+ quaternion: a tensor containing a quaternion to be converted.+ The tensor can be of shape :math:`(*, 4)`.+ eps: A small number for clamping.+ order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.Return:- torch.Tensor: the quaternion log map of shape :math:`(*, 3)`.+ the quaternion log map of shape :math:`(*, 3)`.Example:>>> quaternion = torch.tensor((1., 0., 0., 0.))@@ -731,12 +745,11 @@ def angle_axis_to_quaternion(Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.hArgs:- angle_axis (torch.Tensor): tensor with angle axis.- order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.- Note: 'xyzw' will be deprecated in favor of 'wxyz'.+ angle_axis: tensor with angle axis.+ order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.Return:- torch.Tensor: tensor with quaternion.+ tensor with quaternion.Shape:- Input: :math:`(*, 3)` where `*` means, any number of dimensions@@ -808,14 +821,13 @@ def normalize_pixel_coordinates(Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).Args:- 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).+ pixel_coordinates: the grid with pixel coordinates. Shape can be :math:`(*, 2)`.+ width: the maximum width in the x-axis.+ height: the maximum height in the y-axis.+ eps: safe division by zero.Return:- torch.Tensor: the normalized pixel coordinates.+ the normalized pixel coordinates."""if pixel_coordinates.shape[-1] != 2:raise ValueError("Input pixel_coordinates must be of shape (*, 2). " "Got {}".format(pixel_coordinates.shape))@@ -839,18 +851,16 @@ def denormalize_pixel_coordinates() -> torch.Tensor:r"""Denormalize pixel coordinates.- The input is assumed to be -1 if on extreme left, 1 if on- extreme right (x = w-1).+ The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1).Args:- 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).+ pixel_coordinates: the normalized grid coordinates. Shape can be :math:`(*, 2)`.+ width: the maximum width in the x-axis.+ height: the maximum height in the y-axis.+ eps: safe division by zero.Return:- torch.Tensor: the denormalized pixel coordinates.+ the denormalized pixel coordinates."""if pixel_coordinates.shape[-1] != 2:raise ValueError("Input pixel_coordinates must be of shape (*, 2). " "Got {}".format(pixel_coordinates.shape))@@ -874,15 +884,14 @@ def normalize_pixel_coordinates3d(Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).Args:- 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).+ pixel_coordinates: the grid with pixel coordinates. Shape can be :math:`(*, 3)`.+ depth: the maximum depth in the z-axis.+ height: the maximum height in the y-axis.+ width: the maximum width in the x-axis.+ eps: safe division by zero.Return:- torch.Tensor: the normalized pixel coordinates.+ the normalized pixel coordinates."""if pixel_coordinates.shape[-1] != 3:raise ValueError("Input pixel_coordinates must be of shape (*, 3). " "Got {}".format(pixel_coordinates.shape))@@ -903,20 +912,17 @@ def denormalize_pixel_coordinates3d() -> torch.Tensor:r"""Denormalize pixel coordinates.- The input is assumed to be -1 if on extreme left, 1 if on- extreme right (x = w-1).+ The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1).Args:- 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).-+ pixel_coordinates: the normalized grid coordinates. Shape can be :math:`(*, 3)`.+ depth: the maximum depth in the x-axis.+ height: the maximum height in the y-axis.+ width: the maximum width in the x-axis.+ eps: safe division by zero.Return:- torch.Tensor: the denormalized pixel coordinates.+ the denormalized pixel coordinates."""if pixel_coordinates.shape[-1] != 3:raise ValueError("Input pixel_coordinates must be of shape (*, 3). " "Got {}".format(pixel_coordinates.shape))diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex e85e72d1f..3da3c20e5 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -23,19 +23,17 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin"""Compute a 3d point per pixel given its depth value and the camera intrinsics.Args:- depth (torch.Tensor): image tensor containing a depth value per pixel.- camera_matrix (torch.Tensor): tensor containing the camera intrinsics.- normalize_points (bool): whether to normalise the pointcloud. This- must be set to `True` when the depth is represented as the Euclidean- ray length from the camera position. Default is `False`.+ depth: image tensor containing a depth value per pixel.+ camera_matrix: tensor containing the camera intrinsics.+ normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is+ represented as the Euclidean ray length from the camera position.Shape:- Input: :math:`(B, 1, H, W)` and :math:`(B, 3, 3)`- Output: :math:`(B, 3, H, W)`Return:- torch.Tensor: tensor with a 3d point per pixel of the same resolution as the input.-+ tensor with a 3d point per pixel of the same resolution as the input."""if not isinstance(depth, torch.Tensor):raise TypeError(f"Input depht type is not a torch.Tensor. Got {type(depth)}.")@@ -70,19 +68,17 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize"""Compute the normal surface per pixel.Args:- depth (torch.Tensor): image tensor containing a depth value per pixel.- camera_matrix (torch.Tensor): tensor containing the camera intrinsics.- normalize_points (bool): whether to normalise the pointcloud. This- must be set to `True` when the depth is represented as the Euclidean- ray length from the camera position. Default is `False`.+ depth: image tensor containing a depth value per pixel.+ camera_matrix: tensor containing the camera intrinsics.+ normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is+ represented as the Euclidean ray length from the camera position.Shape:- Input: :math:`(B, 1, H, W)` and :math:`(B, 3, 3)`- Output: :math:`(B, 3, H, W)`Return:- torch.Tensor: tensor with a normal surface vector per pixel of the same resolution as the input.-+ tensor with a normal surface vector per pixel of the same resolution as the input."""if not isinstance(depth, torch.Tensor):raise TypeError(f"Input depht type is not a torch.Tensor. Got {type(depth)}.")@@ -122,17 +118,15 @@ def warp_frame_depth(image plane.Args:- image_src (torch.Tensor): image tensor in the source frame with shape (BxDxHxW).- depth_dst (torch.Tensor): depth tensor in the destination frame with shape (Bx1xHxW).- src_trans_dst (torch.Tensor): transformation matrix from destination to source with shape (Bx4x4).- camera_matrix (torch.Tensor): tensor containing the camera intrinsics with shape (Bx3x3).- normalize_points (bool): whether to normalise the pointcloud. This- must be set to `True` when the depth is represented as the Euclidean- ray length from the camera position. Default is `False`.+ image_src: image tensor in the source frame with shape :math:`(B,D,H,W)`.+ depth_dst: depth tensor in the destination frame with shape :math:`(B,1,H,W)`.+ src_trans_dst: transformation matrix from destination to source with shape :math:`(B,4,4)`.+ camera_matrix: tensor containing the camera intrinsics with shape :math:`(B,3,3)`.+ normalize_points: whether to normalise the pointcloud. This must be set to ``True`` when the depth+ is represented as the Euclidean ray length from the camera position.Return:- torch.Tensor: the warped tensor in the source frame with shape (Bx3xHxW).-+ the warped tensor in the source frame with shape :math:`(B,3,H,W)`."""if not isinstance(image_src, torch.Tensor):raise TypeError(f"Input image_src type is not a torch.Tensor. Got {type(image_src)}.")@@ -186,16 +180,12 @@ class DepthWarper(nn.Module):I_{src} = \\omega(I_{dst}, P_{src}^{\{dst\}}, D_{src})Args:- pinholes_dst (PinholeCamera): the pinhole models for the destination- frame.- height (int): the height of the image to warp.- width (int): the width of the image to warp.- mode (str): interpolation mode to calculate output values- 'bilinear' | 'nearest'. Default: 'bilinear'.- padding_mode (str): padding mode for outside grid values- 'zeros' | 'border' | 'reflection'. Default: 'zeros'.- align_corners(bool): interpolation flag. Default: True. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ pinholes_dst: the pinhole models for the destination frame.+ height: the height of the image to warp.+ width: the width of the image to warp.+ mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.+ padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``.+ align_corners: interpolation flag."""def __init__(@@ -281,8 +271,7 @@ class DepthWarper(nn.Module):return torch.min(0.5 / dxdd)def warp_grid(self, depth_src: torch.Tensor) -> torch.Tensor:- """Computes a grid for warping a given the depth from the reference- pinhole camera.+ """Computes a grid for warping a given the depth from the reference pinhole camera.The function `compute_projection_matrix` has to be called beforehand inorder to have precomputed the relative projection matrices encoding the@@ -318,18 +307,15 @@ class DepthWarper(nn.Module):pixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(pixel_coords_src, self.height, self.width)return pixel_coords_src_norm- def forward(self, depth_src: torch.Tensor, patch_dst: torch.Tensor) -> torch.Tensor: # type: ignore- """Warps a tensor from destination frame to reference given the depth- in the reference frame.+ def forward(self, depth_src: torch.Tensor, patch_dst: torch.Tensor) -> torch.Tensor:+ """Warps a tensor from destination frame to reference given the depth in the reference frame.Args:- depth_src (torch.Tensor): the depth in the reference frame. The- tensor must have a shape :math:`(B, 1, H, W)`.- patch_dst (torch.Tensor): the patch in the destination frame. The- tensor must have a shape :math:`(B, C, H, W)`.+ depth_src: the depth in the reference frame. The tensor must have a shape :math:`(B, 1, H, W)`.+ patch_dst: the patch in the destination frame. The tensor must have a shape :math:`(B, C, H, W)`.Return:- torch.Tensor: the warped patch from destination frame to reference.+ the warped patch from destination frame to reference.Shape:- Output: :math:`(N, C, H, W)` where C = number of channels.diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex 05bfda342..4d693dbbe 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -12,12 +12,12 @@ def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Uses the method from Hartley/Zisserman 9.6 pag 257 (formula 9.12).Args:- F_mat (torch.Tensor): The fundamental matrix with shape of :math:`(*, 3, 3)`.- K1 (torch.Tensor): The camera matrix from first camera with shape :math:`(*, 3, 3)`.- K2 (torch.Tensor): The camera matrix from second camera with shape :math:`(*, 3, 3)`.+ F_mat: The fundamental matrix with shape of :math:`(*, 3, 3)`.+ K1: The camera matrix from first camera with shape :math:`(*, 3, 3)`.+ K2: The camera matrix from second camera with shape :math:`(*, 3, 3)`.Returns:- torch.Tensor: The essential matrix with shape :math:`(*, 3, 3)`.+ The essential matrix with shape :math:`(*, 3, 3)`."""assert len(F_mat.shape) >= 2 and F_mat.shape[-2:] == (3, 3), F_mat.shape@@ -35,12 +35,11 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torchand give the possible solutions: :math:`R1, R2, t`.Args:- E_mat (torch.Tensor): The essential matrix in the form of :math:`(*, 3, 3)`.+ E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.Returns:- Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: A tuple containing the first and- second possible rotation matrices and the translation vector. The shape of the tensors- with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`.+ A tuple containing the first and second possible rotation matrices and the translation vector.+ The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`."""assert len(E_mat.shape) >= 2 and E_mat.shape[-2:], E_mat.shape@@ -78,13 +77,13 @@ def essential_from_Rt(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2:Reference: Hartley/Zisserman 9.6 pag 257 (formula 9.12)Args:- R1 (torch.Tensor): The first camera rotation matrix with shape :math:`(*, 3, 3)`.- t1 (torch.Tensor): The first camera translation vector with shape :math:`(*, 3, 1)`.- R2 (torch.Tensor): The second camera rotation matrix with shape :math:`(*, 3, 3)`.- t2 (torch.Tensor): The second camera translation vector with shape :math:`(*, 3, 1)`.+ R1: The first camera rotation matrix with shape :math:`(*, 3, 3)`.+ t1: The first camera translation vector with shape :math:`(*, 3, 1)`.+ R2: The second camera rotation matrix with shape :math:`(*, 3, 3)`.+ t2: The second camera translation vector with shape :math:`(*, 3, 1)`.Returns:- torch.Tensor: The Essential matrix with the shape :math:`(*, 3, 3)`.+ The Essential matrix with the shape :math:`(*, 3, 3)`."""assert len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3), R1.shape@@ -108,11 +107,11 @@ def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensmatrix. The posible solutions are :math:`[R1,t], [R1,−t], [R2,t], [R2,−t]`.Args:- E_mat (torch.Tensor): The essential matrix in the form of :math:`(*, 3, 3)`.+ E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.Returns:- Tuple[torch.Tensor, torch.Tensor]: The rotation and translation containing the four- possible combination for the retrieved motion. The tuple is as following :math:`[(*, 4, 3, 3), (*, 4, 3, 1)]`.+ The rotation and translation containing the four possible combination for the retrieved motion.+ The tuple is as following :math:`[(*, 4, 3, 3), (*, 4, 3, 1)]`."""assert len(E_mat.shape) >= 2 and E_mat.shape[-2:], E_mat.shape@@ -143,21 +142,21 @@ def motion_from_essential_choose_solution(:py:meth:`~kornia.geometry.epipolar.triangulate_points`.Args:- E_mat (torch.Tensor): The essential matrix in the form of :math:`(*, 3, 3)`.- K1 (torch.Tensor): The camera matrix from first camera with shape :math:`(*, 3, 3)`.- K2 (torch.Tensor): The camera matrix from second camera with shape :math:`(*, 3, 3)`.- x1 (torch.Tensor): The set of points seen from the first camera frame in the camera plane+ E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.+ K1: The camera matrix from first camera with shape :math:`(*, 3, 3)`.+ K2: The camera matrix from second camera with shape :math:`(*, 3, 3)`.+ x1: The set of points seen from the first camera frame in the camera planecoordinates with shape :math:`(*, N, 2)`.- x2 (torch.Tensor): The set of points seen from the first camera frame in the camera plane+ x2: The set of points seen from the first camera frame in the camera planecoordinates with shape :math:`(*, N, 2)`.- mask (torch.Tensor): A boolean mask which can be used to exclude some points from choosing+ mask: A boolean mask which can be used to exclude some points from choosingthe best solution. This is useful for using this function with sets of points ofdifferent cardinality (for instance after filtering with RANSAC) while keeping batchsemantics. Mask is of shape :math:`(*, N)`.Returns:- Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: The rotation and translation plus the- 3d triangulated points. The tuple is as following :math:`[(*, 3, 3), (*, 3, 1), (*, N, 3)]`.+ The rotation and translation plus the 3d triangulated points.+ The tuple is as following :math:`[(*, 3, 3), (*, 3, 1), (*, N, 3)]`."""assert len(E_mat.shape) >= 2 and E_mat.shape[-2:], E_mat.shape@@ -241,13 +240,13 @@ def relative_camera_motion(the computed relative motion is :math:`T = T_{2}T^{−1}_{1}`.Args:- R1 (torch.Tensor): The first camera rotation matrix with shape :math:`(*, 3, 3)`.- t1 (torch.Tensor): The first camera translation vector with shape :math:`(*, 3, 1)`.- R2 (torch.Tensor): The second camera rotation matrix with shape :math:`(*, 3, 3)`.- t2 (torch.Tensor): The second camera translation vector with shape :math:`(*, 3, 1)`.+ R1: The first camera rotation matrix with shape :math:`(*, 3, 3)`.+ t1: The first camera translation vector with shape :math:`(*, 3, 1)`.+ R2: The second camera rotation matrix with shape :math:`(*, 3, 3)`.+ t2: The second camera translation vector with shape :math:`(*, 3, 1)`.Returns:- Tuple[torch.Tensor, torch.Tensor]: A tuple with the relative rotation matrix and+ A tuple with the relative rotation matrix andtranslation vector with the shape of :math:`[(*, 3, 3), (*, 3, 1)]`."""diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex 54d147db4..6c23924ee 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -18,12 +18,12 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tenthe result as optimal.Args:- points (torch.Tensor): Tensor containing the points to be normalized with shape :math:`(B, N, 2)`.- eps (float): epsilon value to avoid numerical instabilities. Default: 1e-8.+ points: Tensor containing the points to be normalized with shape :math:`(B, N, 2)`.+ eps: epsilon value to avoid numerical instabilities.Returns:- Tuple[torch.Tensor, torch.Tensor]: tuple containing the normalized points in the- shape :math:`(B, N, 2)` and the transformation matrix in the shape :math:`(B, 3, 3)`.+ tuple containing the normalized points in the shape :math:`(B, N, 2)` and the transformation matrix+ in the shape :math:`(B, 3, 3)`."""assert len(points.shape) == 3, points.shape@@ -53,11 +53,11 @@ def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensorthe last row and column is one.Args:- M (torch.Tensor): The transformation to be normalized of any shape with a minimum size of 2x2.- eps (float): small value to avoid unstabilities during the backpropagation.+ M: The transformation to be normalized of any shape with a minimum size of 2x2.+ eps: small value to avoid unstabilities during the backpropagation.Returns:- torch.Tensor: the normalized transformation matrix with same shape as the input.+ the normalized transformation matrix with same shape as the input."""assert len(M.shape) >= 2, M.shape@@ -71,12 +71,12 @@ def find_fundamental(points1: torch.Tensor, points2: torch.Tensor, weights: torcThe linear system is solved by using the Weighted Least Squares Solution for the 8 Points algorithm.Args:- points1 (torch.Tensor): A set of points in the first image with a tensor shape :math:`(B, N, 2)`.- points2 (torch.Tensor): A set of points in the second image with a tensor shape :math:`(B, N, 2)`.- weights (torch.Tensor): Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.+ points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.+ points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`.+ weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.Returns:- torch.Tensor: the computed fundamental matrix with shape :math:`(B, 3, 3)`.+ the computed fundamental matrix with shape :math:`(B, 3, 3)`."""assert points1.shape == points2.shape, (points1.shape, points2.shape)@@ -118,13 +118,11 @@ def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> tor"""Computes the corresponding epipolar line for a given set of points.Args:- points (torch.Tensor): tensor containing the set of points to project in- the shape of :math:`(B, N, 2)`.- F_mat (torch.Tensor): the fundamental to use for projection the points in- the shape of :math:`(B, 3, 3)`.+ points: tensor containing the set of points to project in the shape of :math:`(B, N, 2)`.+ F_mat: the fundamental to use for projection the points in the shape of :math:`(B, 3, 3)`.Returns:- torch.Tensor: a tensor with shape :math:`(B, N, 3)` containing a vector of the epipolar+ a tensor with shape :math:`(B, N, 3)` containing a vector of the epipolarlines corresponding to the points to the other image. Each line is described as:math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.@@ -151,12 +149,12 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Uses the method from Hartley/Zisserman 9.6 pag 257 (formula 9.12).Args:- E_mat (torch.Tensor): The essential matrix with shape of :math:`(*, 3, 3)`.- K1 (torch.Tensor): The camera matrix from first camera with shape :math:`(*, 3, 3)`.- K2 (torch.Tensor): The camera matrix from second camera with shape :math:`(*, 3, 3)`.+ E_mat: The essential matrix with shape of :math:`(*, 3, 3)`.+ K1: The camera matrix from first camera with shape :math:`(*, 3, 3)`.+ K2: The camera matrix from second camera with shape :math:`(*, 3, 3)`.Returns:- torch.Tensor: The fundamental matrix with shape :math:`(*, 3, 3)`.+ The fundamental matrix with shape :math:`(*, 3, 3)`."""assert len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3), E_mat.shape@@ -176,11 +174,11 @@ def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Ter"""Get the Fundamental matrix from Projection matrices.Args:- P1 (torch.Tensor): The projection matrix from first camera with shape :math:`(*, 3, 4)`.- P2 (torch.Tensor): The projection matrix from second camera with shape :math:`(*, 3, 4)`.+ P1: The projection matrix from first camera with shape :math:`(*, 3, 4)`.+ P2: The projection matrix from second camera with shape :math:`(*, 3, 4)`.Returns:- torch.Tensor: The fundamental matrix with shape :math:`(*, 3, 3)`.+ The fundamental matrix with shape :math:`(*, 3, 3)`."""assert len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4), P1.shapediff --git a/kornia/geometry/epipolar/metrics.py b/kornia/geometry/epipolar/metrics.pyindex 7e1152c24..324ea7141 100644--- a/kornia/geometry/epipolar/metrics.py+++ b/kornia/geometry/epipolar/metrics.py@@ -11,17 +11,17 @@ def sampson_epipolar_distance(r"""Returns Sampson distance for correspondences given the fundamental matrix.Args:- pts1 (torch.Tensor): correspondences from the left images with shape+ pts1: correspondences from the left images with shape(B, N, 2 or 3). If they are not homogeneous, converted automatically.- pts2 (torch.Tensor): correspondences from the right images with shape+ pts2: correspondences from the right images with shape(B, N, 2 or 3). If they are not homogeneous, converted automatically.- Fm (torch.Tensor): Fundamental matrices with shape :math:`(B, 3, 3)`. Called Fm to+ Fm: Fundamental matrices with shape :math:`(B, 3, 3)`. Called Fm toavoid ambiguity with torch.nn.functional.- squared (bool): if True (default), the squared distance is returned.- eps (float): Small constant for safe sqrt. Default 1e-9.+ squared: if True (default), the squared distance is returned.+ eps: Small constant for safe sqrt.Returns:- torch.Tensor: the computed Sampson distance with shape :math:`(B, N)`.+ the computed Sampson distance with shape :math:`(B, N)`."""if not isinstance(Fm, torch.Tensor):@@ -63,17 +63,17 @@ def symmetrical_epipolar_distance(r"""Returns symmetrical epipolar distance for correspondences given the fundamental matrix.Args:- pts1 (torch.Tensor): correspondences from the left images with shape+ pts1: correspondences from the left images with shape(B, N, 2 or 3). If they are not homogeneous, converted automatically.- pts2 (torch.Tensor): correspondences from the right images with shape+ pts2: correspondences from the right images with shape(B, N, 2 or 3). If they are not homogeneous, converted automatically.- Fm (torch.Tensor): Fundamental matrices with shape :math:`(B, 3, 3)`. Called Fm to+ Fm: Fundamental matrices with shape :math:`(B, 3, 3)`. Called Fm toavoid ambiguity with torch.nn.functional.- squared (bool): if True (default), the squared distance is returned.- eps (float): Small constant for safe sqrt. Default 1e-9.+ squared: if True (default), the squared distance is returned.+ eps: Small constant for safe sqrt.Returns:- torch.Tensor: the computed Symmetrical distance with shape :math:`(B, N)`.+ the computed Symmetrical distance with shape :math:`(B, N)`."""if not isinstance(Fm, torch.Tensor):diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.pyindex e595c5d3c..b81ff6953 100644--- a/kornia/geometry/epipolar/numeric.py+++ b/kornia/geometry/epipolar/numeric.py@@ -9,10 +9,10 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:r"""Returns the cross_product_matrix symmetric matrix of a vector.Args:- x (torch.Tensor): The input vector to construct the matrix in the shape :math:`(B, 3)`.+ x: The input vector to construct the matrix in the shape :math:`(B, 3)`.Returns:- torch.Tensor: The constructed cross_product_matrix symmetric matrix with shape :math:`(B, 3, 3)`.+ The constructed cross_product_matrix symmetric matrix with shape :math:`(B, 3, 3)`."""assert len(x.shape) == 2 and x.shape[1] == 3, x.shape@@ -31,12 +31,12 @@ def eye_like(n: int, input: torch.Tensor) -> torch.Tensor:r"""Returns a 2-D tensor with ones on the diagonal and zeros elsewhere with same size as the input.Args:- n (int): the number of rows :math:`(N)`.- input (torch.Tensor): image tensor that will determine the batch size of the output matrix.+ n: the number of rows :math:`(N)`.+ input: image tensor that will determine the batch size of the output matrix.The expected shape is :math:`(B, *)`.Returns:- torch.Tensor: The identity matrix with same size as input :math:`(*, N, N)`.+ The identity matrix with same size as input :math:`(*, N, N)`."""assert n > 0, (type(n), n)@@ -50,12 +50,12 @@ def vec_like(n, tensor):r"""Returns a 2-D tensor with a vector containing zeros with same size as the input.Args:- n (int): the number of rows :math:`(N)`.- input (torch.Tensor): image tensor that will determine the batch size of the output matrix.+ n: the number of rows :math:`(N)`.+ input: image tensor that will determine the batch size of the output matrix.The expected shape is :math:`(B, *)`.Returns:- torch.Tensor: The vector with same size as input :math:`(*, N, 1)`.+ The vector with same size as input :math:`(*, N, 1)`."""assert n > 0, (type(n), n)diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.pyindex 63c3223d6..4acb603f0 100644--- a/kornia/geometry/epipolar/projection.py+++ b/kornia/geometry/epipolar/projection.py@@ -12,12 +12,12 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:The center of projection will be based in the input image size.Args:- focal (float): the focal length for tha camera matrix.- input (torch.Tensor): image tensor that will determine the batch size and image height+ focal: the focal length for tha camera matrix.+ input: image tensor that will determine the batch size and image heightand width. It is assumed to be a tensor in the shape of :math:`(B, C, H, W)`.Returns:- torch.Tensor: The camera matrix with the shape of :math:`(B, 3, 3)`.+ The camera matrix with the shape of :math:`(B, 3, 3)`."""assert len(input.shape) == 4, input.shape@@ -37,11 +37,11 @@ def random_intrinsics(low: Union[float, torch.Tensor], high: Union[float, torch.r"""Generates a random camera matrix based on a given uniform distribution.Args:- low (Union[float, torch.Tensor]): lower range (inclusive).- high (Union[float, torch.Tensor]): upper range (exclusive).+ low: lower range (inclusive).+ high: upper range (exclusive).Returns:- torch.Tensor: The random camera matrix with the shape of :math:`(1, 3, 3)`.+ the random camera matrix with the shape of :math:`(1, 3, 3)`."""sampler = torch.distributions.Uniform(low, high)@@ -57,12 +57,12 @@ def scale_intrinsics(camera_matrix: torch.Tensor, scale_factor: Union[float, torApplies the scaling factor to the focal length and center of projection.Args:- camera_matrix (torch.Tensor): the camera calibration matrix containing the intrinsic+ camera_matrix: the camera calibration matrix containing the intrinsicparameters. The expected shape for the tensor is :math:`(B, 3, 3)`.- scale_factor (Union[float, torch.Tensor]): the scaling factor to be applied.+ scale_factor: the scaling factor to be applied.Returns:- torch.Tensor: The scaled camera matrix with shame shape as input :math:`(B, 3, 3)`.+ The scaled camera matrix with shame shape as input :math:`(B, 3, 3)`."""K_scale = camera_matrix.clone()@@ -79,12 +79,12 @@ def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> toThis function estimate the projection matrix by solving the following equation: :math:`P = K * [R|t]`.Args:- K (torch.Tensor): the camera matrix with the instrinsics with shape :math:`(B, 3, 3)`.- R (torch.Tensor): The rotation matrix with shape :math:`(B, 3, 3)`.- t (torch.Tensor): The translation vector with shape :math:`(B, 3, 1)`.+ K: the camera matrix with the instrinsics with shape :math:`(B, 3, 3)`.+ R: The rotation matrix with shape :math:`(B, 3, 3)`.+ t: The translation vector with shape :math:`(B, 3, 1)`.Returns:- torch.Tensor: The projection matrix P with shape :math:`(B, 4, 4)`.+ The projection matrix P with shape :math:`(B, 4, 4)`."""assert K.shape[-2:] == (3, 3), K.shape@@ -106,10 +106,9 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tensor"""This function decomposes the Projection matrix into Camera-Matrix, Rotation Matrix and Translation vector.Args:- P (torch.Tensor): the projection matrix with shape :math:`(B, 3, 4)`.+ P: the projection matrix with shape :math:`(B, 3, 4)`.Returns:- Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:- The Camera matrix with shape :math:`(B, 3, 3)`.- The Rotation matrix with shape :math:`(B, 3, 3)`.- The Translation vector with shape :math:`(B, 3)`.@@ -144,12 +143,12 @@ def depth(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch.Tensor:r"""Returns the depth of a point transformed by a rigid transform.Args:- R (torch.Tensor): The rotation matrix with shape :math:`(*, 3, 3)`.- t (torch.Tensor): The translation vector with shape :math:`(*, 3, 1)`.- X (torch.Tensor): The 3d points with shape :math:`(*, 3)`.+ R: The rotation matrix with shape :math:`(*, 3, 3)`.+ t: The translation vector with shape :math:`(*, 3, 1)`.+ X: The 3d points with shape :math:`(*, 3)`.Returns:- torch.Tensor: The depth value per point with shape :math:`(*, 1)`.+ The depth value per point with shape :math:`(*, 1)`."""X_tmp = R @ X.transpose(-2, -1)@@ -174,10 +173,10 @@ def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:r"""Get the projection matrices from the Fundamental Matrix.Args:- F_mat (torch.Tensor): the fundamental matrix with the shape :math:`(*, 3, 3)`.+ F_mat: the fundamental matrix with the shape :math:`(*, 3, 3)`.Returns:- torch.Tensor: The projection matrices with shape :math:`(*, 4, 4, 2)`.+ The projection matrices with shape :math:`(*, 4, 4, 2)`."""assert len(F_mat.shape) >= 2, F_mat.shapediff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.pyindex 6fea70551..ebfa5f2b5 100644--- a/kornia/geometry/epipolar/triangulation.py+++ b/kornia/geometry/epipolar/triangulation.py@@ -19,15 +19,15 @@ def triangulate_points(correspondences. The method does not perform any robust estimation.Args:- P1 (torch.Tensor): The projection matrix for the first camera with shape :math:`(*, 3, 4)`.- P2 (torch.Tensor): The projection matrix for the second camera with shape :math:`(*, 3, 4)`.- points1 (torch.Tensor): The set of points seen from the first camera frame in the camera plane+ P1: The projection matrix for the first camera with shape :math:`(*, 3, 4)`.+ P2: The projection matrix for the second camera with shape :math:`(*, 3, 4)`.+ points1: The set of points seen from the first camera frame in the camera planecoordinates with shape :math:`(*, N, 2)`.- points2 (torch.Tensor): The set of points seen from the second camera frame in the camera plane+ points2: The set of points seen from the second camera frame in the camera planecoordinates with shape :math:`(*, N, 2)`.Returns:- torch.Tensor: The reconstructed 3d points in the world frame with shape :math:`(*, N, 3)`.+ The reconstructed 3d points in the world frame with shape :math:`(*, N, 3)`."""assert len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4), P1.shapediff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex 2a60bddde..564fa4589 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -18,13 +18,12 @@ def find_homography_dlt(The linear system is solved by using the Weighted Least Squares Solution for the 4 Points algorithm.Args:- points1 (torch.Tensor): A set of points in the first image with a tensor shape :math:`(B, N, 2)`.- points2 (torch.Tensor): A set of points in the second image with a tensor shape :math:`(B, N, 2)`.- weights (torch.Tensor, optional): Tensor containing the weights per point correspondence with a shape of- :math:`(B, N)`. Defaults to all ones.+ points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.+ points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`.+ weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.Returns:- torch.Tensor: the computed homography matrix with shape :math:`(B, 3, 3)`.+ the computed homography matrix with shape :math:`(B, 3, 3)`."""assert points1.shape == points2.shape, points1.shapeassert len(points1.shape) >= 1 and points1.shape[-1] == 2, points1.shape@@ -74,15 +73,15 @@ def find_homography_dlt_iterated(The linear system is solved by using the Reweighted Least Squares Solution for the 4 Points algorithm.Args:- points1 (torch.Tensor): A set of points in the first image with a tensor shape :math:`(B, N, 2)`.- points2 (torch.Tensor): A set of points in the second image with a tensor shape :math:`(B, N, 2)`.- weights (torch.Tensor): Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.+ points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.+ points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`.+ weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.Used for the first iteration of the IRWLS.- soft_inl_th (float): Soft inlier threshold used for weight calculation.- n_iter (int): number of iterations. Default is 5.+ soft_inl_th: Soft inlier threshold used for weight calculation.+ n_iter: number of iterations.Returns:- torch.Tensor: the computed homography matrix with shape :math:`(B, 3, 3)`.+ the computed homography matrix with shape :math:`(B, 3, 3)`."""'''Function, which finds homography via iteratively-reweightedleast squares ToDo: add citation'''diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex cac02781a..a1f9d7056 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -21,23 +21,19 @@ def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> tr"""Functions that composes two homogeneous transformations... math::-T_0^{2} = \begin{bmatrix} R_0^1 R_1^{2} & R_0^{1} t_1^{2} + t_0^{1} \\\mathbf{0} & 1\end{bmatrix}Args:- trans_01 (torch.Tensor): tensor with the homogenous transformation from+ trans_01: tensor with the homogenous transformation froma reference frame 1 respect to a frame 0. The tensor has must have ashape of :math:`(B, 4, 4)` or :math:`(4, 4)`.- trans_12 (torch.Tensor): tensor with the homogenous transformation from+ trans_12: tensor with the homogenous transformation froma reference frame 2 respect to a frame 1. The tensor has must have ashape of :math:`(B, 4, 4)` or :math:`(4, 4)`.- Shape:- - Output: :math:`(N, 4, 4)` or :math:`(4, 4)`-Returns:- torch.Tensor: the transformation between the two frames.+ the transformation between the two frames with shape :math:`(N, 4, 4)` or :math:`(4, 4)`.Example::>>> trans_01 = torch.eye(4) # 4x4@@ -47,14 +43,19 @@ def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> t"""if not torch.is_tensor(trans_01):raise TypeError("Input trans_01 type is not a torch.Tensor. Got {}".format(type(trans_01)))+if not torch.is_tensor(trans_12):raise TypeError("Input trans_12 type is not a torch.Tensor. Got {}".format(type(trans_12)))+if not trans_01.dim() in (2, 3) and trans_01.shape[-2:] == (4, 4):raise ValueError("Input trans_01 must be a of the shape Nx4x4 or 4x4." " Got {}".format(trans_01.shape))+if not trans_12.dim() in (2, 3) and trans_12.shape[-2:] == (4, 4):raise ValueError("Input trans_12 must be a of the shape Nx4x4 or 4x4." " Got {}".format(trans_12.shape))+if not trans_01.dim() == trans_12.dim():raise ValueError("Input number of dims must match. Got {} and {}".format(trans_01.dim(), trans_12.dim()))+# unpack input datarmat_01: torch.Tensor = trans_01[..., :3, :3] # Nx3x3rmat_12: torch.Tensor = trans_12[..., :3, :3] # Nx3x3@@ -85,14 +86,10 @@ def inverse_transformation(trans_12):\mathbf{0} & 1\end{bmatrix}Args:- trans_12 (torch.Tensor): transformation tensor of shape- :math:`(N, 4, 4)` or :math:`(4, 4)`.+ trans_12: transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.Returns:- torch.Tensor: tensor with inverted transformations.-- Shape:- - Output: :math:`(N, 4, 4)` or :math:`(4, 4)`+ tensor with inverted transformations with shape :math:`(N, 4, 4)` or :math:`(4, 4)`.Example:>>> trans_12 = torch.rand(1, 4, 4) # Nx4x4@@ -130,17 +127,12 @@ def relative_transformation(trans_01: torch.Tensor, trans_02: torch.Tensor) -> tT_1^{2} = (T_0^{1})^{-1} \cdot T_0^{2}- Arguments:- trans_01 (torch.Tensor): reference transformation tensor of shape- :math:`(N, 4, 4)` or :math:`(4, 4)`.- trans_02 (torch.Tensor): destination transformation tensor of shape- :math:`(N, 4, 4)` or :math:`(4, 4)`.-- Shape:- - Output: :math:`(N, 4, 4)` or :math:`(4, 4)`.+ Args:+ trans_01: reference transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.+ trans_02: destination transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.Returns:- torch.Tensor: the relative transformation between the transformations.+ the relative transformation between the transformations with shape :math:`(N, 4, 4)` or :math:`(4, 4)`.Example::>>> trans_01 = torch.eye(4) # 4x4@@ -214,16 +206,14 @@ def transform_boxes(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xtransformation matrix or a batch of transformation matrices (B, 3, 3)Args:- trans_mat (torch.Tensor): The transformation matrix to be applied- boxes (torch.Tensor): The boxes to be transformed- mode (str): The format in which the boxes are provided. If set to 'xyxy' the boxes- are assumed to be in the format (xmin, ymin, xmax, ymax). If set to 'xywh'- the boxes are assumed to be in the format (xmin, ymin, width, height).- Default: 'xyxy'- Returns:- torch.Tensor: The set of transformed points in the specified mode-+ trans_mat: The transformation matrix to be applied.+ boxes: The boxes to be transformed.+ mode: The format in which the boxes are provided. If set to 'xyxy' the boxes+ are assumed to be in the format (xmin, ymin, xmax, ymax). If set to 'xywh'+ the boxes are assumed to be in the format (xmin, ymin, width, height).+ Returns:+ The set of transformed points in the specified mode."""warnings.warn("`kornia.geometry.linalg.transform_boxes` is deprecated and will be removed > 0.6.0. "@@ -238,14 +228,11 @@ def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) ->r"""Function that applies perspective transformations to a set of local affine frames (LAFs).Args:- trans_01 (torch.Tensor): tensor for perspective transformations of shape- :math:`(B, 3, 3)`.- lafs_1 (torch.Tensor): tensor of lafs of shape :math:`(B, N, 2, 3)`.- Returns:- torch.Tensor: tensor of N-dimensional points.+ trans_01: tensor for perspective transformations of shape :math:`(B, 3, 3)`.+ lafs_1: tensor of lafs of shape :math:`(B, N, 2, 3)`.- Shape:- - Output: :math:`(B, N, 2, 3)`+ Returns:+ tensor of N-dimensional points of shape :math:`(B, N, 2, 3)`.Examples:>>> rng = torch.manual_seed(0)@@ -283,12 +270,16 @@ def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) ->kornia.feature.laf.raise_error_if_laf_is_not_valid(lafs_1)if not torch.is_tensor(trans_01):raise TypeError("Input type is not a torch.Tensor")+if not trans_01.device == lafs_1.device:raise TypeError("Tensor must be in the same device")+if not trans_01.shape[0] == lafs_1.shape[0]:raise ValueError("Input batch size must be the same for both tensors")+if (not (trans_01.shape[-1] == 3)) or (not (trans_01.shape[-2] == 3)):raise ValueError("Transformation should be homography")+bs, n, _, _ = lafs_1.size()# First, we convert LAF to pointsthreepts_1 = kornia.feature.laf.laf_to_three_points(lafs_1)diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.pyindex 9cde27ee1..9fef4ac8a 100644--- a/kornia/geometry/subpix/dsnt.py+++ b/kornia/geometry/subpix/dsnt.py@@ -21,19 +21,15 @@ def _validate_batched_image_tensor_input(tensor):def spatial_softmax2d(input: torch.Tensor, temperature: torch.Tensor = torch.tensor(1.0)) -> torch.Tensor:r"""Applies the Softmax function over features in each image channel.- Note that this function behaves differently to `torch.nn.Softmax2d`, which+ Note that this function behaves differently to :py:class:`torch.nn.Softmax2d`, whichinstead applies Softmax over features at each spatial location.- Returns a 2D probability distribution per image channel.+ Args:+ input: the input tensor with shape :math:`(B, N, H, W)`.+ temperature: factor to apply to input, adjusting the "smoothness" of the output distribution.- Arguments:- input (torch.Tensor): the input tensor.- temperature (torch.Tensor): factor to apply to input, adjusting the- "smoothness" of the output distribution. Default is 1.-- Shape:- - Input: :math:`(B, N, H, W)`- - Output: :math:`(B, N, H, W)`+ Returns:+ a 2D probability distribution per image channel with shape :math:`(B, N, H, W)`.Examples:>>> heatmaps = torch.tensor([[[@@ -59,23 +55,16 @@ def spatial_softmax2d(input: torch.Tensor, temperature: torch.Tensor = torch.tendef spatial_expectation2d(input: torch.Tensor, normalized_coordinates: bool = True) -> torch.Tensor:r"""Computes the expectation of coordinate values using spatial probabilities.- The input heatmap is assumed to represent a valid spatial probability- distribution, which can be achieved using- :class:`~kornia.geometry.dsnt.spatial_softmax2d`.-- Returns the expected value of the 2D coordinates.- The output order of the coordinates is (x, y).+ The input heatmap is assumed to represent a valid spatial probability distribution,+ which can be achieved using :func:`~kornia.geometry.subpixel.spatial_softmax2d`.- Arguments:- input (torch.Tensor): the input tensor representing dense spatial probabilities.- 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.+ Args:+ input: the input tensor representing dense spatial probabilities with shape :math:`(B, N, H, W)`.+ normalized_coordinates: whether to return the coordinates normalized in the range+ of :math:`[-1, 1]`. Otherwise, it will return the coordinates in the range of the input shape.- Shape:- - Input: :math:`(B, N, H, W)`- - Output: :math:`(B, N, 2)`+ Returns:+ expected value of the 2D coordinates with shape :math:`(B, N, 2)`. Output order of the coordinates is (x, y).Examples:>>> heatmaps = torch.tensor([[[@@ -116,24 +105,20 @@ def render_gaussian2d():r"""Renders the PDF of a 2D Gaussian distribution.- Arguments:- mean (torch.Tensor): the mean location of the Gaussian to render,- :math:`(\mu_x, \mu_y)`.- std (torch.Tensor): the standard deviation of the Gaussian to render,- :math:`(\sigma_x, \sigma_y)`.- size (list): the (height, width) of the output image.- normalized_coordinates: whether `mean` and `std` are assumed to use- coordinates normalized in the range of [-1, 1]. Otherwise,- coordinates are assumed to be in the range of the output shape.- Default is True.-- Shape:- - `mean`: :math:`(*, 2)`- - `std`: :math:`(*, 2)`. Should be able to be broadcast with `mean`.- - Output: :math:`(*, H, W)`+ Args:+ mean: the mean location of the Gaussian to render, :math:`(\mu_x, \mu_y)`. Shape: :math:`(*, 2)`.+ std: the standard deviation of the Gaussian to render, :math:`(\sigma_x, \sigma_y)`.+ Shape :math:`(*, 2)`. Should be able to be broadcast with `mean`.+ size: the (height, width) of the output image.+ normalized_coordinates: whether ``mean`` and ``std`` are assumed to use coordinates normalized+ in the range of :math:`[-1, 1]`. Otherwise, coordinates are assumed to be in the range of the output shape.++ Returns:+ tensor including rendered points with shape :math:`(*, H, W)`."""if not (std.dtype == mean.dtype and std.device == mean.device):raise TypeError("Expected inputs to have the same dtype and device")+height, width = size# Create coordinates grid.diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex b162c2bd7..19b3dbb02 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -15,12 +15,12 @@ def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.devicresidual to window center.Args:- h (int): kernel height.- w (int): kernel width.- device (torch.device): device, on which generate.+ h: kernel height.+ : kernel width.+ device: device, on which generate.Returns:- conv_kernel (torch.Tensor) [2x1xhxw]+ conv_kernel [2x1xhxw]"""window_grid2d = create_meshgrid(h, w, False, device=device)window_grid2d = normalize_pixel_coordinates(window_grid2d, h, w)@@ -33,12 +33,12 @@ def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cpwhen applied with F.conv2d to 2d coordinates grid.Args:- h (int): kernel height.- w (int): kernel width.- device (torch.device): device, on which generate.+ h: kernel height.+ w: kernel width.+ device: device, on which generate.Returns:- conv_kernel (torch.Tensor) [2x2xhxw]+ conv_kernel [2x2xhxw]."""center_kernel = torch.zeros(2, 2, h, w, device=device)@@ -64,13 +64,13 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.dewhen applied with F.conv2d to 3d coordinates grid.Args:- d (int): kernel depth.- h (int): kernel height.- w (int): kernel width.- device (torch.device): device, on which generate.+ d: kernel depth.+ h: kernel height.+ w: kernel width.+ device: device, on which generate.Returns:- conv_kernel (torch.Tensor) [3x3xdxhxw]+ conv_kernel [3x3xdxhxw]."""center_kernel = torch.zeros(3, 3, d, h, w, device=device)# If the size is odd, we have one pixel for center, if even - 2@@ -102,13 +102,13 @@ def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = torresidual to window center.Args:- d (int): kernel depth.- h (int): kernel height.- w (int): kernel width.- device (torch.device): device, on which generate.+ d: kernel depth.+ h: kernel height.+ w: kernel width.+ device: device, on which generate.Returns:- conv_kernel (torch.Tensor) [3x1xdxhxw]+ conv_kernel [3x1xdxhxw]"""grid2d = create_meshgrid(h, w, True, device=device)if d > 1:@@ -267,41 +267,43 @@ def conv_soft_argmax2d(eps: float = 1e-8,output_value: bool = False,) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:- r"""Function that computes the convolutional spatial Soft-Argmax 2D over the windows- of a given input heatmap. Function has two outputs: argmax coordinates and the softmaxpooled heatmap values- themselves. On each window, the function computed is+ r"""Computes the convolutional spatial Soft-Argmax 2D over the windows of a given heatmap... math::- ij(X) = \frac{\sum{(i,j)} * exp(x / T) \in X} {\sum{exp(x / T) \in X}}+ ij(X) = \frac{\sum{(i,j)} * 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}}+ val(X) = \frac{\sum{x * exp(x / T) \in X}} {\sum{exp(x / T) \in X}}- where T is temperature.+ where :math:`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- temperature (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.- eps (float): small value to avoid zero division. Default is 1e-8.- output_value (bool): if True, val is output, if False, only ij-- Shape:- - 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+ input: the given heatmap with shape :math:`(N, C, H_{in}, W_{in})`.+ kernel_size: the size of the window.+ stride: the stride of the window.+ padding: input zero padding.+ temperature: factor to apply to input.+ normalized_coordinates: whether to return the coordinates normalized in the range of :math:`[-1, 1]`.+ Otherwise, it will return the coordinates in the range of the input shape.+ eps: small value to avoid zero division.+ output_value: if True, val is output, if False, only ij.++ Returns:+ Function has two outputs - argmax coordinates and the softmaxpooled heatmap values themselves.+ On each window, the function computed returns with shapes :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+ 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+ W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] -+ (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor- Examples::+ Examples:>>> input = torch.randn(20, 16, 50, 32)>>> nms_coords, nms_val = conv_soft_argmax2d(input, (3,3), (2,2), (1,1), output_value=True)"""@@ -379,10 +381,7 @@ def conv_soft_argmax3d(output_value: bool = True,strict_maxima_bonus: float = 0.0,) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:- r"""Function that computes the convolutional spatial Soft-Argmax 3D over the windows- of a given input heatmap. Function has two outputs: argmax coordinates and the softmaxpooled heatmap values- themselves.- On each window, the function computed is:+ r"""Computes the convolutional spatial Soft-Argmax 3D over the windows of a given heatmap... math::ijk(X) = \frac{\sum{(i,j,k)} * exp(x / T) \in X} {\sum{exp(x / T) \in X}}@@ -390,22 +389,27 @@ def conv_soft_argmax3d(.. math::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,int]): size of the window- stride (Tuple[int,int,int]): stride of the window.- padding (Tuple[int,int,int]): input zero padding- temperature (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.- eps (float): small value to avoid zero division. Default is 1e-8.- output_value (bool): if True, val is output, if False, only ij- strict_maxima_bonus (float): pixels, which are strict maxima will score (1 + strict_maxima_bonus) * value.- This is needed for mimic behavior of strict NMS in classic local features- Shape:- - 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+ input: the given heatmap with shape :math:`(N, C, D_{in}, H_{in}, W_{in})`.+ kernel_size: size of the window.+ stride: stride of the window.+ padding: input zero padding.+ temperature: factor to apply to input.+ normalized_coordinates: whether to return the coordinates normalized in the range of :math:[-1, 1]`.+ Otherwise, it will return the coordinates in the range of the input shape.+ eps: small value to avoid zero division.+ output_value: if True, val is output, if False, only ij.+ strict_maxima_bonus: pixels, which are strict maxima will score (1 + strict_maxima_bonus) * value.+ This is needed for mimic behavior of strict NMS in classic local features++ Returns:+ Function has two outputs - argmax coordinates and the softmaxpooled heatmap values themselves.+ On each window, the function computed returns with shapes :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] -@@ -479,6 +483,7 @@ def conv_soft_argmax3d(if not output_value:return coords_max+x_softmaxpool = (pool_coef * F.avg_pool3d(x_exp.view(input.size()) * input, kernel_size, stride=stride, padding=padding) / den)@@ -499,23 +504,18 @@ def spatial_soft_argmax2d(normalized_coordinates: bool = True,eps: float = 1e-8,) -> torch.Tensor:- r"""Function that computes the Spatial Soft-Argmax 2D- of a given input heatmap.+ r"""Function that computes the Spatial Soft-Argmax 2D of a given input heatmap.- Returns the index of the maximum 2d coordinates of the give map.- The output order is x-coord and y-coord.-- Arguments:- temperature (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.- eps (float): small value to avoid zero division. Default is 1e-8.+ Args:+ input: the given heatmap with shape :math:`(B, N, H, W)`.+ temperature: factor to apply to input.+ normalized_coordinates: whether to return the coordinates normalized in the range of :math:`[-1, 1]`.+ Otherwise, it will return the coordinates in the range of the input shape.+ eps: small value to avoid zero division.- Shape:- - Input: :math:`(B, N, H, W)`- - Output: :math:`(B, N, 2)`+ Returns:+ the index of the maximum 2d coordinates of the give map :math:`(B, N, 2)`.+ The output order is x-coord and y-coord.Examples:>>> input = torch.tensor([[[@@ -562,17 +562,22 @@ class SpatialSoftArgmax2d(nn.Module):return spatial_soft_argmax2d(input, self.temperature, self.normalized_coordinates, self.eps)-def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7):- r"""Function that computes the single iteration of quadratic interpolation of of the extremum (max or min) location- and value per each 3x3x3 window which contains strict extremum, similar to one done is SIFT+def conv_quad_interp3d(+ input: torch.Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7+) -> Tuple[torch.Tensor, torch.Tensor]:+ r"""Function that computes the single iteration of quadratic interpolation of the extremum (max or min).Args:- strict_maxima_bonus (float): pixels, which are strict maxima will score (1 + strict_maxima_bonus) * value.- This is needed for mimic behavior of strict NMS in classic local features- eps (float): parameter to control the hessian matrix ill-condition number.- Shape:- - 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+ input: the given heatmap with shape :math:`(N, C, D_{in}, H_{in}, W_{in})`.+ strict_maxima_bonus: pixels, which are strict maxima will score (1 + strict_maxima_bonus) * value.+ This is needed for mimic behavior of strict NMS in classic local features+ eps: parameter to control the hessian matrix ill-condition number.++ Returns:+ the location and value per each 3x3x3 window which contains strict extremum, similar to one done is SIFT.+ :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] -@@ -592,8 +597,10 @@ def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 10.0, e"""if not torch.is_tensor(input):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))+if not len(input.shape) == 5:raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}".format(input.shape))+B, CH, D, H, W = input.shapedev: torch.device = input.devicegrid_global: torch.Tensor = create_meshgrid3d(D, H, W, False, device=input.device).permute(0, 4, 1, 2, 3)@@ -640,6 +647,7 @@ def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 10.0, eclass ConvQuadInterp3d(nn.Module):r"""Module that calculates soft argmax 3d per window+See :func:`~kornia.geometry.subpix.conv_quad_interp3d` for details."""diff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.pyindex e08c627f1..3a5476726 100644--- a/kornia/losses/depth_smooth.py+++ b/kornia/losses/depth_smooth.py@@ -25,11 +25,11 @@ def inverse_depth_smoothness_loss(idepth: torch.Tensor, image: torch.Tensor) ->\partial_y d_{ij} \right | e^{-\left \| \partial_y I_{ij} \right \|}Args:- idepth (torch.Tensor): tensor with the inverse depth with shape :math:`(N, 1, H, W)`.- image (torch.Tensor): tensor with the input image with shape :math:`(N, 3, H, W)`.+ idepth: tensor with the inverse depth with shape :math:`(N, 1, H, W)`.+ image: tensor with the input image with shape :math:`(N, 3, H, W)`.Return:- torch.Tensor: a scalar with the computed loss.+ a scalar with the computed loss.Examples:>>> idepth = torch.rand(1, 1, 4, 5)diff --git a/kornia/losses/dice.py b/kornia/losses/dice.pyindex a6782c47d..e93da37a9 100644--- a/kornia/losses/dice.py+++ b/kornia/losses/dice.py@@ -31,13 +31,13 @@ def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> t[1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficientArgs:- input (torch.Tensor): logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.- labels (torch.Tensor): labels tensor with shape :math:`(N, H, W)` where each value+ input: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.+ labels: labels tensor with shape :math:`(N, H, W)` where each valueis :math:`0 ≤ targets[i] ≤ C−1`.- eps (float, optional): Scalar to enforce numerical stabiliy. Default: 1e-8.+ eps: Scalar to enforce numerical stabiliy.Return:- torch.Tensor: the computed loss.+ the computed loss.Example:>>> N = 5 # num_classes@@ -99,7 +99,7 @@ class DiceLoss(nn.Module):[1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficientArgs:- eps (float, optional): Scalar to enforce numerical stabiliy. Default: 1e-8.+ eps: Scalar to enforce numerical stabiliy.Shape:- Input: :math:`(N, C, H, W)` where C = number of classes.diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.pyindex 58cab1ea1..4fb707c11 100644--- a/kornia/losses/divergence.py+++ b/kornia/losses/divergence.py@@ -33,13 +33,13 @@ def js_div_loss_2d(input: torch.Tensor, target: torch.Tensor, reduction: str = 'r"""Calculates the Jensen-Shannon divergence loss between heatmaps.Args:- input (torch.Tensor): the input tensor with shape :math:`(B, N, H, W)`.- target (torch.Tensor): the target tensor with shape :math:`(B, N, H, W)`.- reduction (string, optional): Specifies the reduction to apply to the- output: `none` | `mean` | `sum`. `none`: no reduction- will be applied, `mean`: the sum of the output will be divided by- the number of elements in the output, `sum`: the output will be- summed. Default: `mean`.+ input: the input tensor with shape :math:`(B, N, H, W)`.+ target: the target tensor with shape :math:`(B, N, H, W)`.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied, ``'mean'``: the sum of the output will be divided by+ the number of elements in the output, ``'sum'``: the output will be+ summed.Examples:>>> input = torch.full((1, 1, 2, 4), 0.125)@@ -54,13 +54,13 @@ def kl_div_loss_2d(input: torch.Tensor, target: torch.Tensor, reduction: str = 'r"""Calculates the Kullback-Leibler divergence loss between heatmaps.Args:- input (torch.Tensor): the input tensor with shape :math:`(B, N, H, W)`.- target (torch.Tensor): the target tensor with shape :math:`(B, N, H, W)`.- reduction (string, optional): Specifies the reduction to apply to the- output: `none` | `mean` | `sum`. `none`: no reduction- will be applied, `mean`: the sum of the output will be divided by- the number of elements in the output, `sum`: the output will be- summed. Default: `mean`.+ input: the input tensor with shape :math:`(B, N, H, W)`.+ target: the target tensor with shape :math:`(B, N, H, W)`.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied, ``'mean'``: the sum of the output will be divided by+ the number of elements in the output, ``'sum'``: the output will be+ summed.Examples:>>> input = torch.full((1, 1, 2, 4), 0.125)diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 0c31cff83..61f44fbf6 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -28,18 +28,19 @@ def focal_loss(- :math:`p_t` is the model's estimated probability for each class.Args:- input (torch.Tensor): logits tensor with shape :math:`(N, C, *)` where C = number of classes.- target (torch.Tensor): labels tensor with shape :math:`(N, *)` where each value is :math:`0 ≤ targets[i] ≤ C−1`.- alpha (float): Weighting factor :math:`\alpha \in [0, 1]`.- gamma (float, optional): Focusing parameter :math:`\gamma >= 0`. Default 2.- reduction (str, optional): Specifies the reduction to apply to the- output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied,- ‘mean’: the sum of the output will be divided by the number of elements- in the output, ‘sum’: the output will be summed. Default: ‘none’.- eps (float, optional): Scalar to enforce numerical stabiliy. Default: 1e-8.+ input: logits tensor with shape :math:`(N, C, *)` where C = number of classes.+ target: labels tensor with shape :math:`(N, *)` where each value is :math:`0 ≤ targets[i] ≤ C−1`.+ alpha: Weighting factor :math:`\alpha \in [0, 1]`.+ gamma: Focusing parameter :math:`\gamma >= 0`.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied, ``'mean'``: the sum of the output will be divided by+ the number of elements in the output, ``'sum'``: the output will be+ summed.+ eps: Scalar to enforce numerical stabiliy.Return:- torch.Tensor: the computed loss.+ the computed loss.Example:>>> N = 5 # num_classes@@ -105,13 +106,14 @@ class FocalLoss(nn.Module):- :math:`p_t` is the model's estimated probability for each class.Args:- alpha (float): Weighting factor :math:`\alpha \in [0, 1]`.- gamma (float, optional): Focusing parameter :math:`\gamma >= 0`. Default 2.- reduction (str, optional): Specifies the reduction to apply to the- output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied,- ‘mean’: the sum of the output will be divided by the number of elements- in the output, ‘sum’: the output will be summed. Default: ‘none’.- eps (float, optional): Scalar to enforce numerical stabiliy. Default: 1e-8.+ alpha: Weighting factor :math:`\alpha \in [0, 1]`.+ gamma: Focusing parameter :math:`\gamma >= 0`.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied, ``'mean'``: the sum of the output will be divided by+ the number of elements in the output, ``'sum'``: the output will be+ summed.+ eps: Scalar to enforce numerical stabiliy.Shape:- Input: :math:`(N, C, *)` where C = number of classes.@@ -157,15 +159,19 @@ def binary_focal_loss_with_logits(- :math:`p_t` is the model's estimated probability for each class.Args:- input (torch.Tensor): input data tensor with shape :math:`(N, 1, *)`.- target (torch.Tensor): the target tensor with shape :math:`(N, 1, *)`.- alpha (float): Weighting factor for the rare class :math:`\alpha \in [0, 1]`. Default: 0.25.- gamma (float): Focusing parameter :math:`\gamma >= 0`. Default: 2.0.- reduction (str, optional): Specifies the reduction to apply to the. Default: 'none'.- eps (float): for numerically stability when dividing. Default: 1e-8.+ input: input data tensor with shape :math:`(N, 1, *)`.+ target: the target tensor with shape :math:`(N, 1, *)`.+ alpha: Weighting factor for the rare class :math:`\alpha \in [0, 1]`.+ gamma: Focusing parameter :math:`\gamma >= 0`.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied, ``'mean'``: the sum of the output will be divided by+ the number of elements in the output, ``'sum'``: the output will be+ summed.+ eps: for numerically stability when dividing.Returns:- torch.tensor: the computed loss.+ the computed loss.Examples:>>> num_classes = 1@@ -209,7 +215,7 @@ def binary_focal_loss_with_logits(class BinaryFocalLossWithLogits(nn.Module):r"""Criterion that computes Focal loss.- According to :cite:`lin2017focal`, the Focal loss is computed as follows:+ According to :cite:`lin2018focal`, the Focal loss is computed as follows:.. math::@@ -219,12 +225,13 @@ class BinaryFocalLossWithLogits(nn.Module):- :math:`p_t` is the model's estimated probability for each class.Args:- alpha (float): Weighting factor for the rare class :math:`\alpha \in [0, 1]`.- gamma (float): Focusing parameter :math:`\gamma >= 0`.- reduction (str, optional): Specifies the reduction to apply to the- output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied,- ‘mean’: the sum of the output will be divided by the number of elements- in the output, ‘sum’: the output will be summed. Default: ‘none’.+ alpha): Weighting factor for the rare class :math:`\alpha \in [0, 1]`.+ gamma: Focusing parameter :math:`\gamma >= 0`.+ reduction: Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction+ will be applied, ``'mean'``: the sum of the output will be divided by+ the number of elements in the output, ``'sum'``: the output will be+ summed.Shape:- Input: :math:`(N, 1, *)`.diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.pyindex 1d88effcb..77419200d 100644--- a/kornia/losses/psnr.py+++ b/kornia/losses/psnr.py@@ -23,12 +23,12 @@ def psnr(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten(e.g for floating point images :math:`\text{MAX}_I=1`).Args:- input (torch.Tensor): the input image with arbitrary shape :math:`(*)`.- labels (torch.Tensor): the labels image with arbitrary shape :math:`(*)`.- max_val (float): The maximum value in the input tensor.+ input: the input image with arbitrary shape :math:`(*)`.+ labels: the labels image with arbitrary shape :math:`(*)`.+ max_val: The maximum value in the input tensor.Return:- torch.Tensor: the computed loss as a scalar.+ the computed loss as a scalar.Examples:>>> ones = torch.ones(1)@@ -62,12 +62,12 @@ def psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torcSee :meth:`~kornia.losses.psnr` for details abut PSNR.Args:- input (torch.Tensor): the input image with shape :math:`(*)`.- labels (torch.Tensor): the labels image with shape :math:`(*)`.- max_val (float): The maximum value in the input tensor.+ input: the input image with shape :math:`(*)`.+ labels : the labels image with shape :math:`(*)`.+ max_val: The maximum value in the input tensor.Return:- torch.Tensor: the computed loss as a scalar.+ the computed loss as a scalar.Examples:>>> ones = torch.ones(1)@@ -89,6 +89,9 @@ class PSNRLoss(nn.Module):See :meth:`~kornia.losses.psnr` for details abut PSNR.+ Args:+ max_val: The maximum value in the input tensor.+Shape:- Input: arbitrary dimensional tensor :math:`(*)`.- Target: arbitrary dimensional tensor :math:`(*)` same shape as input.diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.pyindex 1ffa95565..761806078 100644--- a/kornia/losses/ssim.py+++ b/kornia/losses/ssim.py@@ -25,14 +25,14 @@ def ssim(:math:`2^{\#\text{bits per pixel}}-1`).Args:- img1 (torch.Tensor): the first input image with shape :math:`(B, C, H, W)`.- img2 (torch.Tensor): the second input image with shape :math:`(B, C, H, W)`.- window_size (int): the size of the gaussian kernel to smooth the images.- max_val (float): the dynamic range of the images. Default: 1.- eps (float): Small value for numerically stability when dividing. Default: 1e-12.+ img1: the first input image with shape :math:`(B, C, H, W)`.+ img2: the second input image with shape :math:`(B, C, H, W)`.+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.Returns:- torch.Tensor: The ssim index map with shape :math:`(B, C, H, W)`.+ The ssim index map with shape :math:`(B, C, H, W)`.Examples:>>> input1 = torch.rand(1, 4, 5, 5)@@ -103,18 +103,18 @@ def ssim_loss(See :meth:`~kornia.losses.ssim` for details about SSIM.Args:- img1 (torch.Tensor): the first input image with shape :math:`(B, C, H, W)`.- img2 (torch.Tensor): the second input image with shape :math:`(B, C, H, W)`.- window_size (int): the size of the gaussian kernel to smooth the images.- max_val (float): the dynamic range of the images. Default: 1.- eps (float): Small value for numerically stability when dividing. Default: 1e-12.- reduction (str, optional): Specifies the reduction to apply to the- output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied,- 'mean': the sum of the output will be divided by the number of elements- in the output, 'sum': the output will be summed. Default: 'mean'.+ img1: the first input image with shape :math:`(B, C, H, W)`.+ img2: the second input image with shape :math:`(B, C, H, W)`.+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.+ reduction : Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,+ ``'mean'``: the sum of the output will be divided by the number of elements+ in the output, ``'sum'``: the output will be summed.Returns:- torch.Tensor: The loss based on the ssim index.+ The loss based on the ssim index.Examples:>>> input1 = torch.rand(1, 4, 5, 5)@@ -155,9 +155,9 @@ class SSIM(nn.Module)::math:`2^{\#\text{bits per pixel}}-1`).Args:- window_size (int): the size of the gaussian kernel to smooth the images.- max_val (float): the dynamic range of the images. Default: 1.- eps (float): Small value for numerically stability when dividing. Default: 1e-12.+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.Shape:- Input: :math:`(B, C, H, W)`.@@ -193,16 +193,16 @@ class SSIMLoss(nn.Module):See :meth:`~kornia.losses.ssim_loss` for details about SSIM.Args:- window_size (int): the size of the gaussian kernel to smooth the images.- max_val (float): the dynamic range of the images. Default: 1.- eps (float): Small value for numerically stability when dividing. Default: 1e-12.- reduction (str, optional): Specifies the reduction to apply to the- output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied,- 'mean': the sum of the output will be divided by the number of elements- in the output, 'sum': the output will be summed. Default: 'mean'.+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.+ reduction : Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,+ ``'mean'``: the sum of the output will be divided by the number of elements+ in the output, ``'sum'``: the output will be summed.Returns:- torch.Tensor: The loss based on the ssim index.+ The loss based on the ssim index.Examples:>>> input1 = torch.rand(1, 4, 5, 5)diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.pyindex e04593ad0..ccc4be162 100644--- a/kornia/losses/total_variation.py+++ b/kornia/losses/total_variation.py@@ -6,10 +6,10 @@ def total_variation(img: torch.Tensor) -> torch.Tensor:r"""Function that computes Total Variation according to [1].Args:- img (torch.Tensor): the input image with shape :math:`(N, C, H, W)` or :math:`(C, H, W)`.+ img: the input image with shape :math:`(N, C, H, W)` or :math:`(C, H, W)`.Return:- torch.Tensor: a scalar with the computer loss.+ a scalar with the computer loss.Examples:>>> total_variation(torch.ones(3, 4, 4))diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.pyindex 6ab76f3e6..46fc96a72 100644--- a/kornia/losses/tversky.py+++ b/kornia/losses/tversky.py@@ -32,15 +32,15 @@ def tversky_loss(- :math:`\alpha + \beta = 1` => F beta coeffArgs:- input (torch.Tensor): logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.- target (torch.Tensor): labels tensor with shape :math:`(N, H, W)` where each value+ input: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.+ target: labels tensor with shape :math:`(N, H, W)` where each valueis :math:`0 ≤ targets[i] ≤ C−1`.- alpha (float): the first coefficient in the denominator.- beta (float): the second coefficient in the denominator.- eps (float, optional): scalar for numerical stability. Default: 1e-8.+ alpha: the first coefficient in the denominator.+ beta: the second coefficient in the denominator.+ eps: scalar for numerical stability.Return:- torch.Tensor: the computed loss.+ the computed loss.Example:>>> N = 5 # num_classes@@ -104,9 +104,9 @@ class TverskyLoss(nn.Module):- :math:`\alpha + \beta = 1` => F beta coeffArgs:- alpha (float): the first coefficient in the denominator.- beta (float): the second coefficient in the denominator.- eps (float, optional): scalar for numerical stability. Default: 1e-8.+ alpha: the first coefficient in the denominator.+ beta: the second coefficient in the denominator.+ eps: scalar for numerical stability.Shape:- Input: :math:`(N, C, H, W)` where C = number of classes.diff --git a/kornia/utils/draw.py b/kornia/utils/draw.pyindex e4b613556..b3b271078 100644--- a/kornia/utils/draw.py+++ b/kornia/utils/draw.py@@ -13,16 +13,16 @@ def draw_rectangle(r"""Draws N rectangles on a batch of image tensors.Args:- image (torch.Tensor): is tensor of BxCxHxW.- rectangle (torch.Tensor): represents number of rectangles to draw in BxNx4+ image: is tensor of BxCxHxW.+ rectangle: represents number of rectangles to draw in BxNx4N is the number of boxes to draw per batch index[x1, y1, x2, y2]4 is in (top_left.x, top_left.y, bot_right.x, bot_right.y).- color (torch.Tensor, optional): a size 1, size 3, BxNx1, or BxNx3 tensor.- If C is 3, and color is 1 channel it will be broadcasted Default: None (black).- fill (bool, optional): is a flag used to fill the boxes with color if True. Default: False.- width (int): The line width. Default: 1. (Not implemented yet).+ color: a size 1, size 3, BxNx1, or BxNx3 tensor.+ If C is 3, and color is 1 channel it will be broadcasted.+ fill: is a flag used to fill the boxes with color if True.+ width: The line width (Not implemented yet).Returns:- torch.Tensor: This operation modifies image inplace but also returns the drawn tensor for+ This operation modifies image inplace but also returns the drawn tensor forconvenience with same shape the of the input BxCxHxW.Example:diff --git a/kornia/utils/grid.py b/kornia/utils/grid.pyindex ce7f14469..8bc6a4aff 100644--- a/kornia/utils/grid.py+++ b/kornia/utils/grid.py@@ -12,22 +12,37 @@ def create_meshgrid() -> torch.Tensor:"""Generates a coordinate grid for an image.- When the flag `normalized_coordinates` is set to True, the grid is- normalized to be in the range [-1,1] to be consistent with the pytorch- function grid_sample.- http://pytorch.org/docs/master/nn.html#torch.nn.functional.grid_sample+ When the flag ``normalized_coordinates`` is set to True, the grid is+ normalized to be in the range :math:`[-1,1]` to be consistent with the pytorch+ function :py:func:`torch.nn.functional.grid_sample`.Args:- height (int): the image height (rows).- width (int): the image width (cols).- normalized_coordinates (bool): whether to normalize- coordinates in the range [-1, 1] in order to be consistent with the- PyTorch function grid_sample.- device (torch.device): the device on which the grid will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated gird. Default: float32.+ height: the image height (rows).+ width: the image width (cols).+ normalized_coordinates: whether to normalize+ coordinates in the range :math:`[-1,1]` in order to be consistent with the+ PyTorch function :py:func:`torch.nn.functional.grid_sample`.+ device: the device on which the grid will be generated.+ dtype: the data type of the generated grid.Return:- torch.Tensor: returns a grid tensor with shape :math:`(1, H, W, 2)`.+ grid tensor with shape :math:`(1, H, W, 2)`.++ Example:+ >>> create_meshgrid(2, 2)+ tensor([[[[-1., -1.],+ [ 1., -1.]],+ <BLANKLINE>+ [[-1., 1.],+ [ 1., 1.]]]])++ >>> create_meshgrid(2, 2, normalized_coordinates=False)+ tensor([[[[0., 0.],+ [1., 0.]],+ <BLANKLINE>+ [[0., 1.],+ [1., 1.]]]])+"""xs: torch.Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)ys: torch.Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)@@ -57,23 +72,22 @@ def create_meshgrid3d() -> torch.Tensor:"""Generates a coordinate grid for an image.- When the flag `normalized_coordinates` is set to True, the grid is- normalized to be in the range [-1,1] to be consistent with the pytorch- function grid_sample.- http://pytorch.org/docs/master/nn.html#torch.nn.functional.grid_sample+ When the flag ``normalized_coordinates`` is set to True, the grid is+ normalized to be in the range :math:`[-1,1]` to be consistent with the pytorch+ function :py:func:`torch.nn.functional.grid_sample`.Args:- depth (int): the image depth (channels).- height (int): the image height (rows).- width (int): the image width (cols).- normalized_coordinates (bool): whether to normalize- coordinates in the range [-1, 1] in order to be consistent with the- PyTorch function grid_sample.- device (torch.device): the device on which the grid will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated gird. Default: float32.+ depth: the image depth (channels).+ height: the image height (rows).+ width: the image width (cols).+ normalized_coordinates: whether to normalize+ coordinates in the range :math:`[-1,1]` in order to be consistent with the+ PyTorch function :py:func:`torch.nn.functional.grid_sample`.+ device: the device on which the grid will be generated.+ dtype: the data type of the generated grid.Return:- torch.Tensor: returns a grid tensor with shape :math:`(1, D, H, W, 3)`.+ grid tensor with shape :math:`(1, D, H, W, 3)`."""xs: torch.Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)ys: torch.Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)diff --git a/kornia/utils/image.py b/kornia/utils/image.pyindex 2e4e5dd33..92da9a2c4 100644--- a/kornia/utils/image.py+++ b/kornia/utils/image.py@@ -9,13 +9,13 @@ def image_to_tensor(image: np.ndarray, keepdim: bool = True) -> torch.Tensor:"""Converts a numpy image to a PyTorch 4d tensor image.Args:- image (numpy.ndarray): image of the form :math:`(H, W, C)`, :math:`(H, W)` or+ image: image of the form :math:`(H, W, C)`, :math:`(H, W)` or+ :math:`(B, H, W, C)`.+ keepdim: If ``False`` unsqueeze the input image to match the shape:math:`(B, H, W, C)`.- keepdim (bool): If ``False`` unsqueeze the input image to match the shape- :math:`(B, H, W, C)`. Default: ``True``Returns:- torch.Tensor: tensor of the form :math:`(B, C, H, W)` if keepdim is ``False``,+ tensor of the form :math:`(B, C, H, W)` if keepdim is ``False``,:math:`(C, H, W)` otherwise."""if not isinstance(image, (np.ndarray,)):@@ -47,11 +47,11 @@ def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:"""Converts a PyTorch tensor image to BCHW format.Args:- tensor (torch.Tensor): image of the form :math:`(H, W)`, :math:`(C, H, W)`, :math:`(H, W, C)` or+ tensor: image of the form :math:`(H, W)`, :math:`(C, H, W)`, :math:`(H, W, C)` or:math:`(B, C, H, W)`.Returns:- torch.Tensor: input tensor of the form :math:`(B, C, H, W)`.+ input tensor of the form :math:`(B, C, H, W)`."""if not isinstance(tensor, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")@@ -72,11 +72,11 @@ def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:"""Converts a PyTorch tensor image to BCDHW format.Args:- tensor (torch.Tensor): image of the form :math:`(D, H, W)`, :math:`(C, D, H, W)`, :math:`(D, H, W, C)` or+ tensor: image of the form :math:`(D, H, W)`, :math:`(C, D, H, W)`, :math:`(D, H, W, C)` or:math:`(B, C, D, H, W)`.Returns:- torch.Tensor: input tensor of the form :math:`(B, C, D, H, W)`.+ input tensor of the form :math:`(B, C, D, H, W)`."""if not isinstance(tensor, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")@@ -99,11 +99,11 @@ def tensor_to_image(tensor: torch.Tensor) -> np.ndarray:In case the tensor is in the GPU, it will be copied back to CPU.Args:- tensor (torch.Tensor): image of the form :math:`(H, W)`, :math:`(C, H, W)` or+ tensor: image of the form :math:`(H, W)`, :math:`(C, H, W)` or:math:`(B, C, H, W)`.Returns:- numpy.ndarray: image of the form :math:`(H, W)`, :math:`(H, W, C)` or :math:`(B, H, W, C)`.+ image of the form :math:`(H, W)`, :math:`(H, W, C)` or :math:`(B, H, W, C)`."""if not isinstance(tensor, torch.Tensor):@@ -142,8 +142,7 @@ class ImageToTensor(nn.Module):"""Converts a numpy image to a PyTorch 4d tensor image.Args:- keepdim (bool): If ``False`` unsqueeze the input image to match the shape- :math:`(B, H, W, C)`. Default: ``True``+ keepdim: If ``False`` unsqueeze the input image to match the shape :math:`(B, H, W, C)`."""def __init__(self, keepdim: bool = False):diff --git a/kornia/utils/memory.py b/kornia/utils/memory.pyindex 74bf606cf..47230abf1 100644--- a/kornia/utils/memory.py+++ b/kornia/utils/memory.py@@ -6,25 +6,29 @@ import korniadef batched_forward(model: torch.nn.Module, data: torch.Tensor, device: torch.device, batch_size: int = 128, **kwargs) -> torch.Tensor:- r'''Convenience function, which allows to run the forward in micro-batches,- when the just model.forward(data) does not fit into device memory, e.g. on laptop GPU.+ r"""Convenience function, which allows to run the forward in micro-batches.++ When the just model.forward(data) does not fit into device memory, e.g. on laptop GPU.In the end, it transfers the output to the device of the input data tensor.E.g. running HardNet on 8000x1x32x32 tensor.+Args:- model (torch.nn.Module): Any torch model, which outputs a single tensor as an output- data (torch.Tensor): Input data of Bx(Any) shape- device (torch.device): which device should we run on- batch_size (int): "micro-batch" size. Default: 128- **kwargs: any other arguments, which accepts model+ model: Any torch model, which outputs a single tensor as an output.+ data: Input data of Bx(Any) shape.+ device: which device should we run on.+ batch_size: "micro-batch" size.+ **kwargs: any other arguments, which accepts model.+Returns:- torch.Tensor: output of the model+ output of the model.Example:>>> patches = torch.rand(8000, 1, 32, 32)>>> sift = kornia.feature.SIFTDescriptor(32)>>> desc_batched = batched_forward(sift, patches, torch.device('cpu'), 128)>>> desc = sift(patches)- >>> assert torch.allclose(desc, desc_batched)'''+ >>> assert torch.allclose(desc, desc_batched)+ """model_dev = model.to(device)B: int = len(data)bs: int = batch_sizediff --git a/kornia/utils/metrics/confusion_matrix.py b/kornia/utils/metrics/confusion_matrix.pyindex b062d9681..38148ca4f 100644--- a/kornia/utils/metrics/confusion_matrix.py+++ b/kornia/utils/metrics/confusion_matrix.py@@ -7,28 +7,28 @@ import torchdef confusion_matrix(- input: torch.Tensor, target: torch.Tensor, num_classes: int, normalized: Optional[bool] = False+ input: torch.Tensor, target: torch.Tensor, num_classes: int, normalized: bool = False) -> torch.Tensor:r"""Compute confusion matrix to evaluate the accuracy of a classification.Args:- input (torch.Tensor) : tensor with estimated targets returned by a+ input: tensor with estimated targets returned by aclassifier. The shape can be :math:`(B, *)` and must contain integervalues between 0 and K-1.- target (torch.Tensor) : tensor with ground truth (correct) target+ target: tensor with ground truth (correct) targetvalues. The shape can be :math:`(B, *)` and must contain integervalues between 0 and K-1, where targets are assumed to be provided asone-hot vectors.- num_classes (int): total possible number of classes in target.- normalized: (Optional[bool]): wether to return the confusion matrix- normalized. Default: False.+ num_classes: total possible number of classes in target.+ normalized: wether to return the confusion matrix normalized.Returns:- torch.Tensor: a tensor containing the confusion matrix with shape+ a tensor containing the confusion matrix with shape:math:`(B, K, K)` where K is the number of classes."""if not torch.is_tensor(input) and input.dtype is not torch.int64:raise TypeError("Input input type is not a torch.Tensor with " "torch.int64 dtype. Got {}".format(type(input)))+if not torch.is_tensor(target) and target.dtype is not torch.int64:raise TypeError("Input target type is not a torch.Tensor with " "torch.int64 dtype. Got {}".format(type(target))@@ -39,8 +39,10 @@ def confusion_matrix()if not input.device == target.device:raise ValueError("Inputs must be in the same device. " "Got: {} - {}".format(input.device, target.device))+if not isinstance(num_classes, int) or num_classes < 2:raise ValueError("The number of classes must be an integer bigger " "than two. Got: {}".format(num_classes))+batch_size: int = input.shape[0]# hack for bitcounting 2 arrays togetherdiff --git a/kornia/utils/metrics/mean_iou.py b/kornia/utils/metrics/mean_iou.pyindex 522cc21f5..2705f4784 100644--- a/kornia/utils/metrics/mean_iou.py+++ b/kornia/utils/metrics/mean_iou.py@@ -5,27 +5,28 @@ import torchfrom kornia.utils.metrics.confusion_matrix import confusion_matrix-def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: Optional[float] = 1e-6) -> torch.Tensor:+def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: float = 1e-6) -> torch.Tensor:r"""Calculate mean Intersection-Over-Union (mIOU).The function internally computes the confusion matrix.Args:- input (torch.Tensor) : tensor with estimated targets returned by a+ input : tensor with estimated targets returned by aclassifier. The shape can be :math:`(B, *)` and must contain integervalues between 0 and K-1.- target (torch.Tensor) : tensor with ground truth (correct) target+ target: tensor with ground truth (correct) targetvalues. The shape can be :math:`(B, *)` and must contain integervalues between 0 and K-1, where targets are assumed to be provided asone-hot vectors.- num_classes (int): total possible number of classes in target.+ num_classes: total possible number of classes in target.Returns:- torch.Tensor: a tensor representing the mean intersection-over union+ ta tensor representing the mean intersection-over unionwith shape :math:`(B, K)` where K is the number of classes."""if not torch.is_tensor(input) and input.dtype is not torch.int64:raise TypeError("Input input type is not a torch.Tensor with " "torch.int64 dtype. Got {}".format(type(input)))+if not torch.is_tensor(target) and target.dtype is not torch.int64:raise TypeError("Input target type is not a torch.Tensor with " "torch.int64 dtype. Got {}".format(type(target))@@ -36,8 +37,10 @@ def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: O)if not input.device == target.device:raise ValueError("Inputs must be in the same device. " "Got: {} - {}".format(input.device, target.device))+if not isinstance(num_classes, int) or num_classes < 2:raise ValueError("The number of classes must be an integer bigger " "than two. Got: {}".format(num_classes))+# we first compute the confusion matrixconf_mat: torch.Tensor = confusion_matrix(input, target, num_classes)diff --git a/kornia/utils/one_hot.py b/kornia/utils/one_hot.pyindex 6e56d93ab..603c94d37 100644--- a/kornia/utils/one_hot.py+++ b/kornia/utils/one_hot.py@@ -13,19 +13,14 @@ def one_hot(r"""Converts an integer label x-D tensor to a one-hot (x+1)-D tensor.Args:- labels (torch.Tensor) : tensor with labels of shape :math:`(N, *)`,- where N is batch size. Each value is an integer- representing correct classification.- num_classes (int): number of classes in labels.- device (Optional[torch.device]): the desired device of returned tensor.- Default: if None, uses the current device for the default tensor type- (see torch.set_default_tensor_type()). device will be the CPU for CPU- tensor types and the current CUDA device for CUDA tensor types.- dtype (Optional[torch.dtype]): the desired data type of returned- tensor. Default: if None, infers data type from values.+ labels: tensor with labels of shape :math:`(N, *)`, where N is batch size.+ Each value is an integer representing correct classification.+ num_classes: number of classes in labels.+ device: the desired device of returned tensor.+ dtype: the desired data type of returned tensor.Returns:- torch.Tensor: the labels in one hot tensor of shape :math:`(N, C, *)`,+ the labels in one hot tensor of shape :math:`(N, C, *)`,Examples:>>> labels = torch.LongTensor([[[0, 1], [2, 0]]])diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.pyindex 35e5a93dd..09f770892 100644--- a/kornia/utils/pointcloud_io.py+++ b/kornia/utils/pointcloud_io.py@@ -8,17 +8,20 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:r"""Utility function to save to disk a pointcloud in PLY format.Args:- filename (str): the path to save the pointcloud.- pointcloud (torch.Tensor): tensor containing the pointcloud to save.+ filename: the path to save the pointcloud.+ pointcloud: tensor containing the pointcloud to save.The tensor must be in the shape of :math:`(*, 3)` where the lastcomponent is assumed to be a 3d point coordinate :math:`(X, Y, Z)`."""if not isinstance(filename, str) and filename[-3:] == '.ply':raise TypeError("Input filename must be a string in with the .ply " "extension. Got {}".format(filename))+if not torch.is_tensor(pointcloud):raise TypeError("Input pointcloud type is not a torch.Tensor. Got {}".format(type(pointcloud)))+if not len(pointcloud.shape) == 3 and pointcloud.shape[-1] == 3:raise TypeError("Input pointcloud must be in the following shape " "HxWx3. Got {}.".format(pointcloud.shape))+# flatten the input pointcloud in a vector to iterate pointsxyz_vec: torch.Tensor = pointcloud.reshape(-1, 3)@@ -45,17 +48,17 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:f.write(data_str)-def load_pointcloud_ply(filename: str, header_size: Optional[int] = 8) -> torch.Tensor:+def load_pointcloud_ply(filename: str, header_size: int = 8) -> torch.Tensor:r"""Utility function to load from disk a pointcloud in PLY format.Args:- filename (str): the path to the pointcloud.- header_size (Optional[int]): the size of the ply file header that will- be skipped during loading. Default is 8 lines.+ filename: the path to the pointcloud.+ header_size: the size of the ply file header that will+ be skipped during loading.Return:- torch.Tensor: a tensor containing the loaded point with shape- :math:`(*, 3)` where :math:`*` represents the number of points.+ tensor containing the loaded point with shape :math:`(*, 3)` where+ :math:`*` represents the number of points."""if not isinstance(filename, str) and filename[-3:] == '.ply':raise TypeError("Input filename must be a string in with the .ply " "extension. Got {}".format(filename))