Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

chore (docs): enable some Ruff rules for Docstring (#3088)

Nick7ca9a0abed44
diff --git a/conftest.py b/conftest.py
index f981f418c..b418ac214 100644
--- a/conftest.py
+++ b/conftest.py
@@ -22,8 +22,9 @@ WEIGHTS_CACHE_DIR = "weights/"
def get_test_devices() -> dict[str, torch.device]:
- """Create 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/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 4aeee7f99..7bd84a122 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -223,6 +223,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
params: the corresponding parameters for an operation.
flags: static parameters.
transform: the inverse transformation matrix
+ kwargs: additional arguments
"""
output = input.clone()
diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.py
index a643cf146..879b11a7c 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py
@@ -10,8 +10,9 @@ from kornia.filters import gaussian_blur2d
class RandomGaussianBlur(IntensityAugmentationBase2D):
- r"""Apply gaussian blur given tensor image or a batch of tensor images randomly. The standard deviation is
- sampled for each instance.
+ r"""Apply gaussian blur given tensor image or a batch of tensor images randomly.
+
+ The standard deviation is sampled for each instance.
.. image:: _static/img/RandomGaussianBlur.png
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 6d08c4405..a7b94440e 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -25,7 +25,7 @@ TensorWithTransformMat = Union[Tensor, Tuple[Tensor, Tensor]]
# https://github.com/python/mypy/issues/8795
# Based on the trick that torch.nn.Module does for the forward method
def _apply_transform_unimplemented(self: Module, *input: Any) -> Tensor:
- r"""Defines the computation performed at every call.
+ r"""Define the computation performed at every call.
Should be overridden by all subclasses.
"""
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 2ccbff9e0..ea75ee0c4 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -477,7 +477,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
output_type: str = "tensor",
**kwargs: Any,
) -> Any:
- """Overwrites the __call__ function to handle various inputs.
+ """Overwrite the __call__ function to handle various inputs.
Args:
input_names_to_handle: List of input names to convert, if None, handle all inputs.
@@ -537,7 +537,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
def _read_datakeys_from_dict(self, keys: Sequence[str]) -> Tuple[List[DataKey], Optional[List[str]]]:
def retrieve_key(key: str) -> DataKey:
- """Try to retrieve the datakey value by matching `<datakey>*`"""
+ """Try to retrieve the datakey value by matching `<datakey>*`."""
# Alias cases, like INPUT, will not be get by the enum iterator.
if key.upper().startswith("INPUT"):
return DataKey.INPUT
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index b3669b9d5..8e8eb5ffd 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -323,7 +323,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
output_type: str = "tensor",
**kwargs: Any,
) -> Any:
- """Overwrites the __call__ function to handle various inputs.
+ """Overwrite the __call__ function to handle various inputs.
Args:
input_names_to_handle: List of input names to convert, if None, handle all inputs.
diff --git a/kornia/augmentation/random_generator/_2d/channel_dropout.py b/kornia/augmentation/random_generator/_2d/channel_dropout.py
index 973603742..2d8c037c7 100644
--- a/kornia/augmentation/random_generator/_2d/channel_dropout.py
+++ b/kornia/augmentation/random_generator/_2d/channel_dropout.py
@@ -43,7 +43,7 @@ class ChannelDropoutGenerator(RandomGeneratorBase):
self.drop_sampler = UniformDistribution(drop[0], drop[1], validate_args=False)
def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:
- r"""Generates a mask for dropout channels."""
+ r"""Generate a mask for dropout channels."""
batch_size, channels, _, _ = batch_shape
_common_param_check(batch_size, same_on_batch)
_device, _dtype = self.device, self.dtype
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index d707c9108..88ece6c70 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -195,7 +195,8 @@ def _transform_input3d(input: Tensor) -> Tensor:
def _validate_input_dtype(input: Tensor, accepted_dtypes: List[torch.dtype]) -> None:
- r"""Check if the dtype of the input tensor is in the range of accepted_dtypes
+ r"""Check if the dtype of the input tensor is in the range of accepted_dtypes.
+
Args:
input: Tensor
accepted_dtypes: List. e.g. [torch.float32, torch.float64]
@@ -231,7 +232,8 @@ def _transform_output_shape(
def _validate_shape(shape: Union[Tuple[int, ...], torch.Size], required_shapes: Tuple[str, ...] = ("BCHW",)) -> None:
- r"""Check if the dtype of the input tensor is in the range of accepted_dtypes
+ r"""Check if the dtype of the input tensor is in the range of accepted_dtypes.
+
Args:
shape: tensor shape
required_shapes: List. e.g. ["BCHW", "BCDHW"]
@@ -268,7 +270,7 @@ def _adapted_rsampling(
dist: torch.distributions.Distribution,
same_on_batch: Optional[bool] = False,
) -> Tensor:
- r"""The uniform reparameterized sampling function that accepts 'same_on_batch'.
+ r"""Sample from a 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.
@@ -288,7 +290,7 @@ def _adapted_sampling(
dist: torch.distributions.Distribution,
same_on_batch: Optional[bool] = False,
) -> Tensor:
- r"""The uniform sampling function that accepts 'same_on_batch'.
+ r"""Sample from a 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.
@@ -307,7 +309,7 @@ def _adapted_uniform(
high: Union[float, Tensor],
same_on_batch: bool = False,
) -> Tensor:
- r"""The uniform sampling function that accepts 'same_on_batch'.
+ r"""Sample from a 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.
@@ -332,7 +334,7 @@ def _adapted_beta(
b: Union[float, Tensor],
same_on_batch: bool = False,
) -> Tensor:
- r"""The beta sampling function that accepts 'same_on_batch'.
+ r"""Sample from a beta 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.
@@ -459,9 +461,7 @@ def preprocess_classes(input: Tensor) -> Tensor:
class MultiprocessWrapper:
- """Utility class which when used as a base class, makes the class work with the 'spawn' multiprocessing
- context.
- """
+ """When used as a base class, makes the class work with the 'spawn' multiprocessing context."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
args = tuple(arg.clone() if isinstance(arg, torch.Tensor) else arg for arg in args)
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 46b149593..1c7f5c772 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -6,7 +6,7 @@ from kornia.core import Tensor, as_tensor, tensor
def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None) -> None:
- """Valid batch_size and same_on_batch params."""
+ """Check valid batch_size and same_on_batch params."""
if not (isinstance(batch_size, int) and batch_size >= 0):
raise AssertionError(f"`batch_size` shall be a positive integer. Got {batch_size}.")
if same_on_batch is not None and not isinstance(same_on_batch, bool):
@@ -56,7 +56,7 @@ def _range_bound(
def _joint_range_check(ranged_factor: Tensor, name: str, bounds: Optional[Tuple[float, float]] = None) -> None:
- """Check if bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]"""
+ """Check if bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]."""
if bounds is None:
bounds = (float("-inf"), float("inf"))
if ranged_factor.dim() == 1 and len(ranged_factor) == 2:
@@ -76,7 +76,7 @@ def _singular_range_check(
skip_none: bool = False,
mode: str = "2d",
) -> None:
- """Check if bounds[0] <= ranged_factor[0] <= bounds[1] and bounds[0] <= ranged_factor[1] <= bounds[1]"""
+ """Check if bounds[0] <= ranged_factor[0] <= bounds[1] and bounds[0] <= ranged_factor[1] <= bounds[1]."""
if mode == "2d":
dim_size = 2
elif mode == "3d":
diff --git a/kornia/color/colormap.py b/kornia/color/colormap.py
index 06decb692..d24ac61cb 100644
--- a/kornia/color/colormap.py
+++ b/kornia/color/colormap.py
@@ -72,7 +72,7 @@ class ColorMapType(Enum):
@classmethod
def list(cls) -> list[str]:
- r"""Returns a list of names of enumeration members.
+ r"""Return a list of names of enumeration members.
Returns:
A list containing the names of enumeration members.
@@ -82,7 +82,9 @@ class ColorMapType(Enum):
class ColorMap:
- r"""Class to represent a colour map. It can be created or selected from the built-in colour map. Please refer to
+ r"""Class to represent a colour map.
+
+ It can be created or selected from the built-in colour map. Please refer to
the `ColorMapType` enum class to view all available colormaps.
Args:
@@ -140,7 +142,7 @@ class ColorMap:
self.colors = self._generate_color_map(base_colormap_data, num_colors)
def _generate_color_map(self, base_colormap: list[RGBColor], num_colors: int) -> Tensor:
- r"""Generates a colormap tensor using interpolation.
+ r"""Generate a colormap tensor using interpolation.
Args:
base_colormap: A list of RGB colors defining the colormap.
@@ -154,7 +156,7 @@ class ColorMap:
return interpolate(tensor_colors[None, ...], size=num_colors, mode="linear")[0, ...]
def __len__(self) -> int:
- r"""Returns the number of colors in the colormap.
+ r"""Return the number of colors in the colormap.
Returns:
Number of colors in the colormap.
@@ -270,7 +272,7 @@ class ApplyColorMap(Module):
self.colormap = colormap
def forward(self, input_tensor: Tensor) -> Tensor:
- r"""Applies the colormap to the input tensor.
+ r"""Apply the colormap to the input tensor.
Args:
input_tensor: The input tensor representing the grayscale image.
@@ -292,7 +294,7 @@ class ApplyColorMap(Module):
In favor of using `ColorMap(base='autumn')` instead.",
)
class AUTUMN(ColorMap):
- r"""The GNU Octave colormap `autumn`
+ r"""The GNU Octave colormap `autumn`.
.. image:: _static/img/AUTUMN.png
"""
diff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.py
index 6c645a051..0892db891 100644
--- a/kornia/contrib/connected_components.py
+++ b/kornia/contrib/connected_components.py
@@ -5,7 +5,7 @@ from kornia.core import Tensor
def connected_components(image: Tensor, num_iterations: int = 100) -> Tensor:
- r"""Computes the Connected-component labelling (CCL) algorithm.
+ r"""Compute the Connected-component labelling (CCL) algorithm.
.. image:: https://github.com/kornia/data/raw/main/cells_segmented.png
diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.py
index 0cd7f0594..0b7cea1b6 100644
--- a/kornia/contrib/diamond_square.py
+++ b/kornia/contrib/diamond_square.py
@@ -22,7 +22,7 @@ def _diamond_square_seed(
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> Tensor:
- """Helper function to generate the diamond square image seee.
+ """Generate the diamond square image seee.
Args:
replicates: the num of batched replicas for the image.
@@ -148,7 +148,7 @@ def diamond_square(
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> Tensor:
- """Generates Plasma Fractal Images using the diamond square algorithm.
+ """Generate Plasma Fractal Images using the diamond square algorithm.
See: https://en.wikipedia.org/wiki/Diamond-square_algorithm
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 15ea43357..9dfbfc874 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -62,7 +62,7 @@ def compute_padding(
This function will be implicitly used in :func:`extract_tensor_patches` and :func:`combine_tensor_patches` if
`allow_auto_(un)padding` is set to True.
- """
+ """ # noqa: D205
original_size = cast(Tuple[int, int], _pair(original_size))
window_size = cast(Tuple[int, int], _pair(window_size))
if stride is None:
@@ -421,7 +421,7 @@ def extract_tensor_patches(
padding: PadType = 0,
allow_auto_padding: bool = False,
) -> Tensor:
- r"""Function that extract patches from tensors and stacks them.
+ r"""Extract patches from tensors and stacks them.
See :class:`~kornia.contrib.ExtractTensorPatches` for details.
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
index 46a0af274..6df54c283 100644
--- a/kornia/contrib/face_detection.py
+++ b/kornia/contrib/face_detection.py
@@ -67,7 +67,7 @@ class FaceDetectorResult:
return self._data[..., 3]
def get_keypoint(self, keypoint: FaceKeypoint) -> torch.Tensor:
- """The [x y] position of a given facial keypoint.
+ """Get the [x y] position of a given facial keypoint.
Args:
keypoint: the keypoint type to return the position.
@@ -343,8 +343,7 @@ class YuFaceDetectNet(nn.Module):
# Adapted from https://github.com/Hakuyume/chainer-ssd
def _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> torch.Tensor:
- """Decode locations from predictions using priors to undo the encoding we did for offset regression at train
- time.
+ """Decode locations from predictions using priors to undo the encoding for offset regression at train time.
Args:
loc:location predictions for loc layers. Shape: [num_priors,4].
diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.py
index cb06be99f..fa31827e3 100644
--- a/kornia/contrib/kmeans.py
+++ b/kornia/contrib/kmeans.py
@@ -85,7 +85,7 @@ class KMeans:
return initial_state
def _pairwise_euclidean_distance(self, data1: Tensor, data2: Tensor) -> Tensor:
- """Computes pairwise squared distance between 2 sets of vectors.
+ """Compute pairwise squared distance between 2 sets of vectors.
Args:
data1: 2D tensor of shape N, D
@@ -103,13 +103,13 @@ class KMeans:
return distance
def fit(self, X: Tensor) -> None:
- """Iterative KMeans clustering till a threshold for shift in cluster centers or a maximum no of iterations
+ """Fit iterative KMeans clustering till a threshold for shift in cluster centers or a maximum no of iterations
have reached.
Args:
X: 2D input tensor to be clustered
- """
+ """ # noqa: D205
# X should have only 2 dimensions
KORNIA_CHECK_SHAPE(X, ["N", "D"])
diff --git a/kornia/contrib/models/base.py b/kornia/contrib/models/base.py
index 663a5822f..3df9bbe36 100644
--- a/kornia/contrib/models/base.py
+++ b/kornia/contrib/models/base.py
@@ -33,7 +33,7 @@ class ModelBase(ABC, Module, Generic[ModelConfig]):
@staticmethod
@abstractmethod
def from_config(config: ModelConfig) -> ModelBase[ModelConfig]:
- """This function should build/load the model.
+ """Build/load the model.
Args:
config: The specifications for the model be build/loaded
diff --git a/kornia/contrib/models/rt_detr/architecture/hgnetv2.py b/kornia/contrib/models/rt_detr/architecture/hgnetv2.py
index fa6c5e329..a49b02f9b 100644
--- a/kornia/contrib/models/rt_detr/architecture/hgnetv2.py
+++ b/kornia/contrib/models/rt_detr/architecture/hgnetv2.py
@@ -1,7 +1,7 @@
"""Based on code from
https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/
ppdet/modeling/backbones/hgnet_v2.py.
-"""
+""" # noqa: D205
from __future__ import annotations
diff --git a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
index 2d1412d65..19c054ba3 100644
--- a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
+++ b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
@@ -1,7 +1,7 @@
"""Based on the code from
https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/
ppdet/modeling/transformers/hybrid_encoder.py.
-"""
+""" # noqa: D205
from __future__ import annotations
diff --git a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
index d495d16b2..9e6faa8c1 100644
--- a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
+++ b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
@@ -101,7 +101,9 @@ class MultiScaleDeformableAttention(Module):
def forward(
self, query: Tensor, reference_points: Tensor, value: Tensor, value_spatial_shapes: list[tuple[int, int]]
) -> Tensor:
- """Args:
+ """Run forward.
+
+ Args:
query: shape (N, Lq, C)
reference_points: shape (N, Lq, n_levels, 4)
value: shape (N, Lv, C)
diff --git a/kornia/contrib/models/sam/architecture/image_encoder.py b/kornia/contrib/models/sam/architecture/image_encoder.py
index 5db27f383..6a313b978 100644
--- a/kornia/contrib/models/sam/architecture/image_encoder.py
+++ b/kornia/contrib/models/sam/architecture/image_encoder.py
@@ -39,7 +39,9 @@ class ImageEncoderViT(Module):
window_size: int = 0,
global_attn_indexes: tuple[int, ...] = (),
) -> None:
- """Args:
+ """Construct Image Encoder ViT.
+
+ Args:
img_size: Input image size.
patch_size: Patch size.
in_chans: Number of input image channels.
@@ -124,7 +126,9 @@ class Block(Module):
window_size: int = 0,
input_size: Optional[tuple[int, int]] = None,
) -> None:
- """Args:
+ """Construct transformer block.
+
+ Args:
dim: Number of input channels.
num_heads: Number of attention heads in each ViT block.
mlp_ratio: Ratio of mlp hidden dim to embedding dim.
@@ -184,7 +188,9 @@ class Attention(Module):
rel_pos_zero_init: bool = True,
input_size: Optional[tuple[int, int]] = None,
) -> None:
- """Args:
+ """Construct attention block.
+
+ Args:
dim: Number of input channels.
num_heads: Number of attention heads.
qkv_bias: If True, add a learnable bias to query, key, value.
@@ -306,7 +312,9 @@ class PatchEmbed(Module):
in_chans: int = 3,
embed_dim: int = 768,
) -> None:
- """Args:
+ """Construct Patch Embedding.
+
+ Args:
kernel_size: kernel size of the projection layer.
stride: stride of the projection layer.
padding: padding size of the projection layer.
diff --git a/kornia/contrib/models/sam/architecture/prompt_encoder.py b/kornia/contrib/models/sam/architecture/prompt_encoder.py
index 681274079..ea3cb4085 100644
--- a/kornia/contrib/models/sam/architecture/prompt_encoder.py
+++ b/kornia/contrib/models/sam/architecture/prompt_encoder.py
@@ -25,7 +25,7 @@ class PromptEncoder(Module):
mask_in_chans: int,
activation: type[Module] = nn.GELU,
) -> None:
- """Encodes prompts for input to SAM's mask decoder.
+ """Encode prompts for input to SAM's mask decoder.
Args:
embed_dim: The prompts' embedding dimension
@@ -59,13 +59,13 @@ class PromptEncoder(Module):
self.no_mask_embed = nn.Embedding(1, embed_dim)
def get_dense_pe(self) -> Tensor:
- """Returns the positional encoding used to encode point prompts, applied to a dense set of points the shape
+ """Return the positional encoding used to encode point prompts, applied to a dense set of points the shape
of the image encoding.
Returns:
Positional encoding with shape 1x(embed_dim)x(embedding_h)x(embedding_w)
- """
+ """ # noqa: D205
return self.pe_layer(self.image_embedding_size)[None, ...]
def _embed_points(self, points: Tensor, labels: Tensor, pad: bool) -> Tensor:
@@ -100,7 +100,7 @@ class PromptEncoder(Module):
def _get_batch_size(
self, points: Optional[tuple[Tensor, Tensor]], boxes: Optional[Tensor], masks: Optional[Tensor]
) -> int:
- """Gets the batch size of the output given the batch size of the input prompts."""
+ """Get the batch size of the output given the batch size of the input prompts."""
if points is not None:
return points[0].shape[0]
elif boxes is not None:
diff --git a/kornia/contrib/models/sam/architecture/transformer.py b/kornia/contrib/models/sam/architecture/transformer.py
index 9838ea232..52c2d593c 100644
--- a/kornia/contrib/models/sam/architecture/transformer.py
+++ b/kornia/contrib/models/sam/architecture/transformer.py
@@ -25,7 +25,7 @@ class TwoWayTransformer(Module):
activation: type[Module] = nn.ReLU,
attention_downsample_rate: int = 2,
) -> None:
- """A transformer decoder that attends to an input image using queries whose positional embedding is
+ """Construct a transformer decoder that attends to an input image using queries whose positional embedding is
supplied.
Args:
@@ -35,7 +35,7 @@ class TwoWayTransformer(Module):
mlp_dim: the channel dimension internal to the MLP block
activation: the activation to use in the MLP block
- """
+ """ # noqa: D205
super().__init__()
self.depth = depth
self.embedding_dim = embedding_dim
@@ -59,7 +59,9 @@ class TwoWayTransformer(Module):
self.norm_final_attn = nn.LayerNorm(embedding_dim)
def forward(self, image_embedding: Tensor, image_pe: Tensor, point_embedding: Tensor) -> tuple[Tensor, Tensor]:
- """Args:
+ """Run forward.
+
+ Args:
image_embedding: image to attend to. Should be shape B x embedding_dim x h x w for any h and w.
image_pe: the positional encoding to add to the image. Must have the same shape as image_embedding.
point_embedding: the embedding to add to the query points. Must have shape B x N_points x embedding_dim
@@ -103,8 +105,10 @@ class TwoWayAttentionBlock(Module):
attention_downsample_rate: int = 2,
skip_first_layer_pe: bool = False,
) -> None:
- """A transformer block with four layers: (1) self-attention of sparse inputs, (2) cross attention of sparse
- inputs to dense inputs, (3) mlp block on sparse inputs, and (4) cross attention of dense inputs to sparse
+ """Construct a transformer block with four layers.
+
+ (1) self-attention of sparse inputs, (2) cross attention of
+ sparse inputs to dense inputs, (3) mlp block on sparse inputs, and (4) cross attention of dense inputs to sparse
inputs.
Args:
@@ -163,9 +167,7 @@ class TwoWayAttentionBlock(Module):
class Attention(Module):
- """An attention layer that allows for downscaling the size of the embedding after projection to queries, keys,
- and values.
- """
+ """Attention layer that allows for downscaling the embedding after projection to queries, keys, and values."""
def __init__(self, embedding_dim: int, num_heads: int, downsample_rate: int = 1) -> None:
super().__init__()
diff --git a/kornia/contrib/models/structures.py b/kornia/contrib/models/structures.py
index a2b5e2a43..fa1042377 100644
--- a/kornia/contrib/models/structures.py
+++ b/kornia/contrib/models/structures.py
@@ -102,10 +102,10 @@ class Prompts:
@property
def keypoints(self) -> Optional[Tensor]:
- """The keypoints from the `points`"""
+ """The keypoints from the `points`."""
return self.points[0] if isinstance(self.points, tuple) else None
@property
def keypoints_labels(self) -> Optional[Tensor]:
- """The keypoints labels from the `points`"""
+ """The keypoints labels from the `points`."""
return self.points[1] if isinstance(self.points, tuple) else None
diff --git a/kornia/contrib/models/tiny_vit.py b/kornia/contrib/models/tiny_vit.py
index 129982514..ef0f332db 100644
--- a/kornia/contrib/models/tiny_vit.py
+++ b/kornia/contrib/models/tiny_vit.py
@@ -307,7 +307,7 @@ class BasicLayer(Module):
class TinyViT(Module):
- """TinyViT model, as described in https://arxiv.org/abs/2207.10666
+ """TinyViT model, as described in https://arxiv.org/abs/2207.10666.
Args:
img_size: Size of input image.
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 48ac1e6dd..a5cd42f1c 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -16,7 +16,7 @@ from kornia.geometry.keypoints import Keypoints
class VisualPrompter:
- r"""This class allow the user to run multiple query with multiple prompts for a model.
+ r"""Allow the user to run multiple query with multiple prompts for a model.
At the moment, we just support the SAM model. The model is loaded based on the given config.
@@ -306,7 +306,7 @@ class VisualPrompter:
options: Optional[dict[Any, Any]] = None,
disable: bool = False,
) -> None:
- """Applies `torch.compile(...)`/dynamo API into the VisualPrompter API.
+ """Apply `torch.compile(...)`/dynamo API into the VisualPrompter API.
.. note:: For more information about the dynamo API check the official docs
https://pytorch.org/docs/stable/generated/torch.compile.html
diff --git a/kornia/contrib/vit.py b/kornia/contrib/vit.py
index b40edf433..b23c11c8a 100644
--- a/kornia/contrib/vit.py
+++ b/kornia/contrib/vit.py
@@ -244,7 +244,9 @@ class VisionTransformer(Module):
@staticmethod
def from_config(variant: str, pretrained: bool = False, **kwargs: Any) -> VisionTransformer:
- """Build ViT model based on the given config string. The format is ``vit_{size}/{patch_size}``.
+ """Build ViT model based on the given config string.
+
+ The format is ``vit_{size}/{patch_size}``.
E.g. ``vit_b/16`` means ViT-Base, patch size 16x16. If ``pretrained=True``, AugReg weights are loaded.
The weights are hosted on HuggingFace's model hub: https://huggingface.co/kornia.
diff --git a/kornia/core/external.py b/kornia/core/external.py
index 5f5270a67..c0ecc3be6 100644
--- a/kornia/core/external.py
+++ b/kornia/core/external.py
@@ -26,7 +26,7 @@ class LazyLoader:
auto_install: bool = False
def __init__(self, module_name: str, dev_dependency: bool = False) -> None:
- """Initializes the LazyLoader with the name of the module.
+ """Initialize the LazyLoader with the name of the module.
Args:
module_name: The name of the module to be lazily loaded.
@@ -44,7 +44,7 @@ class LazyLoader:
subprocess.run([sys.executable, "-m", "pip", "install", "-U", module_name], shell=False, check=False) # noqa: S603
def _load(self) -> None:
- """Loads the module if it hasn't been loaded yet.
+ """Load the module if it hasn't been loaded yet.
This method is called internally when an attribute of the module is accessed for the first time. It attempts to
import the module and raises an ImportError with a custom message if the module is not installed.
@@ -99,7 +99,7 @@ class LazyLoader:
self.module = importlib.import_module(self.module_name)
def __getattr__(self, item: str) -> object:
- """Loads the module (if not already loaded) and returns the requested attribute.
+ """Load the module (if not already loaded) and returns the requested attribute.
This method is called when an attribute of the LazyLoader instance is accessed.
It ensures that the module is loaded and then returns the requested attribute.
@@ -115,7 +115,7 @@ class LazyLoader:
return getattr(self.module, item)
def __dir__(self) -> List[str]:
- """Loads the module (if not already loaded) and returns the list of attributes of the module.
+ """Load the module (if not already loaded) and returns the list of attributes of the module.
This method is called when the built-in dir() function is used on the LazyLoader instance.
It ensures that the module is loaded and then returns the list of attributes of the module.
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index 6138d6c4b..21af361ef 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -23,7 +23,7 @@ class ImageModuleMixIn:
input_names_to_handle: Optional[List[Any]] = None,
output_type: str = "tensor",
) -> Callable[[Any], Any]:
- """Decorator to convert input and output types for a function.
+ """Convert input and output types for a function.
Args:
input_names_to_handle: List of input names to convert, if None, handle all inputs.
@@ -185,7 +185,7 @@ class ImageModuleMixIn:
raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")
def show(self, n_row: Optional[int] = None, backend: str = "pil", display: bool = True) -> Optional[Any]:
- """Returns PIL images.
+ """Return PIL images.
Args:
n_row: Number of images displayed in each row of the grid.
@@ -214,7 +214,7 @@ class ImageModuleMixIn:
raise ValueError(f"Unsupported backend `{backend}`.")
def save(self, name: Optional[str] = None, n_row: Optional[int] = None) -> None:
- """Saves the output image(s) to a directory.
+ """Save the output image(s) to a directory.
Args:
name: Directory to save the images.
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index c1c2488bf..a041d4e7a 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -57,7 +57,7 @@ class ONNXExportMixin:
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
) -> onnx.ModelProto: # type: ignore
- """Exports the current object to an ONNX model file.
+ """Export the current object to an ONNX model file.
Args:
onnx_name:
@@ -271,7 +271,7 @@ class ONNXMixin:
arg: Union[onnx.ModelProto, str], # type:ignore
cache_dir: Optional[str] = None,
) -> onnx.ModelProto: # type:ignore
- """Loads an ONNX model, either from a file path or use the provided ONNX ModelProto.
+ """Load an ONNX model, either from a file path or use the provided ONNX ModelProto.
Args:
arg: Either an ONNX ModelProto object or a file path to an ONNX model.
@@ -291,7 +291,7 @@ class ONNXMixin:
*args: Union[onnx.ModelProto, str], # type:ignore
cache_dir: Optional[str] = None,
) -> list[onnx.ModelProto]: # type:ignore
- """Loads multiple ONNX models or operators and returns them as a list.
+ """Load multiple ONNX models or operators and returns them as a list.
Args:
*args: A variable number of ONNX models (either ONNX ModelProto objects or file paths).
@@ -312,8 +312,9 @@ class ONNXMixin:
*args: list[onnx.ModelProto], # type:ignore
io_maps: Optional[list[tuple[str, str]]] = None,
) -> onnx.ModelProto: # type:ignore
- """Combine the provided ONNX models into a single ONNX graph. Optionally, map inputs and outputs between
- operators using the `io_map`.
+ """Combine the provided ONNX models into a single ONNX graph.
+
+ Optionally, map inputs and outputs between operators using the `io_map`.
Args:
io_maps:
diff --git a/kornia/core/module.py b/kornia/core/module.py
index 63670e3b3..3181f3d01 100644
--- a/kornia/core/module.py
+++ b/kornia/core/module.py
@@ -29,7 +29,7 @@ class ImageModuleMixIn:
input_names_to_handle: Optional[list[Any]] = None,
output_type: str = "tensor",
) -> Callable[[Any], Any]:
- """Decorator to convert input and output types for a function.
+ """Convert input and output types for a function.
Args:
input_names_to_handle: List of input names to convert, if None, handle all inputs.
@@ -187,7 +187,7 @@ class ImageModuleMixIn:
raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")
def show(self, n_row: Optional[int] = None, backend: str = "pil", display: bool = True) -> Optional[Any]:
- """Returns PIL images.
+ """Return PIL images.
Args:
n_row: Number of images displayed in each row of the grid.
@@ -214,7 +214,7 @@ class ImageModuleMixIn:
raise ValueError(f"Unsupported backend `{backend}`.")
def save(self, name: Optional[str] = None, n_row: Optional[int] = None) -> None:
- """Saves the output image(s) to a directory.
+ """Save the output image(s) to a directory.
Args:
name: Directory to save the images.
@@ -264,7 +264,7 @@ class ImageModule(Module, ImageModuleMixIn, ONNXExportMixin):
output_type: str = "tensor",
**kwargs: Any,
) -> Any:
- """Overwrites the __call__ function to handle various inputs.
+ """Overwrite the __call__ function to handle various inputs.
Args:
input_names_to_handle: List of input names to convert, if None, handle all inputs.
@@ -321,7 +321,7 @@ class ImageSequential(Sequential, ImageModuleMixIn, ONNXExportMixin):
output_type: str = "tensor",
**kwargs: Any,
) -> Any:
- """Overwrites the __call__ function to handle various inputs.
+ """Overwrite the __call__ function to handle various inputs.
Args:
input_names_to_handle: List of input names to convert, if None, handle all inputs.
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index b1469636d..94ff46fc9 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -612,8 +612,9 @@ 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/histogram.py b/kornia/enhance/histogram.py
index 6f14fb9a9..122d4366a 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -6,8 +6,7 @@ from kornia.core import Tensor
def marginal_pdf(values: Tensor, bins: Tensor, sigma: Tensor, epsilon: float = 1e-10) -> Tuple[Tensor, Tensor]:
- """Calculate the marginal probability distribution function of the input tensor based on the number of
- histogram bins.
+ """Calculate the marginal probability distribution function of the input based on the number of histogram bins.
Args:
values: shape [BxNx1].
@@ -50,8 +49,7 @@ def marginal_pdf(values: Tensor, bins: Tensor, sigma: Tensor, epsilon: float = 1
def joint_pdf(kernel_values1: Tensor, kernel_values2: Tensor, epsilon: float = 1e-10) -> Tensor:
- """Calculate the joint probability distribution function of the input tensors based on the number of histogram
- bins.
+ """Calculate the joint probability distribution function of the input tensors based on the number of histogram bins.
Args:
kernel_values1: shape [BxNxNUM_BINS].
diff --git a/kornia/enhance/integral.py b/kornia/enhance/integral.py
index db15a491b..e9ad23319 100644
--- a/kornia/enhance/integral.py
+++ b/kornia/enhance/integral.py
@@ -6,7 +6,7 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
def integral_tensor(input: Tensor, dim: Optional[Tuple[int, ...]] = None) -> Tensor:
- """Calculates integral of the input tensor.
+ """Calculate integral of the input tensor.
The algorithm computes the integral image by summing over the specified dimensions.
@@ -44,7 +44,7 @@ def integral_tensor(input: Tensor, dim: Optional[Tuple[int, ...]] = None) -> Ten
def integral_image(image: Tensor) -> Tensor:
- r"""Calculates integral of the input image tensor.
+ r"""Calculate integral of the input image tensor.
This particular version sums over the last two dimensions.
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index b64e5233b..ff79303e0 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -26,7 +26,7 @@ __all__ = ["JPEGCodecDifferentiable", "jpeg_codec_differentiable"]
def _get_default_qt_y(device: Device, dtype: Dtype) -> Tensor:
- """Generates default Quantization table of Y channel."""
+ """Generate default Quantization table of Y channel."""
return torch.tensor(
[
[16, 11, 10, 16, 24, 40, 51, 61],
@@ -44,7 +44,7 @@ def _get_default_qt_y(device: Device, dtype: Dtype) -> Tensor:
def _get_default_qt_c(device: Device, dtype: Dtype) -> Tensor:
- """Generates default Quantization table of C channels."""
+ """Generate default Quantization table of C channels."""
return torch.tensor(
[
[17, 18, 24, 47, 99, 99, 99, 99],
@@ -62,7 +62,7 @@ def _get_default_qt_c(device: Device, dtype: Dtype) -> Tensor:
def _patchify_8x8(input: Tensor) -> Tensor:
- """Function extracts non-overlapping 8 x 8 patches from the given input image.
+ """Extract non-overlapping 8 x 8 patches from the given input image.
Args:
input (Tensor): Input image of the shape :math:`(B, H, W)`.
@@ -79,7 +79,7 @@ def _patchify_8x8(input: Tensor) -> Tensor:
def _unpatchify_8x8(input: Tensor, H: int, W: int) -> Tensor:
- """Function reverses non-overlapping 8 x 8 patching.
+ """Reverse non-overlapping 8 x 8 patching.
Args:
input (Tensor): Input image of the shape :math:`(B, N, 8, 8)`.
@@ -96,7 +96,7 @@ def _unpatchify_8x8(input: Tensor, H: int, W: int) -> Tensor:
def _dct_8x8(input: Tensor) -> Tensor:
- """Performs an 8 x 8 discrete cosine transform.
+ """Perform an 8 x 8 discrete cosine transform.
Args:
input (Tensor): Patched input tensor of the shape :math:`(B, N, 8, 8)`.
@@ -121,7 +121,7 @@ def _dct_8x8(input: Tensor) -> Tensor:
def _idct_8x8(input: Tensor) -> Tensor:
- """Performs an 8 x 8 discrete cosine transform.
+ """Perform an 8 x 8 discrete cosine transform.
Args:
input (Tensor): Patched input tensor of the shape :math:`(B, N, 8, 8)`.
@@ -150,7 +150,7 @@ def _idct_8x8(input: Tensor) -> Tensor:
def _jpeg_quality_to_scale(
compression_strength: Tensor,
) -> Tensor:
- """Converts a given JPEG quality to the scaling factor.
+ """Convert a given JPEG quality to the scaling factor.
Args:
compression_strength (Tensor): Compression strength ranging from 0 to 100. Any shape is supported.
@@ -175,7 +175,7 @@ def _quantize(
jpeg_quality: Tensor,
quantization_table: Tensor,
) -> Tensor:
- """Function performs quantization.
+ """Perform quantization.
Args:
input (Tensor): Input tensor of the shape :math:`(B, N, 8, 8)`.
@@ -205,7 +205,7 @@ def _dequantize(
jpeg_quality: Tensor,
quantization_table: Tensor,
) -> Tensor:
- """Function performs dequantization.
+ """Perform dequantization.
Args:
input (Tensor): Input tensor of the shape :math:`(B, N, 8, 8)`.
@@ -228,7 +228,7 @@ def _dequantize(
def _chroma_subsampling(input_ycbcr: Tensor) -> tuple[Tensor, Tensor, Tensor]:
- """This function implements chroma subsampling.
+ """Implement chroma subsampling.
Args:
input_ycbcr (Tensor): YCbCr input tensor of the shape :math:`(B, 3, H, W)`.
@@ -262,7 +262,7 @@ def _chroma_subsampling(input_ycbcr: Tensor) -> tuple[Tensor, Tensor, Tensor]:
def _chroma_upsampling(input_c: Tensor) -> Tensor:
- """Function performs chroma upsampling.
+ """Perform chroma upsampling.
Args:
input_c (Tensor): Cb or Cr component to be upsampled of the shape :math:`(B, H, W)`.
@@ -288,7 +288,7 @@ def _jpeg_encode(
quantization_table_y: Tensor,
quantization_table_c: Tensor,
) -> tuple[Tensor, Tensor, Tensor]:
- """Performs JPEG encoding.
+ """Perform JPEG encoding.
Args:
image_rgb (Tensor): RGB input images of the shape :math:`(B, 3, H, W)`.
@@ -339,7 +339,7 @@ def _jpeg_decode(
quantization_table_y: Tensor,
quantization_table_c: Tensor,
) -> Tensor:
- """Performs JPEG decoding.
+ """Perform JPEG decoding.
Args:
input_y (Tensor): Compressed Y component of the shape :math:`(B, N, 8, 8)`.
@@ -384,7 +384,7 @@ def _jpeg_decode(
def _perform_padding(image: Tensor) -> tuple[Tensor, int, int]:
- """Pads a given image to be dividable by 16.
+ """Pad a given image to be dividable by 16.
Args:
image: Image of the shape :math:`(*, 3, H, W)`.
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index 0753a766f..54de94570 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -89,7 +89,7 @@ class ZCAWhitening(Module):
Args:
x: Input data.
- returns:
+ Returns:
Returns a fitted ZCAWhiten object instance.
"""
@@ -341,7 +341,7 @@ def linear_transform(inp: Tensor, transform_matrix: Tensor, mean_vector: Tensor,
>>> print(out.shape, out.unique()) # Should a be (10,2) tensor of 2s
torch.Size([10, 2]) tensor([2.])
- """
+ """ # noqa: D205
inp_size = inp.size()
if dim >= len(inp_size) or dim < -len(inp_size):
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index 0045a7b35..9ae0a61e9 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -40,8 +40,9 @@ def match_adalam(
hw2: Optional[Tuple[int, int]] = None,
dm: Optional[Tensor] = None,
) -> Tuple[Tensor, Tensor]:
- """Function, which performs descriptor matching, followed by AdaLAM filtering (see :cite:`AdaLAM2020` for more
- details)
+ """Perform descriptor matching, followed by AdaLAM filtering.
+
+ See :cite:`AdaLAM2020` for more details.
If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
@@ -97,7 +98,7 @@ def match_adalam(
class AdalamFilter:
def __init__(self, custom_config: Optional[AdalamConfig] = None) -> None:
- """This class acts as a wrapper to the method AdaLAM for outlier filtering.
+ """Wrap the method AdaLAM for outlier filtering.
init args:
custom_config: dictionary overriding the default configuration. Missing parameters are kept as default.
@@ -123,8 +124,9 @@ class AdalamFilter:
s2: Optional[Tensor] = None,
return_dist: bool = False,
) -> Union[Tuple[Tensor, Tensor], Tensor]:
- """Call the core functionality of AdaLAM, i.e. just outlier filtering. No sanity check is performed on the
- inputs.
+ """Call the core functionality of AdaLAM, i.e. just outlier filtering.
+
+ No sanity check is performed on the inputs.
Inputs:
k1: keypoint locations in the source image, in pixel coordinates.
@@ -191,7 +193,9 @@ class AdalamFilter:
s2: Optional[Tensor] = None,
return_dist: bool = False,
) -> Union[Tuple[Tensor, Tensor], Tensor]:
- """Standard matching and filtering with AdaLAM. This function:
+ """Match and filter with AdaLAM.
+
+ This function:
- performs some elementary sanity check on the inputs;
- wraps input arrays into torch tensors and loads to GPU if necessary;
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index 2341023ec..b0f81bb36 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -51,7 +51,7 @@ class AdalamConfig(TypedDict):
def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
- """Helper function, which output empty tensors.
+ """Output empty tensors.
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(0, 1)`.
@@ -117,7 +117,9 @@ def extract_neighborhood_sets(
SEARCH_EXP: float,
MIN_INLIERS: float,
) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
- """Assign keypoints to seed points. This checks both the distance and the agreement of the local transformation
+ """Assign keypoints to seed points.
+
+ This checks both the distance and the agreement of the local transformation
if available.
o1: Orientations of keypoints in image I_1
@@ -190,7 +192,9 @@ def extract_local_patterns(
im2seeds: Tensor,
scores: Tensor,
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
- """Prepare local neighborhoods around each seed for the parallel RANSACs. This involves two steps: 1) Collect
+ """Prepare local neighborhoods around each seed for the parallel RANSACs.
+
+ This involves two steps: 1) Collect
all selected keypoints and refer them with respect to their seed point 2) Sort keypoints by score for the
progressive sampling to pick the best samples first.
@@ -258,8 +262,9 @@ def adalam_core(
s2: Optional[Tensor] = None,
return_dist: bool = False,
) -> Union[Tuple[Tensor, Tensor], Tensor]:
- """Call the core functionality of AdaLAM, i.e. just outlier filtering. No sanity check is performed on the
- inputs.
+ """Call the core functionality of AdaLAM, i.e. just outlier filtering.
+
+ No sanity check is performed on the inputs.
Inputs:
k1: keypoint locations in the source image, in pixel coordinates.
diff --git a/kornia/feature/adalam/utils.py b/kornia/feature/adalam/utils.py
index 8fc354ba0..88e4ce148 100644
--- a/kornia/feature/adalam/utils.py
+++ b/kornia/feature/adalam/utils.py
@@ -7,7 +7,7 @@ from kornia.core import Tensor
def arange_sequence(ranges: Tensor) -> Tensor:
- """Returns a sequence of the ranges specified by the argument.
+ """Return a sequence of the ranges specified by the argument.
Example:
[2, 5, 1, 2] -> [0, 1, 0, 1, 2, 3, 4, 0, 0, 1]
@@ -39,7 +39,8 @@ def orientation_diff(o1: Tensor, o2: Tensor) -> Tensor:
def piecewise_arange(piecewise_idxer: Tensor) -> Tensor:
- """Count repeated indices
+ """Count repeated indices.
+
Example:
[0, 0, 0, 3, 3, 3, 3, 1, 1, 2] -> [0, 1, 2, 0, 1, 2, 3, 0, 1, 0]
"""
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 8933c8232..036674400 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -46,7 +46,9 @@ class PatchAffineShapeEstimator(nn.Module):
return f"{self.__class__.__name__}(patch_size={self.patch_size}, eps={self.eps})"
def forward(self, patch: torch.Tensor) -> torch.Tensor:
- """Args:
+ """Run forward.
+
+ Args:
patch: :math:`(B, 1, H, W)`
Returns:
@@ -120,7 +122,9 @@ class LAFAffineShapeEstimator(nn.Module):
)
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
- """Args:
+ """Run forward.
+
+ Args:
LAF: :math:`(B, N, 2, 3)`
img: :math:`(B, 1, H, W)`
@@ -205,7 +209,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."""
+ """Normalize 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
@@ -213,7 +217,9 @@ class LAFAffNetShapeEstimator(nn.Module):
return (x - mp.detach()) / (sp.detach() + eps)
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
- """Args:
+ """Run forward.
+
+ Args:
LAF: :math:`(B, N, 2, 3)`
img: :math:`(B, 1, H, W)`
diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.py
index 150c756a3..28fac100c 100644
--- a/kornia/feature/dedode/dedode.py
+++ b/kornia/feature/dedode/dedode.py
@@ -69,7 +69,7 @@ class DeDoDe(Module):
apply_imagenet_normalization: bool = True,
pad_if_not_divisible: bool = True,
) -> Tuple[Tensor, Tensor, Tensor]:
- """Detects and describes keypoints in the input images.
+ """Detect and describe keypoints in the input images.
Args:
images: A tensor of shape :math:`(B, 3, H, W)` containing the ImageNet-Normalized input images.
@@ -106,7 +106,7 @@ class DeDoDe(Module):
crop_h: Optional[int] = None,
crop_w: Optional[int] = None,
) -> Tuple[Tensor, Tensor]:
- """Detects keypoints in the input images.
+ """Detect keypoints in the input images.
Args:
images: A tensor of shape :math:`(B, 3, H, W)` containing the input images.
@@ -143,7 +143,7 @@ class DeDoDe(Module):
def describe(
self, images: Tensor, keypoints: Optional[Tensor] = None, apply_imagenet_normalization: bool = True
) -> Tensor:
- """Describes keypoints in the input images. If keypoints are not provided, returns the dense descriptors.
+ """Describe keypoints in the input images. If keypoints are not provided, returns the dense descriptors.
Args:
images: A tensor of shape :math:`(B, 3, H, W)` containing the input images.
@@ -177,7 +177,7 @@ class DeDoDe(Module):
descriptor_weights: str = "G-upright",
amp_dtype: torch.dtype = torch.float16,
) -> Module:
- r"""Loads a pretrained model.
+ r"""Load a pretrained model.
Args:
detector_weights: The weights to load for the detector.
diff --git a/kornia/feature/dedode/transformer/dinov2.py b/kornia/feature/dedode/transformer/dinov2.py
index c83ab193e..a43a36211 100644
--- a/kornia/feature/dedode/transformer/dinov2.py
+++ b/kornia/feature/dedode/transformer/dinov2.py
@@ -63,7 +63,9 @@ class DinoVisionTransformer(nn.Module):
ffn_layer="mlp",
block_chunks=1,
):
- """Args:
+ """Construct dino vision transformer.
+
+ Args:
img_size (int, tuple): input image size
patch_size (int, tuple): patch size
in_chans (int): number of input channels
@@ -298,7 +300,7 @@ class DinoVisionTransformer(nn.Module):
def init_weights_vit_timm(module: nn.Module, name: str = ""):
- """ViT weight initialization, original timm impl (for reproducibility)"""
+ """ViT weight initialization, original timm impl (for reproducibility)."""
if isinstance(module, nn.Linear):
trunc_normal_(module.weight, std=0.02)
if module.bias is not None:
diff --git a/kornia/feature/dedode/transformer/layers/block.py b/kornia/feature/dedode/transformer/layers/block.py
index a1d1770ba..cea7757ee 100644
--- a/kornia/feature/dedode/transformer/layers/block.py
+++ b/kornia/feature/dedode/transformer/layers/block.py
@@ -155,7 +155,7 @@ attn_bias_cache: Dict[Tuple, Any] = {}
def get_attn_bias_and_cat(x_list, branges=None):
- """This will perform the index select, cat the tensors, and provide the attn_bias from cache."""
+ """Perform the index select, cat the tensors, and provide the attn_bias from cache."""
batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
if all_shapes not in attn_bias_cache.keys():
diff --git a/kornia/feature/dedode/transformer/layers/patch_embed.py b/kornia/feature/dedode/transformer/layers/patch_embed.py
index 96b3c011e..9a6ae2660 100644
--- a/kornia/feature/dedode/transformer/layers/patch_embed.py
+++ b/kornia/feature/dedode/transformer/layers/patch_embed.py
@@ -24,7 +24,7 @@ def make_2tuple(x):
class PatchEmbed(nn.Module):
- """2D image to patch embedding: (B,C,H,W) -> (B,N,D)
+ """2D image to patch embedding: (B,C,H,W) -> (B,N,D).
Args:
img_size: Image size.
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index 632834f0e..070d8e8e0 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -12,8 +12,9 @@ from .structs import DISKFeatures
class DISK(Module):
- r"""Module which detects and described local features in an image using the DISK method. See
- :cite:`tyszkiewicz2020disk` for details.
+ r"""Module which detects and described local features in an image using the DISK method.
+
+ See :cite:`tyszkiewicz2020disk` for details.
.. image:: _static/img/disk_outdoor_depth.jpg
@@ -41,7 +42,7 @@ class DISK(Module):
self.unet = unet
def heatmap_and_dense_descriptors(self, images: Tensor) -> tuple[Tensor, Tensor]:
- """Returns the heatmap and the dense descriptors.
+ """Return the heatmap and the dense descriptors.
.. image:: _static/img/DISK.png
@@ -74,7 +75,7 @@ class DISK(Module):
score_threshold: float = 0.0,
pad_if_not_divisible: bool = False,
) -> list[DISKFeatures]:
- """Detects features in an image, returning keypoint locations, descriptors and detection scores.
+ """Detect features in an image, returning keypoint locations, descriptors and detection scores.
Args:
images: The image to detect features in. Shape :math:`(B, 3, H, W)`.
@@ -110,7 +111,7 @@ class DISK(Module):
@classmethod
def from_pretrained(cls, checkpoint: str = "depth", device: Optional[torch.device] = None) -> DISK:
- r"""Loads a pretrained model.
+ r"""Load a pretrained model.
Depth model was trained using depth map supervision and is slightly more precise but biased to detect keypoints
only where SfM depth is available. Epipolar model was trained using epipolar geometry supervision and
diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.py
index 717c5cc7e..d8a7bbee4 100644
--- a/kornia/feature/disk/structs.py
+++ b/kornia/feature/disk/structs.py
@@ -10,8 +10,9 @@ from kornia.core import Device, Tensor
@dataclass
class DISKFeatures:
- r"""A data structure holding DISK keypoints, descriptors and detection scores for an image. Since DISK detects a
- varying number of keypoints per image, `DISKFeatures` is not batched.
+ r"""A data structure holding DISK keypoints, descriptors and detection scores for an image.
+
+ Since DISK detects a varying number of keypoints per image, `DISKFeatures` is not batched.
Args:
keypoints: Tensor of shape :math:`(N, 2)`, where :math:`N` is the number of keypoints.
@@ -45,7 +46,7 @@ class DISKFeatures:
return self.keypoints[:, 1]
def to(self, *args: Any, **kwargs: Any) -> DISKFeatures:
- """Calls :func:`torch.Tensor.to` on each tensor to move the keypoints, descriptors and detection scores to
+ """Call :func:`torch.Tensor.to` on each tensor to move the keypoints, descriptors and detection scores to
the specified device and/or data type.
Args:
@@ -55,7 +56,7 @@ class DISKFeatures:
Returns:
A new DISKFeatures object with tensors of appropriate type and location.
- """
+ """ # noqa:D205
return DISKFeatures(
self.keypoints.to(*args, **kwargs),
self.descriptors.to(*args, **kwargs),
@@ -74,7 +75,7 @@ class Keypoints:
detection_logp: Tensor
def merge_with_descriptors(self, descriptors: Tensor) -> DISKFeatures:
- """Select descriptors from a dense `descriptors` tensor, at locations given by `self.xys`"""
+ """Select descriptors from a dense `descriptors` tensor, at locations given by `self.xys`."""
dtype = descriptors.dtype
x, y = self.xys.T
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index e8dc49334..eba8ec149 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -74,7 +74,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."""
+ """Normalize the input by batch."""
if not is_mps_tensor_safe(x):
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
else:
@@ -165,7 +165,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."""
+ """Normalize the input by batch."""
if not is_mps_tensor_safe(x):
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
else:
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index 56cb0a0a1..0a9e49975 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -34,7 +34,7 @@ class FilterResponseNorm2d(Module):
- Input: :math:`(B, \text{num_features}, H, W)`
- Output: :math:`(B, \text{num_features}, H, W)`
- """
+ """ # noqa: D205
def __init__(
self,
@@ -101,10 +101,10 @@ class TLU(Module):
- Input: :math:`(B, \text{num_features}, H, W)`
- Output: :math:`(B, \text{num_features}, H, W)`
- """
+ """ # noqa:D205
def __init__(self, num_features: int) -> None:
- """max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau"""
+ """max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau."""
super().__init__()
self.num_features = num_features
self.tau = Parameter(-torch.ones(1, num_features, 1, 1), requires_grad=True)
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index cbd02722b..10ab6f57e 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -30,7 +30,7 @@ from .siftdesc import SIFTDescriptor
def get_laf_descriptors(
img: Tensor, lafs: Tensor, patch_descriptor: Module, patch_size: int = 32, grayscale_descriptor: bool = True
) -> Tensor:
- r"""Function to get local descriptors, corresponding to LAFs (keypoints).
+ r"""Get local descriptors, corresponding to LAFs (keypoints).
Args:
img: image features with shape :math:`(B,C,H,W)`.
@@ -129,7 +129,9 @@ class LocalFeature(Module):
self.scaling_coef = scaling_coef
def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor, Tensor]:
- """Args:
+ """Run forward.
+
+ Args:
img: image to extract features with shape :math:`(B,C,H,W)`.
mask: a mask with weights where to apply the response function.
The shape must be the same as the input image.
@@ -181,8 +183,9 @@ class SIFTFeature(LocalFeature):
class SIFTFeatureScaleSpace(LocalFeature):
- """Convenience module, which implements DoG detector + (Root)SIFT descriptor. Using
- `kornia.feature.ScaleSpaceDetector` with blur pyramid.
+ """Convenience module, which implements DoG detector + (Root)SIFT descriptor.
+
+ Using `kornia.feature.ScaleSpaceDetector` with blur pyramid.
Still not as good as OpenCV/VLFeat because of https://github.com/kornia/kornia/pull/884, but we are working on it
"""
@@ -332,7 +335,7 @@ class LocalFeatureMatcher(Module):
self.eval()
def extract_features(self, image: Tensor, mask: Optional[Tensor] = None) -> Dict[str, Tensor]:
- """Function for feature extraction from simple image."""
+ """Extract features from simple image."""
lafs0, resps0, descs0 = self.local_feature(image, mask)
return {"lafs": lafs0, "responses": resps0, "descriptors": descs0}
@@ -347,7 +350,9 @@ class LocalFeatureMatcher(Module):
}
def forward(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
- """Args:
+ """Run forward.
+
+ Args:
data: dictionary containing the input data in the following format:
Keyword Args:
@@ -463,7 +468,9 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
hw1: Optional[Tuple[int, int]] = None,
hw2: Optional[Tuple[int, int]] = None,
) -> Tuple[Tensor, Tensor]:
- """Args:
+ """Run forward.
+
+ Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index 333c55138..fc43a9591 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -97,7 +97,7 @@ def _KeyNetConvBlock(
padding: int = 2,
dilation: int = 1,
) -> nn.Sequential:
- """Helper function for KeyNet.
+ """Create KeyNet Conv Block.
Default learnable convolutional block for KeyNet.
"""
@@ -109,7 +109,9 @@ def _KeyNetConvBlock(
class KeyNet(Module):
- """Key.Net model definition -- local feature detector (response function). This is based on the original code
+ """Key.Net model definition -- local feature detector (response function).
+
+ This is based on the original code
from paper "Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters". See :cite:`KeyNet2019` for
more details.
@@ -150,7 +152,7 @@ class KeyNet(Module):
self.eval()
def forward(self, x: Tensor) -> Tensor:
- """X - input image"""
+ """X - input image."""
shape_im = x.shape
feats: List[Tensor] = [self.feature_extractor(x)]
for _ in range(1, self.num_levels):
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index c8bb1a520..38f67fd73 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -32,8 +32,9 @@ def get_laf_scale(LAF: Tensor) -> Tensor:
def get_laf_center(LAF: Tensor) -> Tensor:
- """Return a center (keypoint) of the LAFs. The convention is that center of 5-pixel image (coordinates from 0
- to 4) is 2, and not 2.5.
+ """Return a center (keypoint) of the LAFs.
+
+ The convention is that center of 5-pixel image (coordinates from 0 to 4) is 2, and not 2.5.
Args:
LAF: :math:`(B, N, 2, 3)`
@@ -71,8 +72,9 @@ def get_laf_orientation(LAF: Tensor) -> Tensor:
def rotate_laf(LAF: Tensor, angles_degrees: Tensor) -> Tensor:
- """Apply additional rotation to the LAFs. Compared to `set_laf_orientation`, the resulting rotation is original
- LAF orientation plus angles_degrees.
+ """Apply additional rotation to the LAFs.
+
+ Compared to `set_laf_orientation`, the resulting rotation is original LAF orientation plus angles_degrees.
Args:
LAF: :math:`(B, N, 2, 3)`
@@ -108,7 +110,7 @@ def set_laf_orientation(LAF: Tensor, angles_degrees: Tensor) -> Tensor:
def laf_from_center_scale_ori(xy: Tensor, scale: Optional[Tensor] = None, ori: Optional[Tensor] = None) -> Tensor:
- """Creates a LAF from keypoint center, scale and orientation.
+ """Create a LAF from keypoint center, scale and orientation.
Useful to create kornia LAFs from OpenCV keypoints.
@@ -269,7 +271,7 @@ def laf_to_boundary_points(LAF: Tensor, n_pts: int = 50) -> Tensor:
def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0) -> Tuple[List[int], List[int]]:
- """Returns list for drawing LAFs (local features).
+ """Return list for drawing LAFs (local features).
Args:
LAF: :math:`(B, N, 2, 3)`
@@ -294,8 +296,9 @@ def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0) -> Tuple[List[int], List[
def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
- """De-normalize LAFs from scale to image scale. The convention is that center of 5-pixel image (coordinates
- from 0 to 4) is 2, and not 2.5.
+ """De-normalize LAFs from scale to image scale.
+
+ The convention is that center of 5-pixel image (coordinates from 0 to 4) is 2, and not 2.5.
B,N,H,W = images.size()
MIN_SIZE = min(H - 1, W -1)
@@ -325,8 +328,9 @@ def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
def normalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
- """Normalize LAFs to [0,1] scale from pixel scale. See below:
+ """Normalize LAFs to [0,1] scale from pixel scale.
+ See below:
B,N,H,W = images.size()
MIN_SIZE = min(H - 1, W -1)
[a11 a21 x]
@@ -355,7 +359,7 @@ def normalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
def generate_patch_grid_from_normalized_LAF(img: Tensor, LAF: Tensor, PS: int = 32) -> Tensor:
- """Helper function for affine grid generation.
+ """Generate affine grid.
Args:
img: image tensor of shape :math:`(B, CH, H, W)`.
@@ -502,7 +506,7 @@ def laf_to_three_points(laf: Tensor) -> Tensor:
Returns:
threepts :math:`(B, N, 2, 3)`.
- """
+ """ # noqa:D205
KORNIA_CHECK_LAF(laf)
three_pts = stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)
return three_pts
@@ -525,7 +529,7 @@ def laf_from_three_points(threepts: Tensor) -> Tensor:
def perspective_transform_lafs(trans_01: Tensor, lafs_1: Tensor) -> Tensor:
- r"""Function that applies perspective transformations to a set of local affine frames (LAFs).
+ r"""Apply perspective transformations to a set of local affine frames (LAFs).
Args:
trans_01: tensor for perspective transformations of shape :math:`(B, 3, 3)`.
diff --git a/kornia/feature/lightglue_onnx/utils/download.py b/kornia/feature/lightglue_onnx/utils/download.py
index f12c49fc9..404c47164 100644
--- a/kornia/feature/lightglue_onnx/utils/download.py
+++ b/kornia/feature/lightglue_onnx/utils/download.py
@@ -15,7 +15,7 @@ def download_onnx_from_url(
check_hash: bool = False,
file_name: Optional[str] = None,
) -> str:
- r"""Loads the ONNX model at the given URL.
+ r"""Load the ONNX model at the given URL.
If downloaded file is a zip file, it will be automatically
decompressed.
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 766f7ac13..ed9ea6770 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -102,7 +102,9 @@ class LoFTR(Module):
self.eval()
def forward(self, data: dict[str, Tensor]) -> dict[str, Tensor]:
- """Args:
+ """Run forward.
+
+ Args:
data: dictionary containing the input data in the following format:
Keyword Args:
diff --git a/kornia/feature/loftr/loftr_module/linear_attention.py b/kornia/feature/loftr/loftr_module/linear_attention.py
index 118395af4..47495b0df 100644
--- a/kornia/feature/loftr/loftr_module/linear_attention.py
+++ b/kornia/feature/loftr/loftr_module/linear_attention.py
@@ -1,4 +1,5 @@
-"""Linear Transformer proposed in "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention"
+"""Linear Transformer proposed in "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention".
+
Modified from: https://github.com/idiap/fast-
transformers/blob/master/fast_transformers/attention/linear_attention.py.
"""
@@ -29,7 +30,8 @@ class LinearAttention(Module):
q_mask: Optional[Tensor] = None,
kv_mask: Optional[Tensor] = None,
) -> Tensor:
- """Multi-Head linear attention proposed in "Transformers are RNNs"
+ """Multi-Head linear attention proposed in "Transformers are RNNs".
+
Args:
queries: [N, L, H, D]
keys: [N, S, H, D]
diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.py
index 8a1d24bff..3c46f1109 100644
--- a/kornia/feature/loftr/loftr_module/transformer.py
+++ b/kornia/feature/loftr/loftr_module/transformer.py
@@ -37,7 +37,9 @@ class LoFTREncoderLayer(Module):
def forward(
self, x: Tensor, source: Tensor, x_mask: Optional[Tensor] = None, source_mask: Optional[Tensor] = None
) -> Tensor:
- """Args:
+ """Run forward.
+
+ Args:
x: [N, L, C]
source: [N, S, C]
x_mask: [N, L] (optional)
@@ -84,7 +86,9 @@ class LocalFeatureTransformer(Module):
def forward(
self, feat0: Tensor, feat1: Tensor, mask0: None | Tensor = None, mask1: None | Tensor = None
) -> tuple[Tensor, Tensor]:
- """Args:
+ """Run forward.
+
+ Args:
feat0: [N, L, C]
feat1: [N, S, C]
mask0: [N, L] (optional)
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index ee0a50922..772cc0a8e 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -10,7 +10,8 @@ INF = 1e9
def mask_border(m: Tensor, b: int, v: Union[Tensor, float, bool]) -> None:
- """Mask borders with value
+ """Mask borders with value.
+
Args:
m (torch.Tensor): [N, H0, W0, H1, W1]
b (int)
@@ -95,7 +96,9 @@ class CoarseMatching(Module):
mask_c0: Optional[Tensor] = None,
mask_c1: Optional[Tensor] = None,
) -> None:
- """Args:
+ """Run forward.
+
+ Args:
feat0 (torch.Tensor): [N, L, C]
feat1 (torch.Tensor): [N, S, C]
data (dict)
@@ -152,7 +155,9 @@ class CoarseMatching(Module):
@torch.no_grad()
def get_coarse_match(self, conf_matrix: Tensor, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
- """Args:
+ """Get corase matching.
+
+ Args:
conf_matrix (torch.Tensor): [N, L, S]
data (dict): with keys ['hw0_i', 'hw1_i', 'hw0_c', 'hw1_c']
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index bc02e1642..df9cd46aa 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -17,7 +17,9 @@ class FineMatching(Module):
super().__init__()
def forward(self, feat_f0: Tensor, feat_f1: Tensor, data: dict[str, Any]) -> None:
- """Args:
+ """Run forward.
+
+ Args:
feat0 (torch.Tensor): [M, WW, C]
feat1 (torch.Tensor): [M, WW, C]
data (dict)
diff --git a/kornia/feature/loftr/utils/geometry.py b/kornia/feature/loftr/utils/geometry.py
index d5e8ff541..14d019c2b 100644
--- a/kornia/feature/loftr/utils/geometry.py
+++ b/kornia/feature/loftr/utils/geometry.py
@@ -9,8 +9,9 @@ from kornia.core import Tensor
def warp_kpts(
kpts0: Tensor, depth0: Tensor, depth1: Tensor, T_0to1: Tensor, K0: Tensor, K1: Tensor
) -> Tuple[Tensor, Tensor]:
- """Warp kpts0 from I0 to I1 with depth, K and Rt Also check covisibility and depth consistency. Depth is
- consistent if relative error < 0.2 (hard-coded).
+ """Warp kpts0 from I0 to I1 with depth, K and Rt Also check covisibility and depth consistency.
+
+ Depth is consistent if relative error < 0.2 (hard-coded).
Args:
kpts0: [N, L, 2] - <x, y>,
diff --git a/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.py
index ea5c7ee72..36590f3c0 100644
--- a/kornia/feature/loftr/utils/position_encoding.py
+++ b/kornia/feature/loftr/utils/position_encoding.py
@@ -7,12 +7,14 @@ from kornia.core import Module, Tensor, cos, sin, zeros
class PositionEncodingSine(Module):
- """This is a sinusoidal position encoding that generalized to 2-dimensional images."""
+ """A sinusoidal position encoding that generalized to 2-dimensional images."""
pe: Tensor
def __init__(self, d_model: int, max_shape: Tuple[int, int] = (256, 256), temp_bug_fix: bool = True) -> None:
- """Args:
+ """Construct sinusoidal positional encoding.
+
+ Args:
max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels
temp_bug_fix (bool): As noted in this [issue](https://github.com/zju3dv/LoFTR/issues/41),
the original implementation of LoFTR includes a bug in the pos-enc impl, which has little impact
@@ -28,7 +30,7 @@ class PositionEncodingSine(Module):
self.register_buffer("pe", pe, persistent=False) # [1, C, H, W]
def _create_position_encoding(self, max_shape: Tuple[int, int]) -> Tensor:
- """Creates a position encoding from scratch.
+ """Create a position encoding from scratch.
For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape
should be (H//8, W//8).
@@ -52,7 +54,7 @@ class PositionEncodingSine(Module):
return pe.unsqueeze(0)
def update_position_encoding_size(self, max_shape: Tuple[int, int]) -> None:
- """Updates position encoding to new max_shape.
+ """Update position encoding to new max_shape.
For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape
should be (H//8, W//8).
@@ -60,7 +62,9 @@ class PositionEncodingSine(Module):
self.pe = self._create_position_encoding(max_shape).to(self.pe.device)
def forward(self, x: Tensor) -> Tensor:
- """Args:
+ """Run forward.
+
+ Args:
x: [N, C, H, W]
"""
diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.py
index d931e0596..cbd149c25 100644
--- a/kornia/feature/loftr/utils/supervision.py
+++ b/kornia/feature/loftr/utils/supervision.py
@@ -24,7 +24,9 @@ def mask_pts_at_padded_regions(grid_pt: Tensor, mask: Tensor) -> Tensor:
@torch.no_grad()
def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
- """Update:
+ """Perform coarse supervision.
+
+ Update:
data (dict): {
"conf_matrix_gt": [N, hw0, hw1],
'spv_b_ids': [M]
@@ -119,7 +121,9 @@ def compute_supervision_coarse(data: dict[str, Any], config: dict[str, Any]) ->
# Fine-Level supervision
@torch.no_grad()
def spvs_fine(data: dict[str, Any], config: dict[str, Any]) -> None:
- """Update:
+ """Perform fine supervision.
+
+ Update:
data (dict):{
"expec_f_gt": [M, 2]}
"""
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 3332ea81c..6c4ad68c0 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -28,8 +28,7 @@ def _get_default_fginn_params() -> Dict[str, Any]:
def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor] = None) -> Tensor:
- """Helper function, which checks validity of provided distance matrix, or calculates L2-distance matrix dm is
- not provided.
+ """Check validity of provided distance matrix, or calculates L2-distance matrix if dm is not provided.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
@@ -47,7 +46,7 @@ def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor
def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
- """Helper function, which output empty tensors.
+ """Output empty tensors.
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(0, 1)`.
@@ -60,7 +59,7 @@ def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
def match_nn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- r"""Function, which finds nearest neighbors in desc2 for each vector in desc1.
+ r"""Find nearest neighbors in desc2 for each vector in desc1.
If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
@@ -87,7 +86,7 @@ def match_nn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple
def match_mnn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- """Function, which finds mutual nearest neighbors in desc2 for each vector in desc1.
+ """Find mutual nearest neighbors in desc2 for each vector in desc1.
If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
@@ -125,7 +124,7 @@ def match_mnn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tupl
def match_snn(desc1: Tensor, desc2: Tensor, th: float = 0.8, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- """Function, which finds nearest neighbors in desc2 for each vector in desc1.
+ """Find nearest neighbors in desc2 for each vector in desc1.
The method satisfies first to second nearest neighbor distance <= th.
@@ -163,7 +162,7 @@ def match_snn(desc1: Tensor, desc2: Tensor, th: float = 0.8, dm: Optional[Tensor
def match_smnn(desc1: Tensor, desc2: Tensor, th: float = 0.95, dm: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- """Function, which finds mutual nearest neighbors in desc2 for each vector in desc1.
+ """Find mutual nearest neighbors in desc2 for each vector in desc1.
the method satisfies first to second nearest neighbor distance <= th.
@@ -227,7 +226,7 @@ def match_fginn(
mutual: bool = False,
dm: Optional[Tensor] = None,
) -> Tuple[Tensor, Tensor]:
- """Function, which finds nearest neighbors in desc2 for each vector in desc1.
+ """Find nearest neighbors in desc2 for each vector in desc1.
The method satisfies first to second nearest neighbor distance <= th,
and assures 2nd nearest neighbor is geometrically inconsistent with the 1st one
@@ -317,11 +316,13 @@ class DescriptorMatcher(Module):
self.th = th
def forward(self, desc1: Tensor, desc2: Tensor) -> Tuple[Tensor, Tensor]:
- """Args:
+ """Run forward.
+
+ Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
- Return:
+ Returns:
- 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 :math:`0 <= B3 <= B1`.
@@ -425,7 +426,9 @@ class DescriptorMatcherWithSteerer(Module):
normalize: bool = False,
subset_size: Optional[int] = None,
) -> Tuple[Tensor, Tensor, Optional[int]]:
- """Args:
+ """Run forward.
+
+ Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
normalize: bool to decide whether to normalize descriptors to unit norm.
@@ -433,7 +436,7 @@ class DescriptorMatcherWithSteerer(Module):
number of rotations. Smaller subset size leads to faster but less
accurate matching. Only used when `self.steer_mode` is `"global"`.
- Return:
+ Returns:
- 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 :math:`0 <= B3 <= B1`.
@@ -506,13 +509,15 @@ class GeometryAwareDescriptorMatcher(Module):
self.params = params or {}
def forward(self, desc1: Tensor, desc2: Tensor, lafs1: Tensor, lafs2: Tensor) -> Tuple[Tensor, Tensor]:
- """Args:
+ """Run forward.
+
+ Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.
lafs2: LAFs of a shape :math:`(1, B2, 2, 3)`.
- Return:
+ Returns:
- 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 :math:`0 <= B3 <= B1`.
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 951e84685..97f9d44a5 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -19,7 +19,9 @@ class PassLAF(nn.Module):
"""Dummy module to use instead of local feature orientation or affine shape estimator."""
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
- """Args:
+ """Run forward.
+
+ Args:
laf: :math:`(B, N, 2, 3)`
img: :math:`(B, 1, H, W)`
@@ -60,7 +62,9 @@ class PatchDominantGradientOrientation(nn.Module):
)
def forward(self, patch: torch.Tensor) -> torch.Tensor:
- """Args:
+ """Run forward.
+
+ Args:
patch: :math:`(B, 1, H, W)`
Returns:
@@ -169,7 +173,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
@@ -177,7 +181,9 @@ class OriNet(nn.Module):
return (x - mp.detach()) / (sp.detach() + eps)
def forward(self, patch: torch.Tensor) -> torch.Tensor:
- """Args:
+ """Run forward.
+
+ Args:
patch: :math:`(B, 1, H, W)`
Returns:
@@ -219,7 +225,9 @@ class LAFOrienter(nn.Module):
return f"{self.__class__.__name__}(patch_size={self.patch_size}, angle_detector={self.angle_detector})"
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
- """Args:
+ """Run forward.
+
+ Args:
laf: :math:`(B, N, 2, 3)`
img: :math:`(B, 1, H, W)`
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 84553cd8e..bd48165c6 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -16,7 +16,9 @@ from .responses import BlobHessian
def _scale_index_to_scale(max_coords: Tensor, sigmas: Tensor, num_levels: int) -> Tensor:
- r"""Auxiliary function for ScaleSpaceDetector. Converts scale level index from ConvSoftArgmax3d to the actual
+ r"""Auxiliary function for ScaleSpaceDetector.
+
+ Converts scale level index from ConvSoftArgmax3d to the actual
scale, using the sigmas from the ScalePyramid output.
Args:
@@ -50,7 +52,9 @@ def _create_octave_mask(mask: Tensor, octave_shape: List[int]) -> Tensor:
class ScaleSpaceDetector(Module):
- r"""Module for differentiable local feature detection, as close as possible to classical local feature detectors
+ 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,
@@ -219,8 +223,10 @@ class ScaleSpaceDetector(Module):
return responses, lafs
def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- """Three stage local feature detection. First the location and scale of interest points are determined by
- detect function. Then affine shape and orientation.
+ """Three stage local feature detection.
+
+ First the location and scale of interest points are determined by detect function.
+ Then affine shape and orientation.
Args:
img: image to extract features with shape [BxCxHxW]
@@ -307,7 +313,7 @@ class MultiResolutionDetector(Module):
self.aff = aff_module
def remove_borders(self, score_map: Tensor, borders: int = 15) -> Tensor:
- """It removes the borders of the image to avoid detections on the corners."""
+ """Remove the borders of the image to avoid detections on the corners."""
mask = torch.zeros_like(score_map)
mask[:, :, borders:-borders, borders:-borders] = 1
return mask * score_map
@@ -391,8 +397,10 @@ class MultiResolutionDetector(Module):
return responses, lafs
def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- """Three stage local feature detection. First the location and scale of interest points are determined by
- detect function. Then affine shape and orientation.
+ """Three stage local feature detection.
+
+ First the location and scale of interest points are determined by detect function.
+ Then affine shape and orientation.
Args:
img: image to extract features with shape [1xCxHxW]. KeyNetDetector does not support batch processing,
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index fa5d77300..375608edb 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -11,7 +11,7 @@ from kornia.geometry.conversions import pi
def _get_reshape_kernel(kd: int, ky: int, kx: int) -> Tensor:
- """Utility function, which returns neigh2channels conv kernel."""
+ """Return neigh2channels conv kernel."""
numel: int = kd * ky * kx
weight = eye(numel)
return weight.view(numel, kd, ky, kx)
@@ -176,7 +176,7 @@ def sift_describe(
rootsift: bool = True,
clipval: float = 0.2,
) -> Tensor:
- r"""Computes the sift descriptor.
+ r"""Compute the sift descriptor.
See
:class: `~kornia.feature.SIFTDescriptor` for details.
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index f47e5aefb..54d82336f 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -77,14 +77,16 @@ class SOLD2(Module):
self.line_matcher = WunschLineMatcher(self.config.line_matcher_cfg)
def forward(self, img: Tensor) -> Dict[str, Any]:
- """Args:
+ """Run forward.
+
+ Args:
img: batched images with shape :math:`(B, 1, H, W)`.
- Return:
- - ``line_segments``: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`.
- - ``junction_heatmap``: raw junction heatmap of shape :math:`(B, H, W)`.
- - ``line_heatmap``: raw line heatmap of shape :math:`(B, H, W)`.
- - ``dense_desc``: the semi-dense descriptor map of shape :math:`(B, 128, H/4, W/4)`.
+ Returns:
+ line_segments: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`.
+ junction_heatmap: raw junction heatmap of shape :math:`(B, H, W)`.
+ line_heatmap: raw line heatmap of shape :math:`(B, H, W)`.
+ dense_desc: the semi-dense descriptor map of shape :math:`(B, 128, H/4, W/4)`.
"""
KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
@@ -241,8 +243,9 @@ class WunschLineMatcher(Module):
return line_points, valid_points
def filter_and_match_lines(self, scores: Tensor) -> Tensor:
- """Use the scores to keep the top k best lines, compute the Needleman- Wunsch algorithm on each candidate
- pairs, and keep the highest score.
+ """Use scores to keep the top k best lines.
+
+ Compute the Needleman- Wunsch algorithm on each candidate pairs, and keep the highest score.
Inputs:
scores: a (N, M, n, n) Tensor containing the pairwise scores
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 27c9e0599..85d456299 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -78,13 +78,15 @@ class SOLD2_detector(Module):
return state_dict
def forward(self, img: Tensor) -> Dict[str, Any]:
- """Args:
+ """Run forward.
+
+ Args:
img: batched images with shape :math:`(B, 1, H, W)`.
- Return:
- - ``line_segments``: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`.
- - ``junction_heatmap``: raw junction heatmap of shape :math:`(B, H, W)`.
- - ``line_heatmap``: raw line heatmap of shape :math:`(B, H, W)`.
+ Returns:
+ line_segments: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`.
+ junction_heatmap: raw junction heatmap of shape :math:`(B, H, W)`.
+ line_heatmap: raw line heatmap of shape :math:`(B, H, W)`.
"""
KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
@@ -176,7 +178,7 @@ class LineSegmentDetectionModule:
raise ValueError("[Error] Missing junction refinement config.")
def detect(self, junctions: Tensor, heatmap: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
- """Main function performing line segment detection."""
+ """Perform line segment detection."""
KORNIA_CHECK_SHAPE(heatmap, ["H", "W"])
H, W = heatmap.shape
device = junctions.device
@@ -466,7 +468,7 @@ class LineSegmentDetectionModule:
return line_map
def detect_bilinear(self, heatmap: Tensor, cand_h: Tensor, cand_w: Tensor) -> Tensor:
- """Detection by bilinear sampling."""
+ """Detect by bilinear sampling."""
# Get the floor and ceiling locations
cand_h_floor = torch.floor(cand_h).to(torch.long)
cand_h_ceil = torch.ceil(cand_h).to(torch.long)
@@ -493,7 +495,7 @@ class LineSegmentDetectionModule:
normalized_seg_length: Tensor,
device: torch.device,
) -> Tensor:
- """Detection by local maximum search."""
+ """Detect by local maximum search."""
# Compute the distance threshold
dist_thresh = 0.5 * (2**0.5) + self.lambda_radius * normalized_seg_length
# Make it N x 64
diff --git a/kornia/feature/steerers.py b/kornia/feature/steerers.py
index ac7150ad0..7c40037f5 100644
--- a/kornia/feature/steerers.py
+++ b/kornia/feature/steerers.py
@@ -45,7 +45,7 @@ class DiscreteSteerer(Module):
generator_type: str = "C4",
steerer_order: int = 8,
) -> Module:
- r"""Creates a steerer for pretrained DeDoDe descriptors int the "C-setting"
+ r"""Create a steerer for pretrained DeDoDe descriptors int the "C-setting"
from the paper https://arxiv.org/abs/2312.02152, where descriptors were
trained for fixed steerers.
@@ -59,7 +59,7 @@ class DiscreteSteerer(Module):
Returns:
The pretrained model.
- """
+ """ # noqa: D205
descriptor_dim = 256
if generator_type == "C4":
generator = torch.block_diag(
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index 00c354e02..4beabcff2 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -19,7 +19,7 @@ def _bilateral_blur(
border_type: str = "reflect",
color_distance_type: str = "l1",
) -> Tensor:
- """Single implementation for both Bilateral Filter and Joint Bilateral Filter"""
+ """Single implementation for both Bilateral Filter and Joint Bilateral Filter."""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
if guidance is not None:
diff --git a/kornia/filters/in_range.py b/kornia/filters/in_range.py
index cd6c2480d..a800f269c 100644
--- a/kornia/filters/in_range.py
+++ b/kornia/filters/in_range.py
@@ -17,7 +17,7 @@ def in_range(
upper: Union[tuple[Any, ...], Tensor],
return_mask: bool = False,
) -> Tensor:
- r"""Creates a mask indicating whether elements of the input tensor are within the specified range.
+ r"""Create a mask indicating whether elements of the input tensor are within the specified range.
.. image:: _static/img/in_range.png
@@ -136,7 +136,7 @@ def in_range(
class InRange(Module):
- r"""Creates a module for applying lower and upper bounds to input tensors.
+ r"""Create a module for applying lower and upper bounds to input tensors.
Args:
input: The input tensor to be filtered.
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 5f339b7e2..94c2f845f 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -140,10 +140,7 @@ def gaussian_discrete_erf(
def _modified_bessel_0(x: Tensor) -> Tensor:
- r"""Adapted from:
-
- https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
- """
+ """Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py."""
ax = torch.abs(x)
out = zeros_like(x)
@@ -166,10 +163,7 @@ def _modified_bessel_0(x: Tensor) -> Tensor:
def _modified_bessel_1(x: Tensor) -> Tensor:
- r"""Adapted from:
-
- https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
- """
+ """Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py."""
ax = torch.abs(x)
out = zeros_like(x)
@@ -192,10 +186,7 @@ def _modified_bessel_1(x: Tensor) -> Tensor:
def _modified_bessel_i(n: int, x: Tensor) -> Tensor:
- r"""Adapted from:
-
- https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
- """
+ """Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py."""
KORNIA_CHECK(n >= 2, "n must be greater than 1.99")
if (x == 0.0).all():
@@ -280,7 +271,7 @@ def laplacian_1d(window_size: int, *, device: Optional[Device] = None, dtype: Dt
def get_box_kernel1d(kernel_size: int, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- r"""Utility function that returns a 1-D box filter.
+ r"""Return a 1-D box filter.
Args:
kernel_size: the size of the kernel.
@@ -299,7 +290,7 @@ def get_box_kernel1d(kernel_size: int, *, device: Optional[Device] = None, dtype
def get_box_kernel2d(
kernel_size: tuple[int, int] | int, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
- r"""Utility function that returns a 2-D box filter.
+ r"""Return a 2-D box filter.
Args:
kernel_size: the size of the kernel.
@@ -336,12 +327,12 @@ def get_binary_kernel2d(
def get_sobel_kernel_3x3(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- """Utility function that returns a sobel kernel of 3x3."""
+ """Return a sobel kernel of 3x3."""
return tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], device=device, dtype=dtype)
def get_sobel_kernel_5x5_2nd_order(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- """Utility function that returns a 2nd order sobel kernel of 5x5."""
+ """Return a 2nd order sobel kernel of 5x5."""
return tensor(
[
[-1.0, 0.0, 2.0, 0.0, -1.0],
@@ -356,7 +347,7 @@ def get_sobel_kernel_5x5_2nd_order(*, device: Optional[Device] = None, dtype: Op
def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- """Utility function that returns a 2nd order sobel kernel of 5x5."""
+ """Return a 2nd order sobel kernel of 5x5."""
return tensor(
[
[-1.0, -2.0, 0.0, 2.0, 1.0],
@@ -371,12 +362,12 @@ def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Optional[Device] = None, dtype
def get_diff_kernel_3x3(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- """Utility function that returns a first order derivative kernel of 3x3."""
+ """Return a first order derivative kernel of 3x3."""
return tensor([[-0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [-0.0, 0.0, 0.0]], device=device, dtype=dtype)
def get_diff_kernel3d(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- """Utility function that returns a first order derivative kernel of 3x3x3."""
+ """Return a first order derivative kernel of 3x3x3."""
kernel = tensor(
[
[
@@ -402,7 +393,7 @@ def get_diff_kernel3d(device: Optional[Device] = None, dtype: Optional[Dtype] =
def get_diff_kernel3d_2nd_order(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- """Utility function that returns a first order derivative kernel of 3x3x3."""
+ """Return a first order derivative kernel of 3x3x3."""
kernel = tensor(
[
[
@@ -471,9 +462,9 @@ def get_diff_kernel2d_2nd_order(*, device: Optional[Device] = None, dtype: Optio
def get_spatial_gradient_kernel2d(
mode: str, order: int, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
- r"""Function that returns kernel for 1st or 2nd order image gradients, using one of the following operators:
+ r"""Return kernel for 1st or 2nd order image gradients.
- sobel, diff.
+ Uses one of the following operators: sobel, diff.
"""
KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
@@ -495,8 +486,9 @@ def get_spatial_gradient_kernel2d(
def get_spatial_gradient_kernel3d(
mode: str, order: int, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
- r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients, using one of the following
- operators: sobel, diff.
+ r"""Return kernel for 1st or 2nd order scale pyramid gradients.
+
+ Uses one of the following operators: sobel, diff.
"""
KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
@@ -519,7 +511,7 @@ def get_gaussian_kernel1d(
device: Optional[Device] = None,
dtype: Optional[Dtype] = None,
) -> Tensor:
- r"""Function that returns Gaussian filter coefficients.
+ r"""Return Gaussian filter coefficients.
Args:
kernel_size: filter size. It should be odd and positive.
@@ -554,7 +546,7 @@ def get_gaussian_discrete_kernel1d(
device: Optional[Device] = None,
dtype: Optional[Dtype] = None,
) -> Tensor:
- r"""Function that returns Gaussian filter coefficients based on the modified Bessel functions.
+ r"""Return Gaussian filter coefficients based on the modified Bessel functions.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
@@ -591,7 +583,7 @@ def get_gaussian_erf_kernel1d(
device: Optional[Device] = None,
dtype: Optional[Dtype] = None,
) -> Tensor:
- r"""Function that returns Gaussian filter coefficients by interpolating the error function.
+ r"""Return Gaussian filter coefficients by interpolating the error function.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
@@ -628,7 +620,7 @@ def get_gaussian_kernel2d(
device: Optional[Device] = None,
dtype: Optional[Dtype] = None,
) -> Tensor:
- r"""Function that returns Gaussian filter matrix coefficients.
+ r"""Return Gaussian filter matrix coefficients.
Args:
kernel_size: filter sizes in the y and x direction. Sizes should be odd and positive.
@@ -685,7 +677,7 @@ def get_gaussian_kernel3d(
device: Optional[Device] = None,
dtype: Optional[Dtype] = None,
) -> Tensor:
- r"""Function that returns Gaussian filter matrix coefficients.
+ r"""Return Gaussian filter matrix coefficients.
Args:
kernel_size: filter sizes in the z, y and x direction. Sizes should be odd and positive.
@@ -740,7 +732,7 @@ def get_gaussian_kernel3d(
def get_laplacian_kernel1d(
kernel_size: int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32
) -> Tensor:
- r"""Function that returns the coefficients of a 1D Laplacian filter.
+ r"""Return the coefficients of a 1D Laplacian filter.
Args:
kernel_size: filter size. It should be odd and positive.
@@ -770,7 +762,7 @@ def get_laplacian_kernel1d(
def get_laplacian_kernel2d(
kernel_size: tuple[int, int] | int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32
) -> Tensor:
- r"""Function that returns Gaussian filter matrix coefficients.
+ r"""Return Gaussian filter matrix coefficients.
Args:
kernel_size: filter size should be odd.
@@ -903,7 +895,7 @@ def get_pascal_kernel_1d(
def get_canny_nms_kernel(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- """Utility function that returns 3x3 kernels for the Canny Non-maximal suppression."""
+ """Return 3x3 kernels for the Canny Non-maximal suppression."""
return tensor(
[
[[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]]],
@@ -921,7 +913,7 @@ def get_canny_nms_kernel(device: Optional[Device] = None, dtype: Optional[Dtype]
def get_hysteresis_kernel(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- """Utility function that returns the 3x3 kernels for the Canny hysteresis."""
+ """Return the 3x3 kernels for the Canny hysteresis."""
return tensor(
[
[[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]],
@@ -939,7 +931,7 @@ def get_hysteresis_kernel(device: Optional[Device] = None, dtype: Optional[Dtype
def get_hanning_kernel1d(kernel_size: int, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- r"""Returns Hanning (also known as Hann) kernel, used in signal processing and KCF tracker.
+ r"""Return Hanning (also known as Hann) kernel, used in signal processing and KCF tracker.
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
\\qquad 0 \\leq n \\leq M-1
@@ -970,7 +962,7 @@ def get_hanning_kernel1d(kernel_size: int, device: Optional[Device] = None, dtyp
def get_hanning_kernel2d(
kernel_size: tuple[int, int] | int, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
- r"""Returns 2d Hanning kernel, used in signal processing and KCF tracker.
+ r"""Return 2d Hanning kernel, used in signal processing and KCF tracker.
Args:
kernel_size: The size of the kernel for the filter. It should be positive.
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 0dd7852f5..6249a537b 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -10,7 +10,7 @@ from .kernels import _unpack_2d_ks, get_binary_kernel2d
def _compute_zero_padding(kernel_size: tuple[int, int] | int) -> tuple[int, int]:
- r"""Utility function that computes zero padding tuple."""
+ r"""Compute zero padding tuple."""
ky, kx = _unpack_2d_ks(kernel_size)
return (ky - 1) // 2, (kx - 1) // 2
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index d0e2f9d81..daa94570c 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -512,8 +512,7 @@ def transform_bbox(
def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torch.Tensor:
- """Perform non-maxima suppression (NMS) on a given tensor of bounding boxes according to the intersection-over-
- union (IoU).
+ """Perform non-maxima suppression (NMS) on tensor of bounding boxes according to the intersection-over-union (IoU).
Args:
boxes: tensor containing the encoded bounding boxes with the shape :math:`(N, (x_1, y_1, x_2, y_2))`.
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index afc17ad27..fdc434210 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -33,8 +33,9 @@ def _merge_box_list(boxes: list[torch.Tensor], method: str = "pad") -> tuple[tor
def _transform_boxes(boxes: torch.Tensor, M: torch.Tensor) -> torch.Tensor:
- """Transforms 3D and 2D in kornia format by applying the transformation matrix M. Boxes and the transformation
- matrix could be batched or not.
+ """Transform 3D and 2D in kornia format by applying the transformation matrix M.
+
+ Boxes and the transformation matrix could be batched or not.
Args:
boxes: 2D quadrilaterals or 3D hexahedrons in kornia format.
@@ -251,7 +252,7 @@ class Boxes:
return heights, widths
def merge(self, boxes: Boxes, inplace: bool = False) -> Boxes:
- """Merges boxes.
+ """Merge boxes.
Say, current instance holds :math:`(B, N, 4, 2)` and the incoming boxes holds :math:`(B, M, 4, 2)`,
the merge results in :math:`(B, N + M, 4, 2)`.
@@ -396,7 +397,7 @@ class Boxes:
return obj
def compute_area(self) -> torch.Tensor:
- """Returns :math:`(B, N)`."""
+ """Return :math:`(B, N)`."""
coords = self._data.view((-1, 4, 2)) if self._data.ndim == 4 else self._data
# calculate centroid of the box
centroid = coords.mean(dim=1, keepdim=True)
@@ -415,7 +416,7 @@ class Boxes:
def from_tensor(
cls, boxes: torch.Tensor | list[torch.Tensor], mode: str = "xyxy", validate_boxes: bool = True
) -> Boxes:
- r"""Helper method to easily create :class:`Boxes` from boxes stored in another format.
+ r"""Create :class:`Boxes` from boxes stored in another format.
Args:
boxes: 2D boxes, shape of :math:`(N, 4)`, :math:`(B, N, 4)`, :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
@@ -468,8 +469,9 @@ class Boxes:
def to_tensor(
self, mode: Optional[str] = None, as_padded_sequence: bool = False
) -> 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:
@@ -614,11 +616,11 @@ class Boxes:
return obj
def transform_boxes_(self, M: torch.Tensor) -> Boxes:
- """Inplace version of :func:`Boxes.transform_boxes`"""
+ """Inplace version of :func:`Boxes.transform_boxes`."""
return self.transform_boxes(M, inplace=True)
def translate(self, size: Tensor, method: str = "warp", inplace: bool = False) -> Boxes:
- """Translates boxes by the provided size.
+ """Translate boxes by the provided size.
Args:
size: translate size for x, y direction, shape of :math:`(B, 2)`.
@@ -789,7 +791,7 @@ class Boxes3D:
@classmethod
def from_tensor(cls, boxes: torch.Tensor, mode: str = "xyzxyz", validate_boxes: bool = True) -> Boxes3D:
- r"""Helper method to easily create :class:`Boxes3D` from 3D boxes stored in another format.
+ r"""Create :class:`Boxes3D` from 3D boxes stored in another format.
Args:
boxes: 3D boxes, shape of :math:`(N,6)` or :math:`(B,N,6)`.
@@ -866,8 +868,9 @@ 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.
@@ -1049,7 +1052,7 @@ class Boxes3D:
return Boxes3D(transformed_boxes, False, "xyzxyz_plus")
def transform_boxes_(self, M: torch.Tensor) -> Boxes3D:
- """Inplace version of :func:`Boxes3D.transform_boxes`"""
+ """Inplace version of :func:`Boxes3D.transform_boxes`."""
return self.transform_boxes(M, inplace=True)
@property
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index d7ad8f9e8..0278d8d79 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -12,7 +12,7 @@ from kornia.utils.helpers import _torch_linalg_svdvals, _torch_svd_cast
def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
- r"""Normalizes points.
+ r"""Normalize points.
Args:
points : Tensor containing the points to be normalized with shape :math:`(B, N, D)`.
@@ -48,7 +48,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"""Attempt 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/camera/distortion_kannala_brandt.py b/kornia/geometry/camera/distortion_kannala_brandt.py
index 9c2a3778d..73c447aea 100644
--- a/kornia/geometry/camera/distortion_kannala_brandt.py
+++ b/kornia/geometry/camera/distortion_kannala_brandt.py
@@ -42,8 +42,7 @@ def _distort_points_kannala_brandt_impl(
def distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor, params: Tensor) -> Tensor:
- r"""Distort one or more points from the canonical z=1 plane into the camera frame using the Kannala-Brandt
- model.
+ r"""Distort points from the canonical z=1 plane into the camera frame using the Kannala-Brandt model.
Args:
projected_points_in_camera_z1_plane: Tensor representing the points to distort with shape (..., 2).
@@ -81,8 +80,7 @@ def distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor, p
def undistort_points_kannala_brandt(distorted_points_in_camera: Tensor, params: Tensor) -> Tensor:
- r"""Undistort one or more points from the camera frame into the canonical z=1 plane using the Kannala-Brandt
- model.
+ r"""Undistort points from the camera frame into the canonical z=1 plane using the Kannala-Brandt model.
Args:
distorted_points_in_camera: Tensor representing the points to undistort with shape (..., 2).
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 09306df0c..e829141ca 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -67,7 +67,7 @@ class PinholeCamera:
KORNIA_CHECK_SAME_DEVICE(data, first)
def device(self) -> torch.device:
- r"""Returns the device for camera buffers.
+ r"""Return the device for camera buffers.
Returns:
Device type
@@ -454,7 +454,7 @@ class PinholeCamerasList(PinholeCamera):
def pinhole_matrix(pinholes: Tensor, eps: float = 1e-6) -> Tensor:
- r"""Function that returns the pinhole matrix from a pinhole model.
+ r"""Return the pinhole matrix from a pinhole model.
.. note::
This method is going to be deprecated in version 0.2 in favour of
diff --git a/kornia/geometry/camera/projection_orthographic.py b/kornia/geometry/camera/projection_orthographic.py
index 48ae0c07e..651df2a13 100644
--- a/kornia/geometry/camera/projection_orthographic.py
+++ b/kornia/geometry/camera/projection_orthographic.py
@@ -7,8 +7,7 @@ from kornia.core.check import KORNIA_CHECK_SHAPE
def project_points_orthographic(points_in_camera: Tensor) -> Tensor:
- r"""Project one or more points from the camera frame into the canonical z=1 plane through orthographic
- projection.
+ r"""Project points from the camera frame into the canonical z=1 plane through orthographic projection.
.. math::
\begin{bmatrix} u \\ v \end{bmatrix} =
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index e5a8d501c..392937a5b 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -9,7 +9,7 @@ from kornia.utils.grid import create_meshgrid
class StereoException(Exception):
def __init__(self, msg: str, *args: Any, **kwargs: Any) -> None:
- r"""Custom exception for the :module:`~kornia.geometry.camera.stereo` module.
+ r"""Construct custom exception for the :module:`~kornia.geometry.camera.stereo` module.
Adds a general helper module redirecting the user to the proper documentation site.
@@ -51,7 +51,7 @@ class StereoCamera:
@staticmethod
def _check_stereo_camera(rectified_left_camera: Tensor, rectified_right_camera: Tensor) -> None:
- r"""Utility function to ensure user specified correct camera matrices.
+ r"""Ensure user specified correct camera matrices.
Args:
rectified_left_camera: The rectified left camera projection matrix
@@ -204,7 +204,7 @@ class StereoCamera:
return self._Q_matrix
def _init_Q_matrix(self) -> Tensor:
- r"""Initialized the Q matrix of the horizontal stereo setup. See the Q property.
+ r"""Initialize the Q matrix of the horizontal stereo setup. See the Q property.
Returns:
The Q matrix of shape :math:`(B, 4, 4)`.
@@ -235,7 +235,7 @@ class StereoCamera:
def _check_disparity_tensor(disparity_tensor: Tensor) -> None:
- r"""Utility function to ensure correct user provided correct disparity tensor.
+ r"""Ensure correct user provided correct disparity tensor.
Args:
disparity_tensor: The disparity tensor of shape :math:`(B, 1, H, W)`.
@@ -263,7 +263,7 @@ def _check_disparity_tensor(disparity_tensor: Tensor) -> None:
def _check_Q_matrix(Q_matrix: Tensor) -> None:
- r"""Utility function to ensure Q matrix is of correct form.
+ r"""Ensure Q matrix is of correct form.
Args:
Q_matrix: The Q matrix for reprojecting disparity to a point cloud of shape :math:`(B, 4, 4)`
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 9f648d667..c51678f9a 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -61,7 +61,7 @@ __all__ = [
def rad2deg(tensor: Tensor) -> Tensor:
- r"""Function that converts angles from radians to degrees.
+ r"""Convert angles from radians to degrees.
Args:
tensor: Tensor of arbitrary shape.
@@ -82,7 +82,7 @@ def rad2deg(tensor: Tensor) -> Tensor:
def deg2rad(tensor: Tensor) -> Tensor:
- r"""Function that converts angles from degrees to radians.
+ r"""Convert angles from degrees to radians.
Args:
tensor: Tensor of arbitrary shape.
@@ -103,7 +103,7 @@ def deg2rad(tensor: Tensor) -> Tensor:
def pol2cart(rho: Tensor, phi: Tensor) -> tuple[Tensor, Tensor]:
- r"""Function that converts polar coordinates to cartesian coordinates.
+ r"""Convert polar coordinates to cartesian coordinates.
Args:
rho: Tensor of arbitrary shape.
@@ -128,7 +128,7 @@ def pol2cart(rho: Tensor, phi: Tensor) -> tuple[Tensor, Tensor]:
def cart2pol(x: Tensor, y: Tensor, eps: float = 1.0e-8) -> tuple[Tensor, Tensor]:
- """Function that converts cartesian coordinates to polar coordinates.
+ """Convert cartesian coordinates to polar coordinates.
Args:
x: Tensor of arbitrary shape.
@@ -154,7 +154,7 @@ def cart2pol(x: Tensor, y: Tensor, eps: float = 1.0e-8) -> tuple[Tensor, Tensor]
def convert_points_from_homogeneous(points: Tensor, eps: float = 1e-8) -> Tensor:
- r"""Function that converts points from homogeneous to Euclidean space.
+ r"""Convert points from homogeneous to Euclidean space.
Args:
points: the points to be transformed of shape :math:`(B, N, D)`.
@@ -188,7 +188,7 @@ def convert_points_from_homogeneous(points: Tensor, eps: float = 1e-8) -> Tensor
def convert_points_to_homogeneous(points: Tensor) -> Tensor:
- r"""Function that converts points from Euclidean to homogeneous space.
+ r"""Convert points from Euclidean to homogeneous space.
Args:
points: the points to be transformed with shape :math:`(*, N, D)`.
@@ -217,7 +217,7 @@ def _convert_affinematrix_to_homography_impl(A: Tensor) -> Tensor:
def convert_affinematrix_to_homography(A: Tensor) -> Tensor:
- r"""Function that converts batch of affine matrices.
+ r"""Convert batch of affine matrices.
Args:
A: the affine matrix with shape :math:`(B,2,3)`.
@@ -244,7 +244,7 @@ def convert_affinematrix_to_homography(A: Tensor) -> Tensor:
def convert_affinematrix_to_homography3d(A: Tensor) -> Tensor:
- r"""Function that converts batch of 3d affine matrices.
+ r"""Convert batch of 3d affine matrices.
Args:
A: the affine matrix with shape :math:`(B,3,4)`.
@@ -1180,7 +1180,7 @@ def normalize_homography3d(
def normalize_points_with_intrinsics(point_2d: Tensor, camera_matrix: Tensor) -> Tensor:
- """Normalizes points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.
+ """Normalize points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.
Args:
point_2d: tensor containing the 2d points in the image pixel coordinates. The shape of the tensor can be
@@ -1214,7 +1214,7 @@ def normalize_points_with_intrinsics(point_2d: Tensor, camera_matrix: Tensor) ->
def denormalize_points_with_intrinsics(point_2d_norm: Tensor, camera_matrix: Tensor) -> Tensor:
- """Normalizes points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.
+ """Normalize points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.
Args:
point_2d_norm: tensor containing the 2d points in the image pixel coordinates. The shape of the tensor can be
@@ -1259,7 +1259,7 @@ def denormalize_points_with_intrinsics(point_2d_norm: Tensor, camera_matrix: Ten
def Rt_to_matrix4x4(R: Tensor, t: Tensor) -> Tensor:
- r"""Combines 3x3 rotation matrix R and 1x3 translation vector t into 4x4 extrinsics.
+ r"""Combine 3x3 rotation matrix R and 1x3 translation vector t into 4x4 extrinsics.
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -1284,7 +1284,7 @@ def Rt_to_matrix4x4(R: Tensor, t: Tensor) -> Tensor:
def matrix4x4_to_Rt(extrinsics: Tensor) -> tuple[Tensor, Tensor]:
- r"""Converts 4x4 extrinsics into 3x3 rotation matrix R and 1x3 translation vector ts.
+ r"""Convert 4x4 extrinsics into 3x3 rotation matrix R and 1x3 translation vector ts.
Args:
extrinsics: pose matrix :math:`(B, 4, 4)`.
@@ -1309,10 +1309,10 @@ def matrix4x4_to_Rt(extrinsics: Tensor) -> tuple[Tensor, Tensor]:
def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: Tensor) -> Tensor:
- r"""Converts graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.), , i.e. flips y
- and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards]. Vision convention: [+x, +y, +z] ==
+ r"""Convert graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.).
- [right, down, forwards]
+ I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
+ Vision convention: [+x, +y, +z] == [right, down, forwards].
Args:
extrinsics: pose matrix :math:`(B, 4, 4)`.
@@ -1339,10 +1339,10 @@ def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: Tensor) -> Tensor:
def camtoworld_graphics_to_vision_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
- r"""Converts graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.), , i.e. flips y
- and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards]. Vision convention: [+x, +y, +z] ==
+ r"""Convert graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.).
- [right, down, forwards]
+ I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
+ Vision convention: [+x, +y, +z] == [right, down, forwards].
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -1369,9 +1369,10 @@ def camtoworld_graphics_to_vision_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tens
def camtoworld_vision_to_graphics_4x4(extrinsics_vision: Tensor) -> Tensor:
- r"""Converts vision coordinate frame (e.g. OpenCV) to graphics coordinate frame (e.g. OpenGK.), i.e. flips y and
- z axis Graphics convention: [+x, +y, +z] == [right, up, backwards]. Vision convention: [+x, +y, +z] == [right,
- down, forwards]
+ r"""Convert vision coordinate frame (e.g. OpenCV) to graphics coordinate frame (e.g. OpenGK.).
+
+ I.e. flips y and z axis Graphics convention: [+x, +y, +z] == [right, up, backwards].
+ Vision convention: [+x, +y, +z] == [right, down, forwards].
Args:
extrinsics: pose matrix :math:`(B, 4, 4)`.
@@ -1398,10 +1399,10 @@ def camtoworld_vision_to_graphics_4x4(extrinsics_vision: Tensor) -> Tensor:
def camtoworld_vision_to_graphics_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
- r"""Converts graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.), , i.e. flips y
- and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards]. Vision convention: [+x, +y, +z] ==
+ r"""Convert graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.).
- [right, down, forwards]
+ I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
+ Vision convention: [+x, +y, +z] == [right, down, forwards]
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -1428,8 +1429,8 @@ def camtoworld_vision_to_graphics_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tens
def camtoworld_to_worldtocam_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
- r"""Converts camtoworld, i.e. projection from camera coordinate system to world coordinate system, to worldtocam
- frame i.e. projection from world to the camera coordinate system (used in Colmap).
+ r"""Convert camtoworld to worldtocam frame used in Colmap.
+
See
long-url: https://colmap.github.io/format.html#output-format
@@ -1461,8 +1462,7 @@ def camtoworld_to_worldtocam_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
def worldtocam_to_camtoworld_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
- r"""Converts worldtocam frame i.e. projection from world to the camera coordinate system (used in Colmap) to
- camtoworld, i.e. projection from camera coordinate system to world coordinate system.
+ r"""Convert worldtocam frame used in Colmap to camtoworld.
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -1492,8 +1492,9 @@ def worldtocam_to_camtoworld_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
def ARKitQTVecs_to_ColmapQTVecs(qvec: Tensor, tvec: Tensor) -> tuple[Tensor, Tensor]:
- r"""Converts output of Apple ARKit screen pose (in quaternion representation) to the camera-to-world
- transformation, expected by Colmap, also in quaternion representation.
+ r"""Convert output of Apple ARKit screen pose to the camera-to-world transformation, expected by Colmap.
+
+ Both poses in quaternion representation.
Args:
qvec: ARKit rotation quaternion :math:`(B, 4)`, [x, y, z, w] format.
@@ -1522,7 +1523,7 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: Tensor, tvec: Tensor) -> tuple[Tensor, Ten
def vector_to_skew_symmetric_matrix(vec: Tensor) -> Tensor:
- r"""Converts a vector to a skew symmetric matrix.
+ r"""Convert a vector to a skew symmetric matrix.
A vector :math:`(v1, v2, v3)` has a corresponding skew-symmetric matrix, which is of the form:
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index ceb94640b..61c324656 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -210,7 +210,7 @@ def depth_from_plane_equation(
) -> Tensor:
"""Compute depth values from plane equations and pixel coordinates.
- Parameters:
+ Args:
plane_normals (Tensor): Plane normal vectors of shape (B, 3).
plane_offsets (Tensor): Plane offsets of shape (B, 1).
points_uv (Tensor): Pixel coordinates of shape (B, N, 2).
@@ -372,8 +372,7 @@ class DepthWarper(Module):
return kornia_ops.concatenate([_x, _y], 1)
def compute_subpixel_step(self) -> Tensor:
- """Compute the required inverse depth step to achieve sub pixel accurate sampling of the depth cost volume,
- per camera.
+ """Compute the inverse depth step for 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
Vision. Springer Berlin Heidelberg, 2002.
@@ -468,7 +467,7 @@ def depth_warp(
width: int,
align_corners: bool = True,
) -> Tensor:
- r"""Function that warps a tensor from destination frame to reference given the depth in the reference frame.
+ r"""Warp a tensor from destination frame to reference given the depth in the reference frame.
See :class:`~kornia.geometry.warp.DepthWarper` for details.
@@ -490,7 +489,7 @@ def depth_warp(
def depth_from_disparity(disparity: Tensor, baseline: float | Tensor, focal: float | Tensor) -> Tensor:
- """Computes depth from disparity.
+ """Compute depth from disparity.
Args:
disparity: Disparity tensor of shape :math:`(*, H, W)`.
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 8cc54154d..8e9f39206 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -586,7 +586,9 @@ def relative_camera_motion(
def find_essential(
points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None
) -> torch.Tensor:
- r"""Args:
+ r"""Find essential matrices.
+
+ Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=5`.
points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=5`.
weights: Tensor containing the weights per point correspondence with a shape of :math:`(5, N)`.
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 2c04ad314..4b8dacbf3 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -13,7 +13,7 @@ from kornia.utils.helpers import _torch_svd_cast, safe_inverse_with_mask
def normalize_points(points: Tensor, eps: float = 1e-8) -> Tuple[Tensor, Tensor]:
- r"""Normalizes points (isotropic).
+ r"""Normalize points (isotropic).
Computes the transformation matrix such that the two principal moments of the set of points
are equal to unity, forming an approximately symmetric circular cloud of points of radius 1
@@ -231,7 +231,9 @@ def run_8point(points1: Tensor, points2: Tensor, weights: Optional[Tensor] = Non
def find_fundamental(
points1: Tensor, points2: Tensor, weights: Optional[Tensor] = None, method: Literal["8POINT", "7POINT"] = "8POINT"
) -> Tensor:
- r"""Args:
+ r"""Find the fundamental matrix.
+
+ Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.
points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.
weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 91b49d195..fa8265102 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -218,7 +218,7 @@ def find_homography_dlt_iterated(
def sample_is_valid_for_homography(points1: Tensor, points2: Tensor) -> Tensor:
- """Function, which implements oriented constraint check from :cite:`Marquez-Neila2015`.
+ """Implement oriented constraint check from :cite:`Marquez-Neila2015`.
Analogous to https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/usac/degeneracy.cpp#L88
@@ -325,8 +325,9 @@ def find_homography_lines_dlt(ls1: Tensor, ls2: Tensor, weights: Optional[Tensor
def find_homography_lines_dlt_iterated(
ls1: Tensor, ls2: Tensor, weights: Tensor, soft_inl_th: float = 4.0, n_iter: int = 5
) -> Tensor:
- r"""Compute the homography matrix using the iteratively-reweighted least squares (IRWLS) from line segments. The
- linear system is solved by using the Reweighted Least Squares Solution for the 4 line segments algorithm.
+ r"""Compute the homography matrix using the iteratively-reweighted least squares (IRWLS) from line segments.
+
+ The linear system is solved by using the Reweighted Least Squares Solution for the 4 line segments algorithm.
Args:
ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`.
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index 39fb8060c..c519f6cd1 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -146,7 +146,7 @@ class Keypoints:
return Keypoints(transformed_boxes, False)
def transform_keypoints_(self, M: Tensor) -> "Keypoints":
- """Inplace version of :func:`Keypoints.transform_keypoints`"""
+ """Inplace version of :func:`Keypoints.transform_keypoints`."""
return self.transform_keypoints(M, inplace=True)
@classmethod
@@ -154,8 +154,9 @@ class Keypoints:
return cls(keypoints)
def to_tensor(self, as_padded_sequence: bool = False) -> Union[Tensor, List[Tensor]]:
- r"""Cast :class:`Keypoints` to a tensor. ``mode`` controls which 2D keypoints format should be use to
- represent keypoints in the tensor.
+ r"""Cast :class:`Keypoints` to a tensor.
+
+ ``mode`` controls which 2D keypoints format should be use to represent keypoints in the tensor.
Args:
as_padded_sequence: whether to keep the pads for a list of keypoints. This parameter is only valid
@@ -296,7 +297,7 @@ class Keypoints3D:
raise NotImplementedError
def transform_keypoints_(self, M: Tensor) -> "Keypoints3D":
- """Inplace version of :func:`Keypoints.transform_keypoints`"""
+ """Inplace version of :func:`Keypoints.transform_keypoints`."""
return self.transform_keypoints(M, inplace=True)
@classmethod
@@ -304,8 +305,9 @@ class Keypoints3D:
return cls(keypoints)
def to_tensor(self, as_padded_sequence: bool = False) -> Union[Tensor, List[Tensor]]:
- r"""Cast :class:`Keypoints` to a tensor. ``mode`` controls which 2D keypoints format should be use to
- represent keypoints in the tensor.
+ r"""Cast :class:`Keypoints` to a tensor.
+
+ ``mode`` controls which 2D keypoints format should be use to represent keypoints in the tensor.
Args:
as_padded_sequence: whether to keep the pads for a list of keypoints. This parameter is only valid
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 5ca558cf9..79ccf395b 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -54,7 +54,7 @@ class Se2(Module):
"""
def __init__(self, rotation: So2, translation: Vector2 | Tensor) -> None:
- """Constructor for the base class.
+ """Construct the base class.
Internally represented by a complex number `z` and a translation 2-vector.
@@ -155,7 +155,7 @@ class Se2(Module):
@staticmethod
def exp(v: Tensor) -> Se2:
- """Converts elements of lie algebra to elements of lie group.
+ """Convert elements of lie algebra to elements of lie group.
Args:
v: vector of shape :math:`(B, 3)`.
@@ -184,7 +184,7 @@ class Se2(Module):
return Se2(so2, t)
def log(self) -> Tensor:
- """Converts elements of lie group to elements of lie algebra.
+ """Convert elements of lie group to elements of lie algebra.
Example:
>>> v = torch.ones((1, 3))
@@ -207,7 +207,7 @@ class Se2(Module):
@staticmethod
def hat(v: Tensor) -> Tensor:
- """Converts elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 3, 3)`.
+ """Convert elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 3, 3)`.
Args:
v: vector of shape:math:`(B, 3)`.
@@ -228,7 +228,7 @@ class Se2(Module):
@staticmethod
def vee(omega: Tensor) -> Tensor:
- """Converts elements from lie algebra to vector space.
+ """Convert elements from lie algebra to vector space.
Args:
omega: 3x3-matrix representing lie algebra of shape :math:`(B, 3, 3)`.
@@ -273,7 +273,7 @@ class Se2(Module):
return cls(So2.identity(batch_size, device, dtype), Vector2(t))
def matrix(self) -> Tensor:
- """Returns the matrix representation of shape :math:`(B, 3, 3)`.
+ """Return the matrix representation of shape :math:`(B, 3, 3)`.
Example:
>>> s = Se2(So2.identity(1), torch.ones(1, 2))
@@ -312,7 +312,7 @@ class Se2(Module):
return cls(r, t)
def inverse(self) -> Se2:
- """Returns the inverse transformation.
+ """Return the inverse transformation.
Example:
>>> s = Se2(So2.identity(1), torch.ones(1,2))
@@ -391,7 +391,7 @@ class Se2(Module):
return cls.trans(zs, y)
def adjoint(self) -> Tensor:
- """Returns the adjoint matrix of shape :math:`(B, 3, 3)`.
+ """Return the adjoint matrix of shape :math:`(B, 3, 3)`.
Example:
>>> s = Se2.identity()
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index bf883cb7b..6b2f91b53 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -45,7 +45,7 @@ class Se3(Module):
"""
def __init__(self, rotation: Quaternion | So3, translation: Vector3 | Tensor) -> None:
- """Constructor for the base class.
+ """Construct the base class.
Internally represented by a unit quaternion `q` and a translation 3-vector.
@@ -148,7 +148,7 @@ class Se3(Module):
@staticmethod
def exp(v: Tensor) -> Se3:
- """Converts elements of lie algebra to elements of lie group.
+ """Convert elements of lie algebra to elements of lie group.
Args:
v: vector of shape :math:`(B, 6)`.
@@ -180,7 +180,7 @@ class Se3(Module):
return Se3(R, U)
def log(self) -> Tensor:
- """Converts elements of lie group to elements of lie algebra.
+ """Convert elements of lie group to elements of lie algebra.
Example:
>>> from kornia.geometry.quaternion import Quaternion
@@ -204,7 +204,7 @@ class Se3(Module):
@staticmethod
def hat(v: Tensor) -> Tensor:
- """Converts elements from vector space to lie algebra.
+ """Convert elements from vector space to lie algebra.
Args:
v: vector of shape :math:`(B, 6)`.
@@ -229,7 +229,7 @@ class Se3(Module):
@staticmethod
def vee(omega: Tensor) -> Tensor:
- """Converts elements from lie algebra to vector space.
+ """Convert elements from lie algebra to vector space.
Args:
omega: 4x4-matrix representing lie algebra of shape :math:`(B,4,4)`.
@@ -274,7 +274,7 @@ class Se3(Module):
return cls(So3.identity(batch_size, device, dtype), Vector3(t))
def matrix(self) -> Tensor:
- """Returns the matrix representation of shape :math:`(B, 4, 4)`.
+ """Return the matrix representation of shape :math:`(B, 4, 4)`.
Example:
>>> s = Se3(So3.identity(), torch.ones(3))
@@ -336,7 +336,7 @@ class Se3(Module):
return cls(So3.from_wxyz(q), Vector3(xyz))
def inverse(self) -> Se3:
- """Returns the inverse transformation.
+ """Return the inverse transformation.
Example:
>>> s = Se3(So3.identity(), torch.ones(3))
@@ -462,7 +462,7 @@ class Se3(Module):
return cls.trans(zs, zs, z)
def adjoint(self) -> Tensor:
- """Returns the adjoint matrix of shape :math:`(B, 6, 6)`.
+ """Return the adjoint matrix of shape :math:`(B, 6, 6)`.
Example:
>>> s = Se3.identity()
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index ef8bb08d0..e8769bf01 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -35,7 +35,7 @@ class So2(Module):
"""
def __init__(self, z: Tensor) -> None:
- """Constructor for the base class.
+ """Construct the base class.
Internally represented by complex number `z`.
@@ -69,7 +69,7 @@ class So2(Module):
def __mul__(self, right: Tensor) -> Tensor: ...
def __mul__(self, right: So2 | Tensor) -> So2 | Tensor:
- """Performs a left-multiplication either rotation concatenation or point-transform.
+ """Perform a left-multiplication either rotation concatenation or point-transform.
Args:
right: the other So2 transformation.
@@ -104,7 +104,7 @@ class So2(Module):
@staticmethod
def exp(theta: Tensor) -> So2:
- """Converts elements of lie algebra to elements of lie group.
+ """Convert elements of lie algebra to elements of lie group.
Args:
theta: angle in radians of shape :math:`(B, 1)` or :math:`(B)`.
@@ -122,7 +122,7 @@ class So2(Module):
return So2(complex(theta.cos(), theta.sin()))
def log(self) -> Tensor:
- """Converts elements of lie group to elements of lie algebra.
+ """Convert elements of lie group to elements of lie algebra.
Example:
>>> real = torch.tensor([1.0])
@@ -135,7 +135,7 @@ class So2(Module):
@staticmethod
def hat(theta: Tensor) -> Tensor:
- """Converts elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 2, 2)`.
+ """Convert elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 2, 2)`.
Args:
theta: angle in radians of shape :math:`(B)`.
@@ -156,7 +156,7 @@ class So2(Module):
@staticmethod
def vee(omega: Tensor) -> Tensor:
- """Converts elements from lie algebra to vector space. Returns vector of shape :math:`(B,)`.
+ """Convert elements from lie algebra to vector space. Returns vector of shape :math:`(B,)`.
Args:
omega: 2x2-matrix representing lie algebra.
@@ -233,7 +233,7 @@ class So2(Module):
return cls(complex(real_data, imag_data))
def inverse(self) -> So2:
- """Returns the inverse transformation.
+ """Return the inverse transformation.
Example:
>>> s = So2.identity()
@@ -268,7 +268,7 @@ class So2(Module):
return cls(complex(real_data, imag_data))
def adjoint(self) -> Tensor:
- """Returns the adjoint matrix of shape :math:`(B, 2, 2)`.
+ """Return the adjoint matrix of shape :math:`(B, 2, 2)`.
Example:
>>> s = So2.identity()
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 0a27d805d..90325fc4c 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -31,7 +31,7 @@ class So3(Module):
"""
def __init__(self, q: Quaternion) -> None:
- """Constructor for the base class.
+ """Construct the base class.
Internally represented by a unit quaternion `q`.
@@ -89,7 +89,7 @@ class So3(Module):
@staticmethod
def exp(v: Tensor) -> So3:
- """Converts elements of lie algebra to elements of lie group.
+ """Convert elements of lie algebra to elements of lie group.
See more: https://vision.in.tum.de/_media/members/demmeln/nurlanov2021so3log.pdf
@@ -118,7 +118,7 @@ class So3(Module):
return So3(Quaternion(concatenate((w, xyz), -1)))
def log(self) -> Tensor:
- """Converts elements of lie group to elements of lie algebra.
+ """Convert elements of lie group to elements of lie algebra.
Example:
>>> data = torch.ones((2, 4))
@@ -139,7 +139,7 @@ class So3(Module):
@staticmethod
def hat(v: Vector3 | Tensor) -> Tensor:
- """Converts elements from vector space to lie algebra. Returns matrix of shape :math:`(B,3,3)`.
+ """Convert elements from vector space to lie algebra. Returns matrix of shape :math:`(B,3,3)`.
Args:
v: Vector3 or tensor of shape :math:`(B,3)`.
@@ -167,7 +167,7 @@ class So3(Module):
@staticmethod
def vee(omega: Tensor) -> Tensor:
- r"""Converts elements from lie algebra to vector space. Returns vector of shape :math:`(B,3)`.
+ r"""Convert elements from lie algebra to vector space. Returns vector of shape :math:`(B,3)`.
.. math::
omega = \begin{bmatrix} 0 & -c & b \\
@@ -283,7 +283,7 @@ class So3(Module):
return cls(Quaternion.identity(batch_size, device, dtype))
def inverse(self) -> So3:
- """Returns the inverse transformation.
+ """Return the inverse transformation.
Example:
>>> s = So3.identity()
@@ -344,7 +344,7 @@ class So3(Module):
return cls.exp(stack((zs, zs, z), -1))
def adjoint(self) -> Tensor:
- """Returns the adjoint matrix of shape :math:`(B, 3, 3)`.
+ """Return the adjoint matrix of shape :math:`(B, 3, 3)`.
Example:
>>> s = So3.identity()
@@ -358,7 +358,7 @@ class So3(Module):
@staticmethod
def right_jacobian(vec: Tensor) -> Tensor:
- """Computes the right Jacobian of So3.
+ """Compute the right Jacobian of So3.
Args:
vec: the input point of shape :math:`(B, 3)`.
@@ -390,7 +390,7 @@ class So3(Module):
@staticmethod
def left_jacobian(vec: Tensor) -> Tensor:
- """Computes the left Jacobian of So3.
+ """Compute the left Jacobian of So3.
Args:
vec: the input point of shape :math:`(B, 3)`.
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 4c4ae5d5f..009e2d970 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -20,7 +20,7 @@ __all__ = [
def compose_transformations(trans_01: Tensor, trans_12: Tensor) -> Tensor:
- r"""Function that composes two homogeneous transformations.
+ r"""Compose two homogeneous transformations.
.. math::
T_0^{2} = \begin{bmatrix} R_0^1 R_1^{2} & R_0^{1} t_1^{2} + t_0^{1} \\
@@ -74,7 +74,7 @@ def compose_transformations(trans_01: Tensor, trans_12: Tensor) -> Tensor:
def inverse_transformation(trans_12: Tensor) -> Tensor:
- r"""Function that inverts a 4x4 homogeneous transformation.
+ r"""Invert a 4x4 homogeneous transformation.
:math:`T_1^{2} = \begin{bmatrix} R_1 & t_1 \\ \mathbf{0} & 1 \end{bmatrix}`
@@ -117,7 +117,7 @@ def inverse_transformation(trans_12: Tensor) -> Tensor:
def relative_transformation(trans_01: Tensor, trans_02: Tensor) -> Tensor:
- r"""Function that computes the relative homogeneous transformation from a reference transformation.
+ r"""Compute the relative homogeneous transformation from a reference transformation.
:math:`T_1^{0} = \begin{bmatrix} R_1 & t_1 \\ \mathbf{0} & 1 \end{bmatrix}` to destination :math:`T_2^{0} =
\begin{bmatrix} R_2 & t_2 \\ \mathbf{0} & 1 \end{bmatrix}`.
@@ -156,7 +156,7 @@ def relative_transformation(trans_01: Tensor, trans_02: Tensor) -> Tensor:
def transform_points(trans_01: Tensor, points_1: Tensor) -> Tensor:
- r"""Function that applies transformations to a set of points.
+ r"""Apply transformations to a set of points.
Args:
trans_01: tensor for transformations of shape
@@ -233,7 +233,7 @@ def point_line_distance(point: Tensor, line: Tensor, eps: float = 1e-9) -> Tenso
def batched_dot_product(x: Tensor, y: Tensor, keepdim: bool = False) -> Tensor:
- """Return a batched version of .dot()"""
+ """Return a batched version of .dot()."""
KORNIA_CHECK_SHAPE(x, ["*", "N"])
KORNIA_CHECK_SHAPE(y, ["*", "N"])
return (x * y).sum(-1, keepdim)
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 6f1b930f1..4337106bd 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -25,7 +25,7 @@ class ParametrizedLine(Module):
"""
def __init__(self, origin: Tensor, direction: Tensor) -> None:
- """Initializes a parametrized line of direction and origin.
+ """Initialize a parametrized line of direction and origin.
Args:
origin: any point on the line of any dimension.
@@ -69,7 +69,7 @@ class ParametrizedLine(Module):
@classmethod
def through(cls, p0: Tensor, p1: Tensor) -> "ParametrizedLine":
- """Constructs a parametrized line going from a point :math:`p0` to :math:`p1`.
+ """Construct a parametrized line going from a point :math:`p0` to :math:`p1`.
Args:
p0: tensor with first point :math:`(B, D)` where `D` is the point dimension.
@@ -84,7 +84,7 @@ class ParametrizedLine(Module):
return ParametrizedLine(p0, normalize((p1 - p0), p=2, dim=-1))
def point_at(self, t: Union[float, Tensor]) -> Tensor:
- """The point at :math:`t` along this line.
+ """Get the point at :math:`t` along this line.
Args:
t: step along the line.
diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.py
index 2559bb9a3..e9c7746d3 100644
--- a/kornia/geometry/pose.py
+++ b/kornia/geometry/pose.py
@@ -38,7 +38,7 @@ class NamedPose:
"""
def __init__(self, dst_from_src: Se2 | Se3, frame_src: str | None = None, frame_dst: str | None = None) -> None:
- """Constructor for NamedPose.
+ """Construct NamedPose.
Args:
dst_from_src: Pose from source frame to destination frame.
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index f9c8387b3..00f8aa68d 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -57,7 +57,7 @@ class Quaternion(Module):
"""
def __init__(self, data: Tensor) -> None:
- """Constructor for the base class.
+ """Construct the base class.
Args:
data: tensor containing the quaternion data with the sape of :math:`(B, 4)`.
@@ -163,7 +163,7 @@ class Quaternion(Module):
@property
def data(self) -> Tensor:
- """Return the underlying data with shape :math:`(B, 4).`"""
+ """Return the underlying data with shape :math:`(B, 4)`."""
return self._data
@property
@@ -325,7 +325,7 @@ class Quaternion(Module):
return cls(axis_angle_to_quaternion(axis_angle))
def to_axis_angle(self) -> Tensor:
- """Converts the quaternion to an axis-angle representation.
+ """Convert the quaternion to an axis-angle representation.
Example:
>>> q = Quaternion.identity()
@@ -404,7 +404,7 @@ class Quaternion(Module):
return cls(stack((q1, q2, q3, q4), -1))
def slerp(self, q1: "Quaternion", t: float) -> "Quaternion":
- """Returns a unit quaternion spherically interpolated between quaternions self.q and q1.
+ """Return a unit quaternion spherically interpolated between quaternions self.q and q1.
See more: https://en.wikipedia.org/wiki/Slerp
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 905b86bbe..ee5ba8a3e 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -86,10 +86,9 @@ class RANSAC(Module):
raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")
def sample(self, sample_size: int, pop_size: int, batch_size: int, device: Optional[Device] = None) -> Tensor:
- """Minimal sampler, but unlike traditional RANSAC we sample in batches to get benefit of the parallel
- processing, esp.
+ """Minimal sampler, but unlike traditional RANSAC we sample in batches.
- on GPU.
+ Yields the benefit of the parallel processing, esp. on GPU.
"""
if device is None:
device = torch.device("cpu")
@@ -99,9 +98,7 @@ class RANSAC(Module):
@staticmethod
def max_samples_by_conf(n_inl: int, num_tc: int, sample_size: int, conf: float) -> float:
- """Formula to update max_iter in order to stop iterations earlier
- https://en.wikipedia.org/wiki/Random_sample_consensus.
- """
+ """Update max_iter to stop iterations earlier https://en.wikipedia.org/wiki/Random_sample_consensus."""
eps = 1e-9
if num_tc <= sample_size:
return 1.0
@@ -177,7 +174,7 @@ class RANSAC(Module):
)
def forward(self, kp1: Tensor, kp2: Tensor, weights: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- r"""Main forward method to execute the RANSAC algorithm.
+ r"""Call main forward method to execute the RANSAC algorithm.
Args:
kp1: source image keypoints :math:`(N, 2)`.
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 41d23bbb6..d4d145ac0 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -1,5 +1,6 @@
-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 __future__ import annotations
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index d14f6f9bd..c6cf3c9df 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -7,7 +7,7 @@ from kornia.core import Module, Tensor, eye, pad, zeros
def _get_nms_kernel2d(kx: int, ky: int) -> Tensor:
- """Utility function, which returns neigh2channels conv kernel."""
+ """Return neigh2channels conv kernel."""
numel: int = ky * kx
center: int = numel // 2
weight = eye(numel)
@@ -16,7 +16,7 @@ def _get_nms_kernel2d(kx: int, ky: int) -> Tensor:
def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> Tensor:
- """Utility function, which returns neigh2channels conv kernel."""
+ """Return neigh2channels conv kernel."""
numel: int = kd * ky * kx
center: int = numel // 2
weight = eye(numel)
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 2391f4c89..aa396b6b5 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -17,7 +17,7 @@ from .nms import nms3d
def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
- r"""Helper function, which generates a kernel to with window coordinates, residual to window center.
+ r"""Generate a kernel to with window coordinates, residual to window center.
Args:
h: kernel height.
@@ -37,8 +37,7 @@ def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = N
def _get_center_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
- r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 2d
- coordinates grid.
+ r"""Generate a kernel to return center coordinates, when applied with F.conv2d to 2d coordinates grid.
Args:
h: kernel height.
@@ -71,8 +70,7 @@ def _get_center_kernel2d(h: int, w: int, device: Optional[torch.device] = None)
def _get_center_kernel3d(d: int, h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
- r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 3d
- coordinates grid.
+ r"""Generate a kernel to return center coordinates, when applied with F.conv2d to 3d coordinates grid.
Args:
d: kernel depth.
@@ -112,7 +110,7 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: Optional[torch.device]
def _get_window_grid_kernel3d(d: int, h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
- r"""Helper function, which generates a kernel to return coordinates, residual to window center.
+ r"""Generate a kernel to return coordinates, residual to window center.
Args:
d: kernel depth.
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 5d3f9829d..533cca702 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -26,9 +26,7 @@ class BaseModel(Module):
class Homography(BaseModel):
- r"""Homography geometric model to be used together with ImageRegistrator module for the optimization-based
- image registration.
- """
+ r"""Homography geometric model to be used with ImageRegistrator for the optimization-based image registration."""
def __init__(self) -> None:
super().__init__()
@@ -39,7 +37,7 @@ class Homography(BaseModel):
return f"{self.__class__.__name__}({self.model})"
def reset_model(self) -> None:
- """Initializes the model with identity transform."""
+ """Initialize the model with identity transform."""
torch.nn.init.eye_(self.model)
def forward(self) -> Tensor:
@@ -62,8 +60,7 @@ class Homography(BaseModel):
class Similarity(BaseModel):
- """Similarity geometric model to be used together with ImageRegistrator module for the optimization-based image
- registration.
+ """Similarity geometric model to be used with ImageRegistrator module for the optimization-based image registration.
Args:
rotation: if True, the rotation is optimizable, else constant zero.
@@ -205,14 +202,15 @@ class ImageRegistrator(Module):
return loss
def reset_model(self) -> None:
- """Calls model reset function."""
+ """Call model reset function."""
self.model.reset_model()
def register(
self, src_img: Tensor, dst_img: Tensor, verbose: bool = False, output_intermediate_models: bool = False
) -> Union[Tensor, Tuple[Tensor, List[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 transformation 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.
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index ff87c9bc7..c6ff89230 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -739,6 +739,7 @@ def get_shear_matrix3d(
szy: Optional[Tensor] = None,
) -> Tensor:
r"""Compose shear matrix Bx4x4 from the components.
+
Note: Ordered shearing, shear x-axis then y-axis then z-axis.
.. math::
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index c231bc6e9..70dac5c98 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -22,7 +22,7 @@ __all__ = [
def _get_pyramid_gaussian_kernel() -> Tensor:
- """Utility function that return a pre-computed gaussian kernel."""
+ """Return a pre-computed gaussian kernel."""
return (
tensor(
[
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index f72cf6517..72915d5d1 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -13,8 +13,9 @@ __all__ = ["get_tps_transform", "warp_image_tps", "warp_points_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.
+
+ 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)
@@ -99,8 +100,7 @@ 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 arguments.
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,
@@ -172,8 +172,7 @@ def warp_image_tps(
align_corners: bool = False,
padding_mode: str = "zeros",
) -> 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 arguments.
.. image:: _static/img/warp_image_tps.png
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
index fdf57331a..cbf6a367a 100644
--- a/kornia/losses/psnr.py
+++ b/kornia/losses/psnr.py
@@ -7,7 +7,7 @@ from kornia import metrics
def psnr_loss(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
- r"""Function that computes the PSNR loss.
+ r"""Compute the PSNR loss.
The loss is computed as follows:
diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.py
index 3fedf7a7a..352d2ef8a 100644
--- a/kornia/losses/ssim.py
+++ b/kornia/losses/ssim.py
@@ -15,7 +15,7 @@ def ssim_loss(
reduction: str = "mean",
padding: str = "same",
) -> torch.Tensor:
- r"""Function that computes a loss based on the SSIM measurement.
+ r"""Compute a loss based on the SSIM measurement.
The loss, or the Structural dissimilarity (DSSIM) is described as:
diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.py
index 75283151c..692fd9869 100644
--- a/kornia/losses/ssim3d.py
+++ b/kornia/losses/ssim3d.py
@@ -13,7 +13,7 @@ def ssim3d_loss(
reduction: str = "mean",
padding: str = "same",
) -> Tensor:
- r"""Function that computes a loss based on the SSIM measurement.
+ r"""Compute a loss based on the SSIM measurement.
The loss, or the Structural dissimilarity (DSSIM) is described as:
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index a58453b22..27d10fc02 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -5,7 +5,7 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:
- r"""Function that computes Total Variation according to [1].
+ r"""Compute Total Variation according to [1].
Args:
img: the input image with shape :math:`(*, H, W)`.
diff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.py
index 48ca33424..de22ca47b 100644
--- a/kornia/metrics/accuracy.py
+++ b/kornia/metrics/accuracy.py
@@ -4,7 +4,7 @@ from kornia.core import Tensor
def accuracy(pred: Tensor, target: Tensor, topk: Tuple[int, ...] = (1,)) -> List[Tensor]:
- """Computes the accuracy over the k top predictions for the specified values of k.
+ """Compute the accuracy over the k top predictions for the specified values of k.
Args:
pred: the input tensor with the logits to evaluate.
diff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.py
index c3cd5fa22..e8343eef6 100644
--- a/kornia/metrics/ssim.py
+++ b/kornia/metrics/ssim.py
@@ -22,7 +22,7 @@ def ssim(
eps: float = 1e-12,
padding: str = "same",
) -> torch.Tensor:
- r"""Function that computes the Structural Similarity (SSIM) index map between two images.
+ r"""Compute the Structural Similarity (SSIM) index map between two images.
Measures the (SSIM) index between each element in the input `x` and target `y`.
diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.py
index b47f2f16c..fcc8069fb 100644
--- a/kornia/metrics/ssim3d.py
+++ b/kornia/metrics/ssim3d.py
@@ -24,7 +24,7 @@ def _crop(img: Tensor, cropping_shape: List[int]) -> Tensor:
def ssim3d(
img1: Tensor, img2: Tensor, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = "same"
) -> Tensor:
- r"""Function that computes the Structural Similarity (SSIM) index map between two images.
+ r"""Compute the Structural Similarity (SSIM) index map between two images.
Measures the (SSIM) index between each element in the input `x` and target `y`.
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.py
index 488af7320..0d973911f 100644
--- a/kornia/models/_hf_models/hf_onnx_community.py
+++ b/kornia/models/_hf_models/hf_onnx_community.py
@@ -121,7 +121,7 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
) -> onnx.ModelProto: # type:ignore
- """Exports a depth estimation model to ONNX format.
+ """Export a depth estimation model to ONNX format.
Args:
onnx_name:
diff --git a/kornia/models/base.py b/kornia/models/base.py
index 6ba69f91e..ac1b7f308 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -19,7 +19,7 @@ class ModelBaseMixin:
def _tensor_to_type(
self, output: Union[Tensor, List[Tensor]], output_type: str, is_batch: bool = False
) -> Union[Tensor, List[Tensor], List["Image.Image"]]: # type: ignore
- """Converts the output tensor to the desired type.
+ """Convert the output tensor to the desired type.
Args:
output: The output tensor or list of tensors.
@@ -73,7 +73,7 @@ class ModelBaseMixin:
class ModelBase(Module, ONNXExportMixin, ModelBaseMixin):
- """This class wraps a model and performs pre-processing and post-processing."""
+ """Wrap a model and perform pre-processing and post-processing."""
def __init__(
self, model: Module, pre_processor: Module, post_processor: Module, name: Optional[str] = None
diff --git a/kornia/models/depth_estimation/depth_anything.py b/kornia/models/depth_estimation/depth_anything.py
index 6c09ce177..cfe80934c 100644
--- a/kornia/models/depth_estimation/depth_anything.py
+++ b/kornia/models/depth_estimation/depth_anything.py
@@ -12,7 +12,7 @@ class DepthAnythingONNXBuilder:
def build(
model_name: str = "depth-anything-v2-small", model_type: str = "model", cache_dir: Optional[str] = None
) -> DepthEstimation:
- """Exports a DepthAnything model to an ONNX model file.
+ """Export a DepthAnything model to an ONNX model file.
Args:
model_name: The name of the model to be loaded. Valid model names include:
diff --git a/kornia/models/detection/base.py b/kornia/models/detection/base.py
index 1a24abaf7..f3651071a 100644
--- a/kornia/models/detection/base.py
+++ b/kornia/models/detection/base.py
@@ -101,7 +101,7 @@ def results_from_detections(detections: Tensor, format: str | BoundingBoxDataFor
class ObjectDetector(ModelBase):
- """This class wraps an object detection model and performs pre-processing and post-processing."""
+ """Wrap an object detection model and perform pre-processing and post-processing."""
name: str = "detection"
@@ -146,7 +146,7 @@ class ObjectDetector(ModelBase):
def save(
self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, directory: Optional[str] = None
) -> None:
- """Saves the output image(s) to a directory.
+ """Save the output image(s) to a directory.
Args:
images: input tensor.
@@ -166,7 +166,7 @@ class ObjectDetector(ModelBase):
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
) -> onnx.ModelProto: # type: ignore
- """Exports an RT-DETR object detection model to ONNX format.
+ """Export an RT-DETR object detection model to ONNX format.
Either `model_name` or `config` must be provided. If neither is provided,
a default pretrained model (`rtdetr_r18vd`) will be built.
diff --git a/kornia/models/detection/rtdetr.py b/kornia/models/detection/rtdetr.py
index 025c605d4..23fbb9a0e 100644
--- a/kornia/models/detection/rtdetr.py
+++ b/kornia/models/detection/rtdetr.py
@@ -34,7 +34,7 @@ class RTDETRDetectorBuilder:
confidence_threshold: Optional[float] = None,
confidence_filtering: Optional[bool] = None,
) -> ObjectDetector:
- """Builds and returns an RT-DETR object detector model.
+ """Build and returns an RT-DETR object detector model.
Either `model_name` or `config` must be provided. If neither is provided,
a default pretrained model (`rtdetr_r18vd`) will be built.
diff --git a/kornia/models/edge_detection/base.py b/kornia/models/edge_detection/base.py
index d27c817e0..e7064671d 100644
--- a/kornia/models/edge_detection/base.py
+++ b/kornia/models/edge_detection/base.py
@@ -88,7 +88,7 @@ class EdgeDetector(ModelBase):
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
) -> onnx.ModelProto: # type: ignore
- """Exports the current edge detection model to an ONNX model file.
+ """Export the current edge detection model to an ONNX model file.
Args:
onnx_name:
diff --git a/kornia/models/super_resolution/base.py b/kornia/models/super_resolution/base.py
index d1b5518a6..8d1a2c107 100644
--- a/kornia/models/super_resolution/base.py
+++ b/kornia/models/super_resolution/base.py
@@ -101,7 +101,7 @@ class SuperResolution(ModelBase):
additional_metadata: Optional[List[Tuple[str, str]]] = None,
**kwargs: Any,
) -> "onnx.ModelProto": # type: ignore
- """Exports the current super resolution model to an ONNX model file.
+ """Export the current super resolution model to an ONNX model file.
Args:
onnx_name:
diff --git a/kornia/models/utils.py b/kornia/models/utils.py
index 962ca238b..55cedbd92 100644
--- a/kornia/models/utils.py
+++ b/kornia/models/utils.py
@@ -11,13 +11,15 @@ __all__ = ["OutputRangePostProcessor", "ResizePostProcessor", "ResizePreProcesso
class ResizePreProcessor(Module):
- """This module resizes a list of image tensors to the given size.
+ """Resize a list of image tensors to the given size.
Additionally, also returns the original image sizes for further post-processing.
"""
def __init__(self, height: int, width: int, interpolation_mode: str = "bilinear") -> None:
- """Args:
+ """Construct ResizePreprocessor module.
+
+ Args:
height: height of the resized image.
width: width of the resized image.
interpolation_mode: interpolation mode for image resizing. Supported values: ``nearest``, ``bilinear``,
@@ -29,7 +31,9 @@ class ResizePreProcessor(Module):
self.interpolation_mode = interpolation_mode
def forward(self, imgs: Union[Tensor, List[Tensor]]) -> Tuple[Tensor, Tensor]:
- """Returns:
+ """Run forward.
+
+ Returns:
resized_imgs: resized images in a batch.
original_sizes: the original image sizes of (height, width).
@@ -53,7 +57,9 @@ class ResizePostProcessor(Module):
self.interpolation_mode = interpolation_mode
def forward(self, imgs: Union[Tensor, List[Tensor]], original_sizes: Tensor) -> Union[Tensor, List[Tensor]]:
- """Returns:
+ """Run forward.
+
+ Returns:
resized_imgs: resized images in a batch.
original_sizes: the original image sizes of (height, width).
diff --git a/kornia/nerf/camera_utils.py b/kornia/nerf/camera_utils.py
index 8d6f3f6d1..4bfbe104e 100755
--- a/kornia/nerf/camera_utils.py
+++ b/kornia/nerf/camera_utils.py
@@ -11,7 +11,7 @@ from kornia.geometry.conversions import quaternion_to_rotation_matrix
def parse_colmap_output(
cameras_path: str, images_path: str, device: Device, dtype: torch.dtype
) -> Tuple[List[str], PinholeCamera]:
- r"""Parses colmap output to create an PinholeCamera for aligned scene cameras.
+ r"""Parse colmap output to create an PinholeCamera for aligned scene cameras.
Args:
cameras_path: Path to camera.txt Colmap file with camera intrinsics: str
@@ -111,8 +111,7 @@ def parse_colmap_output(
def cameras_for_ids(cameras: PinholeCamera, camera_ids: Union[List[int], Tensor]) -> PinholeCamera:
- r"""Takes a PinholeCamera camera object and a set of camera indices and creates a new PinholeCamera object for
- the requested cameras.
+ r"""Take a PinholeCamera camera and camera indices to create a new PinholeCamera for requested cameras.
Args:
cameras: Scene camera object: PinholeCamera
@@ -130,8 +129,9 @@ def cameras_for_ids(cameras: PinholeCamera, camera_ids: Union[List[int], Tensor]
def create_spiral_path(cameras: PinholeCamera, rad: float, num_views: int, num_circles: int) -> PinholeCamera:
- r"""Creates a PinholeCamera object with cameras that follow a spiral path. Used for novel view synthesis for
- face facing models.
+ r"""Create a PinholeCamera object with cameras that follow a spiral path.
+
+ Used for novel view synthesis for face facing models.
Args:
cameras: Scene cameras used to train the NeRF model: PinholeCamera
diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.py
index f6124b92c..eb56eec01 100755
--- a/kornia/nerf/data_utils.py
+++ b/kornia/nerf/data_utils.py
@@ -48,7 +48,7 @@ class RayDataset(Dataset[RayGroup]):
self._dtype = dtype
def init_ray_dataset(self, num_img_rays: Optional[Tensor] = None) -> None:
- r"""Initializes a ray dataset.
+ r"""Initialize a ray dataset.
Args:
num_img_rays: If not None, number of rays to randomly cast from each camera: math: `(B)`.
@@ -60,8 +60,9 @@ class RayDataset(Dataset[RayGroup]):
self._init_random_ray_dataset(num_img_rays)
def init_images_for_training(self, imgs: Images) -> None:
- r"""Initializes images for training. Images can be either a list of tensors, or a list of paths to image
- disk locations.
+ r"""Initialize images for training.
+
+ Images can be either a list of tensors, or a list of paths to image disk locations.
Args:
imgs: List of image tensors or image paths: Images
@@ -82,7 +83,7 @@ class RayDataset(Dataset[RayGroup]):
self._imgs = [img.to(self._device) for img in images]
def _init_random_ray_dataset(self, num_img_rays: Tensor) -> None:
- r"""Initializes a random ray sampler and calculates dataset ray parameters.
+ r"""Initialize a random ray sampler and calculates dataset ray parameters.
Args:
num_img_rays: If not None, number of rays to randomly cast from each camers: math: `(B)`.
@@ -94,7 +95,7 @@ class RayDataset(Dataset[RayGroup]):
self._ray_sampler.calc_ray_params(self._cameras, num_img_rays)
def _init_uniform_ray_dataset(self) -> None:
- r"""Initializes a uniform ray sampler and calculates dataset ray parameters."""
+ r"""Initialize a uniform ray sampler and calculates dataset ray parameters."""
self._ray_sampler = UniformRaySampler(
self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
)
@@ -131,7 +132,7 @@ class RayDataset(Dataset[RayGroup]):
return 0
def __getitem__(self, idxs: Union[int, List[int]]) -> RayGroup:
- r"""Gets a dataset item.
+ r"""Get a dataset item.
Args:
idxs: An index or group of indices of ray parameter object: Union[int, List[int]]
@@ -159,7 +160,7 @@ class RayDataset(Dataset[RayGroup]):
def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shuffle: bool = True) -> DataLoader[RayGroup]:
- r"""Initializes a dataloader to manage a ray dataset.
+ r"""Initialize a dataloader to manage a ray dataset.
Args:
dataset: A ray dataset: RayDataset
diff --git a/kornia/nerf/nerf_model.py b/kornia/nerf/nerf_model.py
index aaf16d975..44652b7c5 100755
--- a/kornia/nerf/nerf_model.py
+++ b/kornia/nerf/nerf_model.py
@@ -25,7 +25,7 @@ class MLP(Module):
"""
def __init__(self, num_dims: int, num_units: int = 2, num_unit_layers: int = 4, num_hidden: int = 128) -> None:
- """Constructor method.
+ """Construct MLP.
Args:
num_dims: Number of input dimensions (channels).
@@ -154,7 +154,7 @@ class NerfModelRenderer:
def __init__(
self, nerf_model: NerfModel, image_size: tuple[int, int], device: torch.device | None, dtype: torch.dtype | None
) -> None:
- """Constructor method.
+ """Construct NerfModelRenderer.
Args:
nerf_model: NeRF model.
@@ -171,7 +171,7 @@ class NerfModelRenderer:
self._pixels_grid, self._ones = self._create_pixels_grid() # 1xHxWx2 and (H*W)x1
def _create_pixels_grid(self) -> tuple[Tensor, Tensor]:
- """Creates the pixels grid to unproject to plane z=1.
+ """Create the pixels grid to unproject to plane z=1.
Args:
image_size: image size: tuple[int, int]
@@ -192,7 +192,7 @@ class NerfModelRenderer:
return pixels_grid, ones
def render_view(self, camera: PinholeCamera) -> Tensor:
- """Renders a novel synthesis view of a trained NeRF model for given camera.
+ """Render a novel synthesis view of a trained NeRF model for given camera.
Args:
camera: camera for image rendering: PinholeCamera.
@@ -213,7 +213,7 @@ class NerfModelRenderer:
return rgb_image
def _create_rays(self, camera: PinholeCamera) -> Ray:
- """Creates rays for a given camera.
+ """Create rays for a given camera.
Args:
camera: camera for image rendering: PinholeCamera.
diff --git a/kornia/nerf/nerf_solver.py b/kornia/nerf/nerf_solver.py
index cf7c5ee1a..703cddfcb 100755
--- a/kornia/nerf/nerf_solver.py
+++ b/kornia/nerf/nerf_solver.py
@@ -74,7 +74,7 @@ class NerfSolver:
log_space_encoding: bool = True,
lr: float = 1.0e-3,
) -> None:
- """Initializes training settings and model.
+ """Initialize training settings and model.
Args:
cameras: Scene cameras in the order of input images.
@@ -225,7 +225,7 @@ class NerfSolver:
return float(total_psnr / (i_batch + 1))
def run(self, num_epochs: int = 1) -> None:
- r"""Runs training epochs.
+ r"""Run training epochs.
Args:
num_epochs: number of epochs to run. Default: 1.
diff --git a/kornia/nerf/samplers.py b/kornia/nerf/samplers.py
index 1197d82df..5d7e377b5 100755
--- a/kornia/nerf/samplers.py
+++ b/kornia/nerf/samplers.py
@@ -92,8 +92,9 @@ class RaySampler:
return self._camera_ids
def _calc_ray_params(self, cameras: PinholeCamera, points_2d_camera: Dict[int, Points2D]) -> None:
- r"""Calculates ray parameters: origins, directions. Also stored are camera ids for each ray, and its pixel
- coordinates.
+ r"""Calculate ray parameters: origins, directions.
+
+ Also stored are camera ids for each ray, and its pixel coordinates.
Args:
cameras: scene cameras: PinholeCamera
@@ -140,10 +141,10 @@ class RaySampler:
self._points_2d = torch.cat(points_2d)
def transform_ray_params_world_to_ndc(self, cameras: PinholeCamera) -> Tuple[Tensor, Tensor]:
- r"""Transforms ray parameters to normalized coordinate device (camera) system (NDC)
+ r"""Transform ray parameters to normalized coordinate device (camera) system (NDC).
Args:
- cameras: scene cameras: PinholeCamera
+ cameras: scene cameras: PinholeCamera
"""
cams = cameras_for_ids(cameras, self._camera_ids)
@@ -204,9 +205,9 @@ class RaySampler:
def _add_points2d_as_flat_tensors_to_num_ray_dict(
n: int, x: Tensor, y: Tensor, camera_id: int, points2d_as_flat_tensors: Dict[int, Points2D_FlatTensors]
) -> None:
- r"""Adds x/y pixel coordinates for all rays casted by a scene camera to dictionary of pixel coordinates
+ r"""Add x/y pixel coordinates for all rays casted by a scene camera to dictionary of pixel coordinates
grouped by total number of rays.
- """
+ """ # noqa: D205
if n not in points2d_as_flat_tensors:
points2d_as_flat_tensors[n] = RaySampler.Points2D_FlatTensors()
points2d_as_flat_tensors[n]._x = x.flatten()
@@ -220,8 +221,10 @@ class RaySampler:
def _build_num_ray_dict_of_points2d(
points2d_as_flat_tensors: Dict[int, Points2D_FlatTensors],
) -> Dict[int, Points2D]:
- r"""Builds a dictionary of ray pixel points, by total number of rays as key. The dictionary groups rays by
- the total amount of rays, which allows the case of casting different number of rays from each scene camera.
+ r"""Build a dictionary of ray pixel points, by total number of rays as key.
+
+ The dictionary groups rays by the total amount of rays, which allows the case of casting different number
+ of rays from each scene camera.
Args:
points2d_as_flat_tensors: dictionary of pixel coordinates grouped by total number of rays:
@@ -282,8 +285,9 @@ class RandomRaySampler(RaySampler):
return RaySampler._build_num_ray_dict_of_points2d(points2d_as_flat_tensors)
def calc_ray_params(self, cameras: PinholeCamera, num_img_rays: Tensor) -> None:
- r"""Calculates ray parameters: origins, directions. Also stored are camera ids for each ray, and its pixel
- coordinates.
+ r"""Calculate ray parameters: origins, directions.
+
+ Also stored are camera ids for each ray, and its pixel coordinates.
Args:
cameras: scene cameras: PinholeCamera
@@ -415,7 +419,9 @@ def sample_lengths(
def sample_ray_points(
origins: Tensor, directions: Tensor, lengths: Tensor
) -> Tensor: # FIXME: Test by projecting to points_2d and compare with sampler 2d points
- r"""Args:
+ r"""Sample points along ray.
+
+ Args:
origins: tensor containing ray origins in 3d world coordinates. Tensor shape :math:`(*, 3)`.
directions: tensor containing ray directions in 3d world coordinates. Tensor shape :math:`(*, 3)`.
lengths: tensor containing sampled distances along each ray. Tensor shape :math:`(*, num_ray_points)`.
@@ -429,7 +435,7 @@ def sample_ray_points(
def calc_ray_t_vals(points_3d: Tensor) -> Tensor:
- r"""Calculates t values along rays.
+ r"""Calculate t values along rays.
Args:
points_3d: Points along rays :math:`(*, num_ray_points, 3)`
diff --git a/kornia/nerf/volume_renderer.py b/kornia/nerf/volume_renderer.py
index 7f8c4b1a4..a571fc2a2 100755
--- a/kornia/nerf/volume_renderer.py
+++ b/kornia/nerf/volume_renderer.py
@@ -15,7 +15,7 @@ class VolumeRenderer(torch.nn.Module):
_eps = 1.0e-10
def __init__(self, shift: int = 1) -> None:
- """Initializes the renderer.
+ """Initialize the renderer.
Args:
shift: Size of far-field layer: int
@@ -43,7 +43,7 @@ class IrregularRenderer(VolumeRenderer):
"""Renders 3D irregularly sampled points along rays."""
def forward(self, rgbs: Tensor, densities: Tensor, points_3d: Tensor) -> Tensor:
- r"""Renders 3D irregularly sampled points along rays.
+ r"""Render 3D irregularly sampled points along rays.
Args:
rgbs: RGB values of points along rays :math:`(*, N, 3)`
@@ -68,7 +68,7 @@ class RegularRenderer(VolumeRenderer):
"""Renders 3D regularly sampled points along rays."""
def forward(self, rgbs: Tensor, densities: Tensor, points_3d: Tensor) -> Tensor:
- r"""Renders 3D regularly sampled points along rays.
+ r"""Render 3D regularly sampled points along rays.
Args:
rgbs: RGB values of points along rays :math:`(*, N, 3)`
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index 4c74308ec..d8637d472 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -22,7 +22,7 @@ class ONNXLoader(CachedDownloader):
@classmethod
def load_config(cls, url: str, download: bool = True, **kwargs: Any) -> dict[str, Any]:
- """Loads JSON config from the specified URL.
+ """Load JSON config from the specified URL.
Args:
url: The URL of the preprocessor config to load.
@@ -51,7 +51,7 @@ class ONNXLoader(CachedDownloader):
@classmethod
def load_model(cls, model_name: str, download: bool = True, with_data: bool = False, **kwargs) -> onnx.ModelProto: # type:ignore
- """Loads an ONNX model from the local cache or downloads it from Hugging Face if necessary.
+ """Load an ONNX model from the local cache or downloads it from Hugging Face if necessary.
Args:
model_name: The name of the ONNX model or operator. For Hugging Face-hosted models,
@@ -113,7 +113,7 @@ class ONNXLoader(CachedDownloader):
@staticmethod
def _fetch_repo_contents(folder: str) -> list[dict[str, Any]]:
- """Fetches the contents of the Hugging Face repository using the Hugging Face API.
+ """Fetch the contents of the Hugging Face repository using the Hugging Face API.
Returns:
A list of all files in the repository as dictionaries containing file details.
@@ -130,7 +130,7 @@ class ONNXLoader(CachedDownloader):
@classmethod
def list_operators(cls) -> None:
- """Lists all available ONNX operators in the 'operators' folder of the Hugging Face repository."""
+ """List all available ONNX operators in the 'operators' folder of the Hugging Face repository."""
repo_contents = cls._fetch_repo_contents("operators")
# Filter for operators in the 'operators' directory
@@ -140,7 +140,7 @@ class ONNXLoader(CachedDownloader):
@classmethod
def list_models(cls) -> None:
- """Lists all available ONNX models in the 'models' folder of the Hugging Face repository."""
+ """List all available ONNX models in the 'models' folder of the Hugging Face repository."""
repo_contents = cls._fetch_repo_contents("models")
# Filter for models in the 'models' directory
@@ -153,7 +153,7 @@ def io_name_conversion(
onnx_model: onnx.ModelProto, # type:ignore
io_name_mapping: dict[str, str],
) -> onnx.ModelProto: # type:ignore
- """Converts the input and output names of an ONNX model to 'input' and 'output'.
+ """Convert the input and output names of an ONNX model to 'input' and 'output'.
Args:
onnx_model: The ONNX model to convert.
@@ -188,7 +188,7 @@ def add_metadata(
onnx_model: onnx.ModelProto, # type: ignore
additional_metadata: Optional[list[tuple[str, str]]] = None,
) -> onnx.ModelProto: # type: ignore
- """Adds metadata to an ONNX model.
+ """Add metadata to an ONNX model.
The metadata includes the source library (set to "kornia"), the version of kornia,
and any additional metadata provided as a list of key-value pairs.
diff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.py
index 5c348ad3e..e151ce357 100644
--- a/kornia/sensors/camera/camera_model.py
+++ b/kornia/sensors/camera/camera_model.py
@@ -57,7 +57,7 @@ class CameraModelBase:
def __init__(
self, distortion: CameraDistortionType, projection: CameraProjectionType, image_size: ImageSize, params: Tensor
) -> None:
- """Constructor method for CameraModelBase class.
+ """Construct CameraModelBase class.
Args:
distortion: Distortion type
@@ -117,11 +117,11 @@ class CameraModelBase:
return self._params[..., 3]
def matrix(self) -> Tensor:
- """Returns the camera matrix."""
+ """Return the camera matrix."""
raise NotImplementedError
def K(self) -> Tensor:
- """Returns the camera matrix."""
+ """Return the camera matrix."""
return self.matrix()
def project(self, points: Vector3) -> Vector2:
@@ -182,7 +182,7 @@ class PinholeModel(CameraModelBase):
"""
def __init__(self, image_size: ImageSize, params: Tensor) -> None:
- """Constructor method for PinholeModel class.
+ """Construct PinholeModel class.
Args:
image_size: Image size
@@ -194,7 +194,7 @@ class PinholeModel(CameraModelBase):
super().__init__(AffineTransform(), Z1Projection(), image_size, params)
def matrix(self) -> Tensor:
- r"""Returns the camera matrix.
+ r"""Return the camera matrix.
The matrix is of the form:
@@ -248,7 +248,7 @@ class BrownConradyModel(CameraModelBase):
"""Brown Conrady Camera Model."""
def __init__(self, image_size: ImageSize, params: Tensor) -> None:
- """Constructor method for BrownConradyModel class.
+ """Construct BrownConradyModel class.
Args:
image_size: Image size
@@ -265,7 +265,7 @@ class KannalaBrandtK3(CameraModelBase):
"""Kannala Brandt K3 Camera Model."""
def __init__(self, image_size: ImageSize, params: Tensor) -> None:
- """Constructor method for KannalaBrandtK3 class.
+ """Construct KannalaBrandtK3 class.
Args:
image_size: Image size
@@ -281,7 +281,7 @@ class Orthographic(CameraModelBase):
"""Orthographic Camera Model."""
def __init__(self, image_size: ImageSize, params: Tensor) -> None:
- """Constructor method for Orthographic class.
+ """Construct Orthographic class.
Args:
image_size: Image size
@@ -316,7 +316,7 @@ class CameraModel:
"""
def __init__(self, image_size: ImageSize, model_type: CameraModelType, params: Tensor) -> None:
- """Constructor method for CameraModel class.
+ """Construct CameraModel class.
Args:
image_size: Image size
diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.py
index 17fc80c63..4687233eb 100644
--- a/kornia/sensors/camera/projection_model.py
+++ b/kornia/sensors/camera/projection_model.py
@@ -6,8 +6,7 @@ from kornia.geometry.vector import Vector2, Vector3
class Z1Projection:
def project(self, points: Vector3) -> Vector2:
- """Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective
- division.
+ """Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective division.
Args:
points: Vector3 representing the points to project.
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index b9467e079..c928c2bc6 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -154,7 +154,7 @@ class BaseTester(ABC):
atol: Optional[float] = None,
low_tolerance: bool = False,
) -> None:
- """Asserts that `actual` and `expected` are close.
+ """Assert that `actual` and `expected` are close.
Args:
actual: Actual input.
diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.py
index 91fed5b92..be868a6ec 100644
--- a/kornia/tracking/planar_tracker.py
+++ b/kornia/tracking/planar_tracker.py
@@ -11,8 +11,7 @@ from kornia.geometry.transform import warp_perspective
class HomographyTracker(Module):
- r"""Module, which performs local-feature-based tracking of the target planar object in the sequence of the
- frames.
+ r"""Perform 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`
@@ -81,7 +80,7 @@ class HomographyTracker(Module):
return torch.empty(3, 3, device=self.device, dtype=self.dtype), False
def match_initial(self, x: Tensor) -> Tuple[Tensor, bool]:
- """The frame `x` is matched with initial_matcher and verified with ransac."""
+ """Match the frame `x` with initial_matcher and verified with ransac."""
input_dict: Dict[str, Tensor] = {"image0": self.target, "image1": x}
for k, v in self.target_initial_representation.items():
@@ -107,8 +106,9 @@ class HomographyTracker(Module):
return H, True
def track_next_frame(self, x: Tensor) -> Tuple[Tensor, bool]:
- """The frame `x` is prewarped according to the previous frame homography, matched with fast_matcher
- verified with ransac.
+ """Prewarp the frame `x` according to the previous frame homography.
+
+ Matched with fast_matcher verified with ransac.
"""
if self.previous_homography is not None: # mypy, shut up
Hwarp = self.previous_homography.clone()[None]
diff --git a/kornia/utils/download.py b/kornia/utils/download.py
index 9b6506c7f..51829fc11 100644
--- a/kornia/utils/download.py
+++ b/kornia/utils/download.py
@@ -17,7 +17,7 @@ class CachedDownloader:
@classmethod
def _get_file_path(cls, model_name: str, cache_dir: Optional[str], suffix: Optional[str] = None) -> str:
- """Constructs the file path for the ONNX model based on the model name and cache directory.
+ """Construct the file path for the ONNX model based on the model name and cache directory.
Args:
model_name: The name of the model or operator, typically in the format 'operators/model_name'.
@@ -57,7 +57,7 @@ class CachedDownloader:
file_path: str,
download_if_not_exists: bool = True,
) -> None:
- """Downloads an ONNX model from the specified URL and saves it to the specified file path.
+ """Download an ONNX model from the specified URL and save it to the specified file path.
Args:
url: The URL of the ONNX model to download.
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
index 681d3b3ef..b372fc615 100644
--- a/kornia/utils/draw.py
+++ b/kornia/utils/draw.py
@@ -9,7 +9,7 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
def draw_point2d(image: Tensor, points: Tensor, color: Tensor) -> Tensor:
- r"""Sets one or more coordinates in a Tensor to a color.
+ r"""Set one or more coordinates in a Tensor to a color.
Args:
image: the input image on which to draw the points with shape :math`(C,H,W)` or :math`(H,W)`.
@@ -257,7 +257,7 @@ def draw_rectangle(
def _get_convex_edges(polygon: Tensor, h: int, w: int) -> Tuple[Tensor, Tensor]:
- r"""Gets the left and right edges of a polygon for each y-coordinate y \in [0, h)
+ r"""Get the left and right edges of a polygon for each y-coordinate y \in [0, h).
Args:
polygons: represents polygons to draw in BxNx2
@@ -300,7 +300,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.
+ r"""Convert a List of variable length polygons into a fixed size tensor.
Works by repeating the last element in the tensor.
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index e81dc41eb..1be130038 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -27,7 +27,7 @@ def is_mps_tensor_safe(x: Tensor) -> bool:
def get_cuda_device_if_available(index: int = 0) -> torch.device:
- """Tries to get cuda device, if fail, returns cpu.
+ """Try to get cuda device, if fail, return cpu.
Args:
index: cuda device index
@@ -43,7 +43,7 @@ def get_cuda_device_if_available(index: int = 0) -> torch.device:
def get_mps_device_if_available() -> torch.device:
- """Tries to get mps device, if fail, returns cpu.
+ """Try to get mps device, if fail, return cpu.
Returns:
torch.device
@@ -57,7 +57,7 @@ def get_mps_device_if_available() -> torch.device:
def get_cuda_or_mps_device_if_available() -> torch.device:
- """Checks OS and platform and runs get_cuda_device_if_available or get_mps_device_if_available.
+ """Check OS and platform and run get_cuda_device_if_available or get_mps_device_if_available.
Returns:
torch.device
@@ -149,7 +149,7 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
def _torch_inverse_cast(input: Tensor) -> Tensor:
- """Helper function to make torch.inverse work with other than fp32/64.
+ """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.
@@ -163,7 +163,7 @@ def _torch_inverse_cast(input: Tensor) -> Tensor:
def _torch_histc_cast(input: Tensor, bins: int, min: int, max: int) -> Tensor:
- """Helper function to make torch.histc work with other than fp32/64.
+ """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.
@@ -177,7 +177,7 @@ def _torch_histc_cast(input: Tensor, bins: int, min: int, max: int) -> Tensor:
def _torch_svd_cast(input: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
- """Helper function to make torch.svd work with other than fp32/64.
+ """Make torch.svd work with other than fp32/64.
The function torch.svd is only implemented for fp32/64 which makes
impossible to be used by fp16 or others. What this function does, is cast
@@ -200,7 +200,7 @@ def _torch_svd_cast(input: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
def _torch_linalg_svdvals(input: Tensor) -> Tensor:
- """Helper function to make torch.linalg.svdvals work with other than fp32/64.
+ """Make torch.linalg.svdvals work with other than fp32/64.
The function torch.svd is only implemented for fp32/64 which makes
impossible to be used by fp16 or others. What this function does, is cast
@@ -227,7 +227,7 @@ def _torch_linalg_svdvals(input: Tensor) -> Tensor:
# TODO: return only `Tensor` and review all the calls to adjust
def _torch_solve_cast(A: Tensor, B: Tensor) -> Tensor:
- """Helper function to make torch.solve work with other than fp32/64.
+ """Make torch.solve work with other than fp32/64.
For stable operation, the input matrices should be cast to fp64, and the output will be cast back to the input
dtype.
@@ -240,8 +240,9 @@ def _torch_solve_cast(A: Tensor, B: Tensor) -> Tensor:
def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
- r"""Helper function, which avoids crashing because of singular matrix input and outputs the mask of valid
- solution.
+ r"""Solves the system of equations.
+
+ Avoids crashing because of singular matrix input and outputs the mask of valid solution.
"""
if not torch_version_ge(1, 10):
sol = _torch_solve_cast(A, B)
@@ -284,8 +285,9 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
def safe_inverse_with_mask(A: Tensor) -> Tuple[Tensor, Tensor]:
- r"""Helper function, which avoids crashing because of non-invertable matrix input and outputs the mask of valid
- solution.
+ r"""Perform inverse.
+
+ Avoids crashing because of non-invertable matrix input and outputs the mask of valid solution.
"""
if not isinstance(A, Tensor):
raise AssertionError(f"A must be Tensor. Got: {type(A)}.")
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index f22eacaba..c782da9d7 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -57,7 +57,7 @@ def image_to_tensor(image: Any, keepdim: bool = True) -> Tensor:
def image_list_to_tensor(images: List[Any]) -> Tensor:
- """Converts a list of numpy images to a PyTorch 4d tensor image.
+ """Convert a list of numpy images to a PyTorch 4d tensor image.
Args:
images: list of images, each of the form :math:`(H, W, C)`.
@@ -141,7 +141,7 @@ def _to_bcdhw(tensor: Tensor) -> Tensor:
def tensor_to_image(tensor: Tensor, keepdim: bool = False, force_contiguous: bool = False) -> Any:
- """Converts a PyTorch tensor image to a numpy image.
+ """Convert a PyTorch tensor image to a numpy image.
In case the tensor is in the GPU, it will be copied back to CPU.
@@ -260,7 +260,7 @@ def make_grid(tensor: Tensor, n_row: Optional[int] = None, padding: int = 2) ->
def perform_keep_shape_image(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
- """A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, H, W)`.
+ """Apply `f` 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.
@@ -292,7 +292,7 @@ def perform_keep_shape_image(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
def perform_keep_shape_video(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
- """A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, D, H, W)`.
+ """Apply `f` 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.
diff --git a/kornia/utils/memory.py b/kornia/utils/memory.py
index 2ddfc279c..377cec35e 100644
--- a/kornia/utils/memory.py
+++ b/kornia/utils/memory.py
@@ -6,7 +6,7 @@ from kornia.core import Device, Module, Tensor, concatenate
def batched_forward(
model: Module, data: Tensor, device: Device, batch_size: int = 128, **kwargs: Dict[str, Any]
) -> Tensor:
- r"""Convenience function, which allows to run the forward in micro-batches.
+ r"""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.
diff --git a/kornia/utils/misc.py b/kornia/utils/misc.py
index 761183e41..6fb11614d 100644
--- a/kornia/utils/misc.py
+++ b/kornia/utils/misc.py
@@ -61,7 +61,7 @@ def vec_like(n: int, tensor: Tensor, shared_memory: bool = False) -> Tensor:
def differentiable_polynomial_rounding(input: Tensor) -> Tensor:
- """This function implements differentiable rounding.
+ """Differentiable rounding.
Args:
input (Tensor): Input tensor of any shape to be rounded.
@@ -77,7 +77,7 @@ def differentiable_polynomial_rounding(input: Tensor) -> Tensor:
def differentiable_polynomial_floor(input: Tensor) -> Tensor:
- """This function implements differentiable floor.
+ """Perform floor via a differentiable operation.
Args:
input (Tensor): Input tensor of any shape to be floored.
@@ -98,7 +98,7 @@ def differentiable_clipping(
max_val: Optional[float] = None,
scale: float = 0.02,
) -> Tensor:
- """This function implements a differentiable and soft approximation of the clipping operation.
+ """Clip via a differentiable and soft approximation of the clipping operation.
Args:
input (Tensor): Input tensor of any shape.
diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.py
index a559b2cc2..ef70a7a36 100644
--- a/kornia/utils/pointcloud_io.py
+++ b/kornia/utils/pointcloud_io.py
@@ -4,7 +4,7 @@ import torch
def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
- r"""Utility function to save to disk a pointcloud in PLY format.
+ r"""Save to disk a pointcloud in PLY format.
Args:
filename: the path to save the pointcloud.
@@ -50,7 +50,7 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
def load_pointcloud_ply(filename: str, header_size: int = 8) -> torch.Tensor:
- r"""Utility function to load from disk a pointcloud in PLY format.
+ r"""Load from disk a pointcloud in PLY format.
Args:
filename: the path to the pointcloud.
diff --git a/kornia/utils/sample.py b/kornia/utils/sample.py
index 3745067f4..903233020 100644
--- a/kornia/utils/sample.py
+++ b/kornia/utils/sample.py
@@ -43,7 +43,7 @@ def get_sample_images(
divisible_factor: Optional[int] = None,
**kwargs: Any,
) -> Union[Tensor, List[Tensor]]:
- """Loads multiple images from the given URLs.
+ """Load multiple images from the given URLs.
Optionally download them, resize them if specified, and return them as a batch of tensors or a list of tensors.
diff --git a/pyproject.toml b/pyproject.toml
index e593731e0..866fa2ac8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -138,8 +138,18 @@ ignore = [
"UP007", # Prefer Optional[], Union[] over | due to torch jit scripting
"UP006", # Prefer List[], over list due to torch jit scripting
"UP035", # Ignore deprecated typing because of jit scripting
- 'D100', 'D101', 'D102','D103', 'D104', 'D105', 'D107', 'D203', 'D204', 'D205', 'D213', 'D400', 'D401', 'D404', 'D406', 'D407', 'D415', 'D417'# docs -- TODO: unconment some of these rules..
-]
+ 'D100', # Allow Undocumented public module
+ 'D101', # TODO: Undocumented public class
+ 'D102', # TODO: Undocumented public method
+ 'D103', # TODO: Undocumented public function
+ 'D104', # TODO: Undocumented public package
+ 'D105', # Allow Undocumented magic method
+ 'D107', # TODO: Undocumented public init
+ 'D417', # TODO: Undocumented params
+ ]
+
+[tool.ruff.lint.pydocstyle]
+convention = "google"
[tool.ruff.lint.isort]
forced-separate = ["testing", "tests"]
@@ -164,11 +174,13 @@ max-statements = 64 # Recommended: 50
"RUF012",
"S101",
"S311",
+ "D",
] # allow assert, random, ignore BLE, mutable class attr
"docs/*" = [
"PLR0912",
"PLR0915",
"S101",
+ "D",
] # allow assert, ignore max branches and statements
"docs/generate_examples.py" = ["C901"] # Allow too complex function
"kornia/__init__.py" = ["I001"] # Allow unsorted imports
@@ -179,7 +191,10 @@ max-statements = 64 # Recommended: 50
"FLY002",
"PLR1714",
] # allow DINOv2 things
-"testing/*" = ["S101"] # allow assert
+"testing/*" = [
+ "S101", # allow assert
+ "D", # Don't enforce documentation rules
+]
"tests/*" = [
"BLE",
"RUF005",
@@ -187,6 +202,7 @@ max-statements = 64 # Recommended: 50
"S101",
"S311",
"B017", # Check for Exception since KORNIA_CHECK raises it
+ "D", # Don't enforce documentation rules
] # allow assert, random, ignore BLE, mutable class attr
[tool.pytest.ini_options]