Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add docformatter in pre-commit (#1242)

Edgar Riba75250007b59a
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index f44f08f9f..aedf122fc 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -56,3 +56,9 @@ repos:
- --skip
- "B101,B110,B311,B404,B602,B603,B607"
- .
+
+ - repo: https://github.com/myint/docformatter
+ rev: v1.4
+ hooks:
+ - id: docformatter
+ args: [--in-place, --wrap-summaries=115, --wrap-descriptions=120]
diff --git a/conftest.py b/conftest.py
index 9e4c02fd8..67811303f 100644
--- a/conftest.py
+++ b/conftest.py
@@ -8,8 +8,8 @@ import kornia
def get_test_devices() -> Dict[str, torch.device]:
- """Creates a dictionary with the devices to test the source code.
- CUDA devices will be test only in case the current hardware supports it.
+ """Create a dictionary with the devices to test the source code. CUDA devices will be test only in case the
+ current hardware supports it.
Return:
dict(str, torch.device): list with devices names.
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 75dc4aeea..6f670ef9e 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -57,8 +57,7 @@ class _BasicAugmentationBase(nn.Module):
return input
def __check_batching__(self, input: TensorWithTransformMat):
- """Check if a transformation matrix is returned,
- it has to be in the same batching mode as output."""
+ """Check if a transformation matrix is returned, it has to be in the same batching mode as output."""
raise NotImplementedError
def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index cbb41b07c..c56f6a45d 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -237,8 +237,8 @@ class AugmentationSequential(ImageSequential):
) -> Union[torch.Tensor, List[torch.Tensor]]:
"""Reverse the transformation applied.
- Number of input tensors must align with the number of``data_keys``. If ``data_keys``
- is not set, use ``self.data_keys`` by default.
+ Number of input tensors must align with the number of``data_keys``. If ``data_keys`` is not set, use
+ ``self.data_keys`` by default.
"""
if data_keys is None:
data_keys = cast(List[Union[str, int, DataKey]], self.data_keys)
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index a74380e63..a33903b92 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -99,8 +99,7 @@ def _tuple_range_reader(
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
- """
- Given target_size, it will generate the corresponding (target_size, 2) range tensor for element-wise params.
+ """Given target_size, it will generate the corresponding (target_size, 2) range tensor for element-wise params.
Example:
>>> degree = torch.tensor([0.2, 0.3])
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 1b2a10f64..eaeb5f1ec 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -9,8 +9,8 @@ __all__ = ["histogram", "histogram2d", "image_histogram2d"]
def marginal_pdf(
values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float = 1e-10
) -> Tuple[torch.Tensor, torch.Tensor]:
- """Function that calculates the marginal probability distribution function of the input tensor
- based on the number of histogram bins.
+ """Function that calculates the marginal probability distribution function of the input tensor based on the
+ number of histogram bins.
Args:
values: shape [BxNx1].
@@ -22,7 +22,6 @@ def marginal_pdf(
Tuple[torch.Tensor, torch.Tensor]:
- torch.Tensor: shape [BxN].
- torch.Tensor: shape [BxNxNUM_BINS].
-
"""
if not isinstance(values, torch.Tensor):
@@ -54,8 +53,8 @@ def marginal_pdf(
def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:
- """Function that calculates the joint probability distribution function of the input tensors
- based on the number of histogram bins.
+ """Function that calculates the joint probability distribution function of the input tensors based on the
+ number of histogram bins.
Args:
kernel_values1: shape [BxNxNUM_BINS].
@@ -64,7 +63,6 @@ def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilo
Returns:
shape [BxNUM_BINSxNUM_BINS].
-
"""
if not isinstance(kernel_values1, torch.Tensor):
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 6cce0eebb..0a622e1e1 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -186,7 +186,7 @@ class LAFAffNetShapeEstimator(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- "Utility function that normalizes the input by batch." ""
+ """Utility function that normalizes the input by batch."""
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
# WARNING: we need to .detach() input, otherwise the gradients produced by
# the patches extractor with F.grid_sample are very noisy, making the detector
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index ebd7d9345..a60c00817 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -13,12 +13,12 @@ urls["defmo_rendering"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_save
def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
- """1x1 convolution"""
+ """1x1 convolution."""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
- """3x3 convolution with padding"""
+ """3x3 convolution with padding."""
return nn.Conv2d(
in_planes,
out_planes,
@@ -260,8 +260,7 @@ class RenderingDeFMO(nn.Module):
class DeFMO(nn.Module):
- """
- Module that disentangle a fast-moving object from the background and performs deblurring.
+ """Module that disentangle a fast-moving object from the background and performs deblurring.
This is based on the original code from paper "DeFMO: Deblurring and Shape Recovery
of Fast Moving Objects". See :cite:`DeFMO2021` for more details.
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 600083e8e..7cddfbb10 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -69,7 +69,7 @@ class HardNet(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- "Utility function that normalizes the input by batch." ""
+ """Utility function that normalizes the input by batch."""
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
# WARNING: we need to .detach() input, otherwise the gradients produced by
# the patches extractor with F.grid_sample are very noisy, making the detector
@@ -155,7 +155,7 @@ class HardNet8(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
- "Utility function that normalizes the input by batch." ""
+ """Utility function that normalizes the input by batch."""
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
# WARNING: we need to .detach() input, otherwise the gradients produced by
# the patches extractor with F.grid_sample are very noisy, making the detector
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 73f1915e6..9d7c21b84 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -104,7 +104,6 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torc
Shape:
- Input: :math: `(B, N, 2, 3)`, `(B, N, 1)`
- Output: :math: `(B, N, 2, 3)`
-
"""
raise_error_if_laf_is_not_valid(LAF)
B, N = LAF.shape[:2]
@@ -396,7 +395,6 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor
Returns:
grid
-
"""
raise_error_if_laf_is_not_valid(LAF)
B, N, _, _ = LAF.size()
@@ -524,8 +522,8 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0
def laf_to_three_points(laf: torch.Tensor):
- """Converts local affine frame(LAF) to alternative representation: coordinates of
- LAF center, LAF-x unit vector, LAF-y unit vector.
+ """Convert local affine frame(LAF) to alternative representation: coordinates of LAF center, LAF-x unit vector,
+ LAF-y unit vector.
Args:
laf: :math:`(B, N, 2, 3)`.
diff --git a/kornia/feature/nms.py b/kornia/feature/nms.py
index a48ee0b99..949f4cfb8 100644
--- a/kornia/feature/nms.py
+++ b/kornia/feature/nms.py
@@ -6,7 +6,7 @@ import torch.nn.functional as F
def _get_nms_kernel2d(kx: int, ky: int) -> torch.Tensor:
- """Utility function, which returns neigh2channels conv kernel"""
+ """Utility function, which returns neigh2channels conv kernel."""
numel: int = ky * kx
center: int = numel // 2
weight = torch.eye(numel)
@@ -15,7 +15,7 @@ def _get_nms_kernel2d(kx: int, ky: int) -> torch.Tensor:
def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> torch.Tensor:
- """Utility function, which returns neigh2channels conv kernel"""
+ """Utility function, which returns neigh2channels conv kernel."""
numel: int = kd * ky * kx
center: int = numel // 2
weight = torch.eye(numel)
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 3e45a357a..c27400ec1 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -20,7 +20,7 @@ urls["orinet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/Ori
class PassLAF(nn.Module):
- """Dummy module to use instead of local feature orientation or affine shape estimator"""
+ """Dummy module to use instead of local feature orientation or affine shape estimator."""
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
"""
@@ -175,7 +175,7 @@ class OriNet(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- "Utility function that normalizes the input by batch." ""
+ """Utility function that normalizes the input by batch.""" ""
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
# WARNING: we need to .detach() input, otherwise the gradients produced by
# the patches extractor with F.grid_sample are very noisy, making the detector
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 8eaaecd6a..91f936eb6 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -147,12 +147,12 @@ def get_binary_kernel2d(window_size: Tuple[int, int]) -> torch.Tensor:
def get_sobel_kernel_3x3() -> torch.Tensor:
- """Utility function that returns a sobel kernel of 3x3"""
+ """Utility function that returns a sobel kernel of 3x3."""
return torch.tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]])
def get_sobel_kernel_5x5_2nd_order() -> torch.Tensor:
- """Utility function that returns a 2nd order sobel kernel of 5x5"""
+ """Utility function that returns a 2nd order sobel kernel of 5x5."""
return torch.tensor(
[
[-1.0, 0.0, 2.0, 0.0, -1.0],
@@ -165,7 +165,7 @@ def get_sobel_kernel_5x5_2nd_order() -> torch.Tensor:
def _get_sobel_kernel_5x5_2nd_order_xy() -> torch.Tensor:
- """Utility function that returns a 2nd order sobel kernel of 5x5"""
+ """Utility function that returns a 2nd order sobel kernel of 5x5."""
return torch.tensor(
[
[-1.0, -2.0, 0.0, 2.0, 1.0],
@@ -178,12 +178,12 @@ def _get_sobel_kernel_5x5_2nd_order_xy() -> torch.Tensor:
def get_diff_kernel_3x3() -> torch.Tensor:
- """Utility function that returns a first order derivative kernel of 3x3"""
+ """Utility function that returns a first order derivative kernel of 3x3."""
return torch.tensor([[-0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [-0.0, 0.0, 0.0]])
def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
- """Utility function that returns a first order derivative kernel of 3x3x3"""
+ """Utility function that returns a first order derivative kernel of 3x3x3."""
kernel: torch.Tensor = torch.tensor(
[
[
@@ -209,7 +209,7 @@ def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> torch.Te
def get_diff_kernel3d_2nd_order(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
- """Utility function that returns a first order derivative kernel of 3x3x3"""
+ """Utility function that returns a first order derivative kernel of 3x3x3."""
kernel: torch.Tensor = torch.tensor(
[
[
@@ -595,7 +595,7 @@ def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> torch.Tensor:
def get_canny_nms_kernel(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
- """Utility function that returns 3x3 kernels for the Canny Non-maximal suppression"""
+ """Utility function that returns 3x3 kernels for the Canny Non-maximal suppression."""
kernel: torch.Tensor = torch.tensor(
[
[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]],
@@ -614,7 +614,7 @@ def get_canny_nms_kernel(device=torch.device('cpu'), dtype=torch.float) -> torch
def get_hysteresis_kernel(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
- """Utility function that returns the 3x3 kernels for the Canny hysteresis"""
+ """Utility function that returns the 3x3 kernels for the Canny hysteresis."""
kernel: torch.Tensor = torch.tensor(
[
[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]],
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 414c1426f..a8de610ee 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -487,7 +487,7 @@ def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:
- """Get extrinsic transformation matrices for pinholes
+ """Compute extrinsic transformation matrices for pinholes.
Args:
pinholes: tensor of form [fx fy cx cy h w rx ry rz tx ty tz]
@@ -495,7 +495,6 @@ def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:
Returns:
tensor of extrinsic transformation matrices of size (N, 4, 4).
-
"""
if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):
raise AssertionError(pinholes.shape)
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 5cd160f65..7bd409e79 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -258,11 +258,10 @@ class DepthWarper(nn.Module):
return torch.cat([x, y], 1)
def compute_subpixel_step(self) -> torch.Tensor:
- """This computes the required inverse depth step to achieve sub pixel
- accurate sampling of the depth cost volume, per camera.
+ """Compute the required inverse depth step to achieve sub pixel accurate sampling of the depth cost volume,
+ per camera.
- Szeliski, Richard, and Daniel Scharstein.
- "Symmetric sub-pixel stereo matching." European Conference on Computer
+ Szeliski, Richard, and Daniel Scharstein. "Symmetric sub-pixel stereo matching." European Conference on Computer
Vision. Springer Berlin Heidelberg, 2002.
"""
delta_d = 0.01
@@ -274,12 +273,11 @@ 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.
+ """Compute a grid for warping a given the depth from the reference pinhole camera.
- The function `compute_projection_matrix` has to be called beforehand in
- order to have precomputed the relative projection matrices encoding the
- relative pose and the intrinsics between the reference and a non
- reference camera.
+ The function `compute_projection_matrix` has to be called beforehand in order to have precomputed the relative
+ projection matrices encoding the relative pose and the intrinsics between the reference and a non reference
+ camera.
"""
# TODO: add type and value checkings
if self._dst_proj_src is None or self._pinhole_src is None:
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
index 77753970a..7b5116818 100644
--- a/kornia/geometry/epipolar/numeric.py
+++ b/kornia/geometry/epipolar/numeric.py
@@ -1,4 +1,4 @@
-"""Module containing numerical functionalities for SfM"""
+"""Module containing numerical functionalities for SfM."""
import torch
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 824db5835..cb0edce0b 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -170,9 +170,10 @@ def depth(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch.Tensor:
def _nullspace(A):
- '''Compute the null space of A.
+ """Compute the null space of A.
+
Return the smallest singular value and the corresponding vector.
- '''
+ """
u, s, vh = torch.svd(A)
return s[..., -1], vh[..., -1]
diff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.py
index cc8d3397b..8df499082 100644
--- a/kornia/geometry/transform/crop/crop2d.py
+++ b/kornia/geometry/transform/crop/crop2d.py
@@ -284,6 +284,7 @@ def crop_by_transform_mat(
@torch.jit.ignore
def validate_bboxes(boxes: torch.Tensor) -> bool:
"""Validate if a 2D bounding box usable or not.
+
This function checks if the boxes are rectangular or not.
Args:
boxes (torch.Tensor): a tensor containing the coordinates of the
@@ -291,7 +292,6 @@ def validate_bboxes(boxes: torch.Tensor) -> bool:
of Bx4x2, where each box is defined in the following (clockwise)
order: top-left, top-right, bottom-right, bottom-left. The
coordinates must be in the x, y order.
-
"""
warnings.warn(
"`kornia.geometry.transforms.crop.crop2d.validate_bboxes` is deprecated and will be removed > 0.6.0. "
diff --git a/kornia/geometry/transform/crop/crop3d.py b/kornia/geometry/transform/crop/crop3d.py
index 74f3b08e5..fe416ca10 100644
--- a/kornia/geometry/transform/crop/crop3d.py
+++ b/kornia/geometry/transform/crop/crop3d.py
@@ -309,7 +309,6 @@ def crop_by_boxes3d(
[[37., 38., 39.],
[41., 42., 43.],
[45., 46., 47.]]]]])
-
"""
_validate_bbox3d(src_box)
_validate_bbox3d(dst_box)
@@ -377,6 +376,7 @@ def crop_by_transform_mat3d(
@torch.jit.ignore
def validate_bboxes3d(boxes: torch.Tensor) -> bool:
"""Validate if a 3D bounding box usable or not.
+
This function checks if the boxes are cube or not.
Args:
boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 8f41173f9..688cdf681 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -1,6 +1,4 @@
-"""
-The testing package contains testing-specific utilities.
-"""
+"""The testing package contains testing-specific utilities."""
import contextlib
import importlib
from abc import ABC, abstractmethod
@@ -22,19 +20,20 @@ def xla_is_available() -> bool:
# TODO: Isn't this function duplicated with eye_like?
def create_eye_batch(batch_size, eye_size, device=None, dtype=None):
- """Creates a batch of identity matrices of shape Bx3x3"""
+ """Create a batch of identity matrices of shape Bx3x3."""
return torch.eye(eye_size, device=device, dtype=dtype).view(1, eye_size, eye_size).expand(batch_size, -1, -1)
def create_random_homography(batch_size, eye_size, std_val=1e-3):
- """Creates a batch of random homographies of shape Bx3x3"""
+ """Create a batch of random homographies of shape Bx3x3."""
std = torch.FloatTensor(batch_size, eye_size, eye_size)
eye = create_eye_batch(batch_size, eye_size)
return eye + std.uniform_(-std_val, std_val)
def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True):
- """Converts the input tensor to a valid variable to check the gradient.
+ """Convert the input tensor to a valid variable to check the gradient.
+
`gradcheck` needs 64-bit floating point and requires gradient.
"""
if not torch.is_tensor(tensor):
@@ -54,14 +53,14 @@ def check_is_tensor(obj):
def create_rectified_fundamental_matrix(batch_size):
- """Creates a batch of rectified fundamental matrices of shape Bx3x3"""
+ """Create a batch of rectified fundamental matrices of shape Bx3x3."""
F_rect = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).view(1, 3, 3)
F_repeat = F_rect.repeat(batch_size, 1, 1)
return F_repeat
def create_random_fundamental_matrix(batch_size, std_val=1e-3):
- """Creates a batch of random fundamental matrices of shape Bx3x3"""
+ """Create a batch of random fundamental matrices of shape Bx3x3."""
F_rect = create_rectified_fundamental_matrix(batch_size)
H_left = create_random_homography(batch_size, 3, std_val)
H_right = create_random_homography(batch_size, 3, std_val)
@@ -95,7 +94,7 @@ class BaseTester(ABC):
def cartesian_product_of_parameters(**possible_parameters):
- """Creates cartesian product of given parameters"""
+ """Create cartesian product of given parameters."""
parameter_names = possible_parameters.keys()
possible_values = [possible_parameters[parameter_name] for parameter_name in parameter_names]
diff --git a/kornia/utils/grid.py b/kornia/utils/grid.py
index 8bc6a4aff..affc1006e 100644
--- a/kornia/utils/grid.py
+++ b/kornia/utils/grid.py
@@ -42,7 +42,6 @@ def create_meshgrid(
<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)
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 5aee37289..62c3f372e 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -39,9 +39,8 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
"""Helper function to make torch.inverse work with other than fp32/64.
- The function torch.inverse is only implemented for fp32/64 which makes
- impossible to be used by fp16 or others. What this function does, is cast
- input data type to fp32, apply torch.inverse, and cast back to the input dtype.
+ The function torch.inverse is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
+ this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
if not isinstance(input, torch.Tensor):
raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
@@ -54,9 +53,8 @@ def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
def _torch_histc_cast(input: torch.Tensor, bins: int, min: int, max: int) -> torch.Tensor:
"""Helper function to make torch.histc work with other than fp32/64.
- The function torch.histc is only implemented for fp32/64 which makes
- impossible to be used by fp16 or others. What this function does, is cast
- input data type to fp32, apply torch.inverse, and cast back to the input dtype.
+ The function torch.histc is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
+ this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
if not isinstance(input, torch.Tensor):
raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
@@ -90,9 +88,8 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
def _torch_solve_cast(input: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Helper function to make torch.solve work with other than fp32/64.
- The function torch.solve is only implemented for fp32/64 which makes
- impossible to be used by fp16 or others. What this function does, is cast
- input data type to fp32, apply torch.svd, and cast back to the input dtype.
+ The function torch.solve is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
+ this function does, is cast input data type to fp32, apply torch.svd, and cast back to the input dtype.
"""
if not isinstance(input, torch.Tensor):
raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 5f8fd5274..7f0c131e5 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -111,7 +111,6 @@ def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False) -> "np.ndarray"
Returns:
image of the form :math:`(H, W)`, :math:`(H, W, C)` or :math:`(B, H, W, C)`.
-
"""
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
@@ -161,10 +160,10 @@ class ImageToTensor(nn.Module):
def perform_keep_shape_image(f: Callable) -> Callable:
- """
- A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, H, W)`.
- It works by first viewing the image as `(B, C, H, W)`, applying the function and re-viewing the
- image as original shape.
+ """A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, H, W)`.
+
+ It works by first viewing the image as `(B, C, H, W)`, applying the function and re-viewing the image as original
+ shape.
"""
@wraps(f)
@@ -193,10 +192,10 @@ def perform_keep_shape_image(f: Callable) -> Callable:
def perform_keep_shape_video(f: Callable) -> Callable:
- """
- A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, D, H, W)`.
- It works by first viewing the image as `(B, C, D, H, W)`, applying the function and re-viewing the
- image as original shape.
+ """A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, D, H, W)`.
+
+ It works by first viewing the image as `(B, C, D, H, W)`, applying the function and re-viewing the image as original
+ shape.
"""
@wraps(f)
diff --git a/test/enhance/test_zca.py b/test/enhance/test_zca.py
index 445e044f6..8e62d794d 100644
--- a/test/enhance/test_zca.py
+++ b/test/enhance/test_zca.py
@@ -58,11 +58,7 @@ class TestZCA:
@pytest.mark.parametrize("input_shape,eps", [((15, 2, 2, 2), 1e-6), ((10, 4), 0.1), ((20, 3, 2, 2), 1e-3)])
def test_identity(self, input_shape, eps, device, dtype):
- """
-
- Assert that data can be recovered by the inverse transform
-
- """
+ """Assert that data can be recovered by the inverse transform."""
data = torch.randn(*input_shape, device=device, dtype=dtype)
@@ -76,11 +72,7 @@ class TestZCA:
assert_close(data, data_hat, rtol=tol_val, atol=tol_val)
def test_grad_zca_individual_transforms(self, device, dtype):
- """
-
- Checks if the gradients of the transforms are correct w.r.t to the input data
-
- """
+ """Check if the gradients of the transforms are correct w.r.t to the input data."""
data = torch.tensor([[2, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=dtype)
diff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.py
index a00751fb4..84ee5c0e7 100644
--- a/test/geometry/test_conversions.py
+++ b/test/geometry/test_conversions.py
@@ -12,7 +12,7 @@ from kornia.testing import assert_close, create_eye_batch, tensor_to_gradcheck_v
@pytest.fixture
def atol(device, dtype):
- """Lower tolerance for cuda-float16 only"""
+ """Lower tolerance for cuda-float16 only."""
if 'cuda' in device.type and dtype == torch.float16:
return 1.0e-3
return 1.0e-4
@@ -20,7 +20,7 @@ def atol(device, dtype):
@pytest.fixture
def rtol(device, dtype):
- """Lower tolerance for cuda-float16 only"""
+ """Lower tolerance for cuda-float16 only."""
if 'cuda' in device.type and dtype == torch.float16:
return 1.0e-3
return 1.0e-4
diff --git a/test/integration/test_conversions.py b/test/integration/test_conversions.py
index e991a66a7..40c9610e4 100644
--- a/test/integration/test_conversions.py
+++ b/test/integration/test_conversions.py
@@ -9,7 +9,7 @@ from kornia.testing import assert_close
@pytest.fixture
def atol(device, dtype):
- """Lower tolerance for cuda-float16 only"""
+ """Lower tolerance for cuda-float16 only."""
if 'cuda' in device.type and dtype == torch.float16:
return 1.0e-3
return 1.0e-4
@@ -17,7 +17,7 @@ def atol(device, dtype):
@pytest.fixture
def rtol(device, dtype):
- """Lower tolerance for cuda-float16 only"""
+ """Lower tolerance for cuda-float16 only."""
if 'cuda' in device.type and dtype == torch.float16:
return 1.0e-3
return 1.0e-4
@@ -280,15 +280,13 @@ class TestAngleOfRotations:
@staticmethod
def matrix_angle_abs(mx: torch.Tensor):
- """Unsigned rotation matrix angle"""
+ """Unsigned rotation matrix angle."""
trace = torch.diagonal(mx[..., :3, :3], dim1=-1, dim2=-2).sum(-1, keepdim=True)
return torch.acos((trace - 1.0) / 2.0)
@staticmethod
def axis_and_angle_to_rotation_matrix(axis_name: str, angle: torch.Tensor, device, dtype):
- """
- See also: https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations
- """
+ """See also: https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations."""
axis_name = axis_name.lower()
assert axis_name in ('x', 'y', 'z')
sn = torch.sin(angle)
diff --git a/test/integration/test_soft_argmax2d.py b/test/integration/test_soft_argmax2d.py
index fcd423c6d..d7d5898a4 100644
--- a/test/integration/test_soft_argmax2d.py
+++ b/test/integration/test_soft_argmax2d.py
@@ -21,6 +21,7 @@ class TestIntegrationSoftArgmax2d:
def generate_sample(self, base_target, std_val=1.0):
"""Generates a random sample around the given point.
+
The standard deviation is in pixel.
"""
noise = std_val * torch.rand_like(base_target)