Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[pre-commit.ci] pre-commit suggestions (#1828)

pre-commit-ci[bot]e5a975c5f1e8
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 8ec8017dd..12cf1c0ba 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -63,7 +63,7 @@ repos:
- "B101,B311"
- repo: https://github.com/myint/docformatter
- rev: v1.4
+ rev: v1.5.0-rc1
hooks:
- id: docformatter
args: [--in-place, --wrap-summaries=115, --wrap-descriptions=120]
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
index 553e221d4..5bd6f7d63 100644
--- a/kornia/augmentation/_3d/geometric/depthical_flip.py
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -55,7 +55,6 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
>>> aug = RandomDepthicalFlip3D(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
-
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/planckian_jitter.py b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
index 9a81c8065..1f2cbfcb2 100644
--- a/kornia/augmentation/random_generator/_2d/planckian_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
@@ -8,7 +8,7 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
class PlanckianJitterGenerator(RandomGeneratorBase):
- r"""Generate random planckian jitter parameters for a batch of images"""
+ r"""Generate random planckian jitter parameters for a batch of images."""
def __init__(self, domain: List[float]) -> None:
super().__init__()
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 6f323528e..909e28762 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -57,7 +57,10 @@ def _validate_input3d(f: Callable) -> Callable:
def _infer_batch_shape(input: Union[Tensor, Tuple[Tensor, Tensor]]) -> torch.Size:
- r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)"""
+ r"""Infer input shape.
+
+ Input may be either (tensor,) or (tensor, transform_matrix)
+ """
if isinstance(input, tuple):
tensor = _transform_input(input[0])
else:
@@ -66,7 +69,10 @@ def _infer_batch_shape(input: Union[Tensor, Tuple[Tensor, Tensor]]) -> torch.Siz
def _infer_batch_shape3d(input: Union[Tensor, Tuple[Tensor, Tensor]]) -> torch.Size:
- r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)"""
+ r"""Infer input shape.
+
+ Input may be either (tensor,) or (tensor, transform_matrix)
+ """
if isinstance(input, tuple):
tensor = _transform_input3d(input[0])
else:
@@ -168,7 +174,9 @@ def _validate_shape(shape: Union[Tuple, torch.Size], required_shapes: Tuple[str,
def _validate_input_shape(input: Tensor, channel_index: int, number: int) -> bool:
- r"""Validate if an input has the right shape. e.g. to check if an input is channel first.
+ r"""Validate if an input has the right shape.
+
+ e.g. to check if an input is channel first.
If channel first, the second channel of an RGB input shall be fixed to 3. To verify using:
_validate_input_shape(input, 1, 3)
Args:
@@ -186,8 +194,8 @@ def _adapted_rsampling(
) -> Tensor:
r"""The uniform reparameterized sampling function that accepts 'same_on_batch'.
- If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).
- By default, same_on_batch is set to False.
+ If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default,
+ same_on_batch is set to False.
"""
if same_on_batch:
return dist.rsample((1, *shape[1:])).repeat(shape[0], *[1] * (len(shape) - 1))
@@ -199,8 +207,8 @@ def _adapted_sampling(
) -> Tensor:
r"""The uniform sampling function that accepts 'same_on_batch'.
- If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).
- By default, same_on_batch is set to False.
+ If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default,
+ same_on_batch is set to False.
"""
if same_on_batch:
return dist.sample((1, *shape[1:])).repeat(shape[0], *[1] * (len(shape) - 1))
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 98ad5830a..66a95a980 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -20,7 +20,7 @@ def _range_bound(
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.get_default_dtype(),
) -> torch.Tensor:
- r"""Check inputs and compute the corresponding factor bounds"""
+ r"""Check inputs and compute the corresponding factor bounds."""
if not isinstance(factor, (torch.Tensor)):
factor = torch.tensor(factor, device=device, dtype=dtype)
factor_bound: torch.Tensor
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 56eb2c017..7fdbe87ed 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -77,7 +77,6 @@ class DistanceTransform(nn.Module):
Args:
kernel_size: size of the convolution kernel.
h: value that influence the approximation of the min function.
-
"""
def __init__(self, kernel_size: int = 3, h: float = 0.35):
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index bf74699a5..07fa6c240 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -184,7 +184,6 @@ class CombineTensorPatches(nn.Module):
.. note::
This function is supposed to be used in conjunction with :class:`ExtractTensorPatches`.
-
"""
def __init__(
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
index 60efb91d6..317038e66 100644
--- a/kornia/contrib/face_detection.py
+++ b/kornia/contrib/face_detection.py
@@ -32,7 +32,6 @@ class FaceDetectorResult:
Args:
data: the encoded results coming from the feature detector with shape :math:`(14,)`.
-
"""
def __init__(self, data: torch.Tensor) -> None:
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 26ef2522a..5c5539177 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -12,7 +12,10 @@ from kornia.utils.image import perform_keep_shape_image, perform_keep_shape_vide
def adjust_saturation_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
- r"""Adjust color saturation of an image. Expecting image to be in hsv format already."""
+ r"""Adjust color saturation of an image.
+
+ Expecting image to be in hsv format already.
+ """
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
@@ -140,7 +143,10 @@ def adjust_saturation(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
def adjust_hue_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
- r"""Adjust hue of an image. Expecting image to be in hsv format already."""
+ r"""Adjust hue of an image.
+
+ Expecting image to be in hsv format already.
+ """
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(
@@ -601,8 +607,8 @@ def adjust_log(image: Tensor, gain: float = 1, inv: bool = False, clip_output: b
def _solarize(input: Tensor, thresholds: Union[float, Tensor] = 0.5) -> Tensor:
- r"""For each pixel in the image, select the pixel if the value is less than the threshold.
- Otherwise, subtract 1.0 from the pixel.
+ r"""For each pixel in the image, select the pixel if the value is less than the threshold. Otherwise, subtract
+ 1.0 from the pixel.
Args:
input: image or batched images to solarize.
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 8400a0b92..d2b76e100 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -28,7 +28,6 @@ def add_weighted(src1: torch.Tensor, alpha: float, src2: torch.Tensor, beta: flo
>>> output = add_weighted(input1, 0.5, input2, 0.5, 1.0)
>>> output.shape
torch.Size([1, 1, 5, 5])
-
"""
if not isinstance(src1, torch.Tensor):
raise TypeError(f"src1 should be a tensor. Got {type(src1)}")
@@ -72,7 +71,6 @@ class AddWeighted(nn.Module):
>>> output = AddWeighted(0.5, 0.5, 1.0)(input1, input2)
>>> output.shape
torch.Size([1, 1, 5, 5])
-
"""
def __init__(self, alpha: float, beta: float, gamma: float) -> None:
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index d3f939148..7a837a16f 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -28,7 +28,6 @@ def _compute_tiles(
Returns:
tensor with tiles (B, GH, GW, C, TH, TW). B = 1 in case of a single image is provided.
tensor with the padded batch of 2D imageswith shape (B, C, H', W').
-
"""
batch: torch.Tensor = imgs # B x C x H x W
@@ -82,7 +81,6 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[int
Returns:
tensor with the interpolation tiles (B, 2GH, 2GW, C, TH/2, TW/2).
-
"""
if padded_imgs.dim() != 4:
raise AssertionError("Images Tensor must be 4D.")
@@ -136,7 +134,6 @@ def _compute_luts(
Returns:
Lut for each tile (B, GH, GW, C, 256).
-
"""
if tiles_x_im.dim() != 6:
raise AssertionError("Tensor must be 6D.")
@@ -184,7 +181,6 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:
Returns:
mapped luts (B, 2GH, 2GW, 4, C, 256)
-
"""
if interp_tiles.dim() != 6:
raise AssertionError("interp_tiles tensor must be 6D.")
@@ -241,7 +237,6 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
Returns:
equalized tiles (B, 2GH, 2GW, C, TH/2, TW/2)
-
"""
if interp_tiles.dim() != 6:
raise AssertionError("interp_tiles tensor must be 6D.")
@@ -343,7 +338,6 @@ def equalize_clahe(
>>> res = equalize_clahe(img)
>>> res.shape
torch.Size([2, 3, 10, 20])
-
"""
if not isinstance(clip_limit, float):
raise TypeError(f"Input clip_limit type is not float. Got {type(clip_limit)}")
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index eb69b1ff7..6045bd823 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -124,7 +124,6 @@ class ZCAWhitening(nn.Module):
Returns:
The transformed data.
-
"""
if include_fit:
@@ -195,7 +194,6 @@ def zca_mean(
>>> x = torch.rand(3,20,2,2)
>>> transform_matrix, mean_vector, inv_transform = zca_mean(x, dim = 1, return_inverse = True)
>>> # transform_matrix.size() equals (12,12) and the mean vector.size equal (1,12)
-
"""
if not isinstance(inp, torch.Tensor):
@@ -309,12 +307,9 @@ def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: floa
def linear_transform(
inp: torch.Tensor, transform_matrix: torch.Tensor, mean_vector: torch.Tensor, dim: int = 0
) -> torch.Tensor:
- r"""
-
- Given a transformation matrix and a mean vector, this function will flatten
- the input tensor along the given dimension and subtract the mean vector
- from it. Then the dot product with the transformation matrix will be computed
- and then the resulting tensor is reshaped to the original input shape.
+ r"""Given a transformation matrix and a mean vector, this function will flatten the input tensor along the given
+ dimension and subtract the mean vector from it. Then the dot product with the transformation matrix will be
+ computed and then the resulting tensor is reshaped to the original input shape.
.. math::
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 29a037b98..3d961910e 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -252,7 +252,6 @@ def dog_response(input: torch.Tensor) -> torch.Tensor:
Return:
the response map per channel with shape :math:`(B, C, D-1, H, W)`.
-
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "L", "H", "W"])
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 0441a3a5c..7c43be4c1 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -13,8 +13,8 @@ from .responses import BlobHessian
def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_levels: int) -> torch.Tensor:
- r"""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: tensor [BxNx3].
@@ -46,8 +46,8 @@ def _create_octave_mask(mask: torch.Tensor, octave_shape: List[int]) -> torch.Te
class ScaleSpaceDetector(nn.Module):
- r"""Module for differentiable local feature detection, as close as possible to classical
- local feature detectors like Harris, Hessian-Affine or SIFT (DoG).
+ 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.
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index a1b542ed0..e6dff5a9a 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -185,6 +185,7 @@ def sift_describe(
clipval: float = 0.2,
) -> torch.Tensor:
r"""Computes the sift descriptor.
+
See :class:`~kornia.feature.SIFTDescriptor` for details.
"""
return SIFTDescriptor(patch_size, num_ang_bins, num_spatial_bins, rootsift, clipval)(input)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index cc32fcfb0..481d1e284 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -25,7 +25,9 @@ def gaussian(window_size: int, sigma: float) -> torch.Tensor:
def gaussian_discrete_erf(window_size: int, sigma) -> torch.Tensor:
- r"""Discrete Gaussian by interpolating the error function. Adapted from:
+ r"""Discrete Gaussian by interpolating the error function.
+
+ Adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
"""
device = sigma.device if isinstance(sigma, torch.Tensor) else None
@@ -39,6 +41,7 @@ def gaussian_discrete_erf(window_size: int, sigma) -> torch.Tensor:
def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor:
r"""Adapted from:
+
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
"""
if torch.abs(x) < 3.75:
@@ -55,6 +58,7 @@ def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor:
def _modified_bessel_1(x: torch.Tensor) -> torch.Tensor:
r"""adapted from:
+
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
"""
if torch.abs(x) < 3.75:
@@ -71,6 +75,7 @@ def _modified_bessel_1(x: torch.Tensor) -> torch.Tensor:
def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor:
r"""adapted from:
+
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
"""
if n < 2:
@@ -98,7 +103,9 @@ def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor:
def gaussian_discrete(window_size, sigma) -> torch.Tensor:
- r"""Discrete Gaussian kernel based on the modified Bessel functions. Adapted from:
+ r"""Discrete Gaussian kernel based on the modified Bessel functions.
+
+ Adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
"""
device = sigma.device if isinstance(sigma, torch.Tensor) else None
@@ -117,9 +124,7 @@ def gaussian_discrete(window_size, sigma) -> torch.Tensor:
def laplacian_1d(window_size) -> torch.Tensor:
- r"""One could also use the Laplacian of Gaussian formula
- to design the filter.
- """
+ r"""One could also use the Laplacian of Gaussian formula to design the filter."""
filter_1d = torch.ones(window_size)
filter_1d[window_size // 2] = 1 - window_size
@@ -137,8 +142,9 @@ def get_box_kernel2d(kernel_size: Tuple[int, int]) -> torch.Tensor:
def get_binary_kernel2d(window_size: Tuple[int, int]) -> torch.Tensor:
- r"""Create a binary kernel to extract the patches. If the window size
- is HxW will create a (H*W)xHxW kernel.
+ r"""Create a binary kernel to extract the patches.
+
+ If the window size is HxW will create a (H*W)xHxW kernel.
"""
window_range: int = window_size[0] * window_size[1]
kernel: torch.Tensor = torch.zeros(window_range, window_range)
@@ -277,8 +283,10 @@ def get_diff_kernel2d_2nd_order() -> torch.Tensor:
def get_spatial_gradient_kernel2d(mode: str, order: int) -> torch.Tensor:
- r"""Function that returns kernel for 1st or 2nd order image gradients,
- using one of the following operators: sobel, diff"""
+ r"""Function that returns kernel for 1st or 2nd order image gradients, using one of the following operators:
+
+ sobel, diff.
+ """
if mode not in ['sobel', 'diff']:
raise TypeError(
"mode should be either sobel\
@@ -307,8 +315,8 @@ def get_spatial_gradient_kernel2d(mode: str, order: int) -> torch.Tensor:
def get_spatial_gradient_kernel3d(mode: str, order: int, device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
- r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients,
- using one of the following operators: sobel, diff"""
+ r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients, using one of the following
+ operators: sobel, diff."""
if mode not in ['sobel', 'diff']:
raise TypeError(
"mode should be either sobel\
@@ -363,9 +371,8 @@ def get_gaussian_kernel1d(kernel_size: int, sigma: float, force_even: bool = Fal
def get_gaussian_discrete_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> torch.Tensor:
- r"""Function that returns Gaussian filter coefficients
- based on the modified Bessel functions. Adapted from:
- https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
+ r"""Function that returns Gaussian filter coefficients based on the modified Bessel functions. Adapted from:
+ https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
Args:
kernel_size: filter size. It should be odd and positive.
@@ -393,9 +400,8 @@ def get_gaussian_discrete_kernel1d(kernel_size: int, sigma: float, force_even: b
def get_gaussian_erf_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> torch.Tensor:
- r"""Function that returns Gaussian filter coefficients by interpolating the error function,
- adapted from:
- https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
+ r"""Function that returns Gaussian filter coefficients by interpolating the error function, adapted from:
+ https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
Args:
kernel_size: filter size. It should be odd and positive.
@@ -479,7 +485,6 @@ def get_laplacian_kernel1d(kernel_size: int) -> torch.Tensor:
tensor([ 1., -2., 1.])
>>> get_laplacian_kernel1d(5)
tensor([ 1., 1., -4., 1., 1.])
-
"""
if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size <= 0:
raise TypeError(f"ksize must be an odd positive integer. Got {kernel_size}")
@@ -675,7 +680,6 @@ def get_hanning_kernel2d(kernel_size: Tuple[int, int], device=torch.device('cpu'
Shape:
- Output: math:`(\text{kernel_size[0], kernel_size[1]})`
-
"""
if kernel_size[0] <= 2 or kernel_size[1] <= 2:
raise TypeError(f"ksize must be an tuple of positive integers > 2. Got {kernel_size}")
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index e3955a5c7..373b4d27c 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -6,8 +6,7 @@ from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3
def spatial_gradient(input: torch.Tensor, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> torch.Tensor:
- r"""Compute the first order image derivative in both x and y using a Sobel
- operator.
+ r"""Compute the first order image derivative in both x and y using a Sobel operator.
.. image:: _static/img/spatial_gradient.png
@@ -57,8 +56,7 @@ def spatial_gradient(input: torch.Tensor, mode: str = 'sobel', order: int = 1, n
def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1) -> torch.Tensor:
- r"""Compute the first and second order volume derivative in x, y and d using a diff
- operator.
+ r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
Args:
input: input features tensor with shape :math:`(B, C, D, H, W)`.
@@ -164,8 +162,7 @@ def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> to
class SpatialGradient(nn.Module):
- r"""Compute the first order image derivative in both x and y using a Sobel
- operator.
+ r"""Compute the first order image derivative in both x and y using a Sobel operator.
Args:
mode: derivatives modality, can be: `sobel` or `diff`.
@@ -201,8 +198,7 @@ class SpatialGradient(nn.Module):
class SpatialGradient3d(nn.Module):
- r"""Compute the first and second order volume derivative in x, y and d using a diff
- operator.
+ r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
Args:
mode: derivatives modality, can be: `sobel` or `diff`.
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index c368f57a0..5a4416541 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -289,8 +289,8 @@ class Boxes:
def to_tensor(
self, mode: Optional[str] = None, as_padded_sequence: bool = False
) -> Union[torch.Tensor, List[torch.Tensor]]:
- r"""Cast :class:`Boxes` to a tensor. ``mode`` controls which 2D boxes format should be use to represent boxes
- in the tensor.
+ r"""Cast :class:`Boxes` to a tensor. ``mode`` controls which 2D boxes format should be use to represent
+ boxes in the tensor.
Args:
mode: the output box format. It could be:
@@ -604,8 +604,8 @@ class Boxes3D:
return cls(hexahedrons, raise_if_not_floating_point=False, mode=mode)
def to_tensor(self, mode: str = "xyzxyz") -> torch.Tensor:
- r"""Cast :class:`Boxes3D` to a tensor. ``mode`` controls which 3D boxes format should be use to represent boxes
- in the tensor.
+ r"""Cast :class:`Boxes3D` to a tensor. ``mode`` controls which 3D boxes format should be use to represent
+ boxes in the tensor.
Args:
mode: The format in which the boxes are provided.
diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.py
index 18c0e5f8c..a560a4206 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -82,7 +82,6 @@ def distort_points(
>>> K = torch.eye(3)[None]
>>> dist_coeff = torch.rand(1, 4)
>>> points_dist = distort_points(points, K, dist_coeff)
-
"""
if points.dim() < 2 and points.shape[-1] != 2:
raise ValueError(f'points shape is invalid. Got {points.shape}.')
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index 471cfaa9b..23759d1e4 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -18,7 +18,6 @@ def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) ->
Returns:
Tuple containing the normalized points in the shape :math:`(B, N, D)` and the transformation matrix
in the shape :math:`(B, D+1, D+1)`.
-
"""
if not isinstance(points, torch.Tensor):
raise AssertionError(f"points is not an instance of torch.Tensor. Type of points is {type(points)}")
@@ -50,8 +49,7 @@ def solve_pnp_dlt(
weights: Optional[torch.Tensor] = None,
svd_eps: float = 1e-4,
) -> torch.Tensor:
- r"""This function attempts to solve the Perspective-n-Point (PnP)
- problem using Direct Linear Transform (DLT).
+ r"""This function attempts to solve the Perspective-n-Point (PnP) problem using Direct Linear Transform (DLT).
Given a batch (where batch size is :math:`B`) of :math:`N` 3D points
(where :math:`N \geq 6`) in the world space, a batch of :math:`N`
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index bac76289b..65f5d4ec2 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -41,7 +41,6 @@ def undistort_points(
[ 0.0711, 0.1100],
[-0.0697, 0.0228],
[-0.1843, -0.1606]]])
-
"""
if points.dim() < 2 and points.shape[-1] != 2:
raise ValueError(f'points shape is invalid. Got {points.shape}.')
@@ -137,7 +136,6 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
>>> out = undistort_image(img, K, dist_coeff)
>>> out.shape
torch.Size([1, 3, 5, 5])
-
"""
if len(image.shape) < 3:
raise ValueError(f"Image shape is invalid. Got: {image.shape}.")
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 87c09ee3c..0d148ccf4 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -420,7 +420,7 @@ class PinholeCamerasList(PinholeCamera):
def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- r"""Function that returns the pinhole matrix from a pinhole model
+ r"""Function that returns the pinhole matrix from a pinhole model.
.. note::
This method is going to be deprecated in version 0.2 in favour of
@@ -464,7 +464,7 @@ def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- r"""Return the inverted pinhole matrix from a pinhole model
+ r"""Return the inverted pinhole matrix from a pinhole model.
.. note::
This method is going to be deprecated in version 0.2 in favour of
@@ -567,7 +567,7 @@ def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:
def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> torch.Tensor:
- r"""Homography from reference to ith pinhole
+ r"""Homography from reference to ith pinhole.
.. note::
The pinhole model is represented in a single vector as follows:
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index 0e82339fe..13bc8bfea 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -175,7 +175,6 @@ class StereoCamera:
Returns:
Tensor of shape :math:`(B)`
-
"""
return -self.rectified_right_camera[..., 0, 3] / self.fx
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index b3797e5c1..e94f8e64f 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -353,8 +353,7 @@ def depth_warp(
width: int,
align_corners: bool = True,
):
- r"""Function that warps a tensor from destination frame to reference
- given the depth in the reference frame.
+ r"""Function that warps a tensor from destination frame to reference given the depth in the reference frame.
See :class:`~kornia.geometry.warp.DepthWarper` for details.
diff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.py
index abfcadb5c..e90999178 100644
--- a/kornia/geometry/epipolar/_metrics.py
+++ b/kornia/geometry/epipolar/_metrics.py
@@ -24,7 +24,6 @@ def sampson_epipolar_distance(
Returns:
the computed Sampson distance with shape :math:`(*, N)`.
-
"""
if not isinstance(Fm, Tensor):
raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")
@@ -77,7 +76,6 @@ def symmetrical_epipolar_distance(
Returns:
the computed Symmetrical distance with shape :math:`(*, N)`.
-
"""
if not isinstance(Fm, Tensor):
raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")
@@ -116,8 +114,7 @@ def symmetrical_epipolar_distance(
def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:
- r"""Return one-sided epipolar distance for correspondences given the fundamental
- matrix.
+ r"""Return one-sided epipolar distance for correspondences given the fundamental matrix.
This method measures the distance from points in the right images to the epilines
of the corresponding points in the left images as they reflect in the right images.
@@ -150,8 +147,7 @@ def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> T
def right_to_left_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> Tensor:
- r"""Return one-sided epipolar distance for correspondences given the fundamental
- matrix.
+ r"""Return one-sided epipolar distance for correspondences given the fundamental matrix.
This method measures the distance from points in the left images to the epilines
of the corresponding points in the right images as they reflect in the left images.
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 9ec155b69..5888df9af 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -31,7 +31,6 @@ def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
Returns:
The essential matrix with shape :math:`(*, 3, 3)`.
-
"""
if not (len(F_mat.shape) >= 2 and F_mat.shape[-2:] == (3, 3)):
raise AssertionError(F_mat.shape)
@@ -57,7 +56,6 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch
Returns:
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)]`.
-
"""
if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:]):
raise AssertionError(E_mat.shape)
@@ -102,7 +100,6 @@ def essential_from_Rt(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2:
Returns:
The Essential matrix with the shape :math:`(*, 3, 3)`.
-
"""
if not (len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3)):
raise AssertionError(R1.shape)
@@ -134,7 +131,6 @@ def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tens
Returns:
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)]`.
-
"""
if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3)):
raise AssertionError(E_mat.shape)
@@ -180,7 +176,6 @@ def motion_from_essential_choose_solution(
Returns:
The rotation and translation plus the 3d triangulated points.
The tuple is as following :math:`[(*, 3, 3), (*, 3, 1), (*, N, 3)]`.
-
"""
if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3)):
raise AssertionError(E_mat.shape)
@@ -279,7 +274,6 @@ def relative_camera_motion(
Returns:
A tuple with the relative rotation matrix and
translation vector with the shape of :math:`[(*, 3, 3), (*, 3, 1)]`.
-
"""
if not (len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3)):
raise AssertionError(R1.shape)
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 41df71c80..4cdd224e6 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -25,7 +25,6 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Ten
Returns:
tuple containing the normalized points in the shape :math:`(B, N, 2)` and the transformation matrix
in the shape :math:`(B, 3, 3)`.
-
"""
if len(points.shape) != 3:
raise AssertionError(points.shape)
@@ -61,7 +60,6 @@ def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensor
Returns:
the normalized transformation matrix with same shape as the input.
-
"""
if len(M.shape) < 2:
raise AssertionError(M.shape)
@@ -81,7 +79,6 @@ def find_fundamental(points1: torch.Tensor, points2: torch.Tensor, weights: torc
Returns:
the computed fundamental matrix with shape :math:`(B, 3, 3)`.
-
"""
if points1.shape != points2.shape:
raise AssertionError(points1.shape, points2.shape)
@@ -131,7 +128,6 @@ def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> to
a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar
lines 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)`.
-
"""
if not (len(points.shape) >= 2 and points.shape[-1] == 2):
raise AssertionError(points.shape)
@@ -164,7 +160,6 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
Returns:
The fundamental matrix with shape :math:`(*, 3, 3)`.
-
"""
if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3)):
raise AssertionError(E_mat.shape)
@@ -192,7 +187,6 @@ def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Te
Returns:
The fundamental matrix with shape :math:`(*, 3, 3)`.
-
"""
if not (len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4)):
raise AssertionError(P1.shape)
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
index 011df8a6e..b881a8b2a 100644
--- a/kornia/geometry/epipolar/numeric.py
+++ b/kornia/geometry/epipolar/numeric.py
@@ -11,7 +11,6 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
Returns:
The constructed cross_product_matrix symmetric matrix with shape :math:`(*, 3, 3)`.
-
"""
if not x.shape[-1] == 3:
raise AssertionError(x.shape)
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 8e862979f..bff488c29 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -21,7 +21,6 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
Returns:
The camera matrix with the shape of :math:`(B, 3, 3)`.
-
"""
if len(input.shape) != 4:
raise AssertionError(input.shape)
@@ -47,7 +46,6 @@ def random_intrinsics(low: Union[float, torch.Tensor], high: Union[float, torch.
Returns:
the random camera matrix with the shape of :math:`(1, 3, 3)`.
-
"""
sampler = torch.distributions.Uniform(low, high)
fx, fy, cx, cy = (sampler.sample((1,)) for _ in range(4))
@@ -68,7 +66,6 @@ def scale_intrinsics(camera_matrix: torch.Tensor, scale_factor: Union[float, tor
Returns:
The scaled camera matrix with shame shape as input :math:`(B, 3, 3)`.
-
"""
K_scale = camera_matrix.clone()
K_scale[..., 0, 0] *= scale_factor
@@ -90,7 +87,6 @@ def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> to
Returns:
The projection matrix P with shape :math:`(B, 4, 4)`.
-
"""
if K.shape[-2:] != (3, 3):
raise AssertionError(K.shape)
@@ -121,7 +117,6 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tenso
- 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)`.
-
"""
if P.shape[-2:] != (3, 4):
raise AssertionError("P must be of shape [B, 3, 4]")
@@ -160,7 +155,6 @@ def depth_from_point(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch
Returns:
The depth value per point with shape :math:`(*, 1)`.
-
"""
X_tmp = R @ X.transpose(-2, -1)
X_out = X_tmp[..., 2, :] + t[..., 2, :]
@@ -189,7 +183,6 @@ def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:
Returns:
The projection matrices with shape :math:`(B, 3, 4, 2)`.
-
"""
if len(F_mat.shape) != 3:
raise AssertionError(F_mat.shape)
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index 567459339..2cc834a63 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -28,7 +28,6 @@ def triangulate_points(
Returns:
The reconstructed 3d points in the world frame with shape :math:`(*, N, 3)`.
-
"""
if not (len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4)):
raise AssertionError(P1.shape)
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 6d53b88b1..c2869f10a 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -28,7 +28,6 @@ def oneway_transfer_error(
Returns:
the computed distance with shape :math:`(B, N)`.
-
"""
if not isinstance(H, torch.Tensor):
raise TypeError(f"H type is not a torch.Tensor. Got {type(H)}")
@@ -67,7 +66,6 @@ def symmetric_transfer_error(
Returns:
the computed distance with shape :math:`(B, N)`.
-
"""
if not isinstance(H, torch.Tensor):
raise TypeError(f"H type is not a torch.Tensor. Got {type(H)}")
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index c894d5735..c70c8ea17 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -37,7 +37,6 @@ def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> t
>>> trans_01 = torch.eye(4) # 4x4
>>> trans_12 = torch.eye(4) # 4x4
>>> trans_02 = compose_transformations(trans_01, trans_12) # 4x4
-
"""
if not torch.is_tensor(trans_01):
raise TypeError(f"Input trans_01 type is not a torch.Tensor. Got {type(trans_01)}")
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 8b991250c..116cc3bbe 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -1,7 +1,5 @@
-r"""Implementation of "differentiable spatial to numerical" (soft-argmax)
-operations, as described in the paper "Numerical Coordinate Regression with
-Convolutional Neural Networks" by Nibali et al.
-"""
+r"""Implementation of "differentiable spatial to numerical" (soft-argmax) operations, as described in the paper
+"Numerical Coordinate Regression with Convolutional Neural Networks" by Nibali et al."""
from typing import Tuple
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 00872f558..41a92fd1d 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -15,8 +15,7 @@ from .nms import nms3d
def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
- r"""Helper function, which generates a kernel to with window coordinates,
- residual to window center.
+ r"""Helper function, which generates a kernel to with window coordinates, residual to window center.
Args:
h: kernel height.
@@ -33,8 +32,8 @@ def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.devic
def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
- r"""Helper function, which generates a kernel to return center coordinates,
- when applied with F.conv2d to 2d coordinates grid.
+ r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 2d
+ coordinates grid.
Args:
h: kernel height.
@@ -64,8 +63,8 @@ def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cp
def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
- r"""Helper function, which generates a kernel to return center coordinates,
- when applied with F.conv2d to 3d coordinates grid.
+ r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 3d
+ coordinates grid.
Args:
d: kernel depth.
@@ -102,8 +101,7 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.de
def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
- r"""Helper function, which generates a kernel to return coordinates,
- residual to window center.
+ r"""Helper function, which generates a kernel to return coordinates, residual to window center.
Args:
d: kernel depth.
@@ -643,7 +641,7 @@ def conv_quad_interp3d(
class ConvQuadInterp3d(nn.Module):
- r"""Calculate soft argmax 3d per window
+ r"""Calculate soft argmax 3d per window.
See :func:`~kornia.geometry.subpix.conv_quad_interp3d` for details.
"""
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index 69657ea19..cd2dcae01 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -106,7 +106,6 @@ def rot180(input: torch.Tensor) -> torch.Tensor:
Returns:
The rotated image tensor.
-
"""
return torch.flip(input, [-2, -1])
@@ -124,7 +123,6 @@ def hflip(input: torch.Tensor) -> torch.Tensor:
Returns:
The horizontally flipped image tensor.
-
"""
w = input.shape[-1]
return input[..., torch.arange(w - 1, -1, -1, device=input.device)]
@@ -142,7 +140,6 @@ def vflip(input: torch.Tensor) -> torch.Tensor:
Returns:
The vertically flipped image tensor.
-
"""
h = input.shape[-2]
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 311e4aeec..488050869 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -14,9 +14,8 @@ __all__ = ["ImageRegistrator", "Homography", "Similarity"]
class Homography(nn.Module):
- r"""Homography geometric model to be used together with ImageRegistrator
- module for the optimization-based image
- registration."""
+ r"""Homography geometric model to be used together with ImageRegistrator module for the optimization-based
+ image registration."""
def __init__(self) -> None:
super().__init__()
@@ -87,7 +86,8 @@ class Similarity(nn.Module):
r"""Single-batch similarity transform".
Returns:
- Similarity with shape :math:`(1, 3, 3)`"""
+ Similarity with shape :math:`(1, 3, 3)`
+ """
rot = self.scale * angle_to_rotation_matrix(self.rot)
out = convert_affinematrix_to_homography(torch.cat([rot, self.shift], dim=2))
return out
@@ -96,7 +96,8 @@ class Similarity(nn.Module):
r"""Single-batch inverse similarity transform".
Returns:
- Similarity with shape :math:`(1, 3, 3)`"""
+ Similarity with shape :math:`(1, 3, 3)`
+ """
return torch.inverse(self.forward())
@@ -197,8 +198,8 @@ class ImageRegistrator(nn.Module):
verbose: bool = False,
output_intermediate_models: bool = False,
) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]:
- r"""Estimate the tranformation' which warps src_img into dst_img by gradient descent.
- The shape of the tensors is not checked, because it may depend on the model, e.g. volume registration
+ r"""Estimate the tranformation' which warps src_img into dst_img by gradient descent. The shape of the
+ tensors is not checked, because it may depend on the model, e.g. volume registration.
Args:
src_img: Input image tensor.
@@ -209,7 +210,6 @@ class ImageRegistrator(nn.Module):
Returns:
the transformation between two images, shape depends on the model,
typically [1x3x3] tensor for string model_types.
-
"""
self.reset_model()
# ToDo: better parameter passing to optimizer
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 39b135409..fad72c6b6 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -874,7 +874,6 @@ def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
Returns:
the projection matrix with shape :math:`(*, 3, 4)`.
-
"""
if not (len(rmat.shape) >= 2 and rmat.shape[-2:] == (3, 3)):
raise AssertionError(rmat.shape)
@@ -1244,7 +1243,6 @@ def homography_warp(
>>> out = homography_warp(img, H, (4, 2), align_corners=True, normalized_homography=False)
>>> print(out.shape)
torch.Size([1, 4, 4, 2])
-
"""
if not src_homo_dst.device == patch_src.device:
raise TypeError(
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index ef9af3211..3419dda2e 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -12,8 +12,8 @@ __all__ = ["get_tps_transform", "warp_points_tps", "warp_image_tps"]
def _pair_square_euclidean(tensor1: torch.Tensor, tensor2: torch.Tensor) -> torch.Tensor:
- r"""Compute the pairwise squared euclidean distance matrices :math:`(B, N, M)` between two tensors
- with shapes (B, N, C) and (B, M, C)."""
+ r"""Compute the pairwise squared euclidean distance matrices :math:`(B, N, M)` between two tensors with shapes
+ (B, N, C) and (B, M, C)."""
# ||t1-t2||^2 = (t1-t2)^T(t1-t2) = t1^T*t1 + t2^T*t2 - 2*t1^T*t2
t1_sq: torch.Tensor = tensor1.mul(tensor1).sum(dim=-1, keepdim=True)
t2_sq: torch.Tensor = tensor2.mul(tensor2).sum(dim=-1, keepdim=True).transpose(1, 2)
@@ -25,8 +25,10 @@ def _pair_square_euclidean(tensor1: torch.Tensor, tensor2: torch.Tensor) -> torc
def _kernel_distance(squared_distances: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Compute the TPS kernel distance function: :math:`r^2 log(r)`, where `r` is the euclidean distance.
+
Since :math:`\log(r) = 1/2 \log(r^2)`, this function takes the squared distance matrix and calculates
- :math:`0.5 r^2 log(r^2)`."""
+ :math:`0.5 r^2 log(r^2)`.
+ """
# r^2 * log(r) = 1/2 * r^2 * log(r^2)
return 0.5 * squared_distances * squared_distances.add(eps).log()
@@ -93,8 +95,8 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> Tup
def warp_points_tps(
points_src: torch.Tensor, kernel_centers: torch.Tensor, kernel_weights: torch.Tensor, affine_weights: torch.Tensor
) -> torch.Tensor:
- r"""Warp a tensor of coordinate points using the thin plate spline defined by kernel points, kernel weights,
- and affine weights.
+ r"""Warp a tensor of coordinate points using the thin plate spline defined by kernel points, kernel weights, and
+ affine weights.
The source points should be a :math:`(B, N, 2)` tensor of :math:`(x, y)` coordinates. The kernel centers are
a :math:`(B, K, 2)` tensor of :math:`(x, y)` coordinates. The kernel weights are a :math:`(B, K, 2)` tensor,
@@ -164,8 +166,8 @@ def warp_image_tps(
affine_weights: torch.Tensor,
align_corners: bool = False,
) -> torch.Tensor:
- r"""Warp an image tensor according to the thin plate spline transform defined by kernel centers,
- kernel weights, and affine weights.
+ r"""Warp an image tensor according to the thin plate spline transform defined by kernel centers, kernel weights,
+ and affine weights.
.. image:: _static/img/warp_image_tps.png
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 35cb4db24..f7af35228 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -16,7 +16,7 @@ from kornia.testing import KORNIA_CHECK
class ImageLoadType(Enum):
- r"""Enum to specify the desired image type"""
+ r"""Enum to specify the desired image type."""
UNCHANGED = 0
GRAY8 = 1
RGB8 = 2
diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.py
index 610865d25..1c5833969 100644
--- a/kornia/tracking/planar_tracker.py
+++ b/kornia/tracking/planar_tracker.py
@@ -11,8 +11,8 @@ from kornia.geometry.transform import warp_perspective
class HomographyTracker(nn.Module):
- r"""Module, which performs local-feature-based tracking of the target planar object in the
- sequence of the frames.
+ r"""Module, which performs local-feature-based tracking of the target planar object in the sequence of the
+ frames.
Args:
initial_matcher: image matching module, e.g. :class:`~kornia.feature.LocalFeatureMatcher`
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
index fedb08e17..e7bffbc67 100644
--- a/kornia/utils/draw.py
+++ b/kornia/utils/draw.py
@@ -252,6 +252,7 @@ def _get_convex_edges(polygon: Tensor, h: int, w: int) -> Tuple[Tensor, Tensor]:
def _batch_polygons(polygons: List[Tensor]) -> Tensor:
r"""Converts a List of variable length polygons into a fixed size tensor.
+
Works by repeating the last element in the tensor.
Args:
polygon: List of variable length polygons of shape [N_1 x 2, N_2 x 2, ..., N_B x 2].
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 203a95433..cf1bd7fdd 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -146,8 +146,8 @@ def _torch_solve_cast(A: Tensor, B: Tensor) -> Tensor:
def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
- r"""Helper function, which avoids crashing because of singular matrix input and outputs the
- mask of valid solution"""
+ r"""Helper function, which avoids crashing because of singular matrix input and outputs the mask of valid
+ solution."""
if not torch_version_geq(1, 10):
sol = _torch_solve_cast(A, B)
warnings.warn('PyTorch version < 1.10, solve validness mask maybe not correct', RuntimeWarning)
@@ -165,8 +165,8 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor
def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
- r"""Helper function, which avoids crashing because of non-invertable matrix input and outputs the
- mask of valid solution"""
+ r"""Helper function, which avoids crashing because of non-invertable matrix input and outputs the mask of valid
+ solution."""
# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
if not torch_version_geq(1, 9):
inv = _torch_inverse_cast(A)
diff --git a/kornia/utils/misc.py b/kornia/utils/misc.py
index 4a1f5bbc5..04a3a7f24 100644
--- a/kornia/utils/misc.py
+++ b/kornia/utils/misc.py
@@ -11,7 +11,6 @@ def eye_like(n: int, input: torch.Tensor) -> torch.Tensor:
Returns:
The identity matrix with the same batch size as the input :math:`(B, N, N)`.
-
"""
if n <= 0:
raise AssertionError(type(n), n)
@@ -32,7 +31,6 @@ def vec_like(n, tensor):
Returns:
The vector with the same batch size as the input :math:`(B, N, 1)`.
-
"""
if n <= 0:
raise AssertionError(type(n), n)
diff --git a/kornia/utils/one_hot.py b/kornia/utils/one_hot.py
index 028062037..bfb37ebae 100644
--- a/kornia/utils/one_hot.py
+++ b/kornia/utils/one_hot.py
@@ -33,7 +33,6 @@ def one_hot(
<BLANKLINE>
[[1.0000e-06, 1.0000e-06],
[1.0000e+00, 1.0000e-06]]]])
-
"""
if not isinstance(labels, torch.Tensor):
raise TypeError(f"Input labels type is not a torch.Tensor. Got {type(labels)}")
diff --git a/test/geometry/calibration/test_pnp.py b/test/geometry/calibration/test_pnp.py
index de61f1b27..9453f7730 100644
--- a/test/geometry/calibration/test_pnp.py
+++ b/test/geometry/calibration/test_pnp.py
@@ -17,8 +17,8 @@ class TestSolvePnpDlt:
def _project_to_image(world_points, world_to_cam_4x4, repeated_intrinsics):
r"""Projects points in the world coordinate system to the image coordinate system.
- Since cam_points will have shape (B, N, 3), repeated_intrinsics should have
- shape (B, N, 3, 3) so that kornia.geometry.project_points can be used.
+ Since cam_points will have shape (B, N, 3), repeated_intrinsics should have shape (B, N, 3, 3) so that
+ kornia.geometry.project_points can be used.
"""
cam_points = kornia.geometry.transform_points(world_to_cam_4x4, world_points)
img_points = kornia.geometry.project_points(cam_points, repeated_intrinsics)
@@ -29,8 +29,8 @@ class TestSolvePnpDlt:
def _get_world_points_and_img_points(cam_points, world_to_cam_4x4, repeated_intrinsics):
r"""Calculates world_points and img_points.
- Since cam_points will have shape (B, N, 3), repeated_intrinsics should have
- shape (B, N, 3, 3) so that kornia.geometry.project_points can be used.
+ Since cam_points will have shape (B, N, 3), repeated_intrinsics should have shape (B, N, 3, 3) so that
+ kornia.geometry.project_points can be used.
"""
cam_to_world_4x4 = kornia.geometry.inverse_transformation(world_to_cam_4x4)
world_points = kornia.geometry.transform_points(cam_to_world_4x4, cam_points)
diff --git a/test/geometry/test_linalg.py b/test/geometry/test_linalg.py
index 94ba76681..c98e650d0 100644
--- a/test/geometry/test_linalg.py
+++ b/test/geometry/test_linalg.py
@@ -9,12 +9,12 @@ from kornia.testing import assert_close
def identity_matrix(batch_size, device, dtype):
- r"""Create a batched homogeneous identity matrix"""
+ r"""Create a batched homogeneous identity matrix."""
return torch.eye(4, device=device, dtype=dtype).repeat(batch_size, 1, 1) # Nx4x4
def euler_angles_to_rotation_matrix(x, y, z):
- r"""Create a rotation matrix from x, y, z angles"""
+ r"""Create a rotation matrix from x, y, z angles."""
assert x.dim() == 1, x.shape
assert x.shape == y.shape == z.shape
ones, zeros = torch.ones_like(x), torch.zeros_like(x)