Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fixed some docstring mismatches, but msotly wrong torch.where -> where (#3461)

Dmytro Mishkin320b7e927220
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 05f171eae..8ff63b54b 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -47,7 +47,7 @@ class AugmentationBase2D(_AugmentationBase):
"""
def validate_tensor(self, input: torch.Tensor) -> None:
- """Check if the input torch.tensor is formatted as expected."""
+ """Check if the input torch.Tensor is formatted as expected."""
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
if len(input.shape) != 4:
raise RuntimeError(f"Expect (B, C, H, W). Got {input.shape}.")
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index 4b44d4152..fb93a08f9 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -26,7 +26,7 @@ from kornia.geometry.transform import get_affine_matrix2d, warp_affine
class RandomAffine(GeometricAugmentationBase2D):
- r"""Apply a random 2D affine transformation to a torch.tensor image.
+ r"""Apply a random 2D affine transformation to a torch.Tensor image.
.. image:: _static/img/RandomAffine.png
@@ -52,7 +52,7 @@ class RandomAffine(GeometricAugmentationBase2D):
resample: resample mode from "nearest" (0) or "bilinear" (1).
padding_mode: padding mode from "torch.zeros" (0), "border" (1), "reflection" (2) or "fill" (3).
fill_value: the value to be filled in the padding area when padding_mode="fill".
- Can be a float, int, or a torch.tensor of shape (C) or (1).
+ Can be a float, int, or a torch.Tensor of shape (C) or (1).
same_on_batch: apply the same transformation across the batch.
align_corners: interpolation flag.
p: probability of applying the transformation.
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 338802605..7837dfc5e 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -312,7 +312,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if transform is None:
- raise RuntimeError("`transform` has to be a torch.tensor. Got None.")
+ raise RuntimeError("`transform` has to be a torch.Tensor. Got None.")
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
@@ -340,7 +340,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
"""Inverse the transformation on keypoints.
Args:
- input: input keypoints torch.tensor or object.
+ input: input keypoints torch.Tensor or object.
params: the corresponding parameters for an operation.
flags: static parameters.
transform: the inverse transformation matrix
@@ -352,7 +352,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if transform is None:
- raise RuntimeError("`transform` has to be a torch.tensor. Got None.")
+ raise RuntimeError("`transform` has to be a torch.Tensor. Got None.")
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
@@ -385,7 +385,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
"""Perform inverse operations.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
params: the corresponding parameters for an operation.
If None, a new parameter suite will be generated.
**kwargs: key-value pairs to override the parameters and flags.
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 38da2e5e8..30165fc7b 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -26,7 +26,7 @@ from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, ge
class CenterCrop(GeometricAugmentationBase2D):
- r"""Crop a given image torch.tensor at the center.
+ r"""Crop a given image torch.Tensor at the center.
.. image:: _static/img/CenterCrop.png
@@ -39,7 +39,7 @@ class CenterCrop(GeometricAugmentationBase2D):
p: probability of applying the transformation for the whole batch.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.tensor based
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.Tensor based
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
differentiability.
@@ -89,7 +89,7 @@ class CenterCrop(GeometricAugmentationBase2D):
cropping_mode: str = "slice",
) -> None:
# same_on_batch is always True for CenterCrop
- # Since PyTorch does not support ragged torch.tensor. So cropping function happens batch-wisely.
+ # Since PyTorch does not support ragged torch.Tensor. So cropping function happens batch-wisely.
super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
self.size = (size[0], size[1])
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 0aa0f4dec..855f324f4 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -29,7 +29,7 @@ from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, ge
class RandomCrop(GeometricAugmentationBase2D):
- r"""Crop random patches of a torch.tensor image on a given size.
+ r"""Crop random patches of a torch.Tensor image on a given size.
.. image:: _static/img/RandomCrop.png
@@ -54,7 +54,7 @@ class RandomCrop(GeometricAugmentationBase2D):
p: probability of applying the transformation for the whole batch.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.tensor based
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.Tensor based
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
differentiability.
@@ -64,9 +64,9 @@ class RandomCrop(GeometricAugmentationBase2D):
- Output: :math:`(B, C, out_h, out_w)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Examples:
>>> import torch
@@ -104,7 +104,7 @@ class RandomCrop(GeometricAugmentationBase2D):
keepdim: bool = False,
cropping_mode: str = "slice",
) -> None:
- # Since PyTorch does not support ragged torch.tensor. So cropping function happens batch-wisely.
+ # Since PyTorch does not support ragged torch.Tensor. So cropping function happens batch-wisely.
super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self._param_generator = rg.CropGenerator(size)
self.flags = {
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index 549dd9584..49ac10c49 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -26,7 +26,7 @@ from kornia.geometry.transform import elastic_transform2d
class RandomElasticTransform(AugmentationBase2D):
- r"""Add random elastic transformation to a torch.tensor image.
+ r"""Add random elastic transformation to a torch.Tensor image.
.. image:: _static/img/RandomElasticTransform.png
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index fc4ee6ea2..bfaed3fb5 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -25,13 +25,13 @@ from kornia.geometry.transform import hflip
class RandomHorizontalFlip(GeometricAugmentationBase2D):
- r"""Apply a random horizontal flip to a torch.tensor image or a batch of torch.tensor images.
+ r"""Apply a random horizontal flip to a torch.Tensor image or a batch of torch.Tensor images.
The flip is applied with a given probability.
.. image:: _static/img/RandomHorizontalFlip.png
- Input should be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.
+ Input should be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.
If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
the corresponding transformation matrix that has been applied to them. In this case the module
will Horizontally flip the tensors and torch.cat the corresponding transformation matrix to the
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 02baf6f73..07867886a 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -26,7 +26,7 @@ from kornia.geometry.transform import get_perspective_transform, warp_perspectiv
class RandomPerspective(GeometricAugmentationBase2D):
- r"""Apply a random perspective transformation to an image torch.tensor with a given probability.
+ r"""Apply a random perspective transformation to an image torch.Tensor with a given probability.
.. image:: _static/img/RandomPerspective.png
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 0c49faa06..b24b337b4 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -26,7 +26,7 @@ from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, ge
class RandomResizedCrop(GeometricAugmentationBase2D):
- r"""Crop random patches in an image torch.tensor and resizes to a given size.
+ r"""Crop random patches in an image torch.Tensor and resizes to a given size.
.. image:: _static/img/RandomResizedCrop.png
@@ -41,7 +41,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
p: probability of the augmentation been applied.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.tensor based
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.Tensor based
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
differentiability.
@@ -51,9 +51,9 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
- Output: :math:`(B, C, out_h, out_w)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Example:
>>> rng = torch.manual_seed(0)
@@ -91,7 +91,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
keepdim: bool = False,
cropping_mode: str = "slice",
) -> None:
- # Since PyTorch does not support ragged torch.tensor. So cropping function happens all the time.
+ # Since PyTorch does not support ragged torch.Tensor. So cropping function happens all the time.
super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self._param_generator = rg.ResizedCropGenerator(size, scale, ratio)
self.flags = {
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index 05cf68d50..49845b0e7 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -28,7 +28,7 @@ from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute
class RandomRotation(GeometricAugmentationBase2D):
- r"""Apply a random rotation to a torch.tensor image or a batch of torch.tensor images given an amount of degrees.
+ r"""Apply a random rotation to a torch.Tensor image or a batch of torch.Tensor images given an amount of degrees.
.. image:: _static/img/RandomRotation.png
@@ -138,7 +138,7 @@ class RandomRotation(GeometricAugmentationBase2D):
class RandomRotation90(GeometricAugmentationBase2D):
- r"""Apply a random 90 * n degree rotation to a torch.tensor image or a batch of torch.tensor images.
+ r"""Apply a random 90 * n degree rotation to a torch.Tensor image or a batch of torch.Tensor images.
Args:
times: the range of n times 90 degree rotation needs to be applied.
diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.py
index 6a1333013..cb2c51610 100644
--- a/kornia/augmentation/_2d/geometric/shear.py
+++ b/kornia/augmentation/_2d/geometric/shear.py
@@ -28,7 +28,7 @@ from kornia.geometry.transform import get_shear_matrix2d, warp_affine
class RandomShear(GeometricAugmentationBase2D):
- r"""Apply a random 2D shear transformation to a torch.tensor image.
+ r"""Apply a random 2D shear transformation to a torch.Tensor image.
The transformation is computed so that the image center is kept invariant.
diff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.py
index d5be7f353..967fcfff3 100644
--- a/kornia/augmentation/_2d/geometric/translate.py
+++ b/kornia/augmentation/_2d/geometric/translate.py
@@ -26,7 +26,7 @@ from kornia.geometry.transform import get_translation_matrix2d, warp_affine
class RandomTranslate(GeometricAugmentationBase2D):
- r"""Apply a random 2D affine transformation to a torch.tensor image.
+ r"""Apply a random 2D affine transformation to a torch.Tensor image.
Args:
translate_x: tuple of maximum absolute fraction for horizontal translations.
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index 8c808f00a..5fce10ec2 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -24,7 +24,7 @@ from kornia.geometry.transform import vflip
class RandomVerticalFlip(GeometricAugmentationBase2D):
- r"""Apply a random vertical flip to a torch.tensor image or a batch of torch.tensor images with a given probability.
+ r"""Apply a random vertical flip to a torch.Tensor image or a batch of torch.Tensor images with a given probability.
.. image:: _static/img/RandomVerticalFlip.png
diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.py
index 02d2b1287..0b03cb917 100644
--- a/kornia/augmentation/_2d/intensity/auto_contrast.py
+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py
@@ -24,7 +24,7 @@ from kornia.enhance import normalize_min_max
class RandomAutoContrast(IntensityAugmentationBase2D):
- r"""Apply a random auto-contrast of a torch.tensor image.
+ r"""Apply a random auto-contrast of a torch.Tensor image.
Args:
p: probability of applying the transformation.
diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.py
index a2c13006d..d13c58a5c 100644
--- a/kornia/augmentation/_2d/intensity/brightness.py
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -26,7 +26,7 @@ from kornia.enhance.adjust import adjust_brightness
class RandomBrightness(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the brightness of a torch.tensor image.
+ r"""Apply a random transformation to the brightness of a torch.Tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.py
index 64bb64e8a..69efe2c78 100644
--- a/kornia/augmentation/_2d/intensity/clahe.py
+++ b/kornia/augmentation/_2d/intensity/clahe.py
@@ -27,7 +27,7 @@ from kornia.enhance import equalize_clahe
class RandomClahe(IntensityAugmentationBase2D):
- r"""Apply CLAHE equalization on the input torch.tensor randomly.
+ r"""Apply CLAHE equalization on the input torch.Tensor randomly.
.. image:: _static/img/equalize_clahe.png
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index 363e14314..1d25977c2 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -26,7 +26,7 @@ from kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjus
class ColorJiggle(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.tensor image.
+ r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.Tensor image.
.. image:: _static/img/ColorJiggle.png
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
index aaf8d92f7..338152036 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -31,7 +31,7 @@ from kornia.enhance import (
class ColorJitter(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.tensor image.
+ r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.Tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision. However, it does not
follow the color theory and is not be actively maintained. Prefer using
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index 6fcaf0f61..6020f33a2 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -26,7 +26,7 @@ from kornia.enhance.adjust import adjust_contrast
class RandomContrast(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the contrast of a torch.tensor image.
+ r"""Apply a random transformation to the contrast of a torch.Tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.py
index 137e8b45e..f55be6c6a 100644
--- a/kornia/augmentation/_2d/intensity/erasing.py
+++ b/kornia/augmentation/_2d/intensity/erasing.py
@@ -25,7 +25,7 @@ from kornia.geometry.bbox import bbox_generator, bbox_to_mask
class RandomErasing(IntensityAugmentationBase2D):
- r"""Erase a random rectangle of a torch.tensor image according to a probability p value.
+ r"""Erase a random rectangle of a torch.Tensor image according to a probability p value.
.. image:: _static/img/RandomErasing.png
@@ -50,9 +50,9 @@ class RandomErasing(IntensityAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Examples:
>>> rng = torch.manual_seed(0)
diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.py
index 00b9450c6..46b9299ba 100644
--- a/kornia/augmentation/_2d/intensity/gamma.py
+++ b/kornia/augmentation/_2d/intensity/gamma.py
@@ -25,7 +25,7 @@ from kornia.enhance.adjust import adjust_gamma
class RandomGamma(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the gamma of a torch.tensor image.
+ r"""Apply a random transformation to the gamma of a torch.Tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index 9c7996210..a6262ccb9 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -27,7 +27,7 @@ from kornia.enhance.adjust import adjust_hue
class RandomHue(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the hue of a torch.tensor image.
+ r"""Apply a random transformation to the hue of a torch.Tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
diff --git a/kornia/augmentation/_2d/intensity/jpeg.py b/kornia/augmentation/_2d/intensity/jpeg.py
index 299c0fb38..7581f4c43 100644
--- a/kornia/augmentation/_2d/intensity/jpeg.py
+++ b/kornia/augmentation/_2d/intensity/jpeg.py
@@ -25,7 +25,7 @@ from kornia.enhance import jpeg_codec_differentiable
class RandomJPEG(IntensityAugmentationBase2D):
- r"""Applies random (differentiable) JPEG coding to a torch.tensor image.
+ r"""Applies random (differentiable) JPEG coding to a torch.Tensor image.
.. image:: _static/img/RandomJPEG.png
diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.py
index 767210f0a..6befbcde1 100644
--- a/kornia/augmentation/_2d/intensity/motion_blur.py
+++ b/kornia/augmentation/_2d/intensity/motion_blur.py
@@ -26,7 +26,7 @@ from kornia.filters import motion_blur
class RandomMotionBlur(IntensityAugmentationBase2D):
- r"""Perform motion blur on 2D images (4D torch.tensor).
+ r"""Perform motion blur on 2D images (4D torch.Tensor).
.. image:: _static/img/RandomMotionBlur.png
@@ -54,9 +54,9 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Please set ``resample`` to ``'bilinear'`` if more meaningful gradients wanted.
@@ -116,7 +116,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
# selected random index --- `params["idx"][0]` --- to determine the applied kernel size.
# 2. The `VideoSequential` flattens the first two dimensions, effectively creating a larger batch.
# Its method `VideoSequential.__repeat_param_across_channels__` repeats the previously selected index,
- # creating a torch.tensor with equal values. Hence, taking the first one (`params["idx"][0]`) is legit.
+ # creating a torch.Tensor with equal values. Hence, taking the first one (`params["idx"][0]`) is legit.
idx: int = cast(int, params["idx"][0])
return motion_blur(
input,
diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.py
index e1ce62355..d04c3f659 100644
--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py
+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py
@@ -91,7 +91,7 @@ def get_planckian_coeffs(mode: str) -> torch.Tensor:
class RandomPlanckianJitter(IntensityAugmentationBase2D):
- r"""Apply planckian jitter transformation to input torch.tensor.
+ r"""Apply planckian jitter transformation to input torch.Tensor.
.. image:: _static/img/RandomPlanckianJitter.png
@@ -114,7 +114,7 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
.. note::
- Input torch.tensor must be float and normalized into [0, 1].
+ Input torch.Tensor must be float and normalized into [0, 1].
Examples:
To apply planckian jitter based on mode
diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.py
index f39825685..b35fe6373 100644
--- a/kornia/augmentation/_2d/intensity/posterize.py
+++ b/kornia/augmentation/_2d/intensity/posterize.py
@@ -25,7 +25,7 @@ from kornia.enhance import posterize
class RandomPosterize(IntensityAugmentationBase2D):
- r"""Posterize given torch.tensor image or a batch of torch.tensor images randomly.
+ r"""Posterize given torch.Tensor image or a batch of torch.Tensor images randomly.
.. image:: _static/img/RandomPosterize.png
diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.py
index 05e6343ac..2223d3571 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -87,7 +87,7 @@ class RandomRain(IntensityAugmentationBase2D):
modeified_img = image.clone()
for i in range(image.shape[0]):
number_of_drops: int = int(params["number_of_drops_factor"][i])
- # We generate torch.tensor with maximum number of drops, and then remove unnecessary drops.
+ # We generate torch.Tensor with maximum number of drops, and then remove unnecessary drops.
coordinates_of_drops: torch.Tensor = params["coordinates_factor"][i][:number_of_drops]
height_of_drop: int = int(params["drop_height_factor"][i])
diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
index 4896c49a7..571c828d5 100644
--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py
+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
@@ -40,7 +40,7 @@ class RandomRGBShift(IntensityAugmentationBase2D):
to the batch form ``False``.
Note:
- Input torch.tensor must be float and normalized into [0, 1].
+ Input torch.Tensor must be float and normalized into [0, 1].
Examples:
>>> import torch
diff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.py
index 8af4c714c..22892e357 100644
--- a/kornia/augmentation/_2d/intensity/random_snow.py
+++ b/kornia/augmentation/_2d/intensity/random_snow.py
@@ -26,7 +26,7 @@ from kornia.core.check import KORNIA_CHECK
class RandomSnow(IntensityAugmentationBase2D):
- r"""Generates snow effect on given torch.tensor image or a batch torch.tensor images.
+ r"""Generates snow effect on given torch.Tensor image or a batch torch.Tensor images.
Args:
snow_coefficient: A tuple of floats (lower and upper bound) between 0 and 1 that control
@@ -35,7 +35,7 @@ class RandomSnow(IntensityAugmentationBase2D):
brightness of the snow.
same_on_batch: If True, apply the same transformation to each image in a batch. Default: False.
p: Probability of applying the transformation. Default: 0.5.
- keepdim: Keep the output torch.tensor with the same shape as input. Default: False.
+ keepdim: Keep the output torch.Tensor with the same shape as input. Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index cab0e23de..37f1b00a4 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -26,7 +26,7 @@ from kornia.enhance.adjust import adjust_saturation
class RandomSaturation(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the saturation of a torch.tensor image.
+ r"""Apply a random transformation to the saturation of a torch.Tensor image.
This implementation aligns PIL. Hence, the output is close to TorchVision.
diff --git a/kornia/augmentation/_2d/intensity/sharpness.py b/kornia/augmentation/_2d/intensity/sharpness.py
index a25bf43f5..6a095c191 100644
--- a/kornia/augmentation/_2d/intensity/sharpness.py
+++ b/kornia/augmentation/_2d/intensity/sharpness.py
@@ -25,7 +25,7 @@ from kornia.enhance import sharpness
class RandomSharpness(IntensityAugmentationBase2D):
- r"""Sharpen given torch.tensor image or a batch of torch.tensor images randomly.
+ r"""Sharpen given torch.Tensor image or a batch of torch.Tensor images randomly.
.. image:: _static/img/RandomSharpness.png
diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.py
index 5a8ac6146..d195f3182 100644
--- a/kornia/augmentation/_2d/intensity/solarize.py
+++ b/kornia/augmentation/_2d/intensity/solarize.py
@@ -25,7 +25,7 @@ from kornia.enhance import solarize
class RandomSolarize(IntensityAugmentationBase2D):
- r"""Solarize given torch.tensor image or a batch of torch.tensor images randomly.
+ r"""Solarize given torch.Tensor image or a batch of torch.Tensor images randomly.
.. image:: _static/img/RandomSolarize.png
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 8d1512e6c..044c0f8f0 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -76,13 +76,13 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
- # NOTE: apply_transform receives the whole torch.tensor, but returns only altered elements.
+ # NOTE: apply_transform receives the whole torch.Tensor, but returns only altered elements.
raise NotImplementedError
def apply_non_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
) -> torch.Tensor:
- # For the images torch.where batch_prob == False.
+ # For the images where batch_prob == False.
return input
def transform_input(
@@ -120,7 +120,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
# input is BxNx4x2 or Boxes.
if isinstance(input, torch.Tensor):
if not (len(input.shape) == 4 and input.shape[2:] == torch.Size([4, 2])):
- raise RuntimeError(f"Only BxNx4x2 torch.tensor is supported. Got {input.shape}.")
+ raise RuntimeError(f"Only BxNx4x2 torch.Tensor is supported. Got {input.shape}.")
input = Boxes(input, False, mode="vertices_plus")
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 0df93feb4..298c788b5 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -26,15 +26,15 @@ from kornia.geometry.bbox import bbox_to_mask, infer_bbox_shape
class RandomCutMixV2(MixAugmentationBaseV2):
- r"""Apply CutMix augmentation to a batch of torch.tensor images.
+ r"""Apply CutMix augmentation to a batch of torch.Tensor images.
.. image:: _static/img/RandomCutMixV2.png
Implementation for `CutMix: Regularization Strategy to Train Strong Classifiers with
Localizable Features` :cite:`yun2019cutmix`.
- The function returns (inputs, labels), in which the inputs is the torch.tensor that contains the mixup images
- while the labels is a :math:`(\text{num_mixes}, B, 3)` torch.tensor that contains (label_permuted_batch, lambda)
+ The function returns (inputs, labels), in which the inputs is the torch.Tensor that contains the mixup images
+ while the labels is a :math:`(\text{num_mixes}, B, 3)` torch.Tensor that contains (label_permuted_batch, lambda)
for each cutmix.
The implementation referred to the following repository: `https://github.com/clovaai/CutMix-PyTorch
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index 8b9e9fd25..914890dee 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -25,14 +25,14 @@ from kornia.constants import DataKey, DType
class RandomMixUpV2(MixAugmentationBaseV2):
- r"""Apply MixUp augmentation to a batch of torch.tensor images.
+ r"""Apply MixUp augmentation to a batch of torch.Tensor images.
.. image:: _static/img/RandomMixUpV2.png
Implementation for `mixup: BEYOND EMPIRICAL RISK MINIMIZATION` :cite:`zhang2018mixup`.
- The function returns (inputs, labels), in which the inputs is the torch.tensor that contains the mixup images
- while the labels is a :math:`(B, 3)` torch.tensor that contains (label_batch, label_permuted_batch, lambda) for
+ The function returns (inputs, labels), in which the inputs is the torch.Tensor that contains the mixup images
+ while the labels is a :math:`(B, 3)` torch.Tensor that contains (label_batch, label_permuted_batch, lambda) for
each image.
The implementation is on top of the following repository:
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index a02ffa881..983fd07f6 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -46,7 +46,7 @@ class RandomMosaic(MixAugmentationBaseV2):
2. Crop out the outcome image according to the top-left corner and crop size.
Args:
- output_size: the output torch.tensor width and height after mosaicing.
+ output_size: the output torch.Tensor width and height after mosaicing.
start_ratio_range: top-left (x, y) position for cropping the mosaic images.
mosaic_grid: the number of images and image arrangement. e.g. (2, 2) means
each output will mix 4 images in a 2x2 grid.
@@ -60,7 +60,7 @@ class RandomMosaic(MixAugmentationBaseV2):
padding_mode: Type of padding. Should be: constant, reflect, replicate.
resample: the interpolation mode.
align_corners: interpolation flag.
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.tensor based
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.Tensor based
on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
differentiability.
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index 31938af8e..62faad973 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -54,9 +54,9 @@ class RandomTransplantation(MixAugmentationBaseV2):
receive a transplant.
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wise.
- data_keys: the input type sequential for applying augmentations. There must be at least one "mask" torch.tensor.
- If no data keys are given, the first torch.tensor is assumed to be `DataKey.INPUT` and the second
- torch.tensor `DataKey.MASK`.
+ data_keys: the input type sequential for applying augmentations. There must be at least one "mask" torch.Tensor.
+ If no data keys are given, the first torch.Tensor is assumed to be `DataKey.INPUT` and the second
+ torch.Tensor `DataKey.MASK`.
Accepts "input", "mask".
Note:
@@ -68,8 +68,8 @@ class RandomTransplantation(MixAugmentationBaseV2):
:class:`kornia.augmentation.RandomTransplantation3D` for 3D images.
Inputs:
- - Segmentation mask torch.tensor which is used to determine the objects for transplantation: :math:`(B, *)`.
- - (optional) Additional image or mask tensors torch.where the features are transplanted based on the first
+ - Segmentation mask torch.Tensor which is used to determine the objects for transplantation: :math:`(B, *)`.
+ - (optional) Additional image or mask tensors where the features are transplanted based on the first
segmentation mask: :math:`(B, C, *)` (`DataKey.INPUT`) or :math:`(B, *)` (`DataKey.MASK`).
Returns:
@@ -217,7 +217,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
Args:
*input: All input tensors passed to the augmentation pipeline.
- data_keys: Associated data key for every input torch.tensor.
+ data_keys: Associated data key for every input torch.Tensor.
params: Dictionary of parameters computed so far by the augmentation pipeline (e.g. including the
`batch_prob`).
extra_args: Optional dictionary of extra arguments with specific options for different input types.
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 6e820c22f..be716fc7b 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -40,7 +40,7 @@ class AugmentationBase3D(_AugmentationBase):
"""
def validate_tensor(self, input: torch.Tensor) -> None:
- """Check if the input torch.tensor is formatted as expected."""
+ """Check if the input torch.Tensor is formatted as expected."""
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
if len(input.shape) != 5:
raise RuntimeError(f"Expect (B, C, D, H, W). Got {input.shape}.")
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index 0db1bc951..a356fe8d1 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -26,7 +26,7 @@ from kornia.geometry.transform.imgwarp import get_affine_matrix3d, warp_affine3d
class RandomAffine3D(GeometricAugmentationBase3D):
- r"""Apply affine transformation 3D volumes (5D torch.tensor).
+ r"""Apply affine transformation 3D volumes (5D torch.Tensor).
The transformation is computed so that the center is kept invariant.
@@ -67,9 +67,9 @@ class RandomAffine3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, D, H, W)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index 6707b288f..0b0335897 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -26,7 +26,7 @@ from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
class CenterCrop3D(GeometricAugmentationBase3D):
- r"""Apply center crop on 3D volumes (5D torch.tensor).
+ r"""Apply center crop on 3D volumes (5D torch.Tensor).
Args:
p: probability of applying the transformation for the whole batch.
@@ -43,9 +43,9 @@ class CenterCrop3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, out_d, out_h, out_w)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Examples:
>>> import torch
@@ -86,7 +86,7 @@ class CenterCrop3D(GeometricAugmentationBase3D):
keepdim: bool = False,
) -> None:
# same_on_batch is always True for CenterCrop
- # Since PyTorch does not support ragged torch.tensor. So cropping function happens batch-wisely.
+ # Since PyTorch does not support ragged torch.Tensor. So cropping function happens batch-wisely.
super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
self.size = (size[0], size[1], size[2])
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index aba88bfd4..e40ac2284 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -27,7 +27,7 @@ from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
class RandomCrop3D(GeometricAugmentationBase3D):
- r"""Apply random crop on 3D volumes (5D torch.tensor).
+ r"""Apply random crop on 3D volumes (5D torch.Tensor).
Crops random sub-volumes on a given size.
@@ -58,9 +58,9 @@ class RandomCrop3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, , out_d, out_h, out_w)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Examples:
>>> import torch
@@ -95,7 +95,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
p: float = 1.0,
keepdim: bool = False,
) -> None:
- # Since PyTorch does not support ragged torch.tensor. So cropping function happens batch-wisely.
+ # Since PyTorch does not support ragged torch.Tensor. So cropping function happens batch-wisely.
super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self.flags = {
"size": size,
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index 4926bdd01..98165b41e 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -26,7 +26,7 @@ from kornia.geometry import get_perspective_transform3d, warp_perspective3d
class RandomPerspective3D(GeometricAugmentationBase3D):
- r"""Apply andom perspective transformation to 3D volumes (5D torch.tensor).
+ r"""Apply andom perspective transformation to 3D volumes (5D torch.Tensor).
Args:
p: probability of the image being perspectively transformed.
@@ -42,9 +42,9 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, D, H, W)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index aebd473a7..cf933cc11 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -28,9 +28,9 @@ from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compu
class RandomRotation3D(GeometricAugmentationBase3D):
- r"""Apply random rotations to 3D volumes (5D torch.tensor).
+ r"""Apply random rotations to 3D volumes (5D torch.Tensor).
- Input should be a torch.tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`.
+ Input should be a torch.Tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`.
If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
the corresponding transformation matrix that has been applied to them. In this case the module
will rotate the tensors and torch.cat the corresponding transformation matrix to the
@@ -56,9 +56,9 @@ class RandomRotation3D(GeometricAugmentationBase3D):
- Output: :math:`(B, C, D, H, W)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.py
index 9069e4eff..a34c160f4 100644
--- a/kornia/augmentation/_3d/intensity/motion_blur.py
+++ b/kornia/augmentation/_3d/intensity/motion_blur.py
@@ -26,7 +26,7 @@ from kornia.filters import motion_blur3d
class RandomMotionBlur3D(IntensityAugmentationBase3D):
- r"""Apply random motion blur on 3D volumes (5D torch.tensor).
+ r"""Apply random motion blur on 3D volumes (5D torch.Tensor).
Args:
p: probability of applying the transformation.
@@ -57,9 +57,9 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):
- Output: :math:`(B, C, D, H, W)`
Note:
- Input torch.tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.tensor and returned.
+ Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation torch.Tensor and returned.
Examples:
>>> import torch
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index 2ad330786..49cd0d1ce 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -69,7 +69,7 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
"""Compute the transformation matrix according to the provided parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index 23884d8ee..342d70040 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -71,7 +71,7 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
"""Compute the transformation matrix according to the provided parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 00b0e2af7..390900f85 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -130,7 +130,7 @@ class _BasicAugmentationBase(nn.Module):
raise NotImplementedError
def validate_tensor(self, input: torch.Tensor) -> None:
- """Check if the input torch.tensor is formatted as expected."""
+ """Check if the input torch.Tensor is formatted as expected."""
raise NotImplementedError
def transform_output_tensor(self, output: torch.Tensor, output_shape: Tuple[int, ...]) -> torch.Tensor:
@@ -233,7 +233,7 @@ class _BasicAugmentationBase(nn.Module):
"""Perform forward operations.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
params: the corresponding parameters for an operation.
If None, a new parameter suite will be generated.
**kwargs: key-value pairs to override the parameters and flags.
@@ -283,7 +283,7 @@ class _AugmentationBase(_BasicAugmentationBase):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- # apply transform for the input image torch.tensor
+ # apply transform for the input image torch.Tensor
raise NotImplementedError
def apply_non_transform(
@@ -294,7 +294,7 @@ class _AugmentationBase(_BasicAugmentationBase):
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
# apply additional transform for the images that are skipped from transformation
- # torch.where batch_prob == False.
+ # where batch_prob == False.
return input
def transform_inputs(
@@ -319,7 +319,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform(in_tensor, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform(in_tensor, params, flags, transform=transform)
- else: # If any torch.tensor needs to be transformed.
+ else: # If any torch.Tensor needs to be transformed.
output = self.apply_non_transform(in_tensor, params, flags, transform=transform)
applied = self.apply_transform(
in_tensor[to_apply],
@@ -363,7 +363,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform_mask(in_tensor, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform)
- else: # If any torch.tensor needs to be transformed.
+ else: # If any torch.Tensor needs to be transformed.
output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform)
applied = self.apply_transform_mask(
in_tensor[to_apply],
@@ -397,7 +397,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform_box(input, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform_box(input, params, flags, transform=transform)
- else: # If any torch.tensor needs to be transformed.
+ else: # If any torch.Tensor needs to be transformed.
output = self.apply_non_transform_box(input, params, flags, transform=transform)
applied = self.apply_transform_box(
input[to_apply],
@@ -433,7 +433,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform_keypoint(input, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
- else: # If any torch.tensor needs to be transformed.
+ else: # If any torch.Tensor needs to be transformed.
output = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
applied = self.apply_transform_keypoint(
input[to_apply],
@@ -465,7 +465,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = self.apply_transform_class(input, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform_class(input, params, flags, transform=transform)
- else: # If any torch.tensor needs to be transformed.
+ else: # If any torch.Tensor needs to be transformed.
output = self.apply_non_transform_class(input, params, flags, transform=transform)
applied = self.apply_transform_class(
input[to_apply],
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index c69a5f4c7..4c9f0aea5 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -392,7 +392,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
out: List[DataType] = []
for in_arg, out_arg, dcate in zip(in_args, out_args, data_keys):
if DataKey.get(dcate) in _IMG_OPTIONS:
- # It is torch.tensor type already.
+ # It is torch.Tensor type already.
out.append(out_arg)
# TODO: may add the float to integer (for masks), etc.
elif DataKey.get(dcate) in _MSK_OPTIONS:
@@ -450,7 +450,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if DataKey.INPUT in self.transform_op.data_keys:
inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)]
if not isinstance(inp, torch.Tensor):
- raise ValueError(f"`INPUT` should be a torch.tensor but `{type(inp)}` received.")
+ raise ValueError(f"`INPUT` should be a torch.Tensor but `{type(inp)}` received.")
# A video input shall be BCDHW while an image input shall be BCHW
if self.contains_video_sequential or self.contains_3d_augmentation:
_, out_shape = self.autofill_dim(inp, dim_range=(3, 5))
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 7e290913c..faaa4610b 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -170,9 +170,9 @@ class SequentialBase(BasicSequentialBase):
self.update_attribute(keepdim=keepdim)
def autofill_dim(self, input: torch.Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:
- """Fill torch.tensor dim to the upper bound of dim_range.
+ """Fill torch.Tensor dim to the upper bound of dim_range.
- If input torch.tensor dim is smaller than the lower bound of dim_range, an error will be thrown out.
+ If input torch.Tensor dim is smaller than the lower bound of dim_range, an error will be thrown out.
"""
ori_shape = input.shape
if len(ori_shape) < dim_range[0] or len(ori_shape) > dim_range[1]:
@@ -203,7 +203,7 @@ class ImageSequentialBase(SequentialBase):
"""Compute the transformation matrix according to the provided parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
@@ -283,7 +283,7 @@ class ImageSequentialBase(SequentialBase):
) -> torch.Tensor:
"""Inverse transformation.
- Used to inverse a torch.tensor according to the performed transformation by a forward pass, or with respect to
+ Used to inverse a torch.Tensor according to the performed transformation by a forward pass, or with respect to
provided parameters.
"""
if params is None:
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 18228c97a..0341ac867 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -270,7 +270,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
"""Compute the transformation matrix according to the provided parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
@@ -393,9 +393,9 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Siz
batch_shape = _get_new_batch_shape(p, batch_shape)
return batch_shape
- # Carefully avoid evaluating expression multiple times; batch_prob is often a 1-element torch.tensor
+ # Carefully avoid evaluating expression multiple times; batch_prob is often a 1-element torch.Tensor
if "output_size" in data:
- # Inline check for common PyTorch float torch.tensor case
+ # Inline check for common PyTorch float torch.Tensor case
batch_prob = data.get("batch_prob", None)
if batch_prob is not None:
# Avoid repeated indexing, always fetch scalar efficiently
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 3e311917d..814ff4c9c 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -64,7 +64,7 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
"""Apply a transformation with respect to the parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
@@ -78,7 +78,7 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
"""Inverse a transformation with respect to the parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
@@ -285,7 +285,7 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
"""Apply a transformation with respect to the parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
@@ -399,7 +399,7 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
"""Inverse a transformation with respect to the parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
@@ -447,7 +447,7 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
"""Apply a transformation with respect to the parameters.
Args:
- input: the input torch.tensor, (B, N, 4, 2) or (B, 4, 2).
+ input: the input torch.Tensor, (B, N, 4, 2) or (B, 4, 2).
module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
@@ -493,7 +493,7 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
"""Inverse a transformation with respect to the parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
@@ -544,7 +544,7 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
"""Apply a transformation with respect to the parameters.
Args:
- input: the input torch.tensor, (B, N, 4, 2) or (B, 4, 2).
+ input: the input torch.Tensor, (B, N, 4, 2) or (B, 4, 2).
module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
@@ -591,7 +591,7 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
"""Inverse a transformation with respect to the parameters.
Args:
- input: the input torch.tensor.
+ input: the input torch.Tensor.
module: any torch nn.Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index 821fd6052..7a5403739 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -51,7 +51,7 @@ class PatchSequential(ImageSequential):
*args: a list of processing modules.
grid_size: controls the grid board separation.
padding: same or valid padding. If same padding, it will F.pad to include all pixels if the input
- torch.tensor cannot be divisible by grid_size. If valid padding, the redundant border will be removed.
+ torch.Tensor cannot be divisible by grid_size. If valid padding, the redundant border will be removed.
same_on_batch: apply the same transformation across the batch.
If None, it will not overwrite the function-wise settings.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
@@ -189,7 +189,7 @@ class PatchSequential(ImageSequential):
grid_size: Optional[Tuple[int, int]] = None,
pad: Optional[Tuple[int, int, int, int]] = None,
) -> torch.Tensor:
- """Extract patches from torch.tensor.
+ """Extract patches from torch.Tensor.
Example:
>>> import kornia.augmentation as K
@@ -408,7 +408,7 @@ class PatchSequential(ImageSequential):
) -> torch.Tensor:
"""Inverse transformation.
- Used to inverse a torch.tensor according to the performed transformation by a forward pass, or with respect to
+ Used to inverse a torch.Tensor according to the performed transformation by a forward pass, or with respect to
provided parameters.
"""
if self.is_intensity_only():
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 6f3822a9c..762801143 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -291,7 +291,7 @@ class VideoSequential(ImageSequential):
"""Transform bounding boxes.
Args:
- input: torch.tensor with shape :math:`(B, T, N, 4, 2)`.
+ input: torch.Tensor with shape :math:`(B, T, N, 4, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 4, 2)`.
params: params for the sequence.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -311,7 +311,7 @@ class VideoSequential(ImageSequential):
"""Transform bounding boxes.
Args:
- input: torch.tensor with shape :math:`(B, T, N, 4, 2)`.
+ input: torch.Tensor with shape :math:`(B, T, N, 4, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 4, 2)`.
params: params for the sequence.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -334,7 +334,7 @@ class VideoSequential(ImageSequential):
"""Transform bounding boxes.
Args:
- input: torch.tensor with shape :math:`(B, T, N, 2)`.
+ input: torch.Tensor with shape :math:`(B, T, N, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`.
params: params for the sequence.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -357,7 +357,7 @@ class VideoSequential(ImageSequential):
"""Transform bounding boxes.
Args:
- input: torch.tensor with shape :math:`(B, T, N, 2)`.
+ input: torch.Tensor with shape :math:`(B, T, N, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`.
params: params for the sequence.
extra_args: Optional dictionary of extra arguments with specific options for different input types.
@@ -376,7 +376,7 @@ class VideoSequential(ImageSequential):
) -> torch.Tensor:
"""Inverse transformation.
- Used to inverse a torch.tensor according to the performed transformation by a forward pass, or with respect to
+ Used to inverse a torch.Tensor according to the performed transformation by a forward pass, or with respect to
provided parameters.
"""
if params is None:
@@ -392,7 +392,7 @@ class VideoSequential(ImageSequential):
) -> torch.Tensor:
"""Define the video computation performed."""
if len(input.shape) != 5:
- raise AssertionError(f"Input must be a 5-dim torch.tensor. Got {input.shape}.")
+ raise AssertionError(f"Input must be a 5-dim torch.Tensor. Got {input.shape}.")
if params is None:
self._params = self.forward_parameters(input.shape)
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index be7220d52..4d64bccfe 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -42,7 +42,7 @@ class AffineGenerator(RandomGeneratorBase):
If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.
If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
will be applied. Will not apply shear by default.
- If torch.tensor, shear is a 2x2 torch.tensor, a x-axis shear in (shear[0][0], shear[0][1]) and
+ If torch.Tensor, shear is a 2x2 torch.Tensor, a x-axis shear in (shear[0][0], shear[0][1]) and
y-axis shear in
(shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.
@@ -164,7 +164,7 @@ class AffineGenerator(RandomGeneratorBase):
angle = _adapted_rsampling((batch_size,), self.degree_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- # compute torch.tensor ranges
+ # compute torch.Tensor ranges
if self.scale_2_sampler is not None:
_scale = _adapted_rsampling((batch_size,), self.scale_2_sampler, same_on_batch).unsqueeze(1).repeat(1, 2)
if self.scale_4_sampler is not None:
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index 34a28371e..5e48b654f 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -33,7 +33,7 @@ class CropGenerator(RandomGeneratorBase):
Args:
size (tuple): Desired size of the crop operation, like (h, w).
- If torch.tensor, it must be (B, 2).
+ If torch.Tensor, it must be (B, 2).
resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
Returns:
@@ -82,7 +82,7 @@ class CropGenerator(RandomGeneratorBase):
size = self.size.to(device=_device, dtype=_dtype)
if size.shape != torch.Size([batch_size, 2]):
raise AssertionError(
- "If `size` is a torch.tensor, it must be shaped as (B, 2). "
+ "If `size` is a torch.Tensor, it must be shaped as (B, 2). "
f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
)
if not (input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()):
@@ -290,7 +290,7 @@ def center_crop_generator(
r"""Get parameters for ```center_crop``` transformation for center crop transform.
Args:
- batch_size (int): the torch.tensor batch size.
+ batch_size (int): the torch.Tensor batch size.
height (int) : height of the image.
width (int): width of the image.
size (tuple): Desired output size of the crop, like (h, w).
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index 336ba6352..631f5ac3f 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -124,7 +124,7 @@ class CutmixGenerator(RandomGeneratorBase):
cutmix_betas: torch.Tensor = _adapted_rsampling((batch_size * self.num_mix,), self.beta_sampler, same_on_batch)
- # Note: torch.clamp does not accept torch.tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
+ # Note: torch.clamp does not accept torch.Tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
# Argument 1 to "clamp" of "_TensorBase" has incompatible type "torch.Tensor"; expected "float"
cutmix_betas = torch.min(torch.max(cutmix_betas, self._cut_size[0]), self._cut_size[1])
cutmix_rate = torch.sqrt(1.0 - cutmix_betas) * batch_probs
diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.py
index f9c75792a..26e7176f0 100644
--- a/kornia/augmentation/random_generator/_2d/mosaic.py
+++ b/kornia/augmentation/random_generator/_2d/mosaic.py
@@ -32,14 +32,14 @@ class MosaicGenerator(RandomGeneratorBase):
r"""Generate mixup indexes and lambdas for a batch of inputs.
Args:
- output_size: the output torch.tensor width and height after mosaicing.
+ output_size: the output torch.Tensor width and height after mosaicing.
mosaic_grid: the number of images and image arrangement. e.g. (2, 2) means
each output will mix 4 images in a 2x2 grid.
start_ratio_range: top-left (x, y) position for cropping the mosaic images.
Returns:
A dict of parameters to be passed for transformation.
- - mosaic_ids (torch.Tensor): a shape of (B, N) torch.tensor, torch.where n is the number of mosaic images.
+ - mosaic_ids (torch.Tensor): a shape of (B, N) torch.tensor, where n is the number of mosaic images.
- src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
- batch_shapes (torch.Tensor): image shapes in the batch with a shape of (B, 3).
@@ -109,7 +109,7 @@ class MosaicGenerator(RandomGeneratorBase):
device=_device,
dtype=_dtype,
).repeat(batch_size, 1, 1)
- # NOTE: In case we support a list of torch.tensor images later. For a better consistency.
+ # NOTE: In case we support a list of torch.Tensor images later. For a better consistency.
# B x 3
batch_shapes: torch.Tensor
diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.py
index 780c31e8b..5981f8eb5 100644
--- a/kornia/augmentation/random_generator/_2d/plain_uniform.py
+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py
@@ -35,7 +35,7 @@ class PlainUniformGenerator(RandomGeneratorBase):
Args:
*samplers: a list of tuple in a pattern of ``(factor, name, center, range)``, in which
- the factor can be a two-numbered tuple, or a ``(2,)`` shaped torch torch.tensor. The name
+ the factor can be a two-numbered tuple, or a ``(2,)`` shaped torch torch.Tensor. The name
will be the corresponding key of the returning dict. The center and range must be
both provided worked as a validator to the given factor.
diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.py
index 20768133f..11b1be72b 100644
--- a/kornia/augmentation/random_generator/_2d/posterize.py
+++ b/kornia/augmentation/random_generator/_2d/posterize.py
@@ -59,7 +59,7 @@ class PosterizeGenerator(RandomGeneratorBase):
bits = bits.repeat(2)
bits[1] = 8
elif not (len(bits.size()) == 1 and bits.size(0) == 2):
- raise ValueError(f"'bits' shall be either a scalar or a length 2 torch.tensor. Got {bits}.")
+ raise ValueError(f"'bits' shall be either a scalar or a length 2 torch.Tensor. Got {bits}.")
_joint_range_check(bits, "bits", (0, 8))
self.bit_sampler = UniformDistribution(bits[0], bits[1], validate_args=False)
diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.py
index f17c393ca..d1233cb29 100644
--- a/kornia/augmentation/random_generator/_2d/shear.py
+++ b/kornia/augmentation/random_generator/_2d/shear.py
@@ -35,7 +35,7 @@ class ShearGenerator(RandomGeneratorBase):
If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.
If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
will be applied. Will not apply shear by default.
- If torch.tensor, shear is a 2x2 torch.tensor, a x-axis shear in (shear[0][0], shear[0][1]) and
+ If torch.Tensor, shear is a 2x2 torch.Tensor, a x-axis shear in (shear[0][0], shear[0][1]) and
y-axis shear in
(shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 148b7796c..b78861c58 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -31,7 +31,7 @@ class CropGenerator3D(RandomGeneratorBase):
Args:
size (tuple): Desired size of the crop operation, like (d, h, w).
- If torch.tensor, it must be (B, 3).
+ If torch.Tensor, it must be (B, 3).
resize_to (tuple): Desired output size of the crop, like (d, h, w). If None, no resize will be performed.
Returns:
@@ -75,7 +75,7 @@ class CropGenerator3D(RandomGeneratorBase):
size = self.size.to(device=_device, dtype=_dtype)
if size.shape != torch.Size([batch_size, 3]):
raise AssertionError(
- "If `size` is a torch.tensor, it must be shaped as (B, 3). "
+ "If `size` is a torch.Tensor, it must be shaped as (B, 3). "
f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
)
if not (
@@ -166,7 +166,7 @@ def center_crop_generator3d(
r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
Args:
- batch_size (int): the torch.tensor batch size.
+ batch_size (int): the torch.Tensor batch size.
depth (int) : depth of the image.
height (int) : height of the image.
width (int): width of the image.
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 22a037da6..3be42706b 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -30,7 +30,7 @@ def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:
r"""Validate the 2D input of the wrapped function.
Args:
- f: a function that takes the first argument as torch.tensor.
+ f: a function that takes the first argument as torch.Tensor.
Returns:
the wrapped function after input is validated.
@@ -54,7 +54,7 @@ def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:
r"""Validate the 3D input of the wrapped function.
Args:
- f: a function that takes the first argument as torch.tensor.
+ f: a function that takes the first argument as torch.Tensor.
Returns:
the wrapped function after input is validated.
@@ -79,7 +79,7 @@ def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:
def _infer_batch_shape(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:
r"""Infer input shape.
- Input may be either (torch.tensor,) or (torch.tensor, transform_matrix)
+ Input may be either (torch.Tensor,) or (torch.Tensor, transform_matrix)
"""
if isinstance(input, tuple):
tensor_var = _transform_input(input[0])
@@ -91,7 +91,7 @@ def _infer_batch_shape(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tens
def _infer_batch_shape3d(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:
r"""Infer input shape.
- Input may be either (torch.tensor,) or (torch.tensor, transform_matrix)
+ Input may be either (torch.Tensor,) or (torch.Tensor, transform_matrix)
"""
if isinstance(input, tuple):
tensor_var = _transform_input3d(input[0])
@@ -103,10 +103,10 @@ def _infer_batch_shape3d(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Te
def _transform_input_by_shape(
input: torch.Tensor, reference_shape: torch.Tensor, match_channel: bool = True
) -> torch.Tensor:
- """Reshape an input torch.tensor to have the same dimensions as the reference_shape.
+ """Reshape an input torch.Tensor to have the same dimensions as the reference_shape.
Arguments:
- input: torch.tensor to be transformed
+ input: torch.Tensor to be transformed
reference_shape: shape used as reference
match_channel: if True, C_{src} == C_{ref}. otherwise, no constrain. C =1 by default
@@ -124,9 +124,9 @@ def _transform_input_by_shape(
if match_channel and C:
if not input.shape[-3] == C:
- raise ValueError("The C dimension of torch.tensor did not match with the reference torch.tensor.")
+ raise ValueError("The C dimension of torch.Tensor did not match with the reference torch.Tensor.")
elif match_channel and C is None:
- raise ValueError("The reference torch.tensor do not have a C dimension!")
+ raise ValueError("The reference torch.Tensor do not have a C dimension!")
return input
@@ -134,10 +134,10 @@ def _transform_input_by_shape(
def _transform_input3d_by_shape(
input: torch.Tensor, reference_shape: torch.Tensor, match_channel: bool = True
) -> torch.Tensor:
- """Reshape an input torch.tensor to have the same dimensions as the reference_shape.
+ """Reshape an input torch.Tensor to have the same dimensions as the reference_shape.
Arguments:
- input: torch.tensor to be transformed
+ input: torch.Tensor to be transformed
reference_shape: shape used as reference
match_channel: if True, C_{src} == C_{ref}. otherwise, no constrain. C =1 by default
@@ -155,15 +155,15 @@ def _transform_input3d_by_shape(
if match_channel and C:
if not input.shape[-4] == C:
- raise ValueError("The C dimension of torch.tensor did not match with the reference torch.tensor.")
+ raise ValueError("The C dimension of torch.Tensor did not match with the reference torch.Tensor.")
elif match_channel and C is None:
- raise ValueError("The reference torch.tensor do not have a C dimension!")
+ raise ValueError("The reference torch.Tensor do not have a C dimension!")
return input
def _transform_input(input: torch.Tensor) -> torch.Tensor:
- r"""Reshape an input torch.tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).
+ r"""Reshape an input torch.Tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).
Args:
input: torch.Tensor
@@ -188,7 +188,7 @@ def _transform_input(input: torch.Tensor) -> torch.Tensor:
def _transform_input3d(input: torch.Tensor) -> torch.Tensor:
- r"""Reshape an input torch.tensor to be (*, C, D, H, W). Accept either (D, H, W), (C, D, H, W) or (*, C, D, H, W).
+ r"""Reshape an input torch.Tensor to be (*, C, D, H, W). Accept either (D, H, W), (C, D, H, W) or (*, C, D, H, W).
Args:
input: torch.Tensor
@@ -215,7 +215,7 @@ def _transform_input3d(input: torch.Tensor) -> torch.Tensor:
def _validate_input_dtype(input: torch.Tensor, accepted_dtypes: List[torch.dtype]) -> None:
- r"""Check if the dtype of the input torch.tensor is in the range of accepted_dtypes.
+ r"""Check if the dtype of the input torch.Tensor is in the range of accepted_dtypes.
Args:
input: torch.Tensor
@@ -228,7 +228,7 @@ def _validate_input_dtype(input: torch.Tensor, accepted_dtypes: List[torch.dtype
def _transform_output_shape(
output: torch.Tensor, shape: Tuple[int, ...], *, reference_shape: Optional[torch.Tensor] = None
) -> torch.Tensor:
- r"""Collapse the broadcasted batch dimensions an input torch.tensor to be the specified shape.
+ r"""Collapse the broadcasted batch dimensions an input torch.Tensor to be the specified shape.
Args:
output: torch.Tensor
@@ -253,10 +253,10 @@ 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 torch.tensor is in the range of accepted_dtypes.
+ r"""Check if the dtype of the input torch.Tensor is in the range of accepted_dtypes.
Args:
- shape: torch.tensor shape
+ shape: torch.Tensor shape
required_shapes: List. e.g. ["BCHW", "BCDHW"]
"""
passed = False
@@ -335,8 +335,8 @@ def _adapted_uniform(
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.
- By default, sampling happens on the default device and dtype. If low/high is a torch.tensor,
- sampling will happen in the same device/dtype as low/high torch.tensor.
+ By default, sampling happens on the default device and dtype. If low/high is a torch.Tensor,
+ sampling will happen in the same device/dtype as low/high torch.Tensor.
"""
device, dtype = _extract_device_dtype(
[low if isinstance(low, torch.Tensor) else None, high if isinstance(high, torch.Tensor) else None]
@@ -360,8 +360,8 @@ def _adapted_beta(
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.
- By default, sampling happens on the default device and dtype. If a/b is a torch.tensor,
- sampling will happen in the same device/dtype as a/b torch.tensor.
+ By default, sampling happens on the default device and dtype. If a/b is a torch.Tensor,
+ sampling will happen in the same device/dtype as a/b torch.Tensor.
"""
device, dtype = _extract_device_dtype(
[a if isinstance(a, torch.Tensor) else None, b if isinstance(b, torch.Tensor) else None]
@@ -380,7 +380,7 @@ def _shape_validation(param: torch.Tensor, shape: Union[Tuple[int, ...], List[in
def deepcopy_dict(params: Dict[str, Any]) -> Dict[str, Any]:
"""Perform deep copy on any dict.
- Support torch.tensor copying here.
+ Support torch.Tensor copying here.
"""
out = {}
for k, v in params.items():
@@ -431,25 +431,25 @@ def preprocess_boxes(input: Union[torch.Tensor, Boxes], mode: str = "vertices_pl
See below for more details.
mode: The format in which the boxes are provided.
- * 'xyxy': boxes are assumed to be in the format ``xmin, ymin, xmax, ymax`` torch.where
+ * 'xyxy': boxes are assumed to be in the format ``xmin, ymin, xmax, ymax`` where
``width = xmax - xmin``
and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
- * 'xyxy_plus': similar to 'xyxy' mode but torch.where box width and length are defined as
+ * 'xyxy_plus': similar to 'xyxy' mode but where box width and length are defined as
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.
With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
- * 'xywh': boxes are assumed to be in the format ``xmin, ymin, width, height`` torch.where
+ * 'xywh': boxes are assumed to be in the format ``xmin, ymin, width, height`` where
``width = xmax - xmin`` and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
* 'vertices': boxes are defined by their vertices points in the following ``clockwise`` order:
*top-left, top-right, bottom-right, bottom-left*. Vertices coordinates are in (x,y) order. Finally,
box width and height are defined as ``width = xmax - xmin`` and ``height = ymax - ymin``.
With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
- * 'vertices_plus': similar to 'vertices' mode but torch.where box width and length are defined as
+ * 'vertices_plus': similar to 'vertices' mode but where box width and length are defined as
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. ymin + 1``.
With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
Note:
- **2D boxes format** is defined as a floating data type torch.tensor of shape ``Nx4x2`` or ``BxNx4x2``
- torch.where each box is a `quadrilateral <https://en.wikipedia.org/wiki/Quadrilateral>`_ defined by
+ **2D boxes format** is defined as a floating data type torch.Tensor of shape ``Nx4x2`` or ``BxNx4x2``
+ where each box is a `quadrilateral <https://en.wikipedia.org/wiki/Quadrilateral>`_ defined by
it's 4 vertices
coordinates (A, B, C, D). Coordinates must be in ``x, y`` order. The height and width of a box is defined as
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. Examples of
@@ -460,7 +460,7 @@ def preprocess_boxes(input: Union[torch.Tensor, Boxes], mode: str = "vertices_pl
# input is BxNx4x2 or Boxes.
if isinstance(input, torch.Tensor):
if not (len(input.shape) == 4 and input.shape[2:] == torch.Size([4, 2])):
- raise RuntimeError(f"Only BxNx4x2 torch.tensor is supported. Got {input.shape}.")
+ raise RuntimeError(f"Only BxNx4x2 torch.Tensor is supported. Got {input.shape}.")
input = Boxes.from_tensor(input, mode=mode)
if not isinstance(input, Boxes):
raise RuntimeError(f"Expect `Boxes` type. Got {type(input)}.")
@@ -472,7 +472,7 @@ def preprocess_keypoints(input: Union[torch.Tensor, Keypoints]) -> Keypoints:
# TODO: We may allow list here.
if isinstance(input, torch.Tensor):
if not (len(input.shape) == 3 and input.shape[1:] == torch.Size([2])):
- raise RuntimeError(f"Only BxNx2 torch.tensor is supported. Got {input.shape}.")
+ raise RuntimeError(f"Only BxNx2 torch.Tensor is supported. Got {input.shape}.")
input = Keypoints(input, False)
if isinstance(input, Keypoints):
raise RuntimeError(f"Expect `Keypoints` type. Got {type(input)}.")
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index c81a28461..0e1079ec5 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -82,7 +82,7 @@ def _joint_range_check(ranged_factor: torch.Tensor, name: str, bounds: Optional[
raise ValueError(f"{name}[0] should be smaller than {name}[1] got {ranged_factor}")
else:
raise TypeError(
- f"{name} should be a torch.tensor with length 2 whose values between {bounds}. Got {ranged_factor}."
+ f"{name} should be a torch.Tensor with length 2 whose values between {bounds}. Got {ranged_factor}."
)
@@ -122,7 +122,7 @@ def _tuple_range_reader(
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
- """Given target_size, it will generate the corresponding (target_size, 2) range torch.tensor.
+ """Given target_size, it will generate the corresponding (target_size, 2) range torch.Tensor.
This is for element-wise params.
diff --git a/kornia/color/colormap.py b/kornia/color/colormap.py
index 04bf65a6f..e83520367 100644
--- a/kornia/color/colormap.py
+++ b/kornia/color/colormap.py
@@ -158,14 +158,14 @@ 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) -> torch.Tensor:
- r"""Generate a colormap torch.tensor using interpolation.
+ r"""Generate a colormap torch.Tensor using interpolation.
Args:
base_colormap: A list of RGB colors defining the colormap.
num_colors: Number of colors in the colormap.
Returns:
- A torch.tensor representing the colormap.
+ A torch.Tensor representing the colormap.
"""
tensor_colors = torch.tensor(list(base_colormap), dtype=self._dtype, device=self._device).T
@@ -182,22 +182,22 @@ class ColorMap:
def apply_colormap(input_tensor: torch.Tensor, colormap: ColorMap) -> torch.Tensor:
- r"""Apply to a gray torch.tensor a colormap.
+ r"""Apply to a gray torch.Tensor a colormap.
.. image:: _static/img/apply_colormap.png
Args:
- input_tensor: the input torch.tensor of image.
- colormap: the colormap desired to be applied to the input torch.tensor.
+ input_tensor: the input torch.Tensor of image.
+ colormap: the colormap desired to be applied to the input torch.Tensor.
Returns:
- A RGB torch.tensor with the applied color map into the input_tensor.
+ A RGB torch.Tensor with the applied color map into the input_tensor.
Raises:
ValueError: If `colormap` is not a ColorMap object.
.. note::
- The input torch.tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
+ The input torch.Tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
Example:
>>> input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]])
@@ -223,7 +223,7 @@ def apply_colormap(input_tensor: torch.Tensor, colormap: ColorMap) -> torch.Tens
KORNIA_CHECK(
input_tensor.dtype in valid_types, f"`input_tensor` must be a {valid_types}. Got: {input_tensor.dtype}"
)
- KORNIA_CHECK(len(input_tensor.shape) in (3, 4), "Wrong input torch.tensor dimension.")
+ KORNIA_CHECK(len(input_tensor.shape) in (3, 4), "Wrong input torch.Tensor dimension.")
if len(input_tensor.shape) == 3:
input_tensor = input_tensor.unsqueeze_(0)
@@ -256,13 +256,13 @@ class ApplyColorMap(nn.Module):
dtype: The data type of the generated colormap.
Returns:
- A RGB torch.tensor with the applied color map into the input_tensor
+ A RGB torch.Tensor with the applied color map into the input_tensor
Raises:
ValueError: If `colormap` is not a ColorMap object.
.. note::
- The input torch.tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
+ The input torch.Tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
Example:
>>> input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]])
@@ -290,16 +290,16 @@ class ApplyColorMap(nn.Module):
self.colormap = colormap
def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
- r"""Apply the colormap to the input torch.tensor.
+ r"""Apply the colormap to the input torch.Tensor.
Args:
- input_tensor: The input torch.tensor representing the grayscale image.
+ input_tensor: The input torch.Tensor representing the grayscale image.
.. note::
- The input torch.tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
+ The input torch.Tensor must be integer values in the range of [0-255] or float values in the range of [0-1].
Returns:
- The output torch.tensor representing the image with the applied colormap.
+ The output torch.Tensor representing the image with the applied colormap.
"""
return apply_colormap(input_tensor, self.colormap)
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index 8c5f7331b..be9006c1a 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -34,7 +34,7 @@ def grayscale_to_rgb(image: torch.Tensor) -> torch.Tensor:
The image data is assumed to be in the range of (0, 1).
Args:
- image: grayscale image torch.tensor to be converted to RGB with shape :math:`(*,1,H,W)`.
+ image: grayscale image torch.Tensor to be converted to RGB with shape :math:`(*,1,H,W)`.
Returns:
RGB version of the image with shape :math:`(*,3,H,W)`.
@@ -93,7 +93,7 @@ def rgb_to_grayscale(image: torch.Tensor, rgb_weights: Optional[torch.Tensor] =
else:
raise TypeError(f"Unknown data type: {image.dtype}")
else:
- # is torch.tensor that we make sure is in the same device/dtype
+ # is torch.Tensor that we make sure is in the same device/dtype
rgb_weights = rgb_weights.to(image)
# unpack the color image channels with RGB order
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index 109086fd2..ef2783025 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -63,8 +63,8 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
s = maxc - minc
# weird behaviour with undefined vars in JIT...
# scripting requires image_hls be defined even if it is not used :S
- h = l_ # assign to any torch.tensor...
- image_hls = l_ # assign to any torch.tensor...
+ h = l_ # assign to any torch.Tensor...
+ image_hls = l_ # assign to any torch.Tensor...
else:
# define the resulting image to avoid the torch.stack([h, l, s])
# so, h, l and s require inplace operations
@@ -81,7 +81,7 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
# precompute image / (max - min)
im = image / (s + eps).unsqueeze(-3)
- # epsilon cannot be inside the torch.where to avoid precision issues
+ # epsilon cannot be inside the where to avoid precision issues
s /= torch.where(l_ < 1.0, l_, 2.0 - l_) + eps # saturation
l_ /= 2 # luminance
diff --git a/kornia/color/raw.py b/kornia/color/raw.py
index f8766d4d7..10100ab7a 100644
--- a/kornia/color/raw.py
+++ b/kornia/color/raw.py
@@ -36,7 +36,7 @@ class CFA(Enum):
On top of this care is taken to make it reversible going raw -> rgb -> raw. the raw samples remain intact
during conversion and only unknown samples are interpolated.
- The names are based on the OpenCV convention torch.where the BG indicates pixel 1,1 (counting from 0,0) is
+ The names are based on the OpenCV convention where the BG indicates pixel 1,1 (counting from 0,0) is
blue and its neighbour to the right is green. In that case the top left pixel is red. Other options are GB, RG and
GR
@@ -110,7 +110,7 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
raise ValueError(f"Unsupported CFA Got {cfa}.")
# upscaling r and b with bi-linear gives reasonable quality
- # Note that depending on torch.where these are sampled we need to F.pad appropriately
+ # Note that depending on where these are sampled we need to F.pad appropriately
# the bilinear filter will pretty much be based on for example this layout (RG)
# (which needs to be padded bottom right)
# +-+-+
@@ -212,7 +212,7 @@ def rgb_to_raw(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- # pick the torch.tensor with green pixels
+ # pick the torch.Tensor with green pixels
# clone to make sure grad works
output: torch.Tensor = image[..., 1:2, :, :].clone()
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index 7eba91a36..273ae6ed4 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -119,7 +119,7 @@ def bgr_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> t
Args:
image: BGR Image to be converted to RGBA of shape :math:`(*,3,H,W)`.
- alpha_val: A float number for the alpha value or a torch.tensor
+ alpha_val: A float number for the alpha value or a torch.Tensor
of shape :math:`(*,1,H,W)`.
Returns:
@@ -155,8 +155,8 @@ def rgba_to_rgb(image: torch.Tensor, background_color: Optional[torch.Tensor] =
Args:
image: The RGBA image to be converted, with shape :math:`(*,4,H,W)`.
background_color: An optional background color. It can be a *tuple or list* of 3 floats,
- a torch.tensor of shape :math:`(*,3,H,W)` for a per-pixel background, or a broadcastable
- torch.tensor (e.g., :math:`(*,3,1,1)`). If None, a white background is used.
+ a torch.Tensor of shape :math:`(*,3,H,W)` for a per-pixel background, or a broadcastable
+ torch.Tensor (e.g., :math:`(*,3,1,1)`). If None, a white background is used.
Returns:
The converted RGB image with shape :math:`(*,3,H,W)`.
@@ -188,7 +188,7 @@ def rgba_to_rgb(image: torch.Tensor, background_color: Optional[torch.Tensor] =
elif isinstance(background_color, torch.Tensor):
if background_color.shape[-3] != 3:
raise ValueError(
- f"background_color torch.tensor must have 3 channels in dimension -3. "
+ f"background_color torch.Tensor must have 3 channels in dimension -3. "
f"Got shape {background_color.shape}"
)
background_rgb = background_color
@@ -415,7 +415,7 @@ class RgbToRgba(nn.Module):
Add an alpha channel to existing RGB image.
Args:
- alpha_val: A float number for the alpha value or a torch.tensor
+ alpha_val: A float number for the alpha value or a torch.Tensor
of shape :math:`(*,1,H,W)`.
Returns:
@@ -451,7 +451,7 @@ class BgrToRgba(nn.Module):
Add an alpha channel to existing RGB image.
Args:
- alpha_val: A float number for the alpha value or a torch.tensor
+ alpha_val: A float number for the alpha value or a torch.Tensor
of shape :math:`(*,1,H,W)`.
Returns:
diff --git a/kornia/color/sepia.py b/kornia/color/sepia.py
index 36d27c5c4..7a98b3f04 100644
--- a/kornia/color/sepia.py
+++ b/kornia/color/sepia.py
@@ -20,11 +20,11 @@ from torch import nn
def sepia_from_rgb(input: torch.Tensor, rescale: bool = True, eps: float = 1e-6) -> torch.Tensor:
- r"""Apply to a torch.tensor the sepia filter.
+ r"""Apply to a torch.Tensor the sepia filter.
Args:
- input: the input torch.tensor with shape of :math:`(*, C, H, W)`.
- rescale: If True, the output torch.tensor will be rescaled (max values be 1. or 255).
+ input: the input torch.Tensor with shape of :math:`(*, C, H, W)`.
+ rescale: If True, the output torch.Tensor will be rescaled (max values be 1. or 255).
eps: scalar to enforce numerical stability.
Returns:
@@ -65,8 +65,8 @@ class Sepia(nn.Module):
r"""nn.Module that apply the sepia filter to tensors.
Args:
- input: the input torch.tensor with shape of :math:`(*, C, H, W)`.
- rescale: If True, the output torch.tensor will be rescaled (max values be 1. or 255).
+ input: the input torch.Tensor with shape of :math:`(*, C, H, W)`.
+ rescale: If True, the output torch.Tensor will be rescaled (max values be 1. or 255).
eps: scalar to enforce numerical stability.
Returns:
diff --git a/kornia/color/yuv.py b/kornia/color/yuv.py
index 377a54a06..1da2c11b7 100644
--- a/kornia/color/yuv.py
+++ b/kornia/color/yuv.py
@@ -241,7 +241,7 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:
[imagey, imageuv.repeat_interleave(2, dim=-1).repeat_interleave(2, dim=-2)],
dim=-3,
)
- # then convert the yuv444 torch.tensor
+ # then convert the yuv444 torch.Tensor
return yuv_to_rgb(yuv444image)
@@ -293,7 +293,7 @@ def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:
# first upsample
yuv444image = torch.cat([imagey, imageuv.repeat_interleave(2, dim=-1)], dim=-3)
- # then convert the yuv444 torch.tensor
+ # then convert the yuv444 torch.Tensor
return yuv_to_rgb(yuv444image)
diff --git a/kornia/contrib/boxmot_tracker.py b/kornia/contrib/boxmot_tracker.py
index eed984e00..a6a351d62 100644
--- a/kornia/contrib/boxmot_tracker.py
+++ b/kornia/contrib/boxmot_tracker.py
@@ -116,7 +116,7 @@ class BoxMotTracker:
"""
if not (image.ndim == 4 and image.shape[0] == 1) and not image.ndim == 3:
- raise ValueError(f"Input torch.tensor must be of shape (1, 3, H, W) or (3, H, W). Got {image.shape}")
+ raise ValueError(f"Input torch.Tensor must be of shape (1, 3, H, W) or (3, H, W). Got {image.shape}")
if image.ndim == 3:
image = image.unsqueeze(0)
diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.py
index 1727c3ee6..b95da88c3 100644
--- a/kornia/contrib/diamond_square.py
+++ b/kornia/contrib/diamond_square.py
@@ -45,8 +45,8 @@ def _diamond_square_seed(
width: the expected image width.
height: the expected image height.
random_fn: the random function to generate the image seed.
- device: the torch device torch.where to create the image seed.
- dtype: the torch dtype torch.where to create the image seed.
+ device: the torch device where to create the image seed.
+ dtype: the torch dtype where to create the image seed.
Return:
the generated image seed of size Bx1xHxW.
@@ -103,7 +103,7 @@ def _one_diamond_one_square(
If this function is run in the usual sense, it is more efficient if it is run in a no_grad()
Args:
- img: a 4D torch.tensor torch.where dimensions are Batch, Channel, Width, Height.
+ img: a 4D torch.Tensor where dimensions are Batch, Channel, Width, Height.
Width and Height must both be 2^N+1 and
Batch and Channels should in the usual case be 1.
random_scale: a float number in [0,1] controlling the randomness created pixels get. I the usual case, it is
@@ -113,7 +113,7 @@ def _one_diamond_one_square(
square_kernel: the 3x3 kernel to perform the square step.
Return:
- A torch.tensor on the same device as img with the same channels as img and width, height of 2^(N+1)+1.
+ A torch.Tensor on the same device as img with the same channels as img and width, height of 2^(N+1)+1.
"""
KORNIA_CHECK_SHAPE(img, ["B", "C", "H", "W"])
@@ -173,14 +173,14 @@ def diamond_square(
output_size: a tuple of integers with the BxCxHxW of the image to be generated.
roughness: the scale value to apply at each recursion step.
random_scale: the initial value of the scale for recursion.
- random_fn: the callable function to use to sample a random torch.tensor.
+ random_fn: the callable function to use to sample a random torch.Tensor.
normalize_range: whether to F.normalize using min-max the output map. In case of a
range is specified, min-max norm is applied between the provided range.
device: the torch device to place the output map.
dtype: the torch dtype to place the output map.
Returns:
- A torch.tensor with shape :math:`(B,C,H,W)` containing the fractal image.
+ A torch.Tensor with shape :math:`(B,C,H,W)` containing the fractal image.
"""
KORNIA_CHECK(len(output_size) == 4, "output_size must be (B,C,H,W)")
diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.py
index 85fc89860..717b5bb5b 100644
--- a/kornia/contrib/edge_detection.py
+++ b/kornia/contrib/edge_detection.py
@@ -108,7 +108,7 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.
Returns:
- output torch.tensor.
+ output torch.Tensor.
"""
images, image_sizes = self.pre_processor(images)
@@ -124,12 +124,12 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
"""Draw the edge detection results.
Args:
- images: input torch.tensor.
+ images: input torch.Tensor.
edge_maps: detected edges.
output_type: type of the output.
Returns:
- output torch.tensor.
+ output torch.Tensor.
"""
if edge_maps is None:
@@ -150,13 +150,13 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
"""Save the edge detection results.
Args:
- images: input torch.tensor.
+ images: input torch.Tensor.
edge_maps: detected edges.
output_type: type of the output.
- directory: torch.where to save outputs.
+ directory: where to save outputs.
Returns:
- output torch.tensor.
+ output torch.Tensor.
"""
outputs = self.visualize(images, edge_maps, output_type)
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 0a626edfb..6c9b33546 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -58,7 +58,7 @@ def compute_padding(
:func:`combine_tensor_patches` produces expected result.
Args:
- original_size: the size of the original torch.tensor.
+ original_size: the size of the original torch.Tensor.
window_size: the size of the sliding window used while extracting patches.
stride: The stride of the sliding window. Optional: if not specified, window_size will be used.
@@ -123,7 +123,7 @@ class ExtractTensorPatches(nn.Module):
In the simplest case, the output value of the operator with input size
:math:`(B, C, H, W)` is :math:`(B, N, C, H_{out}, W_{out})`.
- torch.where
+ where
- :math:`B` is the batch size.
- :math:`N` denotes the total number of extracted patches stacked in
- :math:`C` denotes the number of input channels.
@@ -133,7 +133,7 @@ class ExtractTensorPatches(nn.Module):
left-right and top-bottom order.
* :attr:`window_size` is the size of the sliding window and controls the
- shape of the output torch.tensor and defines the shape of the output patch.
+ shape of the output torch.Tensor and defines the shape of the output patch.
* :attr:`stride` controls the stride to apply to the sliding window and
regulates the overlapping between the extracted patches.
* :attr:`padding` controls the amount of implicit torch.zeros-paddings on both
@@ -154,7 +154,7 @@ class ExtractTensorPatches(nn.Module):
the width dimension.
Args:
- input: torch.tensor image torch.where to extract the patches with shape :math:`(B, C, H, W)`.
+ input: torch.Tensor image where to extract the patches with shape :math:`(B, C, H, W)`.
window_size: the size of the sliding window and the output patch size.
stride: stride of the sliding window.
padding: Zero-padding added to both side of the input.
@@ -165,7 +165,7 @@ class ExtractTensorPatches(nn.Module):
- Output: :math:`(B, N, C, H_{out}, W_{out})`
Returns:
- the torch.tensor with the extracted patches.
+ the torch.Tensor with the extracted patches.
Examples:
>>> input = torch.arange(9.).view(1, 1, 3, 3)
@@ -209,7 +209,7 @@ class CombineTensorPatches(nn.Module):
In the simplest case, the output value of the operator with input size
:math:`(B, N, C, H_{out}, W_{out})` is :math:`(B, C, H, W)`.
- torch.where
+ where
- :math:`B` is the batch size.
- :math:`N` denotes the total number of extracted patches stacked in
- :math:`C` denotes the number of input channels.
@@ -220,13 +220,13 @@ class CombineTensorPatches(nn.Module):
* :attr:`original_size` is the size of the original image prior to
- extracting torch.tensor patches and defines the shape of the output patch.
+ extracting torch.Tensor patches and defines the shape of the output patch.
* :attr:`window_size` is the size of the sliding window used while
- extracting torch.tensor patches.
+ extracting torch.Tensor patches.
* :attr:`stride` controls the stride to apply to the sliding window and
regulates the overlapping between the extracted patches.
* :attr:`unpadding` is the amount of padding to be removed. If specified,
- this value must be the same as padding used while extracting torch.tensor patches.
+ this value must be the same as padding used while extracting torch.Tensor patches.
* :attr:`allow_auto_unpadding` allows automatic calculation of the padding required
to fit the window and stride into the image. This must be used if the
`allow_auto_padding` flag was used for extracting the patches.
@@ -245,8 +245,8 @@ class CombineTensorPatches(nn.Module):
the width dimension.
Args:
- patches: patched torch.tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.
- original_size: the size of the original torch.tensor and the output size.
+ patches: patched torch.Tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.
+ original_size: the size of the original torch.Tensor and the output size.
window_size: the size of the sliding window used while extracting patches.
stride: stride of the sliding window.
unpadding: remove the padding added to both side of the input.
@@ -324,8 +324,8 @@ def combine_tensor_patches(
See :class:`~kornia.contrib.CombineTensorPatches` for details.
Args:
- patches: patched torch.tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.
- original_size: the size of the original torch.tensor and the output size.
+ patches: patched torch.Tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.
+ original_size: the size of the original torch.Tensor and the output size.
window_size: the size of the sliding window used while extracting patches.
stride: stride of the sliding window.
unpadding: remove the padding added to both side of the input.
@@ -334,7 +334,7 @@ def combine_tensor_patches(
eps: small value used to prevent division by zero.
Return:
- The combined patches in an image torch.tensor with shape :math:`(B, C, H, W)`.
+ The combined patches in an image torch.Tensor with shape :math:`(B, C, H, W)`.
Example:
>>> out = extract_tensor_patches(torch.arange(16).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2))
@@ -409,7 +409,7 @@ def combine_tensor_patches(
if unpadding:
norm_map = F.pad(norm_map, [-i for i in unpadding])
- # Restored torch.tensor
+ # Restored torch.Tensor
saturated_restored_tensor = F.fold(input=patches, output_size=restored_size, kernel_size=window_size, stride=stride)
if unpadding:
saturated_restored_tensor = F.pad(saturated_restored_tensor, [-i for i in unpadding])
@@ -444,14 +444,14 @@ def extract_tensor_patches(
See :class:`~kornia.contrib.ExtractTensorPatches` for details.
Args:
- input: torch.tensor image torch.where to extract the patches with shape :math:`(B, C, H, W)`.
+ input: torch.Tensor image where to extract the patches with shape :math:`(B, C, H, W)`.
window_size: the size of the sliding window and the output patch size.
stride: stride of the sliding window.
padding: Zero-padding added to both side of the input.
allow_auto_padding: whether to allow automatic padding if the window and stride do not fit into the image.
Returns:
- the torch.tensor with the extracted patches with shape :math:`(B, N, C, H_{out}, W_{out})`.
+ the torch.Tensor with the extracted patches with shape :math:`(B, N, C, H_{out}, W_{out})`.
Examples:
>>> input = torch.arange(9.).view(1, 1, 3, 3)
diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.py
index 6d9bff2de..2301ee12b 100644
--- a/kornia/contrib/kmeans.py
+++ b/kornia/contrib/kmeans.py
@@ -30,7 +30,7 @@ class KMeans:
Args:
num_clusters: number of clusters the data has to be assigned to
- cluster_centers: torch.tensor of starting cluster centres can be passed instead of num_clusters
+ cluster_centers: torch.Tensor of starting cluster centres can be passed instead of num_clusters
tolerance: float value. the algorithm terminates if the shift in centers is less than tolerance
max_iterations: number of iterations to run the algorithm for
seed: number to set torch manual seed for reproducibility
@@ -87,7 +87,7 @@ class KMeans:
"""Chooses num_cluster points from X as the initial cluster centers.
Args:
- X: 2D input torch.tensor to be clustered
+ X: 2D input torch.Tensor to be clustered
num_clusters: number of desired cluster centers
Returns:
@@ -104,11 +104,11 @@ class KMeans:
"""Compute pairwise squared distance between 2 sets of vectors.
Args:
- data1: 2D torch.tensor of shape N, D
- data2: 2D torch.tensor of shape C, D
+ data1: 2D torch.Tensor of shape N, D
+ data2: 2D torch.Tensor of shape C, D
Returns:
- 2D torch.tensor of shape N, C
+ 2D torch.Tensor of shape N, C
"""
# N*1*D
@@ -123,7 +123,7 @@ class KMeans:
have reached.
Args:
- X: 2D input torch.tensor to be clustered
+ X: 2D input torch.Tensor to be clustered
""" # noqa: D205
# X should have only 2 dimensions
@@ -180,10 +180,10 @@ class KMeans:
"""Find the cluster center closest to each point in x.
Args:
- x: 2D torch.tensor
+ x: 2D torch.Tensor
Returns:
- 1D torch.tensor containing cluster id assigned to each data point in x
+ 1D torch.Tensor containing cluster id assigned to each data point in x
"""
# x and cluster_centers should have same number of columns
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 608b5b52f..9a5f3dda1 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -93,10 +93,10 @@ class ObjectDetectorResult:
def results_from_detections(
detections: torch.Tensor, format: str | BoundingBoxDataFormat
) -> list[ObjectDetectorResult]:
- """Convert a detection torch.tensor to a list of :py:class:`ObjectDetectorResult`.
+ """Convert a detection torch.Tensor to a list of :py:class:`ObjectDetectorResult`.
Args:
- detections: torch.tensor with shape :math:`(D, 6)`, torch.where :math:`D` is the number of
+ detections: torch.Tensor with shape :math:`(D, 6)`, where :math:`D` is the number of
detections in the given image,
:math:`6` represents class id, score, and `xywh` bounding box.
format: detection format.
@@ -172,7 +172,7 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
Returns:
list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`,
- torch.where :math:`D` is the
+ where :math:`D` is the
number of detections in the given image, :math:`6` represents class id, score, and `xywh` bounding box.
"""
@@ -213,8 +213,8 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
"""Save the output image(s) to a directory.
Args:
- images: input torch.tensor.
- detections: detection torch.tensor.
+ images: input torch.Tensor.
+ detections: detection torch.Tensor.
directory: directory to save the images.
"""
@@ -335,16 +335,16 @@ class BoxFiltering(nn.Module, ONNXExportMixin):
To be ONNX-friendly, the inputs for direct forwarding need to be all tensors.
Args:
- boxes: [B, D, 6], torch.where B is the batchsize, D is the number of detections in the image,
+ boxes: [B, D, 6], where B is the batchsize, D is the number of detections in the image,
6 represent (class_id, confidence_score, x, y, w, h).
confidence_threshold: an 0-d scalar that represents the desired threshold.
- classes_to_keep: a 1-d torch.tensor of classes to keep. If None, keep all classes.
+ classes_to_keep: a 1-d torch.Tensor of classes to keep. If None, keep all classes.
Returns:
Union[torch.Tensor, List[torch.Tensor]]
- If `filter_as_zero` is True, return a torch.tensor of shape [D, 6], torch.where D is the total number of
+ If `filter_as_zero` is True, return a torch.Tensor of shape [D, 6], where D is the total number of
detections as input.
- If `filter_as_zero` is False, return a list of tensors of shape [D, 6], torch.where D is the number of
+ If `filter_as_zero` is False, return a list of tensors of shape [D, 6], where D is the number of
valid detections for each element in the batch.
"""
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index 6149b5c38..a5d4b9605 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -57,7 +57,7 @@ class SuperResolution(ModelBase, ONNXExportMixin):
If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.
Returns:
- output torch.tensor.
+ output torch.Tensor.
"""
output = self.pre_processor(images)
@@ -80,12 +80,12 @@ class SuperResolution(ModelBase, ONNXExportMixin):
"""Draw the super resolution results.
Args:
- images: input torch.tensor.
+ images: input torch.Tensor.
edge_maps: detected edges.
output_type: type of the output.
Returns:
- output torch.tensor.
+ output torch.Tensor.
"""
if edge_maps is None:
@@ -106,14 +106,14 @@ class SuperResolution(ModelBase, ONNXExportMixin):
"""Save the super resolution results.
Args:
- images: input torch.tensor.
+ images: input torch.Tensor.
edge_maps: detected edges.
output_type: type of the output.
- directory: torch.where to save outputs.
+ directory: where to save outputs.
output_type: backend used to generate outputs.
Returns:
- output torch.tensor.
+ output torch.Tensor.
"""
outputs = self.visualize(images, edge_maps, output_type)
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 72cc290d3..c56949a56 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -103,13 +103,13 @@ class VisualPrompter:
def preprocess_image(
self, x: torch.Tensor, mean: Optional[torch.Tensor] = None, std: Optional[torch.Tensor] = None
) -> torch.Tensor:
- """Normalize and F.pad a torch.tensor.
+ """Normalize and F.pad a torch.Tensor.
For F.normalize the tensor: will prioritize the `mean` and `std` passed as argument,
if None will use the default
Sam Dataset values.
- For F.pad the tensor: Will F.pad the torch.tensor into the right and bottom to match with the size of
+ For F.pad the tensor: Will F.pad the torch.Tensor into the right and bottom to match with the size of
`self.model.image_encoder.img_size`
Args:
@@ -202,7 +202,7 @@ class VisualPrompter:
if data_keys is None:
data_keys = []
- # prevent unpacking torch.tensor when creating the output dict (issue #2627)
+ # prevent unpacking torch.Tensor when creating the output dict (issue #2627)
if not isinstance(transformed_prompts, (list, tuple)):
transformed_prompts = [transformed_prompts]
return {key: transformed_prompts[idx] for idx, key in enumerate(data_keys)}
@@ -267,9 +267,9 @@ class VisualPrompter:
keypoints_labels: Labels for the point prompts. 1 indicates a foreground point and 0 indicates a background
point. Shape :math:`(K, N)`. Where `N` is the number of points, and `K` the number of
prompts.
- boxes: A box prompt to the model. If a torch.tensor, should be in a xyxy mode. Shape :math:`(K, 4)`
+ boxes: A box prompt to the model. If a torch.Tensor, should be in a xyxy mode. Shape :math:`(K, 4)`
masks: A low resolution mask input to the model, typically coming from a previous prediction
- iteration. Has shape :math:`(K, 1, H, W)`, torch.where for SAM, H=W=256.
+ iteration. Has shape :math:`(K, 1, H, W)`, where for SAM, H=W=256.
multimask_output: If true, the model will return three masks. For ambiguous input prompts (such as a
single click), this will often produce better masks than a single prediction. If only
a single mask is needed, the model's predicted quality score can be used to select the
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 55be0f02c..193e7d3f5 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -43,7 +43,7 @@ def adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
if isinstance(factor, float):
- # TODO: figure out how to create later a torch.tensor without importing torch
+ # TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
@@ -101,7 +101,7 @@ def adjust_saturation_with_gray_subtraction(image: torch.Tensor, factor: Union[f
return image
if isinstance(factor, float):
- # TODO: figure out how to create later a torch.tensor without importing torch
+ # TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
@@ -314,11 +314,11 @@ def adjust_gamma(
def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], clip_output: bool = True) -> torch.Tensor:
- r"""Adjust the contrast of an image torch.tensor.
+ r"""Adjust the contrast of an image torch.Tensor.
.. image:: _static/img/adjust_contrast.png
- This implementation follows Szeliski's book convention, torch.where contrast is defined as
+ This implementation follows Szeliski's book convention, where contrast is defined as
a `multiplicative` operation directly to raw pixel values. Beware that other frameworks
might use different conventions which can be difficult to reproduce exact results.
@@ -360,7 +360,7 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
if isinstance(factor, float):
- # TODO: figure out how to create later a torch.tensor without importing torch
+ # TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
@@ -382,7 +382,7 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
def adjust_contrast_with_mean_subtraction(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
- r"""Adjust the contrast of an image torch.tensor by subtracting the mean over channels.
+ r"""Adjust the contrast of an image torch.Tensor by subtracting the mean over channels.
.. note::
this is just a convenience function to have compatibility with Pil. For exact
@@ -415,7 +415,7 @@ def adjust_contrast_with_mean_subtraction(image: torch.Tensor, factor: Union[flo
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
if isinstance(factor, float):
- # TODO: figure out how to create later a torch.tensor without importing torch
+ # TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
@@ -442,11 +442,11 @@ def adjust_contrast_with_mean_subtraction(image: torch.Tensor, factor: Union[flo
def adjust_brightness(
image: torch.Tensor, factor: Union[float, torch.Tensor], clip_output: bool = True
) -> torch.Tensor:
- r"""Adjust the brightness of an image torch.tensor.
+ r"""Adjust the brightness of an image torch.Tensor.
.. image:: _static/img/adjust_brightness.png
- This implementation follows Szeliski's book convention, torch.where brightness is defined as
+ This implementation follows Szeliski's book convention, where brightness is defined as
an `additive` operation directly to raw pixel and shift its values according the applied
factor and range of the image values. Beware that other framework might use different
conventions which can be difficult to reproduce exact results.
@@ -468,7 +468,7 @@ def adjust_brightness(
clip_output: Whether to clip output to be in [0,1].
Return:
- Adjusted torch.tensor in the shape of :math:`(*, H, W)`.
+ Adjusted torch.Tensor in the shape of :math:`(*, H, W)`.
.. note::
See a working example `here <https://kornia.github.io/tutorials/nbs/image_enhancement.html>`__.
@@ -488,9 +488,9 @@ def adjust_brightness(
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
- # convert factor to a torch.tensor
+ # convert factor to a torch.Tensor
if isinstance(factor, float):
- # TODO: figure out how to create later a torch.tensor without importing torch
+ # TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
@@ -512,7 +512,7 @@ def adjust_brightness(
def adjust_brightness_accumulative(
image: torch.Tensor, factor: Union[float, torch.Tensor], clip_output: bool = True
) -> torch.Tensor:
- r"""Adjust the brightness accumulatively of an image torch.tensor.
+ r"""Adjust the brightness accumulatively of an image torch.Tensor.
This implementation follows PIL convention.
@@ -526,7 +526,7 @@ def adjust_brightness_accumulative(
clip_output: Whether to clip output to be in [0,1].
Return:
- Adjusted torch.tensor in the shape of :math:`(*, H, W)`.
+ Adjusted torch.Tensor in the shape of :math:`(*, H, W)`.
Example:
>>> x = torch.ones(1, 1, 2, 2)
@@ -543,9 +543,9 @@ def adjust_brightness_accumulative(
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
- # convert factor to a torch.tensor
+ # convert factor to a torch.Tensor
if isinstance(factor, float):
- # TODO: figure out how to create later a torch.tensor without importing torch
+ # TODO: figure out how to create later a torch.Tensor without importing torch
factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)
elif isinstance(factor, torch.Tensor):
factor = factor.to(image.device, image.dtype)
@@ -565,7 +565,7 @@ def adjust_brightness_accumulative(
def adjust_sigmoid(image: torch.Tensor, cutoff: float = 0.5, gain: float = 10, inv: bool = False) -> torch.Tensor:
- """Adjust sigmoid correction on the input image torch.tensor.
+ """Adjust sigmoid correction on the input image torch.Tensor.
The input image is expected to be in the range of [0, 1].
@@ -580,7 +580,7 @@ def adjust_sigmoid(image: torch.Tensor, cutoff: float = 0.5, gain: float = 10, i
inv: If is set to True the function will return the inverse sigmoid correction.
Returns:
- Adjusted torch.tensor in the shape of :math:`(*, H, W)`.
+ Adjusted torch.Tensor in the shape of :math:`(*, H, W)`.
Example:
>>> x = torch.ones(1, 1, 2, 2)
@@ -599,7 +599,7 @@ def adjust_sigmoid(image: torch.Tensor, cutoff: float = 0.5, gain: float = 10, i
def adjust_log(image: torch.Tensor, gain: float = 1, inv: bool = False, clip_output: bool = True) -> torch.Tensor:
- """Adjust log correction on the input image torch.tensor.
+ """Adjust log correction on the input image torch.Tensor.
The input image is expected to be in the range of [0, 1].
@@ -613,7 +613,7 @@ def adjust_log(image: torch.Tensor, gain: float = 1, inv: bool = False, clip_out
clip_output: Whether to clip the output image with range of [0, 1].
Returns:
- Adjusted torch.tensor in the shape of :math:`(*, H, W)`.
+ Adjusted torch.Tensor in the shape of :math:`(*, H, W)`.
Example:
>>> x = torch.zeros(1, 1, 2, 2)
@@ -644,8 +644,8 @@ def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5)
Args:
input: image or batched images to solarize.
thresholds: solarize thresholds.
- If int or one element torch.tensor, input will be solarized across the whole batch.
- If 1-d torch.tensor, input will be solarized element-wise, len(thresholds) == len(input).
+ If int or one element torch.Tensor, input will be solarized across the whole batch.
+ If 1-d torch.Tensor, input will be solarized element-wise, len(thresholds) == len(input).
Returns:
Solarized images.
@@ -680,14 +680,14 @@ def solarize(
The value of 'addition' is between -0.5 and 0.5.
Args:
- input: image torch.tensor with shapes like :math:`(*, C, H, W)` to solarize.
+ input: image torch.Tensor with shapes like :math:`(*, C, H, W)` to solarize.
thresholds: solarize thresholds.
- If int or one element torch.tensor, input will be solarized across the whole batch.
- If 1-d torch.tensor, input will be solarized element-wise, len(thresholds) == len(input).
+ If int or one element torch.Tensor, input will be solarized across the whole batch.
+ If 1-d torch.Tensor, input will be solarized element-wise, len(thresholds) == len(input).
additions: between -0.5 and 0.5.
If None, no addition will be performed.
- If int or one element torch.tensor, same addition will be added across the whole batch.
- If 1-d torch.tensor, additions will be added element-wisely, len(additions) == len(input).
+ If int or one element torch.Tensor, same addition will be added across the whole batch.
+ If 1-d torch.Tensor, additions will be added element-wisely, len(additions) == len(input).
Returns:
The solarized images with shape :math:`(*, C, H, W)`.
@@ -745,11 +745,11 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
Non-differentiable function, ``torch.uint8`` involved.
Args:
- input: image torch.tensor with shape :math:`(*, C, H, W)` to posterize.
+ input: image torch.Tensor with shape :math:`(*, C, H, W)` to posterize.
bits: number of high bits. Must be in range [0, 8].
- If int or one element torch.tensor, input will be posterized by this bits.
- If 1-d torch.tensor, input will be posterized element-wisely, len(bits) == input.shape[-3].
- If n-d torch.tensor, input will be posterized element-channel-wisely,
+ If int or one element torch.Tensor, input will be posterized by this bits.
+ If 1-d torch.Tensor, input will be posterized element-wisely, len(bits) == input.shape[-3].
+ If n-d torch.Tensor, input will be posterized element-channel-wisely,
bits.shape == input.shape[:len(bits.shape)]
Returns:
@@ -828,7 +828,7 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
@perform_keep_shape_image
def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
- r"""Apply sharpness to the input torch.tensor.
+ r"""Apply sharpness to the input torch.Tensor.
.. image:: _static/img/sharpness.png
@@ -836,10 +836,10 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L326
Args:
- input: image torch.tensor with shape :math:`(*, C, H, W)` to sharpen.
+ input: image torch.Tensor with shape :math:`(*, C, H, W)` to sharpen.
factor: factor of sharpness strength. Must be above 0.
- If float or one element torch.tensor, input will be sharpened by the same factor across the whole batch.
- If 1-d torch.tensor, input will be sharpened element-wisely, len(factor) == len(input).
+ If float or one element torch.Tensor, input will be sharpened by the same factor across the whole batch.
+ If 1-d torch.Tensor, input will be sharpened element-wisely, len(factor) == len(input).
Returns:
Sharpened image or images with shape :math:`(*, C, H, W)`.
@@ -855,7 +855,7 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
if len(factor.size()) != 0 and factor.shape != torch.Size([input.size(0)]):
raise AssertionError(
- "Input batch size shall match with factor size if factor is not a 0-dim torch.tensor. "
+ "Input batch size shall match with factor size if factor is not a 0-dim torch.Tensor. "
f"Got {input.size(0)} and {factor.shape}"
)
@@ -886,21 +886,21 @@ def _blend_one(input1: torch.Tensor, input2: torch.Tensor, factor: torch.Tensor)
r"""Blend two images into one.
Args:
- input1: image torch.tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
- input2: image torch.tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
- factor: factor 0-dim torch.tensor.
+ input1: image torch.Tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
+ input2: image torch.Tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
+ factor: factor 0-dim torch.Tensor.
Returns:
- : image torch.tensor with the batch in the zero position.
+ : image torch.Tensor with the batch in the zero position.
"""
if not isinstance(input1, torch.Tensor):
- raise AssertionError(f"`input1` must be a torch.tensor. Got {input1}.")
+ raise AssertionError(f"`input1` must be a torch.Tensor. Got {input1}.")
if not isinstance(input2, torch.Tensor):
- raise AssertionError(f"`input1` must be a torch.tensor. Got {input2}.")
+ raise AssertionError(f"`input1` must be a torch.Tensor. Got {input2}.")
if isinstance(factor, torch.Tensor) and len(factor.size()) != 0:
- raise AssertionError(f"Factor shall be a float or single element torch.tensor. Got {factor}.")
+ raise AssertionError(f"Factor shall be a float or single element torch.Tensor. Got {factor}.")
if factor == 0.0:
return input1
if factor == 1.0:
@@ -929,24 +929,24 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:
r"""Scale the data in the channel to implement equalize.
Args:
- im: image torch.tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
+ im: image torch.Tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
Returns:
- image torch.tensor with the batch in the zero position.
+ image torch.Tensor with the batch in the zero position.
"""
min_ = im.min()
max_ = im.max()
if min_.item() < 0.0 and not torch.isclose(min_, torch.as_tensor(0.0, dtype=min_.dtype)):
- raise ValueError(f"Values in the input torch.tensor must greater or equal to 0.0. Found {min_.item()}.")
+ raise ValueError(f"Values in the input torch.Tensor must greater or equal to 0.0. Found {min_.item()}.")
if max_.item() > 1.0 and not torch.isclose(max_, torch.as_tensor(1.0, dtype=max_.dtype)):
- raise ValueError(f"Values in the input torch.tensor must lower or equal to 1.0. Found {max_.item()}.")
+ raise ValueError(f"Values in the input torch.Tensor must lower or equal to 1.0. Found {max_.item()}.")
ndims = len(im.shape)
if ndims not in (2, 3):
- raise TypeError(f"Input torch.tensor must have 2 or 3 dimensions. Found {ndims}.")
+ raise TypeError(f"Input torch.Tensor must have 2 or 3 dimensions. Found {ndims}.")
im = im * 255.0
# Compute the histogram of the image channel.
@@ -969,7 +969,7 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:
@perform_keep_shape_image
def equalize(input: torch.Tensor) -> torch.Tensor:
- r"""Apply equalize on the input torch.tensor.
+ r"""Apply equalize on the input torch.Tensor.
.. image:: _static/img/equalize.png
@@ -977,10 +977,10 @@ def equalize(input: torch.Tensor) -> torch.Tensor:
https://github.com/tensorflow/tpu/blob/5f71c12a020403f863434e96982a840578fdd127/models/official/efficientnet/autoaugment.py#L355
Args:
- input: image torch.tensor to equalize with shape :math:`(*, C, H, W)`.
+ input: image torch.Tensor to equalize with shape :math:`(*, C, H, W)`.
Returns:
- Equalized image torch.tensor with shape :math:`(*, C, H, W)`.
+ Equalized image torch.Tensor with shape :math:`(*, C, H, W)`.
Example:
>>> x = torch.rand(1, 2, 3, 3)
@@ -999,13 +999,13 @@ def equalize(input: torch.Tensor) -> torch.Tensor:
@perform_keep_shape_video
def equalize3d(input: torch.Tensor) -> torch.Tensor:
- r"""Equalize the values for a 3D volumetric torch.tensor.
+ r"""Equalize the values for a 3D volumetric torch.Tensor.
Implements Equalize function for a sequence of images using PyTorch ops based on uint8 format:
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352
Args:
- input: image torch.tensor with shape :math:`(*, C, D, H, W)` to equalize.
+ input: image torch.Tensor with shape :math:`(*, C, D, H, W)` to equalize.
Returns:
Equalized volume with shape :math:`(B, C, D, H, W)`.
@@ -1022,14 +1022,14 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
def invert(image: torch.Tensor, max_val: Optional[torch.Tensor] = None) -> torch.Tensor:
- r"""Invert the values of an input image torch.tensor by its maximum value.
+ r"""Invert the values of an input image torch.Tensor by its maximum value.
.. image:: _static/img/invert.png
Args:
- image: The input torch.tensor to invert with an arbitatry shape.
- max_val: The expected maximum value in the input torch.tensor. The shape has to
- according to the input torch.tensor shape, or at least has to work with broadcasting.
+ image: The input torch.Tensor to invert with an arbitatry shape.
+ max_val: The expected maximum value in the input torch.Tensor. The shape has to
+ according to the input torch.Tensor shape, or at least has to work with broadcasting.
Example:
>>> img = torch.rand(1, 2, 4, 4)
@@ -1362,7 +1362,7 @@ class AdjustBrightness(nn.Module):
class AdjustSigmoid(nn.Module):
- r"""Adjust the contrast of an image torch.tensor or performs sigmoid correction on the input image torch.tensor.
+ r"""Adjust the contrast of an image torch.Tensor or performs sigmoid correction on the input image torch.Tensor.
The input image is expected to be in the range of [0, 1].
@@ -1395,7 +1395,7 @@ class AdjustSigmoid(nn.Module):
class AdjustLog(nn.Module):
- """Adjust log correction on the input image torch.tensor.
+ """Adjust log correction on the input image torch.Tensor.
The input image is expected to be in the range of [0, 1].
@@ -1464,12 +1464,12 @@ class AdjustBrightnessAccumulative(nn.Module):
class Invert(nn.Module):
- r"""Invert the values of an input torch.tensor by its maximum value.
+ r"""Invert the values of an input torch.Tensor by its maximum value.
Args:
- input: The input torch.tensor to invert with an arbitatry shape.
- max_val: The expected maximum value in the input torch.tensor. The shape has to
- according to the input torch.tensor shape, or at least has to work with broadcasting. Default: 1.0.
+ input: The input torch.Tensor to invert with an arbitatry shape.
+ max_val: The expected maximum value in the input torch.Tensor. The shape has to
+ according to the input torch.Tensor shape, or at least has to work with broadcasting. Default: 1.0.
Example:
>>> img = torch.rand(1, 2, 4, 4)
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index b6294ccac..3528e0140 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -98,7 +98,7 @@ class AddWeighted(nn.Module):
Shape:
- Input1: torch.Tensor with an arbitrary shape, equal to shape of Input2.
- Input2: torch.Tensor with an arbitrary shape, equal to shape of Input1.
- - Output: Weighted torch.tensor with shape equal to src1 and src2 shapes.
+ - Output: Weighted torch.Tensor with shape equal to src1 and src2 shapes.
Example:
>>> input1 = torch.rand(1, 1, 5, 5)
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 281e5d2fd..eb8bba7a8 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -103,12 +103,12 @@ def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilo
def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:
- """Estimate the histogram of the input torch.tensor.
+ """Estimate the histogram of the input torch.Tensor.
The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
Args:
- x: Input torch.tensor to compute the histogram with shape :math:`(B, D)`.
+ x: Input torch.Tensor to compute the histogram with shape :math:`(B, D)`.
bins: The number of bins to use the histogram :math:`(N_{bins})`.
bandwidth: Gaussian smoothing factor with shape shape [1].
epsilon: A scalar, for numerical stability.
@@ -132,13 +132,13 @@ def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsi
def histogram2d(
x1: torch.Tensor, x2: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10
) -> torch.Tensor:
- """Estimate the 2d histogram of the input torch.tensor.
+ """Estimate the 2d histogram of the input torch.Tensor.
The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
Args:
- x1: Input torch.tensor to compute the histogram with shape :math:`(B, D1)`.
- x2: Input torch.tensor to compute the histogram with shape :math:`(B, D2)`.
+ x1: Input torch.Tensor to compute the histogram with shape :math:`(B, D1)`.
+ x2: Input torch.Tensor to compute the histogram with shape :math:`(B, D2)`.
bins: The number of bins to use the histogram :math:`(N_{bins})`.
bandwidth: Gaussian smoothing factor with shape shape [1].
epsilon: A scalar, for numerical stability. Default: 1e-10.
@@ -179,7 +179,7 @@ def image_histogram2d(
The calculation uses triangular kernel density estimation.
Args:
- image: Input torch.tensor to compute the histogram with shape
+ image: Input torch.Tensor to compute the histogram with shape
:math:`(H, W)`, :math:`(C, H, W)` or :math:`(B, C, H, W)`.
min: Lower end of the interval (inclusive).
max: Upper end of the interval (inclusive). Ignored when
diff --git a/kornia/enhance/integral.py b/kornia/enhance/integral.py
index 07d4444ae..78cd599e7 100644
--- a/kornia/enhance/integral.py
+++ b/kornia/enhance/integral.py
@@ -24,19 +24,19 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
def integral_tensor(input: torch.Tensor, dim: Optional[Tuple[int, ...]] = None) -> torch.Tensor:
- """Calculate integral of the input torch.tensor.
+ """Calculate integral of the input torch.Tensor.
The algorithm computes the integral image by summing over the specified dimensions.
In case dim is specified, the contained dimensions must be unique and sorted in ascending order
- and not exceed the number of dimensions of the input torch.tensor.
+ and not exceed the number of dimensions of the input torch.Tensor.
Args:
- input: the input torch.tensor with shape :math:`(*, D)`. Where D is the number of dimensions.
+ input: the input torch.Tensor with shape :math:`(*, D)`. Where D is the number of dimensions.
dim: the dimension to be summed.
Returns:
- Integral torch.tensor for the input torch.tensor with shape :math:`(*, D)`.
+ Integral torch.Tensor for the input torch.Tensor with shape :math:`(*, D)`.
Examples:
>>> input = torch.ones(3, 5)
@@ -62,15 +62,15 @@ def integral_tensor(input: torch.Tensor, dim: Optional[Tuple[int, ...]] = None)
def integral_image(image: torch.Tensor) -> torch.Tensor:
- r"""Calculate integral of the input image torch.tensor.
+ r"""Calculate integral of the input image torch.Tensor.
This particular version sums over the last two dimensions.
Args:
- image: the input image torch.tensor with shape :math:`(*, H, W)`.
+ image: the input image torch.Tensor with shape :math:`(*, H, W)`.
Returns:
- Integral torch.tensor for the input image torch.tensor with shape :math:`(*, H, W)`.
+ Integral torch.Tensor for the input image torch.Tensor with shape :math:`(*, H, W)`.
Examples:
>>> input = torch.ones(1, 5, 5)
@@ -89,13 +89,13 @@ def integral_image(image: torch.Tensor) -> torch.Tensor:
class IntegralTensor(nn.Module):
- r"""Calculates integral of the input torch.tensor.
+ r"""Calculates integral of the input torch.Tensor.
Args:
- image: the input torch.tensor with shape :math:`(B,C,H,W)`.
+ image: the input torch.Tensor with shape :math:`(B,C,H,W)`.
Returns:
- Integral torch.tensor for the input torch.tensor with shape :math:`(B,C,H,W)`.
+ Integral torch.Tensor for the input torch.Tensor with shape :math:`(B,C,H,W)`.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -121,15 +121,15 @@ class IntegralTensor(nn.Module):
class IntegralImage(nn.Module):
- """Calculates integral of the input image torch.tensor.
+ """Calculates integral of the input image torch.Tensor.
This particular version sums over the last two dimensions.
Args:
- image: the input image torch.tensor with shape :math:`(B,C,H,W)`.
+ image: the input image torch.Tensor with shape :math:`(B,C,H,W)`.
Returns:
- Integral torch.tensor for the input image torch.tensor with shape :math:`(B,C,H,W)`.
+ Integral torch.Tensor for the input image torch.Tensor with shape :math:`(B,C,H,W)`.
Shape:
- Input: :math:`(B, C, H, W)`
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index 4ad529057..149718e71 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -153,8 +153,8 @@ def _unpatchify_8x8(input: torch.Tensor, H: int, W: int) -> torch.Tensor:
Args:
input (torch.Tensor): Input image of the shape :math:`(B, N, 8, 8)`.
- H: height of resulting torch.tensor.
- W: width of resulting torch.tensor.
+ H: height of resulting torch.Tensor.
+ W: width of resulting torch.Tensor.
Returns:
output (torch.Tensor): Image patchify of the shape :math:`(B, H, W)`.
@@ -605,7 +605,7 @@ def jpeg_codec_differentiable(
f"Batch dimensions do not match. "
f"Got {image_rgb.shape[0]} images and {jpeg_quality.shape[0]} JPEG qualities.",
)
- # keep jpeg_quality same device as input torch.tensor
+ # keep jpeg_quality same device as input torch.Tensor
jpeg_quality = jpeg_quality.to(device, dtype)
# Quantization tables to same device and dtype as input image
quantization_table_y = quantization_table_y.to(device, dtype)
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index cc7a0a069..a71d521e3 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -28,7 +28,7 @@ __all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_mi
class Normalize(nn.Module):
- r"""Normalize a torch.tensor image with mean and standard deviation.
+ r"""Normalize a torch.Tensor image with mean and standard deviation.
.. math::
\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
@@ -40,8 +40,8 @@ class Normalize(nn.Module):
std: Standard deviations for each channel.
Shape:
- - Input: Image torch.tensor of size :math:`(*, C, ...)`.
- - Output: Normalised torch.tensor with same size as input :math:`(*, C, ...)`.
+ - Input: Image torch.Tensor of size :math:`(*, C, ...)`.
+ - Output: Normalised torch.Tensor with same size as input :math:`(*, C, ...)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -89,7 +89,7 @@ class Normalize(nn.Module):
def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:
- r"""Normalize an image/video torch.tensor with mean and standard deviation.
+ r"""Normalize an image/video torch.Tensor with mean and standard deviation.
.. math::
\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
@@ -97,12 +97,12 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torc
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
Args:
- data: Image torch.tensor of size :math:`(B, C, *)`.
+ data: Image torch.Tensor of size :math:`(B, C, *)`.
mean: Mean for each channel.
std: Standard deviations for each channel.
Return:
- Normalised torch.tensor with same size as input :math:`(B, C, *)`.
+ Normalised torch.Tensor with same size as input :math:`(B, C, *)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -122,7 +122,7 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torc
if torch.onnx.is_in_onnx_export():
if not isinstance(mean, torch.Tensor) or not isinstance(std, torch.Tensor):
- raise ValueError("Only torch.tensor is accepted when converting to ONNX.")
+ raise ValueError("Only torch.Tensor is accepted when converting to ONNX.")
if mean.shape[0] != 1 or std.shape[0] != 1:
raise ValueError(
"Batch dimension must be one for broadcasting when converting to ONNX."
@@ -157,7 +157,7 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torc
class Denormalize(nn.Module):
- r"""Denormalize a torch.tensor image with mean and standard deviation.
+ r"""Denormalize a torch.Tensor image with mean and standard deviation.
.. math::
\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}
@@ -169,8 +169,8 @@ class Denormalize(nn.Module):
std: Standard deviations for each channel.
Shape:
- - Input: Image torch.tensor of size :math:`(*, C, ...)`.
- - Output: Denormalised torch.tensor with same size as input :math:`(*, C, ...)`.
+ - Input: Image torch.Tensor of size :math:`(*, C, ...)`.
+ - Output: Denormalised torch.Tensor with same size as input :math:`(*, C, ...)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -202,7 +202,7 @@ class Denormalize(nn.Module):
def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> torch.Tensor:
- r"""Denormalize an image/video torch.tensor with mean and standard deviation.
+ r"""Denormalize an image/video torch.Tensor with mean and standard deviation.
.. math::
\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}
@@ -210,12 +210,12 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
Args:
- data: Image torch.tensor of size :math:`(B, C, *)`.
+ data: Image torch.Tensor of size :math:`(B, C, *)`.
mean: Mean for each channel.
std: Standard deviations for each channel.
Return:
- Denormalised torch.tensor with same size as input :math:`(B, C, *)`.
+ Denormalised torch.Tensor with same size as input :math:`(B, C, *)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -235,7 +235,7 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union
if torch.onnx.is_in_onnx_export():
if not isinstance(mean, torch.Tensor) or not isinstance(std, torch.Tensor):
- raise ValueError("Only torch.tensor is accepted when converting to ONNX.")
+ raise ValueError("Only torch.Tensor is accepted when converting to ONNX.")
if mean.shape[0] != 1 or std.shape[0] != 1:
raise ValueError("Batch dimension must be one for broadcasting when converting to ONNX.")
else:
@@ -260,7 +260,7 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union
if mean.dim() == 1:
mean = mean.view(1, -1, *([1] * (data.dim() - 2)))
- # If the torch.tensor is >1D (e.g., (B, C)), reshape to (B, C, 1, ...)
+ # If the torch.Tensor is >1D (e.g., (B, C)), reshape to (B, C, 1, ...)
else:
while len(mean.shape) < data.dim():
mean = mean.unsqueeze(-1)
@@ -276,23 +276,23 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union
@perform_keep_shape_image
def normalize_min_max(x: torch.Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> torch.Tensor:
- r"""Normalise an image/video torch.tensor by MinMax and re-scales the value between a range.
+ r"""Normalise an image/video torch.Tensor by MinMax and re-scales the value between a range.
The data is normalised using the following formulation:
.. math::
y_i = (b - a) * \frac{x_i - \text{min}(x)}{\text{max}(x) - \text{min}(x)} + a
- torch.where :math:`a` is :math:`\text{min_val}` and :math:`b` is :math:`\text{max_val}`.
+ where :math:`a` is :math:`\text{min_val}` and :math:`b` is :math:`\text{max_val}`.
Args:
- x: The image torch.tensor to be normalised with shape :math:`(*, C, H, W)`.
+ x: The image torch.Tensor to be normalised with shape :math:`(*, C, H, W)`.
min_val: The minimum value for the new range.
max_val: The maximum value for the new range.
eps: Float number to avoid zero division.
Returns:
- The normalised image torch.tensor with same shape as input :math:`(*, C, H, W)`.
+ The normalised image torch.Tensor with same shape as input :math:`(*, C, H, W)`.
Example:
>>> x = torch.rand(1, 5, 3, 3)
@@ -304,7 +304,7 @@ def normalize_min_max(x: torch.Tensor, min_val: float = 0.0, max_val: float = 1.
"""
if not isinstance(x, torch.Tensor):
- raise TypeError(f"data should be a torch.tensor. Got: {type(x)}.")
+ raise TypeError(f"data should be a torch.Tensor. Got: {type(x)}.")
if not isinstance(min_val, float):
raise TypeError(f"'min_val' should be a float. Got: {type(min_val)}.")
diff --git a/kornia/enhance/rescale.py b/kornia/enhance/rescale.py
index 6b6358b6f..5e7b9a205 100644
--- a/kornia/enhance/rescale.py
+++ b/kornia/enhance/rescale.py
@@ -25,7 +25,7 @@ class Rescale(nn.Module):
r"""Initialize the Rescale operator.
Args:
- factor: The scaling factor. Could be a float or a 0-d torch.tensor.
+ factor: The scaling factor. Could be a float or a 0-d torch.Tensor.
"""
@@ -35,7 +35,7 @@ class Rescale(nn.Module):
self.factor = torch.tensor(factor)
else:
if not isinstance(factor, torch.Tensor) or factor.ndim != 0:
- raise TypeError(f"Expected factor to be a float or a 0-d torch.tensor, got {factor}.")
+ raise TypeError(f"Expected factor to be a float or a 0-d torch.Tensor, got {factor}.")
self.factor = factor
def forward(self, input: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index 601c55303..7637c8b95 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -26,18 +26,18 @@ __all__ = ["ZCAWhitening", "linear_transform", "zca_mean", "zca_whiten"]
class ZCAWhitening(nn.Module):
r"""Compute the ZCA whitening matrix transform and the mean vector and applies the transform to the data.
- The data torch.tensor is flattened, and the mean :math:`\mathbf{\mu}`
+ The data torch.Tensor is flattened, and the mean :math:`\mathbf{\mu}`
and covariance matrix :math:`\mathbf{\Sigma}` are computed from
- the flattened data :math:`\mathbf{X} \in \mathbb{R}^{N \times D}`, torch.where
+ the flattened data :math:`\mathbf{X} \in \mathbb{R}^{N \times D}`, where
:math:`N` is the sample size and :math:`D` is flattened dimensionality
- (e.g. for a torch.tensor with size 5x3x2x2 :math:`N = 5` and :math:`D = 12`). The ZCA whitening
+ (e.g. for a torch.Tensor with size 5x3x2x2 :math:`N = 5` and :math:`D = 12`). The ZCA whitening
transform is given by:
.. math::
\mathbf{X}_{\text{zca}} = (\mathbf{X - \mu})(US^{-\frac{1}{2}}U^T)^T
- torch.where :math:`U` are the eigenvectors of :math:`\Sigma` and :math:`S` contain the corresponding
+ where :math:`U` are the eigenvectors of :math:`\Sigma` and :math:`S` contain the corresponding
eigenvalues of :math:`\Sigma`. After the transform is applied, the output is reshaped to same shape.
Args:
@@ -182,7 +182,7 @@ def zca_mean(
See :class:`~kornia.color.ZCAWhitening` for details.
Args:
- inp: input data torch.tensor.
+ inp: input data torch.Tensor.
dim: Specifies the dimension that serves as the samples dimension.
unbiased: Whether to use the unbiased estimate of the covariance matrix.
eps: a small number used for numerical stability.
@@ -277,7 +277,7 @@ def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: floa
See :class:`~kornia.color.ZCAWhitening` for details.
Args:
- inp: input data torch.tensor.
+ inp: input data torch.Tensor.
dim: Specifies the dimension that serves as the samples dimension.
unbiased: Whether to use the unbiased estimate of the covariance matrix.
eps: a small number used for numerical stability.
@@ -320,8 +320,8 @@ def linear_transform(
inp: torch.Tensor, transform_matrix: torch.Tensor, mean_vector: torch.Tensor, dim: int = 0
) -> torch.Tensor:
r"""Given a transformation matrix and a mean vector, this function will flatten the input
- torch.tensor along the given dimension and subtract the mean vector from it. Then the dot
- product with the transformation matrix will be computed and then the resulting torch.tensor
+ torch.Tensor along the given dimension and subtract the mean vector from it. Then the dot
+ product with the transformation matrix will be computed and then the resulting torch.Tensor
is reshaped to the original input shape.
.. math::
@@ -343,7 +343,7 @@ def linear_transform(
Transformed data.
Example:
- >>> # Example torch.where dim = 3
+ >>> # Example where dim = 3
>>> inp = torch.ones((10,3,4,5))
>>> transform_mat = torch.ones((10*3*4,10*3*4))
>>> mean = 2*torch.ones((1,10*3*4))
@@ -351,7 +351,7 @@ def linear_transform(
>>> print(out.shape, out.unique()) # Should a be (10,3,4,5) torch.tensor of -120s
torch.Size([10, 3, 4, 5]) tensor([-120.])
- >>> # Example torch.where dim = 0
+ >>> # Example where dim = 0
>>> inp = torch.ones((10,2))
>>> transform_mat = torch.ones((2,2))
>>> mean = torch.zeros((1,2))
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index 3e2310243..2828e1776 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -77,8 +77,8 @@ def match_adalam(
Return:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
- torch.where 0 <= B3 <= B1.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
+ where 0 <= B3 <= B1.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -159,19 +159,19 @@ class AdalamFilter:
Args:
k1: keypoint locations in the source image, in pixel coordinates.
- Expected a float32 torch.tensor with shape (num_keypoints_in_source_image, 2).
+ Expected a float32 torch.Tensor with shape (num_keypoints_in_source_image, 2).
k2: keypoint locations in the destination image, in pixel coordinates.
- Expected a float32 torch.tensor with shape (num_keypoints_in_destination_image, 2).
+ Expected a float32 torch.Tensor with shape (num_keypoints_in_destination_image, 2).
putative_matches: Initial set of putative matches to be filtered.
The current implementation assumes that these are unfiltered nearest neighbor matches,
so it requires this to be a list of indices a_i such that the source keypoint i is
associated to the destination keypoint a_i. For now to use AdaLAM on different inputs a
workaround on the input format is required.
- Expected a long torch.tensor with shape (num_keypoints_in_source_image,).
+ Expected a long torch.Tensor with shape (num_keypoints_in_source_image,).
scores: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.
mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on
'force_seed_mnn' in the DEFAULT_CONFIG. If None, it disables the mutual nearest neighbor filtering on
- seed point selection. Expected a bool torch.tensor with shape (num_keypoints_in_source_image,)
+ seed point selection. Expected a bool torch.Tensor with shape (num_keypoints_in_source_image,)
im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of
wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width)
of source image
@@ -180,17 +180,17 @@ class AdalamFilter:
of destination image
o1: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config
is set to None. See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
- Expected a float32 torch.tensor with shape (num_keypoints_in_source/destination_image,)
+ Expected a float32 torch.Tensor with shape (num_keypoints_in_source/destination_image,)
o2: same as o1 but for destination.
s1: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.
See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.
- Expected a float32 torch.tensor with shape (num_keypoints_in_source/destination_image,)
+ Expected a float32 torch.Tensor with shape (num_keypoints_in_source/destination_image,)
s2: same as s1 but for destination.
return_dist: if True, inverse confidence value is also outputted.
Returns:
Filtered putative matches.
- A long torch.tensor with shape (num_filtered_matches, 2) with indices of corresponding
+ A long torch.Tensor with shape (num_filtered_matches, 2) with indices of corresponding
keypoints in k1 and k2.
"""
@@ -262,7 +262,7 @@ class AdalamFilter:
Returns:
Filtered putative matches.
- A long torch.tensor with shape (num_filtered_matches, 2) with indices of corresponding
+ A long torch.Tensor with shape (num_filtered_matches, 2) with indices of corresponding
keypoints in k1 and k2.
"""
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index df9f888fd..3f26d365b 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -70,7 +70,7 @@ def _no_match(dm: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(0, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(0, 2)`.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(0, 2)`.
"""
dists = torch.empty(0, 1, device=dm.device, dtype=dm.dtype)
@@ -94,7 +94,7 @@ def select_seeds(
The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2
mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.
If None, it disables the mutual nearest neighbor filtering on seed point selection.
- Expected a bool torch.tensor with shape (num_keypoints_in_source_image,)
+ Expected a bool torch.Tensor with shape (num_keypoints_in_source_image,)
Returns:
Indices of seed points.
@@ -287,19 +287,19 @@ def adalam_core(
Args:
k1: keypoint locations in the source image, in pixel coordinates.
- Expected a float32 torch.tensor with shape (num_keypoints_in_source_image, 2).
+ Expected a float32 torch.Tensor with shape (num_keypoints_in_source_image, 2).
k2: keypoint locations in the destination image, in pixel coordinates.
- Expected a float32 torch.tensor with shape (num_keypoints_in_destination_image, 2).
+ Expected a float32 torch.Tensor with shape (num_keypoints_in_destination_image, 2).
fnn12: Initial set of putative matches to be filtered.
The current implementation assumes that these are unfiltered nearest neighbor matches,
so it requires this to be a list of indices a_i such that the source keypoint i is associated to the
destination keypoint a_i. For now to use AdaLAM on different inputs a workaround on the input format is
- required. Expected a long torch.tensor with shape (num_keypoints_in_source_image,).
+ required. Expected a long torch.Tensor with shape (num_keypoints_in_source_image,).
scores1: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.
config: Adalam configuration.
mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on
'force_seed_mnn' in the DEFAULT_CONFIG. If None, it disables the mutual nearest neighbor filtering on seed
- point selection. Expected a bool torch.tensor with shape (num_keypoints_in_source_image,)
+ point selection. Expected a bool torch.Tensor with shape (num_keypoints_in_source_image,)
im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted
runtime. So please provide it. Expected a tuple with (width, height) or (height, width) of source
image
@@ -308,16 +308,16 @@ def adalam_core(
destination image
o1: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is
set to None. See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
- Expected a float32 torch.tensor with shape (num_keypoints_in_source/destination_image,)
+ Expected a float32 torch.Tensor with shape (num_keypoints_in_source/destination_image,)
o2: Same as o1 but for destination.
s1: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.
See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.
- Expected a float32 torch.tensor with shape (num_keypoints_in_source/destination_image,)
+ Expected a float32 torch.Tensor with shape (num_keypoints_in_source/destination_image,)
s2: Same as s1 but for destination.
return_dist: if True, inverse confidence value is also outputted. Default is False
Returns:
- idxs: A long torch.tensor with shape (num_filtered_matches, 2) with indices of corresponding
+ idxs: A long torch.Tensor with shape (num_filtered_matches, 2) with indices of corresponding
keypoints in k1 and k2.
dists: inverse confidence ratio.
diff --git a/kornia/feature/adalam/utils.py b/kornia/feature/adalam/utils.py
index 7f44060d8..b0f0a6060 100644
--- a/kornia/feature/adalam/utils.py
+++ b/kornia/feature/adalam/utils.py
@@ -170,7 +170,7 @@ def draw_first_k_couples(k: int, rdims: torch.Tensor, dv: torch.device) -> torch
def random_samples_indices(iters: int, rdims: torch.Tensor, dv: torch.device) -> torch.Tensor:
- """Randomly sample indices of torch.tensor."""
+ """Randomly sample indices of torch.Tensor."""
rands = torch.rand(size=(iters, 2, rdims.shape[0]), device=dv)
scaled_rands = rands * (rdims - 1e-8).float()
rand_samples_rel = scaled_rands.long()
diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.py
index bdab8c401..ae8fc3b6f 100644
--- a/kornia/feature/dedode/dedode.py
+++ b/kornia/feature/dedode/dedode.py
@@ -88,18 +88,18 @@ class DeDoDe(nn.Module):
"""Detect and describe keypoints in the input images.
Args:
- images: A torch.tensor of shape :math:`(B, 3, H, W)` containing the ImageNet-Normalized input images.
+ images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the ImageNet-Normalized input images.
n: The number of keypoints to detect.
apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.
pad_if_not_divisible: F.pad image shape if not evenly divisible.
Returns:
- keypoints: A torch.tensor of shape :math:`(B, N, 2)` containing the detected keypoints in the image range,
+ keypoints: A torch.Tensor of shape :math:`(B, N, 2)` containing the detected keypoints in the image range,
unlike `.detect()` function.
- scores: A torch.tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
+ scores: A torch.Tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
- descriptions: A torch.tensor of shape :math:`(B, N, DIM)` containing the descriptions
+ descriptions: A torch.Tensor of shape :math:`(B, N, DIM)` containing the descriptions
of the detected keypoints. DIM is 256 for B and 512 for G.
"""
@@ -128,7 +128,7 @@ class DeDoDe(nn.Module):
"""Detect keypoints in the input images.
Args:
- images: A torch.tensor of shape :math:`(B, 3, H, W)` containing the input images.
+ images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the input images.
n: The number of keypoints to detect.
apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.
pad_if_not_divisible: F.pad image shape if not evenly divisible.
@@ -136,9 +136,9 @@ class DeDoDe(nn.Module):
crop_w: The width of the crop to be used for detection. If None, the full image is used.
Returns:
- keypoints: A torch.tensor of shape :math:`(B, N, 2)` containing the detected keypoints,
+ keypoints: A torch.Tensor of shape :math:`(B, N, 2)` containing the detected keypoints,
normalized to the range :math:`[-1, 1]`.
- scores: A torch.tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
+ scores: A torch.Tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
"""
KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])
@@ -173,14 +173,14 @@ class DeDoDe(nn.Module):
"""Describe keypoints in the input images. If keypoints are not provided, returns the dense descriptors.
Args:
- images: A torch.tensor of shape :math:`(B, 3, H, W)` containing the input images.
- keypoints: An optional torch.tensor of shape :math:`(B, N, 2)` containing the detected keypoints.
+ images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the input images.
+ keypoints: An optional torch.Tensor of shape :math:`(B, N, 2)` containing the detected keypoints.
apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.
crop_h: The height of the crop to be used for description. If None, the full image is used.
crop_w: The width of the crop to be used for description. If None, the full image is used.
Returns:
- descriptions: A torch.tensor of shape :math:`(B, N, DIM)` containing the descriptions
+ descriptions: A torch.Tensor of shape :math:`(B, N, DIM)` containing the descriptions
of the detected keypoints.
If the dense descriptors are requested, the shape is :math:`(B, DIM, H, W)`.
diff --git a/kornia/feature/dedode/transformer/dinov2.py b/kornia/feature/dedode/transformer/dinov2.py
index 7859a70c9..c1a2be4e9 100644
--- a/kornia/feature/dedode/transformer/dinov2.py
+++ b/kornia/feature/dedode/transformer/dinov2.py
@@ -100,7 +100,6 @@ class DinoVisionTransformer(nn.Module):
ffn_bias (bool): enable bias for ffn if True
drop_path_rate (float): stochastic depth rate
drop_path_uniform (bool): apply uniform drop rate across blocks
- weight_init (str): weight init scheme
init_values (float): layer-scale init values
embed_layer (nn.Module): patch embedding layer
act_layer (nn.Module): MLP activation layer
diff --git a/kornia/feature/dedode/vgg.py b/kornia/feature/dedode/vgg.py
index db0c834db..9a5eff5c3 100644
--- a/kornia/feature/dedode/vgg.py
+++ b/kornia/feature/dedode/vgg.py
@@ -107,8 +107,6 @@ def vgg11(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
:class:`~torchvision.models.VGG11_Weights` below for
more details, and possible values. By default, no pre-trained
weights are used.
- progress (bool, optional): If True, displays a progress bar of the
- download to stderr. Default is True.
**kwargs: parameters passed to the ``torchvision.models.vgg.VGG``
base class. Please refer to the `source code
<https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_
@@ -130,8 +128,6 @@ def vgg11_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
:class:`~torchvision.models.VGG11_BN_Weights` below for
more details, and possible values. By default, no pre-trained
weights are used.
- progress (bool, optional): If True, displays a progress bar of the
- download to stderr. Default is True.
**kwargs: parameters passed to the ``torchvision.models.vgg.VGG``
base class. Please refer to the `source code
<https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_
@@ -153,8 +149,6 @@ def vgg13(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
:class:`~torchvision.models.VGG13_Weights` below for
more details, and possible values. By default, no pre-trained
weights are used.
- progress (bool, optional): If True, displays a progress bar of the
- download to stderr. Default is True.
**kwargs: parameters passed to the ``torchvision.models.vgg.VGG``
base class. Please refer to the `source code
<https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_
@@ -176,8 +170,6 @@ def vgg13_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
:class:`~torchvision.models.VGG13_BN_Weights` below for
more details, and possible values. By default, no pre-trained
weights are used.
- progress (bool, optional): If True, displays a progress bar of the
- download to stderr. Default is True.
**kwargs: parameters passed to the ``torchvision.models.vgg.VGG``
base class. Please refer to the `source code
<https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_
@@ -199,8 +191,6 @@ def vgg16(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
:class:`~torchvision.models.VGG16_Weights` below for
more details, and possible values. By default, no pre-trained
weights are used.
- progress (bool, optional): If True, displays a progress bar of the
- download to stderr. Default is True.
**kwargs: parameters passed to the ``torchvision.models.vgg.VGG``
base class. Please refer to the `source code
<https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_
@@ -222,8 +212,6 @@ def vgg16_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
:class:`~torchvision.models.VGG16_BN_Weights` below for
more details, and possible values. By default, no pre-trained
weights are used.
- progress (bool, optional): If True, displays a progress bar of the
- download to stderr. Default is True.
**kwargs: parameters passed to the ``torchvision.models.vgg.VGG``
base class. Please refer to the `source code
<https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_
@@ -245,8 +233,6 @@ def vgg19(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
:class:`~torchvision.models.VGG19_Weights` below for
more details, and possible values. By default, no pre-trained
weights are used.
- progress (bool, optional): If True, displays a progress bar of the
- download to stderr. Default is True.
**kwargs: parameters passed to the ``torchvision.models.vgg.VGG``
base class. Please refer to the `source code
<https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_
@@ -268,8 +254,6 @@ def vgg19_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
:class:`~torchvision.models.VGG19_BN_Weights` below for
more details, and possible values. By default, no pre-trained
weights are used.
- progress (bool, optional): If True, displays a progress bar of the
- download to stderr. Default is True.
**kwargs: parameters passed to the ``torchvision.models.vgg.VGG``
base class. Please refer to the `source code
<https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index de5635108..74dc76334 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -39,8 +39,8 @@ class DISK(nn.Module):
desc_dim: The dimension of the descriptor.
unet: The U-Net to use. If None, a default U-Net is used. Kornia doesn't provide the training code for DISK
so this is only useful when using a custom checkpoint trained using the code released with the paper.
- The unet should take as input a torch.tensor of shape :math:`(B, C, H, W)` and output
- a torch.tensor of shape
+ The unet should take as input a torch.Tensor of shape :math:`(B, C, H, W)` and output
+ a torch.Tensor of shape
:math:`(B, \mathrm{desc\_dim} + 1, H, W)`.
Example:
@@ -69,7 +69,7 @@ class DISK(nn.Module):
Returns:
A tuple of dense detection scores and descriptors.
- Shapes are :math:`(B, 1, H, W)` and :math:`(B, D, H, W)`, torch.where
+ Shapes are :math:`(B, 1, H, W)` and :math:`(B, D, H, W)`, where
:math:`D` is the descriptor dimension.
"""
@@ -132,8 +132,8 @@ class DISK(nn.Module):
r"""Load a pretrained model.
Depth model was trained using depth map supervision and is slightly more precise but biased to detect keypoints
- only torch.where SfM depth is available. Epipolar model was trained using epipolar geometry supervision and
- is less precise but detects keypoints everywhere torch.where they are matchable. The difference is especially
+ only where SfM depth is available. Epipolar model was trained using epipolar geometry supervision and
+ is less precise but detects keypoints everywhere where they are matchable. The difference is especially
pronounced on thin structures and on edges of objects.
Args:
diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.py
index c23fdedae..662095f10 100644
--- a/kornia/feature/disk/structs.py
+++ b/kornia/feature/disk/structs.py
@@ -31,9 +31,9 @@ class DISKFeatures:
Since DISK detects a varying number of keypoints per image, `DISKFeatures` is not batched.
Args:
- keypoints: torch.Tensor of shape :math:`(N, 2)`, torch.where :math:`N` is the number of keypoints.
- descriptors: torch.Tensor of shape :math:`(N, D)`, torch.where :math:`D` is the descriptor dimension.
- detection_scores: torch.Tensor of shape :math:`(N,)` torch.where the detection score can be interpreted as
+ keypoints: torch.Tensor of shape :math:`(N, 2)`, where :math:`N` is the number of keypoints.
+ descriptors: torch.Tensor of shape :math:`(N, D)`, where :math:`D` is the descriptor dimension.
+ detection_scores: torch.Tensor of shape :math:`(N,)` where the detection score can be interpreted as
the log-probability of keeping a keypoint after it has been proposed (see the paper
section *Method β†’ Feature distribution* for details).
@@ -91,7 +91,7 @@ class Keypoints:
detection_logp: torch.Tensor
def merge_with_descriptors(self, descriptors: torch.Tensor) -> DISKFeatures:
- """Select descriptors from a dense `descriptors` torch.tensor, at locations given by `self.xys`."""
+ """Select descriptors from a dense `descriptors` torch.Tensor, at locations given by `self.xys`."""
dtype = descriptors.dtype
x, y = self.xys.T
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index d22e00ca4..0ae4a5753 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -62,7 +62,7 @@ def get_laf_descriptors(
grayscale_descriptor: True if ``patch_descriptor`` expects single-channel image.
Returns:
- Local descriptors of shape :math:`(B,N,D)` torch.where :math:`D` is descriptor size.
+ Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.
"""
KORNIA_CHECK_LAF(lafs)
@@ -71,13 +71,13 @@ def get_laf_descriptors(
timg: torch.Tensor = img
if lafs.shape[1] == 0:
- warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty torch.tensor", stacklevel=1)
+ warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty torch.Tensor", stacklevel=1)
return torch.empty(lafs.shape[0], lafs.shape[1], 128, dtype=lafs.dtype, device=lafs.device)
if grayscale_descriptor and img.size(1) == 3:
timg = rgb_to_grayscale(img)
patches: torch.Tensor = extract_patches_from_pyramid(timg, lafs, patch_size)
- # Descriptor accepts standard torch.tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
+ # Descriptor accepts standard torch.Tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
# So we need to reshape a bit :)
B, N, CH, H, W = patches.size()
return patch_descriptor(patches.view(B * N, CH, H, W)).view(B, N, -1)
@@ -128,7 +128,7 @@ class LAFDescriptor(nn.Module):
lafs: local affine frames :math:`(B,N,2,3)`.
Returns:
- Local descriptors of shape :math:`(B,N,D)` torch.where :math:`D` is descriptor size.
+ Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.
"""
return get_laf_descriptors(img, lafs, self.descriptor, self.patch_size, self.grayscale_descriptor)
@@ -159,13 +159,13 @@ class LocalFeature(nn.Module):
Args:
img: image to extract features with shape :math:`(B,C,H,W)`.
- mask: a mask with weights torch.where to apply the response function.
+ mask: a mask with weights where to apply the response function.
The shape must be the same as the input image.
Returns:
- Detected local affine frames with shape :math:`(B,N,2,3)`.
- Response function values for corresponding lafs with shape :math:`(B,N,1)`.
- - Local descriptors of shape :math:`(B,N,D)` torch.where :math:`D` is descriptor size.
+ - Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.
"""
lafs, responses = self.detector(img, mask)
@@ -509,8 +509,8 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
Return:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` torch.where :math:`0 <= B3 <= B1`.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
"""
if (desc1.shape[0] < 2) or (desc2.shape[0] < 2):
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index a01029cd6..a8290efb4 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -163,7 +163,7 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torc
Args:
laf: :math:`(B, N, 2, 3)`
- scale_coef: broadcastable torch.tensor or float.
+ scale_coef: broadcastable torch.Tensor or float.
Returns:
LAF :math:`(B, N, 2, 3)`
@@ -223,7 +223,7 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
See also https://github.com/vlfeat/vlfeat/blob/master/toolbox/sift/vl_frame2oell.m
Args:
- ells: torch.tensor :math:`(B, N, 5)` of ellipses in Oxford format [x y a b c].
+ ells: torch.Tensor :math:`(B, N, 5)` of ellipses in Oxford format [x y a b c].
Returns:
LAF :math:`(B, N, 2, 3)`
@@ -266,7 +266,7 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
n_pts: number of points to output.
Returns:
- torch.tensor of boundary points LAF: :math:`(B, N, n_pts, 2)`
+ torch.Tensor of boundary points LAF: :math:`(B, N, n_pts, 2)`
"""
KORNIA_CHECK_LAF(LAF)
@@ -380,7 +380,7 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor
"""Generate affine grid.
Args:
- img: image torch.tensor of shape :math:`(B, CH, H, W)`.
+ img: image torch.Tensor of shape :math:`(B, CH, H, W)`.
LAF: laf with shape :math:`(B, N, 2, 3)`.
PS: patch size to be extracted.
@@ -405,7 +405,7 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor
def extract_patches_simple(
img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
) -> torch.Tensor:
- """Extract patches defined by LAFs from image torch.tensor.
+ """Extract patches defined by LAFs from image torch.Tensor.
No smoothing applied, huge aliasing (better use extract_patches_from_pyramid).
@@ -441,7 +441,7 @@ def extract_patches_simple(
def extract_patches_from_pyramid(
img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
) -> torch.Tensor:
- """Extract patches defined by LAFs from image torch.tensor.
+ """Extract patches defined by LAFs from image torch.Tensor.
Patches are extracted from appropriate pyramid level.
@@ -552,11 +552,11 @@ def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) ->
r"""Apply perspective transformations to a set of local affine frames (LAFs).
Args:
- trans_01: torch.tensor for perspective transformations of shape :math:`(B, 3, 3)`.
- lafs_1: torch.tensor of lafs of shape :math:`(B, N, 2, 3)`.
+ trans_01: torch.Tensor for perspective transformations of shape :math:`(B, 3, 3)`.
+ lafs_1: torch.Tensor of lafs of shape :math:`(B, N, 2, 3)`.
Returns:
- torch.tensor of N-dimensional points of shape :math:`(B, N, 2, 3)`.
+ torch.Tensor of N-dimensional points of shape :math:`(B, N, 2, 3)`.
Examples:
>>> rng = torch.manual_seed(0)
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 22d084e80..a682536dd 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -46,7 +46,7 @@ def math_clamp(x, min_, max_): # type: ignore
@torch.amp.custom_fwd(cast_inputs=torch.float32, device_type="cuda")
def normalize_keypoints(kpts: torch.Tensor, size: torch.Tensor) -> torch.Tensor:
- """Normalize torch.tensor of keypoints."""
+ """Normalize torch.Tensor of keypoints."""
if isinstance(size, torch.Size):
size = torch.tensor(size)[None]
shift = size.float().to(kpts) / 2
@@ -56,7 +56,7 @@ def normalize_keypoints(kpts: torch.Tensor, size: torch.Tensor) -> torch.Tensor:
def pad_to_length(x: torch.Tensor, length: int) -> Tuple[torch.Tensor, torch.Tensor]:
- """Pad torch.tensor to desired length."""
+ """Pad torch.Tensor to desired length."""
if length <= x.shape[-2]:
return x, torch.ones_like(x[..., :1], dtype=torch.bool)
pad_tensor = torch.ones(*x.shape[:-2], length - x.shape[-2], x.shape[-1], device=x.device, dtype=x.dtype)
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 458f9a62c..098697fa1 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -178,7 +178,7 @@ class OnnxLightGlue:
matches, mscores = binding.get_outputs()
# TODO: The following is an unnecessary copy. Replace with a better solution when torch supports
- # constructing a torch.tensor from a data pointer, or when ORT supports converting to torch torch.tensor.
+ # constructing a torch.Tensor from a data pointer, or when ORT supports converting to torch torch.Tensor.
# https://github.com/microsoft/onnxruntime/issues/15963
outputs = {
"matches": torch.from_dlpack(matches.numpy()).to(self.device),
diff --git a/kornia/feature/lightglue_onnx/utils/keypoints.py b/kornia/feature/lightglue_onnx/utils/keypoints.py
index 10f62e9b6..134c9c310 100644
--- a/kornia/feature/lightglue_onnx/utils/keypoints.py
+++ b/kornia/feature/lightglue_onnx/utils/keypoints.py
@@ -21,7 +21,7 @@ import torch
def normalize_keypoints(kpts: torch.Tensor, size: torch.Tensor) -> torch.Tensor:
- """Normalize torch.tensor of keypoints."""
+ """Normalize torch.Tensor of keypoints."""
if isinstance(size, torch.Size):
size = torch.tensor(size)[None]
shift = size.float().to(kpts) / 2
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 7cf7a76dc..a38676b92 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -70,7 +70,7 @@ def _no_match(dm: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(0, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(0, 2)`.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(0, 2)`.
"""
dists = torch.empty(0, 1, device=dm.device, dtype=dm.dtype)
@@ -93,7 +93,7 @@ def match_nn(
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(B1, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -122,8 +122,8 @@ def match_mnn(
Return:
- Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,
- torch.where 0 <= B3 <= min(B1, B2)
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,
+ where 0 <= B3 <= min(B1, B2)
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -165,8 +165,8 @@ def match_snn(
Return:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
- torch.where 0 <= B3 <= B1.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
+ where 0 <= B3 <= B1.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -205,8 +205,8 @@ def match_smnn(
Return:
- Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` torch.where 0 <= B3 <= B1.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` where 0 <= B3 <= B1.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -267,17 +267,16 @@ def match_fginn(
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)`.
-
th: distance ratio threshold.
spatial_th: minimal distance in pixels to 2nd nearest neighbor.
- mutual: also perform mutual nearest neighbor check
+ mutual: also perform mutual nearest neighbor check.
dm: torch.Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
- torch.where 0 <= B3 <= B1.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
+ where 0 <= B3 <= B1.
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
@@ -323,7 +322,10 @@ def match_fginn(
class DescriptorMatcher(nn.Module):
- """nn.Module version of matching functions.
+ """nn.Module version of descriptor-only matching functions.
+
+ This matcher only requires descriptors (no LAFs). For geometry-aware matching that uses LAFs,
+ see :class:`~kornia.feature.GeometryAwareDescriptorMatcher`.
See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`,
:func:`~kornia.feature.match_mnn` or :func:`~kornia.feature.match_smnn` for more details.
@@ -352,8 +354,8 @@ class DescriptorMatcher(nn.Module):
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` torch.where :math:`0 <= B3 <= B1`.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
"""
if self.match_mode == "nn":
@@ -378,7 +380,7 @@ class DescriptorMatcherWithSteerer(nn.Module):
steer_mode: can be `global`, `local`.
`global` means that the we output matches from the global rotation with most matches.
`local` means that we output matches from a distance matrix
- torch.where the distance between each descriptor pair is the minimal over rotations.
+ where the distance between each descriptor pair is the minimal over rotations.
match_mode: type of matching, can be `nn`, `snn`, `mnn`, `smnn`.
WARNING: using steer_mode `global` with match_mode `nn` will lead to bad results
since `nn` doesn't generate different amount of matches depending on goodness of fit.
@@ -468,8 +470,8 @@ class DescriptorMatcherWithSteerer(nn.Module):
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` torch.where :math:`0 <= B3 <= B1`.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
- Number of global rotations from desc1 to desc2, in terms of `self.steerer_order`
(will be `None` if `self.steer_mode` is `local`).
@@ -517,14 +519,14 @@ class DescriptorMatcherWithSteerer(nn.Module):
class GeometryAwareDescriptorMatcher(nn.Module):
- """nn.Module version of matching functions.
+ """nn.Module version of geometry-aware matching functions that use LAFs (Local Affine Frames).
- See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`,
- :func:`~kornia.feature.match_mnn` or :func:`~kornia.feature.match_smnn` for more details.
+ Unlike :class:`~kornia.feature.DescriptorMatcher`, this matcher requires both descriptors and LAFs.
+ See :func:`~kornia.feature.match_fginn` or :func:`~kornia.feature.match_adalam` for more details.
Args:
- match_mode: type of matching, can be `fginn`.
- th: threshold on distance ratio, or other quality measure.
+ match_mode: type of matching, can be `fginn` or `adalam`.
+ params: dictionary of parameters for the matching function.
"""
@@ -551,8 +553,8 @@ class GeometryAwareDescriptorMatcher(nn.Module):
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- - Long torch.tensor indexes of matching descriptors in desc1 and desc2,
- shape of :math:`(B3, 2)` torch.where :math:`0 <= B3 <= B1`.
+ - Long torch.Tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
"""
if self.match_mode == "fginn":
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index bc8fc8e5f..1627d04f2 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -108,7 +108,7 @@ def harris_response(
dx: torch.Tensor = gradients[:, :, 0]
dy: torch.Tensor = gradients[:, :, 1]
- # compute the structure torch.tensor M elements
+ # compute the structure torch.Tensor M elements
dx2: torch.Tensor = gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))
dy2: torch.Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))
@@ -286,7 +286,7 @@ def dog_response(input: torch.Tensor) -> torch.Tensor:
r"""Compute the Difference-of-Gaussian response.
Args:
- input: a given the gaussian 5d torch.tensor :math:`(B, C, D, H, W)`.
+ input: a given the gaussian 5d torch.Tensor :math:`(B, C, D, H, W)`.
Return:
the response map per channel with shape :math:`(B, C, D-1, H, W)`.
@@ -303,7 +303,7 @@ def dog_response_single(input: torch.Tensor, sigma1: float = 1.0, sigma2: float
.. image:: _static/img/dog_response_single.png
Args:
- input: a given the gaussian 4d torch.tensor :math:`(B, C, H, W)`.
+ input: a given the gaussian 4d torch.Tensor :math:`(B, C, H, W)`.
sigma1: lower gaussian sigma
sigma2: bigger gaussian sigma
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index bb9707319..c34068ffa 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -39,12 +39,12 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_le
scale, using the sigmas from the ScalePyramid output.
Args:
- max_coords: torch.tensor [BxNx3].
- sigmas: torch.tensor [BxNxD], D >= 1
+ max_coords: torch.Tensor [BxNx3].
+ sigmas: torch.Tensor [BxNxD], D >= 1
num_levels: number of levels in the scale index.
Returns:
- torch.tensor [BxNx3].
+ torch.Tensor [BxNx3].
"""
# depth (scale) in coord_max is represented as (float) index, not the scale yet.
@@ -250,7 +250,7 @@ class ScaleSpaceDetector(nn.Module):
Args:
img: image to extract features with shape [BxCxHxW]
- mask: a mask with weights torch.where to apply the response function. The shape must be the same as
+ mask: a mask with weights where to apply the response function. The shape must be the same as
the input image.
Returns:
@@ -429,7 +429,7 @@ class MultiResolutionDetector(nn.Module):
Args:
img: image to extract features with shape [1xCxHxW]. KeyNetDetector does not support batch processing,
because the number of detections is different on each image.
- mask: a mask with weights torch.where to apply the response function. The shape must be the same as
+ mask: a mask with weights where to apply the response function. The shape must be the same as
the input image.
Returns:
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index e3b2a6f04..75bbf769f 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -302,7 +302,7 @@ class DenseSIFTDescriptor(nn.Module):
PoolingConv.weight.data.copy_(self._poolingconv_weight)
self.PoolingConv = PoolingConv
- # Cache pooling kernel torch.tensor for fast return in get_pooling_kernel
+ # Cache pooling kernel torch.Tensor for fast return in get_pooling_kernel
self._pooling_kernel = self._bin_pooling_kernel_weight.detach()
def get_pooling_kernel(self) -> torch.Tensor:
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index d76d9415e..057c7682a 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -328,7 +328,7 @@ def keypoints_to_grid(keypoints: torch.Tensor, img_size: Tuple[int, int]) -> tor
"""Convert a list of keypoints into a grid in [-1, 1]Β² that can be used in torch.nn.functional.interpolate.
Args:
- keypoints: a torch.tensor [N, 2] of N keypoints (ij coordinates convention).
+ keypoints: a torch.Tensor [N, 2] of N keypoints (ij coordinates convention).
img_size: the original image size (H, W)
"""
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index a2cda9462..5669f8686 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -564,7 +564,7 @@ class LineSegmentDetectionModule:
def line_map_to_segments(junctions: torch.Tensor, line_map: torch.Tensor) -> torch.Tensor:
- """Convert a junction connectivity map to a Nx2x2 torch.tensor of segments."""
+ """Convert a junction connectivity map to a Nx2x2 torch.Tensor of segments."""
junc_loc1, junc_loc2 = torch.where(torch.triu(line_map))
segments = torch.stack([junctions[junc_loc1], junctions[junc_loc2]], 1)
return segments
diff --git a/kornia/feature/steerers.py b/kornia/feature/steerers.py
index 7a9acabac..822756775 100644
--- a/kornia/feature/steerers.py
+++ b/kornia/feature/steerers.py
@@ -28,7 +28,7 @@ class DiscreteSteerer(nn.Module):
A steerer rotates keypoint descriptions in latent space as if they were obtained from rotated images.
Args:
- generator: [N, N] torch.tensor torch.where N is the descriptor dimension.
+ generator: [N, N] torch.Tensor where N is the descriptor dimension.
Example:
>>> desc = torch.randn(512, 128)
@@ -65,7 +65,7 @@ class DiscreteSteerer(nn.Module):
steerer_order: int = 8,
) -> nn.Module:
r"""Create a steerer for pretrained DeDoDe descriptors int the "C-setting"
- from the paper https://arxiv.org/abs/2312.02152, torch.where descriptors were
+ from the paper https://arxiv.org/abs/2312.02152, where descriptors were
trained for fixed steerers.
Args:
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index e280cf36c..8cd9aa2e4 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -92,7 +92,7 @@ def bilateral_blur(
border_type: str = "reflect",
color_distance_type: str = "l1",
) -> torch.Tensor:
- r"""Blur a torch.tensor using a Bilateral filter.
+ r"""Blur a torch.Tensor using a Bilateral filter.
.. image:: _static/img/bilateral_blur.png
@@ -101,7 +101,7 @@ def bilateral_blur(
to the center pixel, but also the difference in intensity or color.
Arguments:
- input: the input torch.tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.Tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
Smaller values preserve more edges.
@@ -116,7 +116,7 @@ def bilateral_blur(
Default: ``'l1'``.
Returns:
- the blurred torch.tensor with shape :math:`(B, C, H, W)`.
+ the blurred torch.Tensor with shape :math:`(B, C, H, W)`.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -137,7 +137,7 @@ def joint_bilateral_blur(
border_type: str = "reflect",
color_distance_type: str = "l1",
) -> torch.Tensor:
- r"""Blur a torch.tensor using a Joint Bilateral filter.
+ r"""Blur a torch.Tensor using a Joint Bilateral filter.
.. image:: _static/img/joint_bilateral_blur.png
@@ -146,8 +146,8 @@ def joint_bilateral_blur(
a guidance image. See :func:`bilateral_blur()` for more information.
Arguments:
- input: the input torch.tensor with shape :math:`(B,C,H,W)`.
- guidance: the guidance torch.tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.Tensor with shape :math:`(B,C,H,W)`.
+ guidance: the guidance torch.Tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
Smaller values preserve more edges.
@@ -161,7 +161,7 @@ def joint_bilateral_blur(
match OpenCV implementation.
Returns:
- the blurred torch.tensor with shape :math:`(B, C, H, W)`.
+ the blurred torch.Tensor with shape :math:`(B, C, H, W)`.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -203,7 +203,7 @@ class _BilateralBlur(nn.Module):
class BilateralBlur(_BilateralBlur):
- r"""Blur a torch.tensor using a Bilateral filter.
+ r"""Blur a torch.Tensor using a Bilateral filter.
The operator is an edge-preserving image smoothing filter. The weight
for each pixel in a neighborhood is determined not only by its distance
@@ -224,7 +224,7 @@ class BilateralBlur(_BilateralBlur):
Default: ``'l1'``.
Returns:
- the blurred input torch.tensor.
+ the blurred input torch.Tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -246,7 +246,7 @@ class BilateralBlur(_BilateralBlur):
class JointBilateralBlur(_BilateralBlur):
- r"""Blur a torch.tensor using a Joint Bilateral filter.
+ r"""Blur a torch.Tensor using a Joint Bilateral filter.
This operator is almost identical to a Bilateral filter. The only difference
is that the color Gaussian kernel is computed based on another image called
@@ -266,7 +266,7 @@ class JointBilateralBlur(_BilateralBlur):
match OpenCV implementation.
Returns:
- the blurred input torch.tensor.
+ the blurred input torch.Tensor.
Shape:
- Input: :math:`(B, C, H, W)`, :math:`(B, C, H, W)`
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index 058d103cb..b852e6f01 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -52,7 +52,7 @@ def box_blur(
separable: run as composition of two 1d-convolutions.
Returns:
- the blurred torch.tensor with shape :math:`(B,C,H,W)`.
+ the blurred torch.Tensor with shape :math:`(B,C,H,W)`.
.. note::
See a working example `here <https://kornia.github.io/tutorials/nbs/filtering_operators.html>`__.
@@ -100,7 +100,7 @@ class BoxBlur(nn.Module):
separable: run as composition of two 1d-convolutions.
Returns:
- the blurred input torch.tensor.
+ the blurred input torch.Tensor.
Shape:
- Input: :math:`(B, C, H, W)`
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index cb3aeca6d..ad1eb47ae 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -47,7 +47,7 @@ class BlurPool2D(nn.Module):
Shape:
- Input: :math:`(B, C, H, W)`
- - Output: :math:`(N, C, H_{out}, W_{out})`, torch.where
+ - Output: :math:`(N, C, H_{out}, W_{out})`, where
.. math::
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{kernel\_size//2}[0] -
@@ -167,13 +167,13 @@ def blur_pool2d(input: torch.Tensor, kernel_size: tuple[int, int] | int, stride:
See :cite:`zhang2019shiftinvar` for more details.
Args:
- input: torch.tensor to apply operation to.
+ input: torch.Tensor to apply operation to.
kernel_size: the kernel size for max pooling.
stride: stride for pooling.
Shape:
- Input: :math:`(B, C, H, W)`
- - Output: :math:`(N, C, H_{out}, W_{out})`, torch.where
+ - Output: :math:`(N, C, H_{out}, W_{out})`, where
.. math::
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{kernel\_size//2}[0] -
@@ -184,7 +184,7 @@ def blur_pool2d(input: torch.Tensor, kernel_size: tuple[int, int] | int, stride:
\text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
Returns:
- the transformed torch.tensor.
+ the transformed torch.Tensor.
.. note::
This function is tested against https://github.com/adobe/antialiased-cnns.
@@ -220,7 +220,7 @@ def max_blur_pool2d(
See :class:`~kornia.filters.MaxBlurPool2D` for details.
Args:
- input: torch.tensor to apply operation to.
+ input: torch.Tensor to apply operation to.
kernel_size: the kernel size for max pooling.
stride: stride for pooling.
max_pool_size: the kernel size for max pooling.
@@ -280,7 +280,7 @@ def edge_aware_blur_pool2d(
edge_dilation_kernel_size: int = 3,
epsilon: float = 1e-6,
) -> torch.Tensor:
- r"""Blur the input torch.tensor while maintaining its edges.
+ r"""Blur the input torch.Tensor while maintaining its edges.
Args:
input: the input image to blur with shape :math:`(B, C, H, W)`.
@@ -290,7 +290,7 @@ def edge_aware_blur_pool2d(
epsilon: for numerical stability.
Returns:
- The blurred torch.tensor of shape :math:`(B, C, H, W)`.
+ The blurred torch.Tensor of shape :math:`(B, C, H, W)`.
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index cda6834a2..4944aa661 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -45,7 +45,7 @@ def canny(
.. image:: _static/img/canny.png
Args:
- input: input image torch.tensor with shape :math:`(B,C,H,W)`.
+ input: input image torch.Tensor with shape :math:`(B,C,H,W)`.
low_threshold: lower threshold for the hysteresis procedure.
high_threshold: upper threshold for the hysteresis procedure.
kernel_size: the size of the kernel for the gaussian blur.
@@ -165,7 +165,7 @@ class Canny(nn.Module):
r"""nn.Module that finds edges of the input image and filters them using the Canny algorithm.
Args:
- input: input image torch.tensor with shape :math:`(B,C,H,W)`.
+ input: input image torch.Tensor with shape :math:`(B,C,H,W)`.
low_threshold: lower threshold for the hysteresis procedure.
high_threshold: upper threshold for the hysteresis procedure.
kernel_size: the size of the kernel for the gaussian blur.
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 797da997e..d7c920fa8 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -209,7 +209,7 @@ class DexiNed(nn.Module):
r"""Definition of the DXtrem network from :cite:`xsoria2020dexined`.
Return:
- A list of torch.tensor with the intermediate features which the last element
+ A list of torch.Tensor with the intermediate features which the last element
is the edges map with shape :math:`(B,1,H,W)`.
Example:
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 8bdb07314..2bbfec6e3 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -36,17 +36,17 @@ def gaussian_blur2d(
border_type: str = "reflect",
separable: bool = True,
) -> torch.Tensor:
- r"""Create an operator that blurs a torch.tensor using a Gaussian filter.
+ r"""Create an operator that blurs a torch.Tensor using a Gaussian filter.
.. image:: _static/img/gaussian_blur2d.png
- The operator smooths the given torch.tensor with a gaussian kernel by convolving
+ The operator smooths the given torch.Tensor with a gaussian kernel by convolving
it to each channel. It supports batched operation.
Arguments:
- input: the input torch.tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.Tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel. Can be an integer or tuple of two integers (height, width).
- sigma: the standard deviation of the kernel. Can be a tuple of two floats or a torch.tensor
+ sigma: the standard deviation of the kernel. Can be a tuple of two floats or a torch.Tensor
with shape :math:`(B, 2)`. Values must be positive.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
@@ -54,10 +54,10 @@ def gaussian_blur2d(
separable: run as composition of two 1d-convolutions. Default: ``True``.
Returns:
- the blurred torch.tensor with shape :math:`(B, C, H, W)`.
+ the blurred torch.Tensor with shape :math:`(B, C, H, W)`.
Raises:
- RuntimeError: if input is not a 4D torch.tensor.
+ RuntimeError: if input is not a 4D torch.Tensor.
RuntimeError: if sigma values are not positive.
RuntimeError: if kernel_size is not a positive odd integer.
@@ -116,9 +116,9 @@ def gaussian_blur2d(
class GaussianBlur2d(nn.Module):
- r"""Create an operator that blurs a torch.tensor using a Gaussian filter.
+ r"""Create an operator that blurs a torch.Tensor using a Gaussian filter.
- The operator smooths the given torch.tensor with a gaussian kernel by convolving
+ The operator smooths the given torch.Tensor with a gaussian kernel by convolving
it to each channel. It supports batched operation.
Arguments:
@@ -130,7 +130,7 @@ class GaussianBlur2d(nn.Module):
separable: run as composition of two 1d-convolutions.
Returns:
- the blurred torch.tensor.
+ the blurred torch.Tensor.
Shape:
- Input: :math:`(B, C, H, W)`
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index cba43c990..b234ec4e2 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -134,7 +134,7 @@ def guided_blur(
border_type: str = "reflect",
subsample: int = 1,
) -> torch.Tensor:
- r"""Blur a torch.tensor using a Guided filter.
+ r"""Blur a torch.Tensor using a Guided filter.
.. image:: _static/img/guided_blur.png
@@ -142,8 +142,8 @@ def guided_blur(
and :cite:`he2015fast` for details. Guidance and input can have different number of channels.
Arguments:
- guidance: the guidance torch.tensor with shape :math:`(B,C,H,W)`.
- input: the input torch.tensor with shape :math:`(B,C,H,W)`.
+ guidance: the guidance torch.Tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.Tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel.
eps: regularization parameter. Smaller values preserve more edges.
border_type: the padding mode to be applied before convolving.
@@ -152,7 +152,7 @@ def guided_blur(
subsample: subsampling factor for Fast Guided filtering. Default: 1 (no subsampling)
Returns:
- the blurred torch.tensor with same shape as `input` :math:`(B, C, H, W)`.
+ the blurred torch.Tensor with same shape as `input` :math:`(B, C, H, W)`.
Examples:
>>> guidance = torch.rand(2, 3, 5, 5)
@@ -179,7 +179,7 @@ def guided_blur(
class GuidedBlur(nn.Module):
- r"""Blur a torch.tensor using a Guided filter.
+ r"""Blur a torch.Tensor using a Guided filter.
The operator is an edge-preserving image smoothing filter. See :cite:`he2010guided`
and :cite:`he2015fast` for details. Guidance and input can have different number of channels.
@@ -193,7 +193,7 @@ class GuidedBlur(nn.Module):
subsample: subsampling factor for Fast Guided filtering. Default: 1 (no subsampling)
Returns:
- the blurred input torch.tensor.
+ the blurred input torch.Tensor.
Shape:
- Input: :math:`(B, C, H, W)`, :math:`(B, C, H, W)`
diff --git a/kornia/filters/in_range.py b/kornia/filters/in_range.py
index 4597dda44..565b2cefd 100644
--- a/kornia/filters/in_range.py
+++ b/kornia/filters/in_range.py
@@ -32,25 +32,25 @@ def in_range(
upper: Union[tuple[Any, ...], torch.Tensor],
return_mask: bool = False,
) -> torch.Tensor:
- r"""Create a mask indicating whether elements of the input torch.tensor are within the specified range.
+ r"""Create a mask indicating whether elements of the input torch.Tensor are within the specified range.
.. image:: _static/img/in_range.png
- The formula applied for single-channel torch.tensor is:
+ The formula applied for single-channel torch.Tensor is:
.. math::
\text{out}(I) = \text{lower}(I) \leq \text{input}(I) \geq \text{upper}(I)
- The formula applied for multi-channel torch.tensor is:
+ The formula applied for multi-channel torch.Tensor is:
.. math::
\text{out}(I) = \bigwedge_{c=0}^{C}
\left( \text{lower}_c(I) \leq \text{input}_c(I) \geq \text{upper}_c(I) \right)
- torch.where `C` is the number of channels.
+ where `C` is the number of channels.
Args:
- input: The input torch.tensor to be filtered in the shape of :math:`(*, *, H, W)`.
+ input: The input torch.Tensor to be filtered in the shape of :math:`(*, *, H, W)`.
lower: The lower bounds of the filter (inclusive).
upper: The upper bounds of the filter (inclusive).
return_mask: If is true, the filtered mask is returned, otherwise the filtered input image.
@@ -65,14 +65,14 @@ def in_range(
.. note::
Clarification of `lower` and `upper`:
- - If provided as a tuple, it should have the same number of elements as the channels in the input torch.tensor.
+ - If provided as a tuple, it should have the same number of elements as the channels in the input torch.Tensor.
This bound is then applied uniformly across all batches.
- - When provided as a torch.tensor, it allows for different bounds to be applied to each batch.
- The torch.tensor shape should be (B, C, 1, 1), torch.where B is the batch size and C is
+ - When provided as a torch.Tensor, it allows for different bounds to be applied to each batch.
+ The torch.Tensor shape should be (B, C, 1, 1), where B is the batch size and C is
the number of channels.
- - If the torch.tensor has a 1-D shape, same bound will be applied across all batches.
+ - If the torch.Tensor has a 1-D shape, same bound will be applied across all batches.
Examples:
>>> rng = torch.manual_seed(1)
@@ -152,7 +152,7 @@ class InRange(nn.Module):
r"""Create a module for applying lower and upper bounds to input tensors.
Args:
- input: The input torch.tensor to be filtered.
+ input: The input torch.Tensor to be filtered.
lower: The lower bounds of the filter (inclusive).
upper: The upper bounds of the filter (inclusive).
return_mask: If is true, the filtered mask is returned, otherwise the filtered input image.
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 2d2e68592..ba307f80d 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -42,7 +42,7 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int) -> torc
kernel_size: the blurring kernel size.
Returns:
- the blurred input torch.tensor with shape :math:`(B,C,H,W)`.
+ the blurred input torch.Tensor with shape :math:`(B,C,H,W)`.
.. note::
See a working example `here <https://kornia.github.io/tutorials/nbs/filtering_operators.html>`__.
@@ -78,7 +78,7 @@ class MedianBlur(nn.Module):
kernel_size: the blurring kernel size.
Returns:
- the blurred input torch.tensor.
+ the blurred input torch.Tensor.
Shape:
- Input: :math:`(B, C, H, W)`
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index 83a275f8d..3031db458 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -31,7 +31,7 @@ _VALID_BORDER = {"constant", "reflect", "replicate", "circular"}
class MotionBlur(nn.Module):
- r"""Blur 2D images (4D torch.tensor) using the motion filter.
+ r"""Blur 2D images (4D torch.Tensor) using the motion filter.
Args:
kernel_size: motion kernel width and height. It should be odd and positive.
@@ -45,7 +45,7 @@ class MotionBlur(nn.Module):
mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
Returns:
- the blurred input torch.tensor.
+ the blurred input torch.Tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -79,7 +79,7 @@ class MotionBlur(nn.Module):
class MotionBlur3D(nn.Module):
- r"""Blur 3D volumes (5D torch.tensor) using the motion filter.
+ r"""Blur 3D volumes (5D torch.Tensor) using the motion filter.
Args:
kernel_size: motion kernel width and height. It should be odd and positive.
@@ -93,7 +93,7 @@ class MotionBlur3D(nn.Module):
mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
Returns:
- the blurred input torch.tensor.
+ the blurred input torch.Tensor.
Shape:
- Input: :math:`(B, C, D, H, W)`
@@ -151,20 +151,20 @@ def motion_blur(
border_type: str = "constant",
mode: str = "nearest",
) -> torch.Tensor:
- r"""Perform motion blur on torch.tensor images.
+ r"""Perform motion blur on torch.Tensor images.
.. image:: _static/img/motion_blur.png
Args:
- input: the input torch.tensor with shape :math:`(B, C, H, W)`.
+ input: the input torch.Tensor with shape :math:`(B, C, H, W)`.
kernel_size: motion kernel width and height. It should be odd and positive.
angle (Union[torch.Tensor, float]): angle of the motion blur in degrees (anti-clockwise rotation).
- If torch.tensor, it must be :math:`(B,)`.
+ If torch.Tensor, it must be :math:`(B,)`.
direction : forward/backward direction of the motion blur.
Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
uniformly (but still angled) motion blur.
- If torch.tensor, it must be :math:`(B,)`.
+ If torch.Tensor, it must be :math:`(B,)`.
border_type: the padding mode to be applied before convolving. The expected modes are:
``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.
mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
@@ -196,18 +196,18 @@ def motion_blur3d(
border_type: str = "constant",
mode: str = "nearest",
) -> torch.Tensor:
- r"""Perform motion blur on 3D volumes (5D torch.tensor).
+ r"""Perform motion blur on 3D volumes (5D torch.Tensor).
Args:
- input: the input torch.tensor with shape :math:`(B, C, D, H, W)`.
+ input: the input torch.Tensor with shape :math:`(B, C, D, H, W)`.
kernel_size: motion kernel width, height and depth. It should be odd and positive.
angle: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
- If torch.tensor, it must be :math:`(B, 3)`.
+ If torch.Tensor, it must be :math:`(B, 3)`.
direction: forward/backward direction of the motion blur.
Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
uniformly (but still angled) motion blur.
- If torch.tensor, it must be :math:`(B,)`.
+ If torch.Tensor, it must be :math:`(B,)`.
border_type: the padding mode to be applied before convolving. The expected modes are:
``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.
mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index a24eebad2..b237e01da 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -34,7 +34,7 @@ def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, n
.. image:: _static/img/spatial_gradient.png
Args:
- input: input image torch.tensor with shape :math:`(B, C, H, W)`.
+ input: input image torch.Tensor with shape :math:`(B, C, H, W)`.
mode: derivatives modality, can be: `sobel` or `diff`.
order: the order of the derivatives.
normalized: whether the output is normalized.
@@ -76,7 +76,7 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1)
r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
Args:
- input: input features torch.tensor with shape :math:`(B, C, D, H, W)`.
+ input: input features torch.Tensor with shape :math:`(B, C, D, H, W)`.
mode: derivatives modality, can be: `sobel` or `diff`.
order: the order of the derivatives.
@@ -115,7 +115,7 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1)
tmp_kernel = kernel.repeat(c, 1, 1, 1, 1)
- # convolve input torch.tensor with grad kernel
+ # convolve input torch.Tensor with grad kernel
kernel_flip = tmp_kernel.flip(-3)
# Pad with "replicate for spatial dims, but with torch.zeros for channel
diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.py
index 07119c815..ce5934852 100644
--- a/kornia/filters/unsharp.py
+++ b/kornia/filters/unsharp.py
@@ -29,12 +29,12 @@ def unsharp_mask(
sigma: tuple[float, float] | torch.Tensor,
border_type: str = "reflect",
) -> torch.Tensor:
- r"""Create an operator that sharpens a torch.tensor by applying operation out = 2 * image - gaussian_blur2d(image).
+ r"""Create an operator that sharpens a torch.Tensor by applying operation out = 2 * image - gaussian_blur2d(image).
.. image:: _static/img/unsharp_mask.png
Args:
- input: the input torch.tensor with shape :math:`(B,C,H,W)`.
+ input: the input torch.Tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel.
sigma: the standard deviation of the kernel.
border_type: the padding mode to be applied before convolving.
@@ -42,7 +42,7 @@ def unsharp_mask(
``'replicate'`` or ``'circular'``.
Returns:
- the blurred torch.tensor with shape :math:`(B,C,H,W)`.
+ the blurred torch.Tensor with shape :math:`(B,C,H,W)`.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -66,7 +66,7 @@ class UnsharpMask(nn.Module):
``'replicate'`` or ``'circular'``.
Returns:
- the sharpened torch.tensor with shape :math:`(B,C,H,W)`.
+ the sharpened torch.Tensor with shape :math:`(B,C,H,W)`.
Shape:
- Input: :math:`(B, C, H, W)`
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 4dc7a94db..4f449cb27 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -440,6 +440,7 @@ class Boxes:
Args:
boxes: 2D boxes, shape of :math:`(N, 4)`, :math:`(B, N, 4)`, :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
mode: The format in which the boxes are provided.
+ validate_boxes: Check if boxes are valid. Default is True.
* 'xyxy': boxes are assumed to be in the format ``xmin, ymin, xmax, ymax`` where ``width = xmax - xmin``
and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index 51b5445ca..e6da068e6 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -85,18 +85,18 @@ def solve_pnp_dlt(
twisted cubic. However, this function does not check for this condition.
Args:
- world_points : A torch.tensor with shape :math:`(B, N, 3)` representing
+ world_points : A torch.Tensor with shape :math:`(B, N, 3)` representing
the points in the world space.
- img_points : A torch.tensor with shape :math:`(B, N, 2)` representing
+ img_points : A torch.Tensor with shape :math:`(B, N, 2)` representing
the points in the image space.
- intrinsics : A torch.tensor with shape :math:`(B, 3, 3)` representing
+ intrinsics : A torch.Tensor with shape :math:`(B, 3, 3)` representing
the intrinsic matrices.
- weights : A torch.tensor with shape :math:`(B, N)` representing the
+ weights : A torch.Tensor with shape :math:`(B, N)` representing the
weights for each point. If None, all points are considered to be equally important.
svd_eps : A small float value to avoid numerical precision issues.
Returns:
- A torch.tensor with shape :math:`(B, 3, 4)` representing the estimated world to
+ A torch.Tensor with shape :math:`(B, 3, 4)` representing the estimated world to
camera transformation matrices (also known as the extrinsic matrices).
Example:
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index a105cf99e..5c18454a3 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -29,12 +29,12 @@ class PinholeCamera:
r"""Class that represents a Pinhole Camera model.
Args:
- intrinsics: torch.tensor with shape :math:`(B, 4, 4)`
+ intrinsics: torch.Tensor with shape :math:`(B, 4, 4)`
containing the full 4x4 camera calibration matrix.
- extrinsics: torch.tensor with shape :math:`(B, 4, 4)`
+ extrinsics: torch.Tensor with shape :math:`(B, 4, 4)`
containing the full 4x4 rotation-translation matrix.
- height: torch.tensor with shape :math:`(B)` containing the image height.
- width: torch.tensor with shape :math:`(B)` containing the image width.
+ height: torch.Tensor with shape :math:`(B)` containing the image height.
+ width: torch.Tensor with shape :math:`(B)` containing the image width.
.. note::
We assume that the class attributes are in batch form in order to take
@@ -98,7 +98,7 @@ class PinholeCamera:
r"""The full 4x4 intrinsics matrix.
Returns:
- torch.tensor of shape :math:`(B, 4, 4)`.
+ torch.Tensor of shape :math:`(B, 4, 4)`.
"""
if not self._check_valid_params(self._intrinsics, "intrinsics"):
@@ -110,7 +110,7 @@ class PinholeCamera:
r"""The full 4x4 extrinsics matrix.
Returns:
- torch.tensor of shape :math:`(B, 4, 4)`.
+ torch.Tensor of shape :math:`(B, 4, 4)`.
"""
if not self._check_valid_params(self._extrinsics, "extrinsics"):
@@ -132,7 +132,7 @@ class PinholeCamera:
r"""Return the focal length in the x-direction.
Returns:
- torch.tensor of shape :math:`(B)`.
+ torch.Tensor of shape :math:`(B)`.
"""
return self.intrinsics[..., 0, 0]
@@ -142,7 +142,7 @@ class PinholeCamera:
r"""Return the focal length in the y-direction.
Returns:
- torch.tensor of shape :math:`(B)`.
+ torch.Tensor of shape :math:`(B)`.
"""
return self.intrinsics[..., 1, 1]
@@ -152,7 +152,7 @@ class PinholeCamera:
r"""Return the x-coordinate of the principal point.
Returns:
- torch.tensor of shape :math:`(B)`.
+ torch.Tensor of shape :math:`(B)`.
"""
return self.intrinsics[..., 0, 2]
@@ -162,7 +162,7 @@ class PinholeCamera:
r"""Return the y-coordinate of the principal point.
Returns:
- torch.tensor of shape :math:`(B)`.
+ torch.Tensor of shape :math:`(B)`.
"""
return self.intrinsics[..., 1, 2]
@@ -172,7 +172,7 @@ class PinholeCamera:
r"""Return the x-coordinate of the translation vector.
Returns:
- torch.tensor of shape :math:`(B)`.
+ torch.Tensor of shape :math:`(B)`.
"""
return self.extrinsics[..., 0, -1]
@@ -187,7 +187,7 @@ class PinholeCamera:
r"""Return the y-coordinate of the translation vector.
Returns:
- torch.tensor of shape :math:`(B)`.
+ torch.Tensor of shape :math:`(B)`.
"""
return self.extrinsics[..., 1, -1]
@@ -202,7 +202,7 @@ class PinholeCamera:
r"""Returns the z-coordinate of the translation vector.
Returns:
- torch.tensor of shape :math:`(B)`.
+ torch.Tensor of shape :math:`(B)`.
"""
return self.extrinsics[..., 2, -1]
@@ -217,7 +217,7 @@ class PinholeCamera:
r"""Return the 3x4 rotation-translation matrix.
Returns:
- torch.tensor of shape :math:`(B, 3, 4)`.
+ torch.Tensor of shape :math:`(B, 3, 4)`.
"""
return self.extrinsics[..., :3, :4]
@@ -227,7 +227,7 @@ class PinholeCamera:
r"""Return the 3x3 camera matrix containing the intrinsics.
Returns:
- torch.tensor of shape :math:`(B, 3, 3)`.
+ torch.Tensor of shape :math:`(B, 3, 3)`.
"""
return self.intrinsics[..., :3, :3]
@@ -237,7 +237,7 @@ class PinholeCamera:
r"""Return the 3x3 rotation matrix from the extrinsics.
Returns:
- torch.tensor of shape :math:`(B, 3, 3)`.
+ torch.Tensor of shape :math:`(B, 3, 3)`.
"""
return self.extrinsics[..., :3, :3]
@@ -247,7 +247,7 @@ class PinholeCamera:
r"""Return the translation vector from the extrinsics.
Returns:
- torch.tensor of shape :math:`(B, 3, 1)`.
+ torch.Tensor of shape :math:`(B, 3, 1)`.
"""
return self.extrinsics[..., :3, -1:]
@@ -264,7 +264,7 @@ class PinholeCamera:
r"""Return the inverse of the 4x4 instrisics matrix.
Returns:
- torch.tensor of shape :math:`(B, 4, 4)`.
+ torch.Tensor of shape :math:`(B, 4, 4)`.
"""
return self.intrinsics.inverse()
@@ -273,7 +273,7 @@ class PinholeCamera:
r"""Scale the pinhole model.
Args:
- scale_factor: a torch.tensor with the scale factor. It has
+ scale_factor: a torch.Tensor with the scale factor. It has
to be broadcastable with class members. The expected shape is
:math:`(B)` or :math:`(1)`.
@@ -296,7 +296,7 @@ class PinholeCamera:
r"""Scale the pinhole model in-place.
Args:
- scale_factor: a torch.tensor with the scale factor. It has
+ scale_factor: a torch.Tensor with the scale factor. It has
to be broadcastable with class members. The expected shape is
:math:`(B)` or :math:`(1)`.
@@ -318,11 +318,11 @@ class PinholeCamera:
r"""Project a 3d point in world coordinates onto the 2d camera plane.
Args:
- point_3d: torch.tensor containing the 3d points to be projected
- to the camera plane. The shape of the torch.tensor can be :math:`(*, 3)`.
+ point_3d: torch.Tensor containing the 3d points to be projected
+ to the camera plane. The shape of the torch.Tensor can be :math:`(*, 3)`.
Returns:
- torch.tensor of (u, v) cam coordinates with shape :math:`(*, 2)`.
+ torch.Tensor of (u, v) cam coordinates with shape :math:`(*, 2)`.
Example:
>>> _ = torch.manual_seed(0)
@@ -345,16 +345,16 @@ class PinholeCamera:
Transform coordinates in the pixel frame to the world frame.
Args:
- point_2d: torch.tensor containing the 2d to be projected to
- world coordinates. The shape of the torch.tensor can be :math:`(*, 2)`.
- depth: torch.tensor containing the depth value of each 2d
- points. The torch.tensor shape must be equal to point2d :math:`(*, 1)`.
+ point_2d: torch.Tensor containing the 2d to be projected to
+ world coordinates. The shape of the torch.Tensor can be :math:`(*, 2)`.
+ depth: torch.Tensor containing the depth value of each 2d
+ points. The torch.Tensor shape must be equal to point2d :math:`(*, 1)`.
normalize: whether to F.normalize the pointcloud. This
must be set to `True` when the depth is represented as the Euclidean
ray length from the camera position.
Returns:
- torch.tensor of (x, y, z) world coordinates with shape :math:`(*, 3)`.
+ torch.Tensor of (x, y, z) world coordinates with shape :math:`(*, 3)`.
Example:
>>> _ = torch.manual_seed(0)
@@ -418,9 +418,9 @@ class PinholeCamerasList(PinholeCamera):
it will keep the same class properties but with an extra dimension.
.. note::
- The underlying data torch.tensor will be stacked in the first dimension.
- That's it, given a list of two camera instances, the intrinsics torch.tensor
- will have a shape :math:`(B, N, 4, 4)` torch.where :math:`B` is the batch
+ The underlying data torch.Tensor will be stacked in the first dimension.
+ That's it, given a list of two camera instances, the intrinsics torch.Tensor
+ will have a shape :math:`(B, N, 4, 4)` where :math:`B` is the batch
size and :math:`N` is the numbers of cameras (in this case two).
Args:
@@ -476,11 +476,11 @@ def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
:attr:`kornia.PinholeCamera.camera_matrix`.
Args:
- pinholes: torch.tensor of pinhole models.
+ pinholes: torch.Tensor of pinhole models.
eps: epsilon for numerical stability.
Returns:
- torch.tensor of pinhole matrices.
+ torch.Tensor of pinhole matrices.
Shape:
- Input: :math:`(N, 12)`
@@ -522,11 +522,11 @@ def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Te
:attr:`kornia.PinholeCamera.intrinsics_inverse()`.
Args:
- pinhole: torch.tensor with pinhole models.
+ pinhole: torch.Tensor with pinhole models.
eps: epsilon for numerical stability.
Returns:
- torch.tensor of inverted pinhole matrices.
+ torch.Tensor of inverted pinhole matrices.
Shape:
- Input: :math:`(N, 12)`
@@ -568,11 +568,11 @@ def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
:attr:`kornia.PinholeCamera.scale()`.
Args:
- pinholes: torch.tensor with the pinhole model.
- scale: torch.tensor of scales.
+ pinholes: torch.Tensor with the pinhole model.
+ scale: torch.Tensor of scales.
Returns:
- torch.tensor of scaled pinholes.
+ torch.Tensor of scaled pinholes.
Shape:
- Input: :math:`(N, 12)` and :math:`(N, 1)`
@@ -603,16 +603,16 @@ def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:
"""Compute extrinsic transformation matrices for pinholes.
Args:
- pinholes: torch.tensor of form [fx fy cx cy h w rx ry rz tx ty tz]
+ pinholes: torch.Tensor of form [fx fy cx cy h w rx ry rz tx ty tz]
of size (N, 12).
Returns:
- torch.tensor of extrinsic transformation matrices of size (N, 4, 4).
+ torch.Tensor of extrinsic transformation matrices of size (N, 4, 4).
"""
if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):
raise AssertionError(pinholes.shape)
- # TODO: torch.where is rtvec_to_pose?
+ # TODO: where is rtvec_to_pose?
raise NotImplementedError
# TODO: We have rtvec_to_pose in torchgeometry
# https://github.com/whh14/torchgeometry/blob/master/torchgeometry/conversions.py#L240
@@ -642,8 +642,8 @@ def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> to
H_{ref}^{i} = K_{i} * T_{ref}^{i} * K_{ref}^{-1}
Args:
- pinhole_i: torch.tensor with pinhole model for ith frame.
- pinhole_ref: torch.tensor with pinhole model for reference frame.
+ pinhole_i: torch.Tensor with pinhole model for ith frame.
+ pinhole_ref: torch.Tensor with pinhole model for reference frame.
Returns:
tensors that convert depth points (u, v, d) from pinhole_ref to pinhole_i.
@@ -682,7 +682,7 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: t
pixel_coords: the grid with (u, v, 1) pixel coordinates. Shape must be BxHxWx3.
Returns:
- torch.tensor of shape BxHxWx3 with (x, y, z) cam coordinates.
+ torch.Tensor of shape BxHxWx3 with (x, y, z) cam coordinates.
"""
if not len(depth.shape) == 4 and depth.shape[1] == 1:
@@ -709,7 +709,7 @@ def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: flo
eps: small value to avoid division by zero error.
Returns:
- torch.tensor of shape BxHxWx2 with (u, v) pixel coordinates.
+ torch.Tensor of shape BxHxWx2 with (u, v) pixel coordinates.
"""
if not len(cam_coords_src.shape) == 4 and cam_coords_src.shape[3] == 3:
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index 2c079fafc..37f74020c 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -153,7 +153,7 @@ class StereoCamera:
camera are assumed to be equal.
Returns:
- torch.tensor of shape :math:`(B)`
+ torch.Tensor of shape :math:`(B)`
"""
return self.rectified_left_camera[..., 0, 0]
@@ -166,7 +166,7 @@ class StereoCamera:
camera are assumed to be equal.
Returns:
- torch.tensor of shape :math:`(B)`
+ torch.Tensor of shape :math:`(B)`
"""
return self.rectified_left_camera[..., 1, 1]
@@ -176,7 +176,7 @@ class StereoCamera:
r"""Return the x-coordinate of the principal point for the left camera.
Returns:
- torch.tensor of shape :math:`(B)`
+ torch.Tensor of shape :math:`(B)`
"""
return self.rectified_left_camera[..., 0, 2]
@@ -186,7 +186,7 @@ class StereoCamera:
r"""Return the x-coordinate of the principal point for the right camera.
Returns:
- torch.tensor of shape :math:`(B)`
+ torch.Tensor of shape :math:`(B)`
"""
return self.rectified_right_camera[..., 0, 2]
@@ -199,7 +199,7 @@ class StereoCamera:
is assumed to be equal for the left and right camera.
Returns:
- torch.tensor of shape :math:`(B)`
+ torch.Tensor of shape :math:`(B)`
"""
return self.rectified_left_camera[..., 1, 2]
@@ -218,7 +218,7 @@ class StereoCamera:
def Q(self) -> torch.Tensor:
r"""The Q matrix of the horizontal stereo setup.
- This matrix is used for reprojecting a disparity torch.tensor to
+ This matrix is used for reprojecting a disparity torch.Tensor to
the corresponding point cloud. Note that this is in a general form that allows different focal
lengths in the x and y direction.
@@ -247,10 +247,10 @@ class StereoCamera:
return Q
def reproject_disparity_to_3D(self, disparity_tensor: torch.Tensor) -> torch.Tensor:
- r"""Reproject the disparity torch.tensor to a 3D point cloud.
+ r"""Reproject the disparity torch.Tensor to a 3D point cloud.
Args:
- disparity_tensor: Disparity torch.tensor of shape :math:`(B, 1, H, W)`.
+ disparity_tensor: Disparity torch.Tensor of shape :math:`(B, 1, H, W)`.
Returns:
The 3D point cloud of shape :math:`(B, H, W, 3)`
@@ -260,10 +260,10 @@ class StereoCamera:
def _check_disparity_tensor(disparity_tensor: torch.Tensor) -> None:
- r"""Ensure correct user provided correct disparity torch.tensor.
+ r"""Ensure correct user provided correct disparity torch.Tensor.
Args:
- disparity_tensor: The disparity torch.tensor of shape :math:`(B, 1, H, W)`.
+ disparity_tensor: The disparity torch.Tensor of shape :math:`(B, 1, H, W)`.
"""
if not isinstance(disparity_tensor, torch.Tensor):
@@ -310,10 +310,10 @@ def _check_Q_matrix(Q_matrix: torch.Tensor) -> None:
def reproject_disparity_to_3D(disparity_tensor: torch.Tensor, Q_matrix: torch.Tensor) -> torch.Tensor:
- r"""Reproject the disparity torch.tensor to a 3D point cloud.
+ r"""Reproject the disparity torch.Tensor to a 3D point cloud.
Args:
- disparity_tensor: Disparity torch.tensor of shape :math:`(B, H, W, 1)`.
+ disparity_tensor: Disparity torch.Tensor of shape :math:`(B, H, W, 1)`.
Q_matrix: torch.Tensor of Q matrices of shapes :math:`(B, 4, 4)`.
Returns:
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 9e97ef657..07a1e464d 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -758,7 +758,7 @@ def find_essential(
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)`.
+ weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
Returns:
the computed essential matrices with shape :math:`(B, 10, 3, 3)`.
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index c62067d06..4ed7bea46 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -309,7 +309,7 @@ class Se2(nn.Module):
"""Create an Se2 group from a matrix.
Args:
- matrix: torch.tensor of shape :math:`(B, 3, 3)`.
+ matrix: torch.Tensor of shape :math:`(B, 3, 3)`.
Example:
>>> s = Se2.from_matrix(torch.eye(3).repeat(2, 1, 1))
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 31bfe5def..d073221af 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -57,7 +57,7 @@ class Se3(nn.Module):
Args:
rotation: So3 group encompassing a rotation.
- translation: Vector3 or translation torch.tensor with the shape of :math:`(B, 3)`.
+ translation: Vector3 or translation torch.Tensor with the shape of :math:`(B, 3)`.
Example:
>>> from kornia.geometry.quaternion import Quaternion
@@ -306,7 +306,7 @@ class Se3(nn.Module):
"""Create a Se3 group from a matrix.
Args:
- matrix: torch.tensor of shape :math:`(B, 4, 4)`.
+ matrix: torch.Tensor of shape :math:`(B, 4, 4)`.
Example:
>>> s = Se3.from_matrix(torch.eye(4))
@@ -327,7 +327,7 @@ class Se3(nn.Module):
"""Create a Se3 group a quaternion and translation vector.
Args:
- qxyz: torch.tensor of shape :math:`(B, 7)`.
+ qxyz: torch.Tensor of shape :math:`(B, 7)`.
Example:
>>> qxyz = torch.tensor([1., 2., 3., 0., 0., 0., 1.])
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index d9db81972..f76be1160 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -159,7 +159,7 @@ class So3(nn.Module):
"""Convert elements from vector space to lie algebra. Returns matrix of shape :math:`(B,3,3)`.
Args:
- v: Vector3 or torch.tensor of shape :math:`(B,3)`.
+ v: Vector3 or torch.Tensor of shape :math:`(B,3)`.
Example:
>>> v = torch.ones((1,3))
@@ -258,7 +258,7 @@ class So3(nn.Module):
@classmethod
def from_wxyz(cls, wxyz: torch.Tensor) -> So3:
- """Create So3 from a torch.tensor representing a quaternion.
+ """Create So3 from a torch.Tensor representing a quaternion.
Args:
wxyz: the quaternion to convert of shape :math:`(B,4)`.
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index fb023cb34..2a821b62f 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -50,7 +50,7 @@ class Quaternion(nn.Module):
Q = a + b \cdot \mathbf{i} + c \cdot \mathbf{j} + d \cdot \mathbf{k}
- Thus, we represent a rotation quaternion as a contiguous torch.tensor structure to
+ Thus, we represent a rotation quaternion as a contiguous torch.Tensor structure to
perform rigid bodies transformations:
.. math::
@@ -77,10 +77,10 @@ class Quaternion(nn.Module):
_data: Union[torch.Tensor, nn.Parameter]
def __init__(self, data: Union[torch.Tensor, nn.Parameter]) -> None:
- """Construct a quaternion from torch.tensor or parameter data.
+ """Construct a quaternion from torch.Tensor or parameter data.
Args:
- data: torch.tensor or parameter containing the quaternion data with the shape of :math:`(B, 4)`.
+ data: torch.Tensor or parameter containing the quaternion data with the shape of :math:`(B, 4)`.
Example:
>>> # Create with torch.tensor(no gradients tracked by default)
@@ -101,8 +101,8 @@ class Quaternion(nn.Module):
"""Move and/or cast the quaternion data.
Args:
- *args: Arguments to pass to torch.tensor.to()
- **kwargs: Keyword arguments to pass to torch.tensor.to()
+ *args: Arguments to pass to torch.Tensor.to()
+ **kwargs: Keyword arguments to pass to torch.Tensor.to()
Returns:
A new Quaternion with converted data.
@@ -110,12 +110,12 @@ class Quaternion(nn.Module):
return Quaternion(self._data.to(*args, **kwargs))
def _to_scalar_quaternion(self, value: Union[torch.Tensor, float]) -> "Quaternion":
- """Convert a scalar, torch.tensor, or numeric value to a scalar quaternion.
+ """Convert a scalar, torch.Tensor, or numeric value to a scalar quaternion.
- A scalar quaternion has the form [real, 0, 0, 0] torch.where real is the input value.
+ A scalar quaternion has the form [real, 0, 0, 0] where real is the input value.
Args:
- value: The scalar, torch.tensor, or numeric value to convert.
+ value: The scalar, torch.Tensor, or numeric value to convert.
Returns:
A Quaternion object representing the scalar quaternion.
@@ -167,10 +167,10 @@ class Quaternion(nn.Module):
return Quaternion(-self.data)
def __add__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion":
- """Add a given quaternion, scalar, or torch.tensor.
+ """Add a given quaternion, scalar, or torch.Tensor.
Args:
- right: the quaternion, scalar, or torch.tensor to add.
+ right: the quaternion, scalar, or torch.Tensor to add.
Example:
>>> q1 = Quaternion.identity()
@@ -187,10 +187,10 @@ class Quaternion(nn.Module):
return Quaternion(self.data + right_quat.data)
def __sub__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion":
- """Subtract a given quaternion, scalar, or torch.tensor.
+ """Subtract a given quaternion, scalar, or torch.Tensor.
Args:
- right: the quaternion, scalar, or torch.tensor to subtract.
+ right: the quaternion, scalar, or torch.Tensor to subtract.
Example:
>>> q1 = Quaternion(torch.tensor([2., 0., 1., 1.]))
@@ -204,10 +204,10 @@ class Quaternion(nn.Module):
return Quaternion(self.data - right.data)
else:
right_quat = self._to_scalar_quaternion(right)
- # For scalar operations, ensure we return a torch.tensor to preserve gradients
+ # For scalar operations, ensure we return a torch.Tensor to preserve gradients
result_data = self.data - right_quat.data
if isinstance(result_data, nn.Parameter):
- result_data = result_data.data # Convert to torch.tensor to preserve gradients
+ result_data = result_data.data # Convert to torch.Tensor to preserve gradients
return Quaternion(result_data)
def __mul__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion":
@@ -221,7 +221,7 @@ class Quaternion(nn.Module):
)
return Quaternion(torch.cat((new_real[..., None], new_vec), -1))
- # If right is a scalar/torch.tensor, convert to scalar quaternion and multiply
+ # If right is a scalar/torch.Tensor, convert to scalar quaternion and multiply
else:
right_quat = self._to_scalar_quaternion(right)
new_real = self.real * right_quat.real - batched_dot_product(self.vec, right_quat.vec)
@@ -233,7 +233,7 @@ class Quaternion(nn.Module):
return Quaternion(torch.cat((new_real[..., None], new_vec), -1))
def __rmul__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
- """Right multiplication (left * self) torch.where left is a scalar or torch.tensor."""
+ """Right multiplication (left * self) where left is a scalar or torch.Tensor."""
left_quat = self._to_scalar_quaternion(left)
new_real = left_quat.real * self.real - batched_dot_product(left_quat.vec, self.vec)
new_vec = (
@@ -257,35 +257,35 @@ class Quaternion(nn.Module):
if right_tensor.dim() == 0: # scalar
divisor = right_tensor.expand_as(self.data[..., 0]).unsqueeze(-1).expand_as(self.data)
else:
- # Broadcast the torch.tensor to match the quaternion dimensions
+ # Broadcast the torch.Tensor to match the quaternion dimensions
divisor = right_tensor.unsqueeze(-1).expand_as(self.data)
- # For scalar operations, ensure we return a torch.tensor to preserve gradients
+ # For scalar operations, ensure we return a torch.Tensor to preserve gradients
result_data = self.data / divisor
if isinstance(result_data, nn.Parameter):
- result_data = result_data.data # Convert to torch.tensor to preserve gradients
+ result_data = result_data.data # Convert to torch.Tensor to preserve gradients
return Quaternion(result_data)
def __truediv__(self, right: Union[torch.Tensor, "Quaternion", float]) -> "Quaternion":
return self.__div__(right)
def __radd__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
- """Right addition (left + self) torch.where left is a scalar or torch.tensor."""
+ """Right addition (left + self) where left is a scalar or torch.Tensor."""
left_quat = self._to_scalar_quaternion(left)
return left_quat + self
def __rsub__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
- """Right subtraction (left - self) torch.where left is a scalar or torch.tensor."""
+ """Right subtraction (left - self) where left is a scalar or torch.Tensor."""
left_quat = self._to_scalar_quaternion(left)
return left_quat - self
def __rtruediv__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
- """Right division (left / self) torch.where left is a scalar or torch.tensor."""
+ """Right division (left / self) where left is a scalar or torch.Tensor."""
left_quat = self._to_scalar_quaternion(left)
return left_quat / self
def __rdiv__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
- """Right division (left / self) torch.where left is a scalar or torch.tensor."""
+ """Right division (left / self) where left is a scalar or torch.Tensor."""
return self.__rtruediv__(left)
def __pow__(self, t: float) -> "Quaternion":
@@ -580,7 +580,7 @@ class Quaternion(nn.Module):
keepdim: whether to retain the last dimension.
Returns:
- The norm of the quaternion(s) as a torch.tensor.
+ The norm of the quaternion(s) as a torch.Tensor.
Example:
>>> q = Quaternion.identity()
@@ -634,7 +634,7 @@ class Quaternion(nn.Module):
"""Compute the squared norm (magnitude) of the quaternion.
Returns:
- The squared norm of the quaternion(s) as a torch.tensor.
+ The squared norm of the quaternion(s) as a torch.Tensor.
Example:
>>> q = Quaternion.identity()
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index 6f1530172..ea781a39e 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -36,14 +36,14 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:
coeffs : The coefficients of quadratic equation :`(B, 3)`
Returns:
- A torch.tensor of shape `(B, 2)` containing the real roots to the quadratic equation.
+ A torch.Tensor of shape `(B, 2)` containing the real roots to the quadratic equation.
Example:
>>> coeffs = torch.tensor([[1., 4., 4.]])
>>> roots = solve_quadratic(coeffs)
.. note::
- In cases torch.where a quadratic polynomial has only one real root, the output will be in the format
+ In cases where a quadratic polynomial has only one real root, the output will be in the format
[real_root, 0]. And for the torch.complex roots should be represented as 0. This is done to maintain
a consistent output shape for all cases.
@@ -65,7 +65,7 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:
# Calculate 1/(2*a) for efficient computation
inv_2a = 0.5 / a
- # Initialize solutions torch.tensor
+ # Initialize solutions torch.Tensor
solutions = torch.zeros((coeffs.shape[0], 2), device=coeffs.device, dtype=coeffs.dtype)
# Handle cases with zero discriminant
@@ -98,14 +98,14 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:
coeffs : The coefficients cubic equation : `(B, 4)`
Returns:
- A torch.tensor of shape `(B, 3)` containing the real roots to the cubic equation.
+ A torch.Tensor of shape `(B, 3)` containing the real roots to the cubic equation.
Example:
>>> coeffs = torch.tensor([[32., 3., -11., -6.]])
>>> roots = solve_cubic(coeffs)
.. note::
- In cases torch.where a cubic polynomial has only one or two real roots, the output for the non-real
+ In cases where a cubic polynomial has only one or two real roots, the output for the non-real
roots should be represented as 0. Thus, the output for a single real root should be in the
format [real_root, 0, 0], and for two real roots, it should be [real_root_1, real_root_2, 0].
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 699933763..6909def36 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -43,7 +43,7 @@ def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor] =
instead applies Softmax over features at each spatial location.
Args:
- input: the input torch.tensor with shape :math:`(B, N, H, W)`.
+ input: the input torch.Tensor with shape :math:`(B, N, H, W)`.
temperature: factor to apply to input, adjusting the "smoothness" of the output distribution.
Returns:
@@ -80,7 +80,7 @@ def spatial_expectation2d(input: torch.Tensor, normalized_coordinates: bool = Tr
which can be achieved using :func:`~kornia.geometry.subpixel.spatial_softmax2d`.
Args:
- input: the input torch.tensor representing dense spatial probabilities with shape :math:`(B, N, H, W)`.
+ input: the input torch.Tensor representing dense spatial probabilities with shape :math:`(B, N, H, W)`.
normalized_coordinates: whether to return the coordinates normalized in the range
of :math:`[-1, 1]`. Otherwise, it will return the coordinates in the range of the input shape.
@@ -132,7 +132,7 @@ def render_gaussian2d(
in the range of :math:`[-1, 1]`. Otherwise, coordinates are assumed to be in the range of the output shape.
Returns:
- torch.tensor including rendered points with shape :math:`(*, H, W)`.
+ torch.Tensor including rendered points with shape :math:`(*, H, W)`.
"""
if not (std.dtype == mean.dtype and std.device == mean.device):
@@ -157,7 +157,7 @@ def render_gaussian2d(
# Gaussian PDF = exp(-(x - \mu)^2 / (2 \sigma^2))
# = exp(dists * ks),
- # torch.where dists = (x - \mu)^2 and ks = -1 / (2 \sigma^2)
+ # where dists = (x - \mu)^2 and ks = -1 / (2 \sigma^2)
# dists <- (x - \mu)^2
dist_x_sq = (xs - mu_x) ** 2
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index d7d4e20c6..fa8945ea7 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -275,7 +275,7 @@ def conv_soft_argmax2d(
.. math::
val(X) = \frac{\sum{x * exp(x / T) \in X}} {\sum{exp(x / T) \in X}}
- torch.where :math:`T` is temperature.
+ where :math:`T` is temperature.
Args:
input: the given heatmap with shape :math:`(N, C, H_{in}, W_{in})`.
@@ -293,7 +293,7 @@ def conv_soft_argmax2d(
On each window, the function computed returns with shapes :math:`(N, C, 2, H_{out},
W_{out})`, :math:`(N, C, H_{out}, W_{out})`,
- torch.where
+ where
.. math::
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] -
@@ -315,7 +315,7 @@ def conv_soft_argmax2d(
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
if temperature <= 0:
- raise ValueError(f"Temperature should be positive float or torch.tensor. Got: {temperature}")
+ raise ValueError(f"Temperature should be positive float or torch.Tensor. Got: {temperature}")
b, c, h, w = input.shape
ky, kx = kernel_size
@@ -390,7 +390,7 @@ def conv_soft_argmax3d(
.. math::
val(X) = \frac{\sum{x * exp(x / T) \in X}} {\sum{exp(x / T) \in X}}
- torch.where ``T`` is temperature.
+ where ``T`` is temperature.
Args:
input: the given heatmap with shape :math:`(N, C, D_{in}, H_{in}, W_{in})`.
@@ -410,7 +410,7 @@ def conv_soft_argmax3d(
On each window, the function computed returns with shapes :math:`(N, C, 3, D_{out}, H_{out}, W_{out})`,
:math:`(N, C, D_{out}, H_{out}, W_{out})`,
- torch.where
+ where
.. math::
D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -
@@ -436,7 +436,7 @@ def conv_soft_argmax3d(
raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")
if temperature <= 0:
- raise ValueError(f"Temperature should be positive float or torch.tensor. Got: {temperature}")
+ raise ValueError(f"Temperature should be positive float or torch.Tensor. Got: {temperature}")
b, c, d, h, w = input.shape
kz, ky, kx = kernel_size
@@ -570,7 +570,7 @@ def conv_quad_interp3d(
the location and value per each 3x3x3 window which contains strict extremum, similar to one done is SIFT.
:math:`(N, C, 3, D_{out}, H_{out}, W_{out})`, :math:`(N, C, D_{out}, H_{out}, W_{out})`,
- torch.where
+ where
.. math::
D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -
@@ -599,7 +599,7 @@ def conv_quad_interp3d(
grid_global: torch.Tensor = create_meshgrid3d(D, H, W, False, device=input.device).permute(0, 4, 1, 2, 3)
grid_global = grid_global.to(input.dtype)
- # to determine the location we are solving system of linear equations Ax = b, torch.where b is 1st order gradient
+ # to determine the location we are solving system of linear equations Ax = b, where b is 1st order gradient
# and A is Hessian matrix
b: torch.Tensor = spatial_gradient3d(input, order=1, mode="diff")
b = b.permute(0, 1, 3, 4, 5, 2).reshape(-1, 3, 1)
@@ -621,7 +621,7 @@ def conv_quad_interp3d(
x_solved: torch.Tensor = torch.zeros_like(b)
x_solved_masked, _, solved_correctly = safe_solve_with_mask(b[nms_mask.view(-1)], Hes[nms_mask.view(-1)])
- # Kill those points, torch.where we cannot solve
+ # Kill those points, where we cannot solve
new_nms_mask = nms_mask.masked_scatter(nms_mask, solved_correctly)
x_solved[torch.where(new_nms_mask.view(-1, 1, 1))[0]] = x_solved_masked[solved_correctly]
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 6c9619a66..a91b8b05e 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -261,9 +261,9 @@ def rotate(
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
angle: The angle through which to rotate. The tensor
- must have a shape of (B), torch.where B is batch size.
+ must have a shape of (B), where B is batch size.
center: The center through which to rotate. The tensor
- must have a shape of (B, 2), torch.where B is batch size and last
+ must have a shape of (B, 2), where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
@@ -326,13 +326,13 @@ def rotate3d(
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, D, H, W)`.
yaw: The yaw angle through which to rotate. The tensor
- must have a shape of (B), torch.where B is batch size.
+ must have a shape of (B), where B is batch size.
pitch: The pitch angle through which to rotate. The tensor
- must have a shape of (B), torch.where B is batch size.
+ must have a shape of (B), where B is batch size.
roll: The roll angle through which to rotate. The tensor
- must have a shape of (B), torch.where B is batch size.
+ must have a shape of (B), where B is batch size.
center: The center through which to rotate. The tensor
- must have a shape of (B, 2), torch.where B is batch size and last
+ must have a shape of (B, 2), where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
@@ -393,7 +393,7 @@ def translate(
tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
translation: tensor containing the amount of pixels to
translate in the x and y direction. The tensor must have a shape of
- (B, 2), torch.where B is batch size, last dimension contains dx dy.
+ (B, 2), where B is batch size, last dimension contains dx dy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
@@ -442,11 +442,11 @@ def scale(
Args:
tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.
scale_factor: The scale factor apply. The tensor
- must have a shape of (B) or (B, 2), torch.where B is batch size.
+ must have a shape of (B) or (B, 2), where B is batch size.
If (B), isotropic scaling will perform.
If (B, 2), x-y-direction specific scaling will perform.
center: The center through which to scale. The tensor
- must have a shape of (B, 2), torch.where B is batch size and last
+ must have a shape of (B, 2), where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
@@ -504,7 +504,7 @@ def shear(
tensor: The image tensor to be skewed with shape of :math:`(B, C, H, W)`.
shear: tensor containing the angle to shear
in the x and y direction. The tensor must have a shape of
- (B, 2), torch.where B is batch size, last dimension contains shx shy.
+ (B, 2), where B is batch size, last dimension contains shx shy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
@@ -775,15 +775,15 @@ class Affine(nn.Module):
Args:
angle: Angle in degrees for counter-clockwise rotation around the center. The tensor
- must have a shape of (B), torch.where B is the batch size.
+ must have a shape of (B), where B is the batch size.
translation: Amount of pixels for translation in x- and y-direction. The tensor must
- have a shape of (B, 2), torch.where B is the batch size and the last dimension contains dx and dy.
- scale_factor: Factor for scaling. The tensor must have a shape of (B,2), torch.where B is the
+ have a shape of (B, 2), where B is the batch size and the last dimension contains dx and dy.
+ scale_factor: Factor for scaling. The tensor must have a shape of (B,2), where B is the
batch size and the last dimension contains scale factors for x and y direction.
shear: Factor for shearing in x- and y-direction around the center. The
- tensor must have a shape of (B, 2), torch.where B is the batch size and the last dimension
+ tensor must have a shape of (B, 2), where B is the batch size and the last dimension
contains sx and sy.
- center: Transformation center in pixels. The tensor must have a shape of (B, 2), torch.where
+ center: Transformation center in pixels. The tensor must have a shape of (B, 2), where
B is the batch size and the last dimension contains cx and cy. Defaults to the center of image to be
transformed.
mode: interpolation mode to calculate output values
@@ -917,9 +917,9 @@ class Rotate(nn.Module):
Args:
angle: The angle through which to rotate. The tensor
- must have a shape of (B), torch.where B is batch size.
+ must have a shape of (B), where B is batch size.
center: The center through which to rotate. The tensor
- must have a shape of (B, 2), torch.where B is batch size and last
+ must have a shape of (B, 2), where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
@@ -964,7 +964,7 @@ class Translate(nn.Module):
Args:
translation: tensor containing the amount of pixels to
translate in the x and y direction. The tensor must have a shape of
- (B, 2), torch.where B is batch size, last dimension contains dx dy.
+ (B, 2), where B is batch size, last dimension contains dx dy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
@@ -1005,11 +1005,11 @@ class Scale(nn.Module):
Args:
scale_factor: The scale factor apply. The tensor
- must have a shape of (B) or (B, 2), torch.where B is batch size.
+ must have a shape of (B) or (B, 2), where B is batch size.
If (B), isotropic scaling will perform.
If (B, 2), x-y-direction specific scaling will perform.
center: The center through which to scale. The tensor
- must have a shape of (B, 2), torch.where B is batch size and last
+ must have a shape of (B, 2), where B is batch size and last
dimension contains cx and cy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
@@ -1054,7 +1054,7 @@ class Shear(nn.Module):
Args:
shear: tensor containing the angle to shear
in the x and y direction. The tensor must have a shape of
- (B, 2), torch.where B is batch size, last dimension contains shx shy.
+ (B, 2), where B is batch size, last dimension contains shx shy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 49b904ca6..1fe8b4fe5 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -46,12 +46,12 @@ def crop_and_resize(
padding_mode: str = "zeros",
align_corners: bool = True,
) -> torch.Tensor:
- r"""Extract crops from 2D images (4D torch.tensor) and resize given a bounding box.
+ r"""Extract crops from 2D images (4D torch.Tensor) and resize given a bounding box.
Args:
- input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
- boxes : a torch.tensor containing the coordinates of the bounding boxes to be extracted.
- The torch.tensor must have the shape of Bx4x2, torch.where each box is defined in the following (clockwise)
+ input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
+ boxes : a torch.Tensor containing the coordinates of the bounding boxes to be extracted.
+ The torch.Tensor must have the shape of Bx4x2, where each box is defined in the following (clockwise)
order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.
The coordinates would compose a rectangle with a shape of (N1, N2).
size: a tuple with the height and width that will be
@@ -93,7 +93,7 @@ def crop_and_resize(
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
if len(input_tensor.shape) != 4:
- raise AssertionError(f"Only torch.tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
+ raise AssertionError(f"Only torch.Tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
# unpack input data
dst_h, dst_w = size
@@ -120,10 +120,10 @@ def center_crop(
padding_mode: str = "zeros",
align_corners: bool = True,
) -> torch.Tensor:
- r"""Crop the 2D images (4D torch.tensor) from the center.
+ r"""Crop the 2D images (4D torch.Tensor) from the center.
Args:
- input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
+ input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
size: a tuple with the expected height and width
of the output patch.
mode: interpolation mode to calculate output values
@@ -133,7 +133,7 @@ def center_crop(
align_corners: mode for grid_generation.
Returns:
- the output torch.tensor with patches.
+ the output torch.Tensor with patches.
Examples:
>>> input = torch.tensor([[[
@@ -154,7 +154,7 @@ def center_crop(
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
if len(input_tensor.shape) != 4:
- raise AssertionError(f"Only torch.tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
+ raise AssertionError(f"Only torch.Tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
# unpack input sizes
dst_h, dst_w = size
@@ -200,21 +200,21 @@ def crop_by_boxes(
align_corners: bool = True,
validate_boxes: bool = True,
) -> torch.Tensor:
- """Perform crop transform on 2D images (4D torch.tensor) given two bounding boxes.
+ """Perform crop transform on 2D images (4D torch.Tensor) given two bounding boxes.
- Given an input torch.tensor, this function selected the interested areas by the provided bounding boxes (src_box).
+ Given an input torch.Tensor, this function selected the interested areas by the provided bounding boxes (src_box).
Then the selected areas would be fitted into the targeted bounding boxes (dst_box) by a perspective transformation.
- So far, the ragged torch.tensor is not supported by PyTorch right now. This function hereby requires
+ So far, the ragged torch.Tensor is not supported by PyTorch right now. This function hereby requires
the bounding boxes in a batch must be rectangles with same width and height.
Args:
- input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
- src_box: a torch.tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
- to be extracted. The torch.tensor must have the shape of Bx4x2, torch.where each box is defined
+ input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
+ src_box: a torch.Tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
+ to be extracted. The torch.Tensor must have the shape of Bx4x2, where each box is defined
in the clockwise order: top-left, top-right, bottom-right and bottom-left.
The coordinates must be in x, y order.
- dst_box: a torch.tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
- to be placed. The torch.tensor must have the shape of Bx4x2, torch.where each box is defined
+ dst_box: a torch.Tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
+ to be placed. The torch.Tensor must have the shape of Bx4x2, where each box is defined
in the clockwise order: top-left, top-right, bottom-right and bottom-left.
The coordinates must be in x, y order.
mode: interpolation mode to calculate output values
@@ -255,7 +255,7 @@ def crop_by_boxes(
validate_bbox(dst_box)
if len(input_tensor.shape) != 4:
- raise AssertionError(f"Only torch.tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
+ raise AssertionError(f"Only torch.Tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
# compute transformation between points and warp
# Note: torch.Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
@@ -283,10 +283,10 @@ def crop_by_transform_mat(
padding_mode: str = "zeros",
align_corners: bool = True,
) -> torch.Tensor:
- """Perform crop transform on 2D images (4D torch.tensor) given a perspective transformation matrix.
+ """Perform crop transform on 2D images (4D torch.Tensor) given a perspective transformation matrix.
Args:
- input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
+ input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
transform: a perspective transformation matrix with shape (B, 3, 3).
out_size: size of the output image (height, width).
mode: interpolation mode to calculate output values
@@ -296,7 +296,7 @@ def crop_by_transform_mat(
align_corners: mode for grid_generation.
Returns:
- the output torch.tensor with patches.
+ the output torch.Tensor with patches.
"""
# simulate broadcasting
@@ -328,9 +328,9 @@ def crop_by_indices(
"""Crop tensors with naive indices.
Args:
- input_tensor: the 2D image torch.tensor with shape (B, C, H, W).
- src_box: a torch.tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
- to be extracted. The torch.tensor must have the shape of Bx4x2, torch.where each box is defined
+ input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
+ src_box: a torch.Tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
+ to be extracted. The torch.Tensor must have the shape of Bx4x2, where each box is defined
in the clockwise order: top-left, top-right, bottom-right and bottom-left.
The coordinates must be in x, y order.
size: output size. An auto resize or F.pad will be performed according to ``shape_compensation``
@@ -393,7 +393,7 @@ def crop_by_indices(
class CenterCrop2D(nn.Module):
- """Center crop the input torch.tensor.
+ """Center crop the input torch.Tensor.
Args:
size: Size (h, w) in pixels of the resized region or just one side.
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index 878eaf7e6..a7a3696a0 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -22,15 +22,15 @@ __all__ = ["Hflip", "Rot180", "Vflip", "hflip", "rot180", "vflip"]
class Vflip(nn.Module):
- r"""Vertically flip a torch.tensor image or a batch of torch.tensor images.
+ r"""Vertically flip a torch.Tensor image or a batch of torch.Tensor images.
- Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input torch.tensor.
+ input: input torch.Tensor.
Returns:
- The vertically flipped image torch.tensor.
+ The vertically flipped image torch.Tensor.
Examples:
>>> vflip = Vflip()
@@ -54,15 +54,15 @@ class Vflip(nn.Module):
class Hflip(nn.Module):
- r"""Horizontally flip a torch.tensor image or a batch of torch.tensor images.
+ r"""Horizontally flip a torch.Tensor image or a batch of torch.Tensor images.
- Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input torch.tensor.
+ input: input torch.Tensor.
Returns:
- The horizontally flipped image torch.tensor.
+ The horizontally flipped image torch.Tensor.
Examples:
>>> hflip = Hflip()
@@ -86,12 +86,12 @@ class Hflip(nn.Module):
class Rot180(nn.Module):
- r"""Rotate a torch.tensor image or a batch of torch.tensor images 180 degrees.
+ r"""Rotate a torch.Tensor image or a batch of torch.Tensor images 180 degrees.
- Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input torch.tensor.
+ input: input torch.Tensor.
Examples:
>>> rot180 = Rot180()
@@ -115,51 +115,51 @@ class Rot180(nn.Module):
def rot180(input: torch.Tensor) -> torch.Tensor:
- r"""Rotate a torch.tensor image or a batch of torch.tensor images 180 degrees.
+ r"""Rotate a torch.Tensor image or a batch of torch.Tensor images 180 degrees.
.. image:: _static/img/rot180.png
- Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input torch.tensor.
+ input: input torch.Tensor.
Returns:
- The rotated image torch.tensor.
+ The rotated image torch.Tensor.
"""
return torch.flip(input, [-2, -1])
def hflip(input: torch.Tensor) -> torch.Tensor:
- r"""Horizontally flip a torch.tensor image or a batch of torch.tensor images.
+ r"""Horizontally flip a torch.Tensor image or a batch of torch.Tensor images.
.. image:: _static/img/hflip.png
- Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input torch.tensor.
+ input: input torch.Tensor.
Returns:
- The horizontally flipped image torch.tensor.
+ The horizontally flipped image torch.Tensor.
"""
return input.flip(-1).contiguous()
def vflip(input: torch.Tensor) -> torch.Tensor:
- r"""Vertically flip a torch.tensor image or a batch of torch.tensor images.
+ r"""Vertically flip a torch.Tensor image or a batch of torch.Tensor images.
.. image:: _static/img/vflip.png
- Input must be a torch.tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ Input must be a torch.Tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
- input: input torch.tensor.
+ input: input torch.Tensor.
Returns:
- The vertically flipped image torch.tensor.
+ The vertically flipped image torch.Tensor.
"""
return input.flip(-2).contiguous()
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 63b78cb7a..3abe29c63 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -54,8 +54,8 @@ class HomographyWarper(BaseWarper):
X_{dst} = H_{src}^{\{dst\}} * X_{src}
Args:
- height: The height of the destination torch.tensor.
- width: The width of the destination torch.tensor.
+ height: The height of the destination torch.Tensor.
+ width: The width of the destination torch.Tensor.
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
``'torch.zeros'`` | ``'border'`` | ``'reflection'``.
@@ -102,10 +102,10 @@ class HomographyWarper(BaseWarper):
self._warped_grid = warp_grid(self.grid, src_homo_dst)
def forward(self, patch_src: torch.Tensor, src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
- r"""Warp a torch.tensor from source into reference frame.
+ r"""Warp a torch.Tensor from source into reference frame.
Args:
- patch_src: The torch.tensor to warp.
+ patch_src: The torch.Tensor to warp.
src_homo_dst: The homography or torch.stack of
homographies from destination to source. The homography assumes
normalized coordinates [-1, 1] if normalized_coordinates is True.
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 90914b08a..9f14b8d26 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -237,14 +237,14 @@ class ImageRegistrator(nn.Module):
The shape of the tensors is not checked, because it may depend on the model, e.g. volume registration.
Args:
- src_img: Input image torch.tensor.
- dst_img: Input image torch.tensor.
+ src_img: Input image torch.Tensor.
+ dst_img: Input image torch.Tensor.
verbose: if True, outputs loss every 10 iterations.
output_intermediate_models: if True with intermediate models
Returns:
the transformation between two images, shape depends on the model,
- typically [1x3x3] torch.tensor for string model_types.
+ typically [1x3x3] torch.Tensor for string model_types.
"""
self.reset_model()
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 4fc6bcf62..e8155fa5e 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -89,7 +89,7 @@ def warp_perspective(
padding_mode: padding mode for outside grid values ``'torch.zeros'`` | ``'border'`` | ``'reflection'``
| ``'fill'``.
align_corners: interpolation flag.
- fill_value: torch.tensor of shape :math:`(3)` that fills the padding area. Only supported for RGB.
+ fill_value: torch.Tensor of shape :math:`(3)` that fills the padding area. Only supported for RGB.
Returns:
the warped input image :math:`(B, C, H, W)`.
@@ -115,10 +115,10 @@ def warp_perspective(
raise TypeError(f"Input M type is not a torch.Tensor. Got {type(M)}")
if not len(src.shape) == 4:
- raise ValueError(f"Input src must be a BxCxHxW torch.tensor. Got {src.shape}")
+ raise ValueError(f"Input src must be a BxCxHxW torch.Tensor. Got {src.shape}")
if not (len(M.shape) == 3 and M.shape[-2:] == (3, 3)):
- raise ValueError(f"Input M must be a Bx3x3 torch.tensor. Got {M.shape}")
+ raise ValueError(f"Input M must be a Bx3x3 torch.Tensor. Got {M.shape}")
# fill padding is only supported for 3 channels because we can't set fill_value default
# to None as this gives jit issues.
@@ -157,11 +157,11 @@ def warp_affine(
align_corners: bool = True,
fill_value: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- r"""Apply an affine transformation to a torch.tensor.
+ r"""Apply an affine transformation to a torch.Tensor.
.. image:: _static/img/warp_affine.png
- The function warp_affine transforms the source torch.tensor using
+ The function warp_affine transforms the source torch.Tensor using
the specified matrix:
.. math::
@@ -169,17 +169,17 @@ def warp_affine(
M_{21} x + M_{22} y + M_{23} \right )
Args:
- src: input torch.tensor of shape :math:`(B, C, H, W)`.
+ src: input torch.Tensor of shape :math:`(B, C, H, W)`.
M: affine transformation of shape :math:`(B, 2, 3)`.
dsize: size of the output image (height, width).
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values ``'torch.zeros'`` | ``'border'`` | ``'reflection'``
| ``'fill'``.
align_corners : mode for grid_generation.
- fill_value: torch.tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.
+ fill_value: torch.Tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.
Returns:
- the warped torch.tensor with shape :math:`(B, C, H, W)`.
+ the warped torch.Tensor with shape :math:`(B, C, H, W)`.
.. note::
This function is often used in conjunction with :func:`get_rotation_matrix2d`,
@@ -203,10 +203,10 @@ def warp_affine(
raise TypeError(f"Input M type is not a torch.Tensor. Got {type(M)}")
if not len(src.shape) == 4:
- raise ValueError(f"Input src must be a BxCxHxW torch.tensor. Got {src.shape}")
+ raise ValueError(f"Input src must be a BxCxHxW torch.Tensor. Got {src.shape}")
if not (len(M.shape) == 3 or M.shape[-2:] == (2, 3)):
- raise ValueError(f"Input M must be a Bx2x3 torch.tensor. Got {M.shape}")
+ raise ValueError(f"Input M must be a Bx2x3 torch.Tensor. Got {M.shape}")
B, C, H, W = src.size()
@@ -231,14 +231,14 @@ def _fill_and_warp(
r"""Warp a mask of torch.ones, then multiply with fill_value and add to default warp.
Args:
- src: input torch.tensor of shape :math:`(B, C, H, W)`.
- grid: grid torch.tensor from `transform_points`.
+ src: input torch.Tensor of shape :math:`(B, C, H, W)`.
+ grid: grid torch.Tensor from `transform_points`.
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
align_corners: interpolation flag.
- fill_value: torch.tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.
+ fill_value: torch.Tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.
Returns:
- the warped and filled torch.tensor with shape :math:`(B, C, H, W)`.
+ the warped and filled torch.Tensor with shape :math:`(B, C, H, W)`.
"""
ones_mask = torch.ones_like(src)
fill_value = fill_value.to(ones_mask)
@@ -367,7 +367,7 @@ def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor
# system is solved with the least square method, so here
# we could even pass more correspondence
- # create the lhs torch.tensor with shape # Bx8x8
+ # create the lhs torch.Tensor with shape # Bx8x8
B: int = points_src.shape[0] # batch_size
A = torch.empty(B, 8, 8, device=points_src.device, dtype=points_src.dtype)
@@ -383,7 +383,7 @@ def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor
A[:, 2 * i] = torch.stack([x1, y1, _ones, _zeros, _zeros, _zeros, -x1 * x2, -y1 * x2], -1)
A[:, 2 * i + 1] = torch.stack([_zeros, _zeros, _zeros, x1, y1, _ones, -x1 * y2, -y1 * y2], -1)
- # the rhs torch.tensor
+ # the rhs torch.Tensor
b = points_dst.view(-1, 8, 1)
# solve the system Ax = b
@@ -411,7 +411,7 @@ def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torc
+ (1 - \alpha) \cdot \text{y}
\end{bmatrix}
- torch.where
+ where
.. math::
\alpha = \text{scale} \cdot torch.cos(\text{angle}) \\
@@ -452,13 +452,13 @@ def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torc
raise TypeError(f"Input scale type is not a torch.Tensor. Got {type(scale)}")
if not (len(center.shape) == 2 and center.shape[1] == 2):
- raise ValueError(f"Input center must be a Bx2 torch.tensor. Got {center.shape}")
+ raise ValueError(f"Input center must be a Bx2 torch.Tensor. Got {center.shape}")
if not len(angle.shape) == 1:
- raise ValueError(f"Input angle must be a B torch.tensor. Got {angle.shape}")
+ raise ValueError(f"Input angle must be a B torch.Tensor. Got {angle.shape}")
if not (len(scale.shape) == 2 and scale.shape[1] == 2):
- raise ValueError(f"Input scale must be a Bx2 torch.tensor. Got {scale.shape}")
+ raise ValueError(f"Input scale must be a Bx2 torch.Tensor. Got {scale.shape}")
if not (center.shape[0] == angle.shape[0] == scale.shape[0]):
raise ValueError(
@@ -498,22 +498,22 @@ def remap(
align_corners: Optional[bool] = None,
normalized_coordinates: bool = False,
) -> torch.Tensor:
- r"""Apply a generic geometrical transformation to an image torch.tensor.
+ r"""Apply a generic geometrical transformation to an image torch.Tensor.
.. image:: _static/img/remap.png
- The function remap transforms the source torch.tensor using the specified map:
+ The function remap transforms the source torch.Tensor using the specified map:
.. math::
\text{dst}(x, y) = \text{src}(map_x(x, y), map_y(x, y))
Args:
- image: the torch.tensor to remap with shape (B, C, H, W).
+ image: the torch.Tensor to remap with shape (B, C, H, W).
Where C is the number of channels.
map_x: the flow in the x-direction in pixel coordinates.
- The torch.tensor must be in the shape of (B, H, W).
+ The torch.Tensor must be in the shape of (B, H, W).
map_y: the flow in the y-direction in pixel coordinates.
- The torch.tensor must be in the shape of (B, H, W).
+ The torch.Tensor must be in the shape of (B, H, W).
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values
@@ -523,7 +523,7 @@ def remap(
normalized in the range of [-1, 1].
Returns:
- the warped torch.tensor with same shape as the input grid maps.
+ the warped torch.Tensor with same shape as the input grid maps.
Example:
>>> import torch
@@ -578,7 +578,7 @@ def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
The result is also a 2x3 matrix of the same type as M.
Args:
- matrix: original affine transform. The torch.tensor must be
+ matrix: original affine transform. The torch.Tensor must be
in the shape of :math:`(B, 2, 3)`.
Return:
@@ -592,7 +592,7 @@ def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
raise TypeError(f"Input matrix type is not a torch.Tensor. Got {type(matrix)}")
if not (len(matrix.shape) == 3 and matrix.shape[-2:] == (2, 3)):
- raise ValueError(f"Input matrix must be a Bx2x3 torch.tensor. Got {matrix.shape}")
+ raise ValueError(f"Input matrix must be a Bx2x3 torch.Tensor. Got {matrix.shape}")
matrix_tmp: torch.Tensor = convert_affinematrix_to_homography(matrix)
matrix_inv: torch.Tensor = _torch_inverse_cast(matrix_tmp)
@@ -611,12 +611,12 @@ def get_affine_matrix2d(
r"""Compose affine matrix from the components.
Args:
- translations: torch.tensor containing the translation vector with shape :math:`(B, 2)`.
- center: torch.tensor containing the center vector with shape :math:`(B, 2)`.
- scale: torch.tensor containing the scale factor with shape :math:`(B, 2)`.
- angle: torch.tensor of angles in degrees :math:`(B)`.
- sx: torch.tensor containing the shear factor in the x-direction with shape :math:`(B)`.
- sy: torch.tensor containing the shear factor in the y-direction with shape :math:`(B)`.
+ translations: torch.Tensor containing the translation vector with shape :math:`(B, 2)`.
+ center: torch.Tensor containing the center vector with shape :math:`(B, 2)`.
+ scale: torch.Tensor containing the scale factor with shape :math:`(B, 2)`.
+ angle: torch.Tensor of angles in degrees :math:`(B)`.
+ sx: torch.Tensor containing the shear factor in the x-direction with shape :math:`(B)`.
+ sy: torch.Tensor containing the shear factor in the y-direction with shape :math:`(B)`.
Returns:
the affine transformation matrix :math:`(B, 3, 3)`.
@@ -642,7 +642,7 @@ def get_translation_matrix2d(translations: torch.Tensor) -> torch.Tensor:
r"""Compose translation matrix from the components.
Args:
- translations: torch.tensor containing the translation vector with shape :math:`(B, 2)`.
+ translations: torch.Tensor containing the translation vector with shape :math:`(B, 2)`.
Returns:
the affine transformation matrix :math:`(B, 3, 3)`.
@@ -728,18 +728,18 @@ def get_affine_matrix3d(
r"""Compose 3d affine matrix from the components.
Args:
- translations: torch.tensor containing the translation vector (dx,dy,dz) with shape :math:`(B, 3)`.
- center: torch.tensor containing the center vector (x,y,z) with shape :math:`(B, 3)`.
- scale: torch.tensor containing the scale factor with shape :math:`(B)`.
+ translations: torch.Tensor containing the translation vector (dx,dy,dz) with shape :math:`(B, 3)`.
+ center: torch.Tensor containing the center vector (x,y,z) with shape :math:`(B, 3)`.
+ scale: torch.Tensor containing the scale factor with shape :math:`(B)`.
angles: axis angle vector containing the rotation angles in degrees in the form
of (rx, ry, rz) with shape :math:`(B, 3)`. Internally it calls Rodrigues to compute
the rotation matrix from axis-angle.
- sxy: torch.tensor containing the shear factor in the xy-direction with shape :math:`(B)`.
- sxz: torch.tensor containing the shear factor in the xz-direction with shape :math:`(B)`.
- syx: torch.tensor containing the shear factor in the yx-direction with shape :math:`(B)`.
- syz: torch.tensor containing the shear factor in the yz-direction with shape :math:`(B)`.
- szx: torch.tensor containing the shear factor in the zx-direction with shape :math:`(B)`.
- szy: torch.tensor containing the shear factor in the zy-direction with shape :math:`(B)`.
+ sxy: torch.Tensor containing the shear factor in the xy-direction with shape :math:`(B)`.
+ sxz: torch.Tensor containing the shear factor in the xz-direction with shape :math:`(B)`.
+ syx: torch.Tensor containing the shear factor in the yx-direction with shape :math:`(B)`.
+ syz: torch.Tensor containing the shear factor in the yz-direction with shape :math:`(B)`.
+ szx: torch.Tensor containing the shear factor in the zx-direction with shape :math:`(B)`.
+ szy: torch.Tensor containing the shear factor in the zy-direction with shape :math:`(B)`.
Returns:
the 3d affine transformation matrix :math:`(B, 3, 3)`.
@@ -882,13 +882,13 @@ def warp_affine3d(
padding_mode: str = "zeros",
align_corners: bool = True,
) -> torch.Tensor:
- r"""Apply a projective transformation a to 3d torch.tensor.
+ r"""Apply a projective transformation a to 3d torch.Tensor.
.. warning::
This API signature it is experimental and might suffer some changes in the future.
Args:
- src : input torch.tensor of shape :math:`(B, C, D, H, W)`.
+ src : input torch.Tensor of shape :math:`(B, C, D, H, W)`.
M: projective transformation matrix of shape :math:`(B, 3, 4)`.
dsize: size of the output image (depth, height, width).
flags: interpolation mode to calculate output values
@@ -1030,7 +1030,7 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
1 \\
\end{bmatrix}
- torch.where
+ where
.. math::
dst(i) = (x_{i}^{'},y_{i}^{'},z_{i}^{'}), src(i) = (x_{i}, y_{i}, z_{i}), i = 0,1,2,5,7
@@ -1085,7 +1085,7 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
raise TypeError(f"Input type is not a torch.Tensor. Got {type(dst)}")
if not src.shape[-2:] == (8, 3):
- raise ValueError(f"Inputs must be a Bx8x3 torch.tensor. Got {src.shape}")
+ raise ValueError(f"Inputs must be a Bx8x3 torch.Tensor. Got {src.shape}")
if not src.shape == dst.shape:
raise ValueError(f"Inputs must have the same shape. Got {dst.shape}")
@@ -1266,10 +1266,10 @@ def warp_perspective3d(
raise TypeError(f"Input M type is not a torch.Tensor. Got {type(M)}")
if not len(src.shape) == 5:
- raise ValueError(f"Input src must be a BxCxDxHxW torch.tensor. Got {src.shape}")
+ raise ValueError(f"Input src must be a BxCxDxHxW torch.Tensor. Got {src.shape}")
if not (len(M.shape) == 3 or M.shape[-2:] == (4, 4)):
- raise ValueError(f"Input M must be a Bx4x4 torch.tensor. Got {M.shape}")
+ raise ValueError(f"Input M must be a Bx4x4 torch.Tensor. Got {M.shape}")
# launches the warper
d, h, w = src.shape[-3:]
@@ -1291,7 +1291,7 @@ def homography_warp(
See :class:`~kornia.geometry.warp.HomographyWarper` for details.
Args:
- patch_src: The image or torch.tensor to warp. Should be from source of shape :math:`(N, C, H, W)`.
+ patch_src: The image or torch.Tensor to warp. Should be from source of shape :math:`(N, C, H, W)`.
src_homo_dst: The homography or torch.stack of homographies from destination to source of shape
:math:`(N, 3, 3)`.
dsize:
@@ -1365,7 +1365,7 @@ def homography_warp3d(
r"""Warp image patches or tensors by normalized 3D homographies.
Args:
- patch_src: The image or torch.tensor to warp. Should be from source of shape :math:`(N, C, D, H, W)`.
+ patch_src: The image or torch.Tensor to warp. Should be from source of shape :math:`(N, C, D, H, W)`.
src_homo_dst: The homography or torch.stack of homographies from destination to source of shape
:math:`(N, 4, 4)`.
dsize: The height and width of the image to warp.
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index a44100edd..47aff9fd7 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -57,7 +57,7 @@ def _get_pyramid_gaussian_kernel() -> torch.Tensor:
class PyrDown(nn.Module):
- r"""Blur a torch.tensor and downsamples it.
+ r"""Blur a torch.Tensor and downsamples it.
Args:
border_type: the padding mode to be applied before convolving.
@@ -67,7 +67,7 @@ class PyrDown(nn.Module):
factor: the downsampling factor
Return:
- the downsampled torch.tensor.
+ the downsampled torch.Tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -90,7 +90,7 @@ class PyrDown(nn.Module):
class PyrUp(nn.Module):
- r"""Upsample a torch.tensor and then blurs it.
+ r"""Upsample a torch.Tensor and then blurs it.
Args:
borde_type: the padding mode to be applied before convolving.
@@ -99,7 +99,7 @@ class PyrUp(nn.Module):
align_corners: interpolation flag.
Return:
- the upsampled torch.tensor.
+ the upsampled torch.Tensor.
Shape:
- Input: :math:`(B, C, H, W)`
@@ -250,12 +250,12 @@ class ScalePyramid(nn.Module):
def pyrdown(
input: torch.Tensor, border_type: str = "reflect", align_corners: bool = False, factor: float = 2.0
) -> torch.Tensor:
- r"""Blur a torch.tensor and downsamples it.
+ r"""Blur a torch.Tensor and downsamples it.
.. image:: _static/img/pyrdown.png
Args:
- input: the torch.tensor to be downsampled.
+ input: the torch.Tensor to be downsampled.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``.
@@ -263,7 +263,7 @@ def pyrdown(
factor: the downsampling factor
Return:
- the downsampled torch.tensor.
+ the downsampled torch.Tensor.
Examples:
>>> input = torch.arange(16, dtype=torch.float32).reshape(1, 1, 4, 4)
@@ -291,18 +291,18 @@ def pyrdown(
def pyrup(input: torch.Tensor, border_type: str = "reflect", align_corners: bool = False) -> torch.Tensor:
- r"""Upsample a torch.tensor and then blurs it.
+ r"""Upsample a torch.Tensor and then blurs it.
.. image:: _static/img/pyrup.png
Args:
- input: the torch.tensor to be downsampled.
+ input: the torch.Tensor to be downsampled.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
align_corners: interpolation flag.
Return:
- the downsampled torch.tensor.
+ the downsampled torch.Tensor.
Examples:
>>> input = torch.arange(4, dtype=torch.float32).reshape(1, 1, 2, 2)
@@ -316,14 +316,14 @@ def pyrup(input: torch.Tensor, border_type: str = "reflect", align_corners: bool
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
kernel: torch.Tensor = _get_pyramid_gaussian_kernel()
- # upsample torch.tensor
+ # upsample torch.Tensor
_, _, height, width = input.shape
# TODO: use kornia.geometry.resize/rescale
x_up: torch.Tensor = F.interpolate(
input, size=(height * 2, width * 2), mode="bilinear", align_corners=align_corners
)
- # blurs upsampled torch.tensor
+ # blurs upsampled torch.Tensor
x_blur: torch.Tensor = filter2d(x_up, kernel, border_type)
return x_blur
@@ -331,7 +331,7 @@ def pyrup(input: torch.Tensor, border_type: str = "reflect", align_corners: bool
def build_pyramid(
input: torch.Tensor, max_level: int, border_type: str = "reflect", align_corners: bool = False
) -> list[torch.Tensor]:
- r"""Construct the Gaussian pyramid for a torch.tensor image.
+ r"""Construct the Gaussian pyramid for a torch.Tensor image.
.. image:: _static/img/build_pyramid.png
@@ -339,7 +339,7 @@ def build_pyramid(
by recursively applying pyrDown to the previously built pyramid layers.
Args:
- input : the torch.tensor to be used to construct the pyramid.
+ input : the torch.Tensor to be used to construct the pyramid.
max_level: 0-based index of the last (the smallest) pyramid layer.
It must be non-negative.
border_type: the padding mode to be applied before convolving.
@@ -383,7 +383,7 @@ def find_next_powerof_two(x: int) -> int:
def build_laplacian_pyramid(
input: torch.Tensor, max_level: int, border_type: str = "reflect", align_corners: bool = False
) -> list[torch.Tensor]:
- r"""Construct the Laplacian pyramid for a torch.tensor image.
+ r"""Construct the Laplacian pyramid for a torch.Tensor image.
The function constructs a vector of images and builds the Laplacian pyramid
by recursively computing the difference after applying
@@ -392,7 +392,7 @@ def build_laplacian_pyramid(
See :cite:`burt1987laplacian` for more details.
Args:
- input : the torch.tensor to be used to construct the pyramid with shape :math:`(B, C, H, W)`.
+ input : the torch.Tensor to be used to construct the pyramid with shape :math:`(B, C, H, W)`.
max_level: 0-based index of the last (the smallest) pyramid layer.
It must be non-negative.
border_type: the padding mode to be applied before convolving.
@@ -415,7 +415,7 @@ def build_laplacian_pyramid(
require_padding = not (is_powerof_two(w) or is_powerof_two(h))
if require_padding:
- # in case of arbitrary shape torch.tensor image need to be padded.
+ # in case of arbitrary shape torch.Tensor image need to be padded.
# Reference: https://stackoverflow.com/a/29967555
padding = (0, find_next_powerof_two(w) - w, 0, find_next_powerof_two(h) - h)
input = F.pad(input, padding, "reflect")
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index 041efff0a..0777888e7 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -43,7 +43,7 @@ def _pair_square_euclidean(tensor1: torch.Tensor, tensor2: torch.Tensor) -> torc
def _kernel_distance(squared_distances: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
- r"""Compute the TPS kernel distance function: :math:`r^2 log(r)`, torch.where `r` is the euclidean distance.
+ r"""Compute the TPS kernel distance function: :math:`r^2 log(r)`, where `r` is the euclidean distance.
Since
:math: `\log(r) = 1/2 \log(r^2)`, this function takes the squared distance matrix and calculates
@@ -56,16 +56,16 @@ def _kernel_distance(squared_distances: torch.Tensor, eps: float = 1e-8) -> torc
def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Compute the TPS transform parameters that warp source points to target points.
- The input to this function is a torch.tensor of :math:`(x, y)` source points :math:`(B, N, 2)` and a corresponding
- torch.tensor of target :math:`(x, y)` points :math:`(B, N, 2)`.
+ The input to this function is a torch.Tensor of :math:`(x, y)` source points :math:`(B, N, 2)` and a corresponding
+ torch.Tensor of target :math:`(x, y)` points :math:`(B, N, 2)`.
Args:
points_src: batch of source points :math:`(B, N, 2)` as :math:`(x, y)` coordinate vectors.
points_dst: batch of target points :math:`(B, N, 2)` as :math:`(x, y)` coordinate vectors.
Returns:
- :math:`(B, N, 2)` torch.tensor of kernel weights and :math:`(B, 3, 2)`
- torch.tensor of affine weights. The last dimension contains the x-transform and y-transform weights
+ :math:`(B, N, 2)` torch.Tensor of kernel weights and :math:`(B, 3, 2)`
+ torch.Tensor of affine weights. The last dimension contains the x-transform and y-transform weights
as separate columns.
Example:
@@ -116,22 +116,22 @@ 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 torch.tensor of coordinate points using the thin plate spline defined by arguments.
+ r"""Warp a torch.Tensor of coordinate points using the thin plate spline defined by arguments.
- The source points should be a :math:`(B, N, 2)` torch.tensor of :math:`(x, y)` coordinates. The kernel centers are
- a :math:`(B, K, 2)` torch.tensor of :math:`(x, y)` coordinates. The kernel weights are a :math:`(B, K, 2)`
- torch.tensor, and the affine weights are a :math:`(B, 3, 2)` torch.tensor. For the weight tensors,
- torch.tensor[..., 0] contains the weights for the x-transform and torch.tensor[..., 1] the weights
+ The source points should be a :math:`(B, N, 2)` torch.Tensor of :math:`(x, y)` coordinates. The kernel centers are
+ a :math:`(B, K, 2)` torch.Tensor of :math:`(x, y)` coordinates. The kernel weights are a :math:`(B, K, 2)`
+ torch.Tensor, and the affine weights are a :math:`(B, 3, 2)` torch.Tensor. For the weight tensors,
+ torch.Tensor[..., 0] contains the weights for the x-transform and torch.Tensor[..., 1] the weights
for the y-transform.
Args:
- points_src: torch.tensor of source points :math:`(B, N, 2)`.
- kernel_centers: torch.tensor of kernel center points :math:`(B, K, 2)`.
- kernel_weights: torch.tensor of kernl weights :math:`(B, K, 2)`.
- affine_weights: torch.tensor of affine weights :math:`(B, 3, 2)`.
+ points_src: torch.Tensor of source points :math:`(B, N, 2)`.
+ kernel_centers: torch.Tensor of kernel center points :math:`(B, K, 2)`.
+ kernel_weights: torch.Tensor of kernl weights :math:`(B, K, 2)`.
+ affine_weights: torch.Tensor of affine weights :math:`(B, 3, 2)`.
Returns:
- The :math:`(B, N, 2)` torch.tensor of warped source points, from applying the TPS transform.
+ The :math:`(B, N, 2)` torch.Tensor of warped source points, from applying the TPS transform.
Example:
>>> points_src = torch.rand(1, 5, 2)
@@ -189,7 +189,7 @@ def warp_image_tps(
align_corners: bool = False,
padding_mode: str = "zeros",
) -> torch.Tensor:
- r"""Warp an image torch.tensor according to the thin plate spline transform defined by arguments.
+ r"""Warp an image torch.Tensor according to the thin plate spline transform defined by arguments.
.. image:: _static/img/warp_image_tps.png
@@ -197,19 +197,19 @@ def warp_image_tps(
image for interpolation of the output pixel. So the TPS parameters should correspond to a warp from
output space to input space.
- The input `image` is a :math:`(B, C, H, W)` torch.tensor. The kernel centers, kernel weight and affine weights
+ The input `image` is a :math:`(B, C, H, W)` torch.Tensor. The kernel centers, kernel weight and affine weights
are the same as in `warp_points_tps`.
Args:
- image: input image torch.tensor :math:`(B, C, H, W)`.
+ image: input image torch.Tensor :math:`(B, C, H, W)`.
kernel_centers: kernel center points :math:`(B, K, 2)`.
- kernel_weights: torch.tensor of kernl weights :math:`(B, K, 2)`.
- affine_weights: torch.tensor of affine weights :math:`(B, 3, 2)`.
+ kernel_weights: torch.Tensor of kernl weights :math:`(B, K, 2)`.
+ affine_weights: torch.Tensor of affine weights :math:`(B, 3, 2)`.
align_corners: interpolation flag used by `grid_sample`.
padding_mode: padding flag used by `grid_sample`.
Returns:
- warped image torch.tensor :math:`(B, C, H, W)`.
+ warped image torch.Tensor :math:`(B, C, H, W)`.
Example:
>>> points_src = torch.rand(1, 5, 2)
diff --git a/kornia/image/image.py b/kornia/image/image.py
index d358a72b5..c5ceec90c 100644
--- a/kornia/image/image.py
+++ b/kornia/image/image.py
@@ -40,7 +40,7 @@ class Image:
.. note::
Disclaimer: This class provides the minimum functionality for image manipulation. However, as soon
- as you start to experiment with advanced torch.tensor manipulation, you might expect fancy
+ as you start to experiment with advanced torch.Tensor manipulation, you might expect fancy
polymorphic behaviours.
.. warning::
@@ -48,7 +48,7 @@ class Image:
This API is experimental and might suffer changes in the future.
Args:
- data: a torch torch.tensor containing the image data.
+ data: a torch torch.Tensor containing the image data.
layout: a dataclass containing the image layout information.
Examples:
@@ -79,7 +79,7 @@ class Image:
"""Image constructor.
Args:
- data: a torch torch.tensor containing the image data.
+ data: a torch torch.Tensor containing the image data.
pixel_format: the pixel format of the image.
layout: a dataclass containing the image layout information.
@@ -127,7 +127,7 @@ class Image:
@property
def data(self) -> torch.Tensor:
- """Return the underlying torch.tensor data."""
+ """Return the underlying torch.Tensor data."""
return self._data
@property
@@ -278,13 +278,13 @@ class Image:
color_space: ColorSpace = ColorSpace.RGB,
channels_order: ChannelsOrder = ChannelsOrder.CHANNELS_LAST,
) -> Image:
- """Construct an image torch.tensor from a numpy array.
+ """Construct an image torch.Tensor from a numpy array.
Args:
data: a numpy array containing the image data.
color_space: the color space of the image.
pixel_format: the pixel format of the image.
- channels_order: what dimension the channels are in the image torch.tensor.
+ channels_order: what dimension the channels are in the image torch.Tensor.
Example:
>>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC
@@ -309,16 +309,16 @@ class Image:
# create the image layout based on the input data
layout = ImageLayout(image_size=image_size, channels=channels, channels_order=channels_order)
- # create the image torch.tensor
+ # create the image torch.Tensor
return cls(torch.from_numpy(data), pixel_format, layout)
def to_numpy(self) -> np_ndarray:
- """Return a numpy array in cpu from the image torch.tensor."""
+ """Return a numpy array in cpu from the image torch.Tensor."""
return self.data.cpu().detach().numpy()
@classmethod
def from_dlpack(cls, data: DLPack) -> Image:
- """Construct an image torch.tensor from a DLPack capsule.
+ """Construct an image torch.Tensor from a DLPack capsule.
Args:
data: a DLPack capsule from numpy, tvm or jax.
@@ -342,12 +342,12 @@ class Image:
return cls(_data, pixel_format, layout)
def to_dlpack(self) -> DLPack:
- """Return a DLPack capsule from the image torch.tensor."""
+ """Return a DLPack capsule from the image torch.Tensor."""
return to_dlpack(self.data)
@classmethod
def from_file(cls, file_path: str | Path) -> Image:
- """Construct an image torch.tensor from a file.
+ """Construct an image torch.Tensor from a file.
Args:
file_path: the path to the file to read the image from.
@@ -385,7 +385,7 @@ class Image:
write_image(file_path, data)
def print(self, max_width: int = 256) -> None:
- """Print the image torch.tensor to the console.
+ """Print the image torch.Tensor to the console.
Args:
max_width: the maximum width of the image to print.
diff --git a/kornia/image/image_print.py b/kornia/image/image_print.py
index 54d21d28a..e5f7c2195 100644
--- a/kornia/image/image_print.py
+++ b/kornia/image/image_print.py
@@ -16,7 +16,7 @@
#
-"""Convert an image torch.tensor to an ANSI text string (xterm-256color).
+"""Convert an image torch.Tensor to an ANSI text string (xterm-256color).
Nice long listing of all 256 colors and their codes.
@@ -356,9 +356,9 @@ def rgb2short(rgb: str) -> Tuple[str, str]:
def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
- """Obtain the closest xterm-256 approximation string from an image torch.tensor.
+ """Obtain the closest xterm-256 approximation string from an image torch.Tensor.
- The torch.tensor shall be either 0~1 float type or 0~255 long type.
+ The torch.Tensor shall be either 0~1 float type or 0~255 long type.
Args:
image: an RGB image with shape :math:`3HW`.
@@ -402,7 +402,7 @@ def print_image(image: Union[str, torch.Tensor], max_width: int = 96) -> None:
.. image:: https://github.com/kornia/data/blob/main/print_image.png?raw=true
Args:
- image: path to a valid image file or a torch.tensor.
+ image: path to a valid image file or a torch.Tensor.
max_width: maximum width to print to terminal.
Note:
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 16681f13b..5cec60c30 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -47,10 +47,10 @@ def _load_image_to_tensor(path_file: Path, device: Union[str, torch.device, None
Args:
path_file: Path to a valid image file.
- device: the device torch.where you want to get your image placed.
+ device: the device where you want to get your image placed.
Return:
- Image torch.tensor with shape :math:`(3,H,W)`.
+ Image torch.Tensor with shape :math:`(3,H,W)`.
"""
# read image and return as `np.ndarray` with shape HxWxC
@@ -59,23 +59,23 @@ def _load_image_to_tensor(path_file: Path, device: Union[str, torch.device, None
else:
img = kornia_rs.read_image_any(str(path_file))
- # convert the image to torch.tensor with shape CxHxW
+ # convert the image to torch.Tensor with shape CxHxW
img_t = image_to_tensor(img, keepdim=True)
- # move the torch.tensor to the desired device,
+ # move the torch.Tensor to the desired device,
dev = device if isinstance(device, torch.device) or device is None else torch.device(device)
return img_t.to(device=dev)
def _to_float32(image: torch.Tensor) -> torch.Tensor:
- """Convert an image torch.tensor to float32."""
+ """Convert an image torch.Tensor to float32."""
KORNIA_CHECK(image.dtype == torch.uint8)
return image.float() / 255.0
def _to_uint8(image: torch.Tensor) -> torch.Tensor:
- """Convert an image torch.tensor to uint8."""
+ """Convert an image torch.Tensor to uint8."""
KORNIA_CHECK(image.dtype == torch.float32)
return image.mul(255.0).byte()
@@ -90,10 +90,10 @@ def load_image(
Args:
path_file: Path to a valid image file.
desired_type: the desired image type, defined by color space and dtype.
- device: the device torch.where you want to get your image placed.
+ device: the device where you want to get your image placed.
Return:
- Image torch.tensor with shape :math:`(3,H,W)`.
+ Image torch.Tensor with shape :math:`(3,H,W)`.
"""
if not isinstance(path_file, Path):
@@ -186,7 +186,7 @@ def write_image(path_file: str | Path, image: torch.Tensor, quality: int = 80) -
Args:
path_file: Path to a valid image file.
- image: Image torch.tensor with shape :math:`(3,H,W)`, `(1,H,W)` and `(H,W)`.
+ image: Image torch.Tensor with shape :math:`(3,H,W)`, `(1,H,W)` and `(H,W)`.
quality: The quality of the JPEG encoding. If the file extension is .png or .tiff, the quality is ignored.
Return:
diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.py
index 7df3633d5..7c55491c3 100644
--- a/kornia/losses/cauchy.py
+++ b/kornia/losses/cauchy.py
@@ -41,8 +41,8 @@ def cauchy_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none")
[2] https://files.is.tue.mpg.de/black/papers/cviu.63.1.1996.pdf
Args:
- img1: the predicted torch.tensor with shape :math:`(*)`.
- img2: the target torch.tensor with the same shape as img1.
+ img1: the predicted torch.Tensor with shape :math:`(*)`.
+ img2: the target torch.Tensor with the same shape as img1.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied (default), ``'mean'``: the sum of the output will be divided
@@ -112,8 +112,8 @@ class CauchyLoss(nn.Module):
summed.
Shape:
- - img1: the predicted torch.tensor with shape :math:`(*)`.
- - img2: the target torch.tensor with the same shape as img1.
+ - img1: the predicted torch.Tensor with shape :math:`(*)`.
+ - img2: the target torch.Tensor with the same shape as img1.
Example:
>>> criterion = CauchyLoss(reduction="mean")
diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.py
index a619c79df..ad3d8b897 100644
--- a/kornia/losses/charbonnier.py
+++ b/kornia/losses/charbonnier.py
@@ -48,8 +48,8 @@ def charbonnier_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "n
a slightly different implementation (see [4]).
Args:
- img1: the predicted torch.tensor with shape :math:`(*)`.
- img2: the target torch.tensor with the same shape as img1.
+ img1: the predicted torch.Tensor with shape :math:`(*)`.
+ img2: the target torch.Tensor with the same shape as img1.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied (default), ``'mean'``: the sum of the output will be divided
@@ -125,8 +125,8 @@ class CharbonnierLoss(nn.Module):
summed.
Shape:
- - img1: the predicted torch.tensor with shape :math:`(*)`.
- - img2: the target torch.tensor with the same shape as img1.
+ - img1: the predicted torch.Tensor with shape :math:`(*)`.
+ - img2: the target torch.Tensor with the same shape as img1.
Example:
>>> criterion = CharbonnierLoss(reduction="mean")
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 76d2122a5..9833a4d79 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -50,7 +50,7 @@ def dice_loss(
Where:
- :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the one-hot torch.tensor with the class labels.
+ - :math:`Y` expects to be the one-hot torch.Tensor with the class labels.
the loss, is finally computed as:
@@ -62,9 +62,9 @@ def dice_loss(
[1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
Args:
- pred: logits torch.tensor with shape :math:`(N, C, H, W)` torch.where C = number of classes.
- target: labels torch.tensor with shape :math:`(N, H, W)` torch.where each value
- is :math:`0 ≀ targets[i] ≀ C-1`.
+ pred: logits torch.Tensor with shape :math:`(N, C, H, W)` where C = number of classes.
+ target: labels torch.Tensor with shape :math:`(N, H, W)` where each value
+ is in range :math:`0 ≀ targets[i] ≀ C-1`.
average:
Reduction applied in multi-class scenario:
- ``'micro'`` [default]: Calculate the loss across all classes.
@@ -74,7 +74,7 @@ def dice_loss(
ignore_index: labels with this value are ignored in the loss computation.
Return:
- One-element torch.tensor of the computed loss.
+ One-element torch.Tensor of the computed loss.
Example:
>>> N = 5 # num_classes
@@ -103,7 +103,7 @@ def dice_loss(
target, target_mask = mask_ignore_pixels(target, ignore_index)
- # create the labels one hot torch.tensor
+ # create the labels one hot torch.Tensor
target_one_hot: torch.Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
# mask ignore pixels
@@ -162,7 +162,7 @@ class DiceLoss(nn.Module):
Where:
- :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the one-hot torch.tensor with the class labels.
+ - :math:`Y` expects to be the one-hot torch.Tensor with the class labels.
the loss, is finally computed as:
@@ -183,8 +183,8 @@ class DiceLoss(nn.Module):
ignore_index: labels with this value are ignored in the loss computation.
Shape:
- - Pred: :math:`(N, C, H, W)` torch.where C = number of classes.
- - Target: :math:`(N, H, W)` torch.where each value is
+ - Pred: :math:`(N, C, H, W)` where C = number of classes.
+ - Target: :math:`(N, H, W)` where each value is
:math:`0 ≀ targets[i] ≀ C-1`.
Example:
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index 2caafcfd9..d367d1e48 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -50,8 +50,8 @@ def js_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "m
r"""Calculate the Jensen-Shannon divergence loss between heatmaps.
Args:
- pred: the input torch.tensor with shape :math:`(B, N, H, W)`.
- target: the target torch.tensor with shape :math:`(B, N, H, W)`.
+ pred: the input torch.Tensor with shape :math:`(B, N, H, W)`.
+ target: the target torch.Tensor with shape :math:`(B, N, H, W)`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
@@ -72,8 +72,8 @@ def kl_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "m
r"""Calculate the Kullback-Leibler divergence loss between heatmaps.
Args:
- pred: the input torch.tensor with shape :math:`(B, N, H, W)`.
- target: the target torch.tensor with shape :math:`(B, N, H, W)`.
+ pred: the input torch.Tensor with shape :math:`(B, N, H, W)`.
+ target: the target torch.Tensor with shape :math:`(B, N, H, W)`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index d7df190b1..55ba6b773 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -51,8 +51,8 @@ def focal_loss(
- :math:`p_t` is the model's estimated probability for each class.
Args:
- pred: logits torch.tensor with shape :math:`(N, C, *)` torch.where C = number of classes.
- target: labels torch.tensor with shape :math:`(N, *)` torch.where each value is an integer
+ pred: logits torch.Tensor with shape :math:`(N, C, *)` where C = number of classes.
+ target: labels torch.Tensor with shape :math:`(N, *)` where each value is an integer
representing correct classification :math:`target[i] \in [0, C)`.
alpha: Weighting factor :math:`\alpha \in [0, 1]`.
gamma: Focusing parameter :math:`\gamma >= 0`.
@@ -89,7 +89,7 @@ def focal_loss(
target, target_mask = mask_ignore_pixels(target, ignore_index)
- # create the labels one hot torch.tensor
+ # create the labels one hot torch.Tensor
target_one_hot: torch.Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
# mask ignore pixels
@@ -161,8 +161,8 @@ class FocalLoss(nn.Module):
ignore_index: labels with this value are ignored in the loss computation.
Shape:
- - Pred: :math:`(N, C, *)` torch.where C = number of classes.
- - Target: :math:`(N, *)` torch.where each value is an integer
+ - Pred: :math:`(N, C, *)` where C = number of classes.
+ - Target: :math:`(N, *)` where each value is an integer
representing correct classification :math:`target[i] \in [0, C)`.
Example:
@@ -213,13 +213,13 @@ def binary_focal_loss_with_logits(
\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)
- torch.where:
+ Where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
- pred: logits torch.tensor with shape :math:`(N, C, *)` torch.where C = number of classes.
- target: labels torch.tensor with the same shape as pred :math:`(N, C, *)`
- torch.where each value is between 0 and 1.
+ pred: logits torch.Tensor with shape :math:`(N, C, *)` where C = number of classes.
+ target: labels torch.Tensor with the same shape as pred :math:`(N, C, *)`
+ where each value is between 0 and 1.
alpha: Weighting factor :math:`\alpha \in [0, 1]`.
gamma: Focusing parameter :math:`\gamma >= 0`.
reduction: Specifies the reduction to apply to the
@@ -335,9 +335,9 @@ class BinaryFocalLossWithLogits(nn.Module):
ignore_index: labels with this value are ignored in the loss computation.
Shape:
- - Pred: :math:`(N, C, *)` torch.where C = number of classes.
+ - Pred: :math:`(N, C, *)` where C = number of classes.
- Target: the same shape as Pred :math:`(N, C, *)`
- torch.where each value is between 0 and 1.
+ where each value is between 0 and 1.
Examples:
>>> C = 3 # num_classes
diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.py
index 2c953dbd7..367335acb 100644
--- a/kornia/losses/geman_mcclure.py
+++ b/kornia/losses/geman_mcclure.py
@@ -41,8 +41,8 @@ def geman_mcclure_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str =
[2] Bayesian image analysis: An application to single photon emission tomography, Geman and McClure, 1985
Args:
- img1: the predicted torch.tensor with shape :math:`(*)`.
- img2: the target torch.tensor with the same shape as img1.
+ img1: the predicted torch.Tensor with shape :math:`(*)`.
+ img2: the target torch.Tensor with the same shape as img1.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied (default), ``'mean'``: the sum of the output will be divided
@@ -114,8 +114,8 @@ class GemanMcclureLoss(nn.Module):
summed.
Shape:
- - img1: the predicted torch.tensor with shape :math:`(*)`.
- - img2: the target torch.tensor with the same shape as img1.
+ - img1: the predicted torch.Tensor with shape :math:`(*)`.
+ - img2: the target torch.Tensor with the same shape as img1.
Example:
>>> criterion = GemanMcclureLoss(reduction="mean")
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index e298ff17e..1b8bf38ea 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -96,9 +96,9 @@ class _HausdorffERLossBase(nn.Module):
"""Compute Hausdorff loss.
Args:
- pred: predicted torch.tensor with a shape of :math:`(B, C, H, W)` or :math:`(B, C, D, H, W)`.
+ pred: predicted torch.Tensor with a shape of :math:`(B, C, H, W)` or :math:`(B, C, D, H, W)`.
Each channel is as binary as: 1 -> fg, 0 -> bg.
- target: target torch.tensor with a shape of :math:`(B, 1, H, W)` or :math:`(B, C, D, H, W)`.
+ target: target torch.Tensor with a shape of :math:`(B, 1, H, W)` or :math:`(B, C, D, H, W)`.
Returns:
Estimated Hausdorff Loss.
@@ -189,9 +189,9 @@ class HausdorffERLoss(_HausdorffERLossBase):
"""Compute Hausdorff loss.
Args:
- pred: predicted torch.tensor with a shape of :math:`(B, C, H, W)`.
+ pred: predicted torch.Tensor with a shape of :math:`(B, C, H, W)`.
Each channel is as binary as: 1 -> fg, 0 -> bg.
- target: target torch.tensor with a shape of :math:`(B, 1, H, W)`.
+ target: target torch.Tensor with a shape of :math:`(B, 1, H, W)`.
Returns:
Estimated Hausdorff Loss.
@@ -261,9 +261,9 @@ class HausdorffERLoss3D(_HausdorffERLossBase):
"""Compute 3D Hausdorff loss.
Args:
- pred: predicted torch.tensor with a shape of :math:`(B, C, D, H, W)`.
+ pred: predicted torch.Tensor with a shape of :math:`(B, C, D, H, W)`.
Each channel is as binary as: 1 -> fg, 0 -> bg.
- target: target torch.tensor with a shape of :math:`(B, 1, D, H, W)`.
+ target: target torch.Tensor with a shape of :math:`(B, 1, D, H, W)`.
Returns:
Estimated Hausdorff Loss.
diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.py
index af73c4331..29427813f 100644
--- a/kornia/losses/lovasz_softmax.py
+++ b/kornia/losses/lovasz_softmax.py
@@ -59,7 +59,7 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =
Args:
pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1.
target: labels tensor with shape :math:`(N, H, W)` where each value
- is :math:`0 ≀ targets[i] ≀ C-1`.
+ is in range :math:`0 ≀ targets[i] ≀ C-1`.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
Return:
@@ -162,7 +162,7 @@ class LovaszSoftmaxLoss(nn.Module):
Args:
pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1.
labels: labels tensor with shape :math:`(N, H, W)` where each value
- is :math:`0 ≀ targets[i] ≀ C-1`.
+ is in range :math:`0 ≀ targets[i] ≀ C-1`.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
Return:
diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.py
index 3b63c7ee7..6e0000665 100644
--- a/kornia/losses/mutual_information.py
+++ b/kornia/losses/mutual_information.py
@@ -17,6 +17,7 @@
from __future__ import annotations
from enum import Enum, member
+from functools import partial
import torch
@@ -119,7 +120,7 @@ class EntropyBasedLossBase(torch.nn.Module):
raise ValueError(
f"The passed_kernel_function is not an accepted Kernel, the available options are {list(Kernel)}."
)
- self.kernel_function = kernel_function.value
+ self.kernel_function = partial(kernel_function.value, window_radius=window_radius)
self.window_radius = window_radius
self.bin_centers = torch.arange(self.num_bins, device=self.signal.device)
@@ -149,8 +150,8 @@ class EntropyBasedLossBase(torch.nn.Module):
diff_1 = self.bin_centers.unsqueeze(-1) - self.signal.unsqueeze(-2)
diff_2 = self.bin_centers.unsqueeze(-1) - other_signal.unsqueeze(-2)
- vals_1 = self.kernel_function(diff_1, window_radius=self.window_radius)
- vals_2 = self.kernel_function(diff_2, window_radius=self.window_radius)
+ vals_1 = self.kernel_function(diff_1)
+ vals_2 = self.kernel_function(diff_2)
joint_histogram = torch.einsum("...in,...jn->...ij", vals_1, vals_2)
diff --git a/kornia/losses/one_hot.py b/kornia/losses/one_hot.py
index e465431c6..b82ce27ad 100644
--- a/kornia/losses/one_hot.py
+++ b/kornia/losses/one_hot.py
@@ -24,18 +24,18 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
def one_hot(
labels: torch.Tensor, num_classes: int, device: torch.device, dtype: torch.dtype, eps: float = 1e-6
) -> torch.Tensor:
- r"""Convert an integer label x-D torch.tensor to a one-hot (x+1)-D torch.tensor.
+ r"""Convert an integer label x-D torch.Tensor to a one-hot (x+1)-D torch.Tensor.
Args:
- labels: torch.tensor with labels of shape :math:`(N, *)`, torch.where N is batch size.
+ labels: torch.Tensor with labels of shape :math:`(N, *)`, where N is batch size.
Each value is an integer representing correct classification.
num_classes: number of classes in labels.
- device: the desired device of returned torch.tensor.
- dtype: the desired data type of returned torch.tensor.
+ device: the desired device of returned torch.Tensor.
+ dtype: the desired data type of returned torch.Tensor.
eps: epsilon for numerical stability.
Returns:
- the labels in one hot torch.tensor of shape :math:`(N, C, *)`,
+ the labels in one hot torch.Tensor of shape :math:`(N, C, *)`,
Examples:
>>> labels = torch.LongTensor([[[0, 1], [2, 0]]])
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index 9e61784c7..45b3f0e9a 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -33,7 +33,7 @@ def total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:
in the output, ``'sum'``: the output will be summed.
Return:
- a torch.tensor with shape :math:`(*,)`.
+ a torch.Tensor with shape :math:`(*,)`.
Examples:
>>> total_variation(torch.ones(4, 4))
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index 687f4b4da..7d5cd1450 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -60,7 +60,7 @@ def tversky_loss(
Args:
pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.
target: labels tensor with shape :math:`(N, H, W)` where each value
- is :math:`0 ≀ targets[i] ≀ C-1`.
+ is in range :math:`0 ≀ targets[i] ≀ C-1`.
alpha: the first coefficient in the denominator.
beta: the second coefficient in the denominator.
eps: scalar for numerical stability.
diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.py
index d24f949f1..57c847fd7 100644
--- a/kornia/losses/welsch.py
+++ b/kornia/losses/welsch.py
@@ -43,8 +43,8 @@ def welsch_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none")
[3] https://link.springer.com/article/10.1007/BF00054839
Args:
- img1: the predicted torch.tensor with shape :math:`(*)`.
- img2: the target torch.tensor with the same shape as img1.
+ img1: the predicted torch.Tensor with shape :math:`(*)`.
+ img2: the target torch.Tensor with the same shape as img1.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied (default), ``'mean'``: the sum of the output will be divided
@@ -113,8 +113,8 @@ class WelschLoss(nn.Module):
summed.
Shape:
- - img1: the predicted torch.tensor with shape :math:`(*)`.
- - img2: the target torch.tensor with the same shape as img1.
+ - img1: the predicted torch.Tensor with shape :math:`(*)`.
+ - img2: the target torch.Tensor with the same shape as img1.
Example:
>>> criterion = WelschLoss(reduction="mean")
diff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.py
index 89456977b..a729f7351 100644
--- a/kornia/metrics/accuracy.py
+++ b/kornia/metrics/accuracy.py
@@ -24,8 +24,8 @@ def accuracy(pred: torch.Tensor, target: torch.Tensor, topk: Tuple[int, ...] = (
"""Compute the accuracy over the k top predictions for the specified values of k.
Args:
- pred: the input torch.tensor with the logits to evaluate.
- target: the torch.tensor containing the ground truth.
+ pred: the input torch.Tensor with the logits to evaluate.
+ target: the torch.Tensor containing the ground truth.
topk: the expected topk ranking.
Example:
diff --git a/kornia/metrics/average_meter.py b/kornia/metrics/average_meter.py
index 3c9791182..bbc9ff84d 100644
--- a/kornia/metrics/average_meter.py
+++ b/kornia/metrics/average_meter.py
@@ -26,7 +26,7 @@ class AverageMeter:
Example:
>>> stats = AverageMeter()
>>> acc1 = torch.tensor(0.99) # coming from K.metrics.accuracy
- >>> stats.update(acc1, n=1) # torch.where n is batch size usually
+ >>> stats.update(acc1, n=1) # where n is batch size usually
>>> round(stats.avg, 2)
0.99
diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.py
index 1ac4956a9..d75a8c9ba 100644
--- a/kornia/metrics/mean_average_precision.py
+++ b/kornia/metrics/mean_average_precision.py
@@ -37,11 +37,11 @@ def mean_average_precision(
Background class (0 index) is excluded.
Args:
- pred_boxes: a torch.tensor list of predicted bounding boxes.
- pred_labels: a torch.tensor list of predicted labels.
- pred_scores: a torch.tensor list of predicted labels' scores.
- gt_boxes: a torch.tensor list of ground truth bounding boxes.
- gt_labels: a torch.tensor list of ground truth labels.
+ pred_boxes: a torch.Tensor list of predicted bounding boxes.
+ pred_labels: a torch.Tensor list of predicted labels.
+ pred_scores: a torch.Tensor list of predicted labels' scores.
+ gt_boxes: a torch.Tensor list of ground truth bounding boxes.
+ gt_labels: a torch.Tensor list of ground truth labels.
n_classes: the number of classes.
threshold: count as a positive if the overlap is greater than the threshold.
@@ -59,7 +59,7 @@ def mean_average_precision(
if not len(pred_boxes) == len(pred_labels) == len(pred_scores) == len(gt_boxes) == len(gt_labels):
raise AssertionError
- # Store all (true) objects in a single continuous torch.tensor while keeping track of the image it is from
+ # Store all (true) objects in a single continuous torch.Tensor while keeping track of the image it is from
gt_images = []
for i, labels in enumerate(gt_labels):
gt_images.extend([i] * labels.size(0))
@@ -71,7 +71,7 @@ def mean_average_precision(
if not _gt_images.size(0) == _gt_boxes.size(0) == _gt_labels.size(0):
raise AssertionError
- # Store all detections in a single continuous torch.tensor while keeping track of the image it is from
+ # Store all detections in a single continuous torch.Tensor while keeping track of the image it is from
pred_images = []
for i, labels in enumerate(pred_labels):
pred_images.extend([i] * labels.size(0))
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.py
index 9f6d49587..0e5a15adb 100644
--- a/kornia/models/_hf_models/hf_onnx_community.py
+++ b/kornia/models/_hf_models/hf_onnx_community.py
@@ -39,7 +39,7 @@ class HFONNXComunnityModelLoader:
Args:
model_name: The name of the model to load.
model_type: The type of the model to load.
- cache_dir: The directory torch.where models are cached locally.
+ cache_dir: The directory where models are cached locally.
Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
with_data: Whether to download the model weights such as `model.onnx_data`.