Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

chore (docstrings): addopt ruff over docformatter (#3082)

João G. Atkinson A.b230615f08bb
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 9a5145d87..310c72af6 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -30,9 +30,3 @@ repos:
- "ans,hist,laf,cofusion"
- --skip
- "*.bib,*.ipynb"
-
- - repo: https://github.com/PyCQA/docformatter
- rev: 06907d0
- hooks:
- - id: docformatter
- args: [--in-place, --config, ./pyproject.toml, --wrap-summaries=115, --wrap-descriptions=120]
diff --git a/conftest.py b/conftest.py
index d881f79da..f981f418c 100644
--- a/conftest.py
+++ b/conftest.py
@@ -27,6 +27,7 @@ def get_test_devices() -> dict[str, torch.device]:
Return:
dict(str, torch.device): list with devices names.
+
"""
devices: dict[str, torch.device] = {}
devices["cpu"] = torch.device("cpu")
@@ -47,6 +48,7 @@ def get_test_dtypes() -> dict[str, torch.dtype]:
Return:
dict(str, torch.dtype): list with dtype names.
+
"""
dtypes: dict[str, torch.dtype] = {}
dtypes["bfloat16"] = torch.bfloat16
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 71d8bf4f6..c5fc04706 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -25,6 +25,7 @@ class AugmentationBase2D(_AugmentationBase):
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
form ``False``.
+
"""
def validate_tensor(self, input: Tensor) -> None:
@@ -57,6 +58,7 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
form ``False``.
+
"""
_transform_matrix: Optional[Tensor]
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index b6bee1598..0cd3414b1 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -72,6 +72,7 @@ class RandomAffine(GeometricAugmentationBase2D):
>>> aug = RandomAffine((-15., 20.), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 8f25db7a3..4aeee7f99 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -19,6 +19,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
+
"""
def inverse_transform(
@@ -65,6 +66,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
Note:
Convert "resample" arguments to "nearest" by default.
+
"""
resample_method: Optional[Resample]
if "resample" in flags:
@@ -221,6 +223,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
params: the corresponding parameters for an operation.
flags: static parameters.
transform: the inverse transformation matrix
+
"""
output = input.clone()
batch_prob = params["batch_prob"]
@@ -262,6 +265,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
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.
+
"""
input_shape = input.shape
in_tensor = self.transform_tensor(input)
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 266c251cc..23e34d4ec 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -58,6 +58,7 @@ class CenterCrop(GeometricAugmentationBase2D):
>>> aug = CenterCrop(2, p=1., cropping_mode="resample")
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index c95196eef..bf8a9d726 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -70,6 +70,7 @@ class RandomCrop(GeometricAugmentationBase2D):
>>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample")
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index 686a10566..7d37f07b7 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -43,6 +43,7 @@ class RandomElasticTransform(AugmentationBase2D):
>>> aug = RandomElasticTransform(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
index 4fd1c5c4a..37ad3a434 100644
--- a/kornia/augmentation/_2d/geometric/fisheye.py
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -36,6 +36,7 @@ class RandomFisheye(AugmentationBase2D):
>>> aug = RandomFisheye(center_x, center_y, gamma, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index 5e1e3d34c..51de8addf 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -51,6 +51,7 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
>>> seq = RandomHorizontalFlip(p=1.0)
>>> (seq(input) == seq(input, params=seq._params)).all()
tensor(True)
+
"""
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
diff --git a/kornia/augmentation/_2d/geometric/pad.py b/kornia/augmentation/_2d/geometric/pad.py
index dcd568cc6..3c85e0390 100644
--- a/kornia/augmentation/_2d/geometric/pad.py
+++ b/kornia/augmentation/_2d/geometric/pad.py
@@ -43,6 +43,7 @@ class PadTo(GeometricAugmentationBase2D):
tensor([[[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]]])
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 879f7b48c..9b5638449 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -53,6 +53,7 @@ class RandomPerspective(GeometricAugmentationBase2D):
>>> aug = RandomPerspective(0.5, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 240bfd986..df443209b 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -22,6 +22,7 @@ class Resize(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).
+
"""
def __init__(
@@ -100,6 +101,7 @@ class LongestMaxSize(Resize):
Args:
max_size: maximum size of the image after the transformation.
+
"""
def __init__(
@@ -118,6 +120,7 @@ class SmallestMaxSize(Resize):
Args:
max_size: maximum size of the image after the transformation.
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 07ec15e9b..a3e599143 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -58,6 +58,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
>>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample")
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index 526cee540..f7ce24534 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -55,6 +55,7 @@ class RandomRotation(GeometricAugmentationBase2D):
>>> aug = RandomRotation(degrees=45.0, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
# Note: Extra params, center=None, fill=0 in TorchVision
@@ -158,6 +159,7 @@ class RandomRotation90(GeometricAugmentationBase2D):
>>> aug = RandomRotation90(times=(-1, 1), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.py
index 449fa9808..4b61959b8 100644
--- a/kornia/augmentation/_2d/geometric/shear.py
+++ b/kornia/augmentation/_2d/geometric/shear.py
@@ -55,6 +55,7 @@ class RandomShear(GeometricAugmentationBase2D):
>>> aug = RandomShear((-15., 20.), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index 24f4f814a..240c31bb6 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -35,6 +35,7 @@ class RandomThinPlateSpline(AugmentationBase2D):
>>> aug = RandomThinPlateSpline(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.py
index 496358463..1e00fde42 100644
--- a/kornia/augmentation/_2d/geometric/translate.py
+++ b/kornia/augmentation/_2d/geometric/translate.py
@@ -53,6 +53,7 @@ class RandomTranslate(GeometricAugmentationBase2D):
>>> aug = RandomTranslate((-0.2, 0.2), (-0.1, 0.1), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index ae9d14b83..75c69b36b 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -43,6 +43,7 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
>>> seq = RandomVerticalFlip(p=1.0)
>>> (seq(input) == seq(input, params=seq._params)).all()
tensor(True)
+
"""
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.py
index a9e542b70..6ca956475 100644
--- a/kornia/augmentation/_2d/intensity/auto_contrast.py
+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py
@@ -20,6 +20,7 @@ class RandomAutoContrast(IntensityAugmentationBase2D):
.. note::
This function internally uses :func:`kornia.enhance.normalize_min_max`
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.py
index d4906e365..c6fe206bf 100644
--- a/kornia/augmentation/_2d/intensity/base.py
+++ b/kornia/augmentation/_2d/intensity/base.py
@@ -18,6 +18,7 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
+
"""
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
diff --git a/kornia/augmentation/_2d/intensity/box_blur.py b/kornia/augmentation/_2d/intensity/box_blur.py
index 4d421c0cb..e7353757e 100644
--- a/kornia/augmentation/_2d/intensity/box_blur.py
+++ b/kornia/augmentation/_2d/intensity/box_blur.py
@@ -34,6 +34,7 @@ class RandomBoxBlur(IntensityAugmentationBase2D):
>>> aug = RandomBoxBlur((7, 7), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.py
index 57e867dc6..61b6bcca2 100644
--- a/kornia/augmentation/_2d/intensity/brightness.py
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -52,6 +52,7 @@ class RandomBrightness(IntensityAugmentationBase2D):
>>> aug = RandomBrightness((0.8,1.2), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/channel_dropout.py b/kornia/augmentation/_2d/intensity/channel_dropout.py
index e80fb5efd..585aa6666 100644
--- a/kornia/augmentation/_2d/intensity/channel_dropout.py
+++ b/kornia/augmentation/_2d/intensity/channel_dropout.py
@@ -53,6 +53,7 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
>>> aug = RandomChannelDropout(num_drop_channels=1, fill_value=0.0, p=1.0)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.py
index 573ab9220..bf50ee99b 100644
--- a/kornia/augmentation/_2d/intensity/channel_shuffle.py
+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py
@@ -32,6 +32,7 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
>>> aug = RandomChannelShuffle(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.py
index 162f0caf1..9455ac2e2 100644
--- a/kornia/augmentation/_2d/intensity/clahe.py
+++ b/kornia/augmentation/_2d/intensity/clahe.py
@@ -42,6 +42,7 @@ class RandomClahe(IntensityAugmentationBase2D):
>>> aug = RandomClahe(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index 792b13480..8500882b5 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -52,6 +52,7 @@ class ColorJiggle(IntensityAugmentationBase2D):
>>> aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
index 93cd38b60..e22304fce 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -66,6 +66,7 @@ class ColorJitter(IntensityAugmentationBase2D):
>>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index fe4b91f73..9b2e6799b 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -51,6 +51,7 @@ class RandomContrast(IntensityAugmentationBase2D):
>>> aug = RandomContrast((0.8,1.2), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/denormalize.py b/kornia/augmentation/_2d/intensity/denormalize.py
index 7b4189eae..ccef61b73 100644
--- a/kornia/augmentation/_2d/intensity/denormalize.py
+++ b/kornia/augmentation/_2d/intensity/denormalize.py
@@ -30,12 +30,12 @@ class Denormalize(IntensityAugmentationBase2D):
This function internally uses :func:`kornia.enhance.denormalize`.
Examples:
-
>>> norm = Denormalize(mean=torch.zeros(1, 4), std=torch.ones(1, 4))
>>> x = torch.rand(1, 4, 3, 3)
>>> out = norm(x)
>>> out.shape
torch.Size([1, 4, 3, 3])
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/dissolving.py b/kornia/augmentation/_2d/intensity/dissolving.py
index f64bc9367..a743ccbe4 100644
--- a/kornia/augmentation/_2d/intensity/dissolving.py
+++ b/kornia/augmentation/_2d/intensity/dissolving.py
@@ -36,6 +36,7 @@ class RandomDissolving(IntensityAugmentationBase2D):
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`.
- Output: :math:`(B, C, H, W)`
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.py
index ea4eec9e6..3199f1cee 100644
--- a/kornia/augmentation/_2d/intensity/equalize.py
+++ b/kornia/augmentation/_2d/intensity/equalize.py
@@ -40,6 +40,7 @@ class RandomEqualize(IntensityAugmentationBase2D):
>>> aug = RandomEqualize(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.py
index ed5c4333d..ff16a503a 100644
--- a/kornia/augmentation/_2d/intensity/erasing.py
+++ b/kornia/augmentation/_2d/intensity/erasing.py
@@ -50,6 +50,7 @@ class RandomErasing(IntensityAugmentationBase2D):
>>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.py
index 76ce8d526..9f0db2e86 100644
--- a/kornia/augmentation/_2d/intensity/gamma.py
+++ b/kornia/augmentation/_2d/intensity/gamma.py
@@ -49,6 +49,7 @@ class RandomGamma(IntensityAugmentationBase2D):
>>> aug = RandomGamma((0.8,1.2), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.py
index 655297142..a643cf146 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py
@@ -50,6 +50,7 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
>>> aug = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
index 09ac4a840..4c03d4634 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
@@ -57,6 +57,7 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):
>>> aug = RandomGaussianIllumination(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.py
index 99f9396a5..4700d8017 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py
@@ -27,6 +27,7 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+
Examples:
>>> rng = torch.manual_seed(0)
>>> img = torch.ones(1, 1, 2, 2)
@@ -39,6 +40,7 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
>>> aug = RandomGaussianNoise(mean=0., std=1., p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/grayscale.py b/kornia/augmentation/_2d/intensity/grayscale.py
index cbdfed6aa..d7ec665ba 100644
--- a/kornia/augmentation/_2d/intensity/grayscale.py
+++ b/kornia/augmentation/_2d/intensity/grayscale.py
@@ -49,6 +49,7 @@ class RandomGrayscale(IntensityAugmentationBase2D):
>>> aug = RandomGrayscale(p=1.0)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index 97a2f737d..75c66f976 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -51,6 +51,7 @@ class RandomHue(IntensityAugmentationBase2D):
>>> aug = RandomHue((-0.2,0.2), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/invert.py b/kornia/augmentation/_2d/intensity/invert.py
index 8b83af89d..1de948bd0 100644
--- a/kornia/augmentation/_2d/intensity/invert.py
+++ b/kornia/augmentation/_2d/intensity/invert.py
@@ -38,6 +38,7 @@ class RandomInvert(IntensityAugmentationBase2D):
>>> aug = RandomInvert(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/jpeg.py b/kornia/augmentation/_2d/intensity/jpeg.py
index cc8654bdc..887ee31fc 100644
--- a/kornia/augmentation/_2d/intensity/jpeg.py
+++ b/kornia/augmentation/_2d/intensity/jpeg.py
@@ -37,6 +37,7 @@ class RandomJPEG(IntensityAugmentationBase2D):
>>> aug = RandomJPEG(jpeg_quality=20.0, p=1.) # Samples a JPEG quality from the range [30.0, 70.0]
>>> (aug(images) == aug(images, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/linear_illumination.py b/kornia/augmentation/_2d/intensity/linear_illumination.py
index c16278dfb..03e483544 100644
--- a/kornia/augmentation/_2d/intensity/linear_illumination.py
+++ b/kornia/augmentation/_2d/intensity/linear_illumination.py
@@ -51,6 +51,7 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):
>>> aug = RandomLinearIllumination(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
@@ -109,7 +110,6 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):
transform: Optional[Tensor] = None,
) -> Tensor:
r"""Apply random gaussian gradient illumination to the input image."""
-
return input.add(params["gradient"].to(input)).clamp(0, 1)
@@ -158,6 +158,7 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
>>> aug = RandomLinearCornerIllumination(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/median_blur.py b/kornia/augmentation/_2d/intensity/median_blur.py
index 5c93a33ad..6c0c173e9 100644
--- a/kornia/augmentation/_2d/intensity/median_blur.py
+++ b/kornia/augmentation/_2d/intensity/median_blur.py
@@ -21,7 +21,6 @@ class RandomMedianBlur(IntensityAugmentationBase2D):
This function internally uses :func:`kornia.filters.median_blur`.
Examples:
-
>>> img = torch.ones(1, 1, 4, 4)
>>> out = RandomMedianBlur((3, 3), p = 1)(img)
>>> out.shape
@@ -37,6 +36,7 @@ class RandomMedianBlur(IntensityAugmentationBase2D):
>>> aug = RandomMedianBlur((7, 7), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.py
index a6a68840a..2b83ea792 100644
--- a/kornia/augmentation/_2d/intensity/motion_blur.py
+++ b/kornia/augmentation/_2d/intensity/motion_blur.py
@@ -63,6 +63,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
>>> aug = RandomMotionBlur(3, 35., 0.5, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.py
index 7f8386ddc..231c8d127 100644
--- a/kornia/augmentation/_2d/intensity/normalize.py
+++ b/kornia/augmentation/_2d/intensity/normalize.py
@@ -31,12 +31,12 @@ class Normalize(IntensityAugmentationBase2D):
This function internally uses :func:`kornia.enhance.normalize`.
Examples:
-
>>> norm = Normalize(mean=torch.zeros(4), std=torch.ones(4))
>>> x = torch.rand(1, 4, 3, 3)
>>> out = norm(x)
>>> out.shape
torch.Size([1, 4, 3, 3])
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.py
index 6e53cf70f..8bd9fd815 100644
--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py
+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py
@@ -99,7 +99,6 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
Input tensor must be float and normalized into [0, 1].
Examples:
-
To apply planckian jitter based on mode
>>> rng = torch.manual_seed(0)
@@ -139,6 +138,7 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
<BLANKLINE>
[[ 0.2426, -0.1621],
[-0.3302, -0.9093]]]])
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.py
index b36f3b2f5..bea9aad92 100644
--- a/kornia/augmentation/_2d/intensity/plasma.py
+++ b/kornia/augmentation/_2d/intensity/plasma.py
@@ -32,6 +32,7 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
tensor([[[[0.6415, 1.0000, 0.3142, 0.6836],
[1.0000, 0.5593, 0.5556, 0.4566],
[0.5809, 1.0000, 0.7005, 1.0000]]]])
+
"""
def __init__(
@@ -83,6 +84,7 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
tensor([[[[0.9651, 1.0000, 1.0000, 1.0000],
[1.0000, 0.9103, 0.8038, 0.9263],
[0.6882, 1.0000, 0.9544, 1.0000]]]])
+
"""
def __init__(
@@ -131,6 +133,7 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
tensor([[[[0.7682, 1.0000, 1.0000, 1.0000],
[1.0000, 1.0000, 1.0000, 1.0000],
[1.0000, 1.0000, 1.0000, 1.0000]]]])
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.py
index 3ffa40226..0c279841d 100644
--- a/kornia/augmentation/_2d/intensity/posterize.py
+++ b/kornia/augmentation/_2d/intensity/posterize.py
@@ -43,6 +43,7 @@ class RandomPosterize(IntensityAugmentationBase2D):
>>> aug = RandomPosterize(3., p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.py
index a089bbe86..9035c0c92 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -32,6 +32,7 @@ class RandomRain(IntensityAugmentationBase2D):
[0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
[0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
index 59e9082c9..4f9333eb2 100644
--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py
+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
@@ -71,6 +71,7 @@ class RandomRGBShift(IntensityAugmentationBase2D):
[0.2914, 0.2663, 0.0000, 0.2163, 0.3397],
[0.0021, 0.0843, 0.1811, 0.3754, 0.5453],
[0.0000, 0.0000, 0.2617, 0.4795, 0.5003]]]])
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.py
index d804cc931..2a6470330 100644
--- a/kornia/augmentation/_2d/intensity/random_snow.py
+++ b/kornia/augmentation/_2d/intensity/random_snow.py
@@ -31,6 +31,7 @@ class RandomSnow(IntensityAugmentationBase2D):
>>> output = snow(inputs)
>>> output.shape
torch.Size([2, 3, 4, 4])
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
index 7a3e791ac..5112e3851 100644
--- a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
+++ b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
@@ -56,6 +56,7 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
>>> aug = RandomSaltAndPepperNoise(amount=0.05, salt_vs_pepper=0.5, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index 94f7f7cff..49305861a 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -50,6 +50,7 @@ class RandomSaturation(IntensityAugmentationBase2D):
>>> aug = RandomSaturation((0.8,1.2), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/sharpness.py b/kornia/augmentation/_2d/intensity/sharpness.py
index 81a78d7bc..e3b4e6af4 100644
--- a/kornia/augmentation/_2d/intensity/sharpness.py
+++ b/kornia/augmentation/_2d/intensity/sharpness.py
@@ -41,6 +41,7 @@ class RandomSharpness(IntensityAugmentationBase2D):
>>> aug = RandomSharpness(1., p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.py
index 4ab6773a3..85894bd98 100644
--- a/kornia/augmentation/_2d/intensity/solarize.py
+++ b/kornia/augmentation/_2d/intensity/solarize.py
@@ -46,6 +46,7 @@ class RandomSolarize(IntensityAugmentationBase2D):
>>> aug = RandomSolarize(0.1, 0.1, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 66a565150..710fbbe3d 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -30,6 +30,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
to the batch form ``False``.
data_keys: the input type sequential for applying augmentations.
Accepts "input", "image", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints", "class", "label".
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 037ca1fe6..f2db9e51d 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -65,6 +65,7 @@ class RandomCutMixV2(MixAugmentationBaseV2):
[1.0000, 1.0000, 0.0542],
[0.4594, 0.1756, 0.9492]]]]), tensor([[[0.0000, 1.0000, 0.4444],
[1.0000, 0.0000, 0.4444]]])]
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
index ba0b23929..0dfd0aaba 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -37,6 +37,7 @@ class RandomJigsaw(MixAugmentationBaseV2):
>>> out = jigsaw(input)
>>> out.shape
torch.Size([8, 3, 256, 256])
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index 857f01d14..5b738f060 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -73,6 +73,7 @@ class RandomMixUpV2(MixAugmentationBaseV2):
[0.6826, 0.3051, 0.4635],
[0.4550, 0.5725, 0.4980]]]]), tensor([[0.0000, 0.0000, 0.1980],
[1.0000, 1.0000, 0.4162]])]
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 822b9372d..ff1a60f04 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -58,6 +58,7 @@ class RandomMosaic(MixAugmentationBaseV2):
>>> out = mosaic(input, boxes)
>>> out[0].shape, out[1].shape
(torch.Size([8, 3, 300, 300]), torch.Size([8, 8, 4]))
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index 3c3c4fde6..21b4d82ad 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -144,6 +144,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
[1., 1., 1., 1., 0.],
[0., 0., 0., 0., 1.],
[1., 1., 1., 0., 1.]]])
+
"""
def __init__(
@@ -205,6 +206,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
Returns:
Updated dictionary of parameters with the necessary information to apply the augmentation on all input
tensors separately.
+
"""
KORNIA_CHECK(
len(data_keys) == len(input),
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 180959943..4b871233f 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -19,6 +19,7 @@ class AugmentationBase3D(_AugmentationBase):
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wise.
same_on_batch: apply the same transformation across the batch.
+
"""
def validate_tensor(self, input: Tensor) -> None:
@@ -54,6 +55,7 @@ class RigidAffineAugmentationBase3D(AugmentationBase3D):
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
form ``False``.
+
"""
_transform_matrix: Optional[Tensor]
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index d0e62bbfc..2bfc7e2b6 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -79,6 +79,7 @@ class RandomAffine3D(GeometricAugmentationBase3D):
>>> aug = RandomAffine3D((15., 20., 20.), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index 337726a3f..051c54054 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -56,6 +56,7 @@ class CenterCrop3D(GeometricAugmentationBase3D):
>>> aug = CenterCrop3D(24, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index f02a75c81..e93f3bb57 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -60,6 +60,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
>>> aug = RandomCrop3D((24, 24, 24), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
index 85866afb0..13035723f 100644
--- a/kornia/augmentation/_3d/geometric/depthical_flip.py
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -55,6 +55,7 @@ class RandomDepthicalFlip3D(GeometricAugmentationBase3D):
>>> aug = RandomDepthicalFlip3D(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
diff --git a/kornia/augmentation/_3d/geometric/horizontal_flip.py b/kornia/augmentation/_3d/geometric/horizontal_flip.py
index 5fcc9836e..3a228ecc0 100644
--- a/kornia/augmentation/_3d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_3d/geometric/horizontal_flip.py
@@ -49,6 +49,7 @@ class RandomHorizontalFlip3D(GeometricAugmentationBase3D):
>>> aug = RandomHorizontalFlip3D(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index 7404852cf..59f4c3223 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -61,6 +61,7 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
>>> aug = RandomPerspective3D(0.5, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index 16218cae9..8267c31ed 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -68,6 +68,7 @@ class RandomRotation3D(GeometricAugmentationBase3D):
>>> aug = RandomRotation3D((15., 20., 20.), p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/_3d/geometric/vertical_flip.py b/kornia/augmentation/_3d/geometric/vertical_flip.py
index fa130e099..a9023dde8 100644
--- a/kornia/augmentation/_3d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_3d/geometric/vertical_flip.py
@@ -55,6 +55,7 @@ class RandomVerticalFlip3D(GeometricAugmentationBase3D):
>>> aug = RandomVerticalFlip3D(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
diff --git a/kornia/augmentation/_3d/intensity/equalize.py b/kornia/augmentation/_3d/intensity/equalize.py
index e37ca4374..dad2791d2 100644
--- a/kornia/augmentation/_3d/intensity/equalize.py
+++ b/kornia/augmentation/_3d/intensity/equalize.py
@@ -47,6 +47,7 @@ class RandomEqualize3D(IntensityAugmentationBase3D):
>>> aug = RandomEqualize3D(p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(self, p: float = 0.5, same_on_batch: bool = False, keepdim: bool = False) -> None:
diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.py
index 7bc7c227e..8ccf24e57 100644
--- a/kornia/augmentation/_3d/intensity/motion_blur.py
+++ b/kornia/augmentation/_3d/intensity/motion_blur.py
@@ -72,6 +72,7 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):
>>> aug = RandomMotionBlur3D(3, 35., 0.5, p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
+
"""
def __init__(
diff --git a/kornia/augmentation/auto/autoaugment/autoaugment.py b/kornia/augmentation/auto/autoaugment/autoaugment.py
index 8f5543e34..6c079112b 100644
--- a/kornia/augmentation/auto/autoaugment/autoaugment.py
+++ b/kornia/augmentation/auto/autoaugment/autoaugment.py
@@ -116,6 +116,7 @@ class AutoAugment(PolicyAugmentBase):
>>> aug = K.AugmentationSequential(AutoAugment())
>>> aug(in_tensor).shape
torch.Size([5, 3, 30, 30])
+
"""
def __init__(
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index b7cc90057..ba0a5f428 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -56,6 +56,7 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
+
"""
if params is None:
raise NotImplementedError("requires params to be provided.")
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index e27a43472..f7c0872ea 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -23,6 +23,7 @@ class OperationBase(Module):
temperature: temperature for RelaxedBernoulli distribution used during training.
is_batch_operation: determine if to obtain the probability from `p` or `p_batch`.
Set to True for most non-shape-persistent operations (e.g. cropping).
+
"""
def __init__(
diff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.py
index c1353243d..dd611cb35 100644
--- a/kornia/augmentation/auto/operations/ops.py
+++ b/kornia/augmentation/auto/operations/ops.py
@@ -36,6 +36,7 @@ class AutoContrast(OperationBase):
applied according to he augmentation sampling range.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
def __init__(
@@ -59,6 +60,7 @@ class Brightness(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
def __init__(
@@ -87,6 +89,7 @@ class Contrast(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
def __init__(
@@ -115,6 +118,7 @@ class Hue(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
def __init__(
@@ -143,6 +147,7 @@ class Saturate(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
def __init__(
@@ -175,6 +180,7 @@ class Equalize(OperationBase):
Note:
STE gradient estimator applied for back propagation.
+
"""
def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
@@ -194,6 +200,7 @@ class Gray(OperationBase):
initial_probability: the initial probability. If None, the augmentation will be randomly
applied according to he augmentation sampling range.
temperature: temperature for RelaxedBernoulli distribution used during training.
+
"""
def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
@@ -212,6 +219,7 @@ class Invert(OperationBase):
initial_probability: the initial probability. If None, the augmentation will be randomly
applied according to he augmentation sampling range.
temperature: temperature for RelaxedBernoulli distribution used during training.
+
"""
def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
@@ -236,6 +244,7 @@ class Posterize(OperationBase):
Note:
STE gradient estimator applied for back propagation.
+
"""
@staticmethod
@@ -273,6 +282,7 @@ class Solarize(OperationBase):
Note:
STE gradient estimator applied for back propagation.
+
"""
def __init__(
@@ -305,6 +315,7 @@ class SolarizeAdd(OperationBase):
Note:
STE gradient estimator applied for back propagation.
+
"""
def __init__(
@@ -334,6 +345,7 @@ class Sharpness(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
def __init__(
@@ -359,6 +371,7 @@ class HorizontalFlip(OperationBase):
initial_probability: the initial probability. If None, the augmentation will be randomly
applied according to he augmentation sampling range.
temperature: temperature for RelaxedBernoulli distribution used during training.
+
"""
def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
@@ -376,6 +389,7 @@ class VerticalFlip(OperationBase):
Args:
initial_magnitude: the initial magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
+
"""
def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
@@ -397,6 +411,7 @@ class Rotate(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
def __init__(
@@ -430,6 +445,7 @@ class ShearX(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
@staticmethod
@@ -469,6 +485,7 @@ class ShearY(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
@staticmethod
@@ -513,6 +530,7 @@ class TranslateX(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
def __init__(
@@ -546,6 +564,7 @@ class TranslateY(OperationBase):
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
temperature: temperature for RelaxedBernoulli distribution used during training.
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
"""
def __init__(
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index 52866869c..8f3fe9d4f 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -17,6 +17,7 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
Args:
operations: a list of operations to perform.
+
"""
def __init__(self, *operations: OperationBase) -> None:
@@ -57,6 +58,7 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
+
"""
if params is None:
raise NotImplementedError("requires params to be provided.")
diff --git a/kornia/augmentation/auto/rand_augment/rand_augment.py b/kornia/augmentation/auto/rand_augment/rand_augment.py
index 87ffcd9eb..926c97338 100644
--- a/kornia/augmentation/auto/rand_augment/rand_augment.py
+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py
@@ -51,6 +51,7 @@ class RandAugment(PolicyAugmentBase):
>>> aug = K.AugmentationSequential(RandAugment(n=2, m=10))
>>> aug(in_tensor).shape
torch.Size([5, 3, 30, 30])
+
"""
def __init__(
diff --git a/kornia/augmentation/auto/trivial_augment/trivial_augment.py b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
index 4a444a262..5cd237726 100644
--- a/kornia/augmentation/auto/trivial_augment/trivial_augment.py
+++ b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
@@ -46,6 +46,7 @@ class TrivialAugment(PolicyAugmentBase):
>>> aug = K.AugmentationSequential(TrivialAugment())
>>> aug(in_tensor).shape
torch.Size([5, 3, 30, 30])
+
"""
def __init__(
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index a4cfa33e2..6d08c4405 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -51,6 +51,7 @@ class _BasicAugmentationBase(Module):
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to
the batch form ``False``.
+
"""
# TODO: Hard to support. Many codes are not ONNX-friendly that contains lots of if-else blocks, etc.
@@ -130,6 +131,7 @@ class _BasicAugmentationBase(Module):
Note:
The generated random numbers are not reproducible across different devices and dtypes.
+
"""
self.device = device
self.dtype = dtype
@@ -222,6 +224,7 @@ class _BasicAugmentationBase(Module):
By default, all the overwriting parameters in kwargs will not be recorded
as in ``self._params``. If you wish it to be recorded, you may pass
``save_kwargs=True`` additionally.
+
"""
in_tensor = self.__unpack_input__(input)
input_shape = in_tensor.shape
@@ -252,6 +255,7 @@ class _AugmentationBase(_BasicAugmentationBase):
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
+
"""
def apply_transform(
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index d17ae7744..0db74087a 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -200,6 +200,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
>>> out = aug_dict(data)
>>> out.keys()
dict_keys(['image', 'mask', 'mask-b', 'bbox', 'bbox-other'])
+
"""
input_dtype = None
@@ -484,8 +485,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
Returns:
Callable: Decorated function with converted input and output types.
- """
+ """
# Wrap the forward method with the decorator
if not self._disable_features:
# TODO: Some more behaviour for AugmentationSequential needs to be revisited later
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 896f888c5..86f89f407 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -22,6 +22,7 @@ class BasicSequentialBase(nn.Sequential):
Args:
*args : a list of kornia augmentation and image operation modules.
+
"""
def __init__(self, *args: Module) -> None:
@@ -53,6 +54,7 @@ class BasicSequentialBase(nn.Sequential):
AttributeError: If the target string references an invalid
path or resolves to something that is not an
``Module``
+
"""
if len(target) == 0:
return self
@@ -107,6 +109,7 @@ class SequentialBase(BasicSequentialBase):
applied to each. 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
to the batch form (False). If None, it will not overwrite the function-wise settings.
+
"""
def __init__(self, *args: Module, same_on_batch: Optional[bool] = None, keepdim: Optional[bool] = None) -> None:
@@ -182,6 +185,7 @@ class ImageSequentialBase(SequentialBase):
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
+
"""
raise NotImplementedError
diff --git a/kornia/augmentation/container/dispatcher.py b/kornia/augmentation/container/dispatcher.py
index a0da5296b..a12fa0e05 100644
--- a/kornia/augmentation/container/dispatcher.py
+++ b/kornia/augmentation/container/dispatcher.py
@@ -28,6 +28,7 @@ class ManyToManyAugmentationDispather(nn.Module):
... )
... )
>>> output = aug_list((input_1, mask_1), (input_2, mask_2))
+
"""
def __init__(self, *augmentations: AugmentationSequential) -> None:
@@ -72,6 +73,7 @@ class ManyToOneAugmentationDispather(nn.Module):
... )
... )
>>> output = aug_list(input, mask)
+
"""
def __init__(self, *augmentations: AugmentationSequential, strict: bool = True) -> None:
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index d1bc87797..b3669b9d5 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -93,6 +93,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
>>> out= aug_list(input)
>>> out.shape
torch.Size([2, 3, 5, 6])
+
"""
def __init__(
@@ -159,6 +160,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
Note:
Mix augmentations (e.g. RandomMixUp) will be only applied once even in a random forward.
+
"""
if isinstance(self.random_apply, tuple):
num_samples = int(torch.randint(*self.random_apply, (1,)).item())
@@ -246,6 +248,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
params: params for the sequence.
recompute: if to recompute the transformation matrix according to the params.
default: False.
+
"""
if params is None:
raise NotImplementedError("requires params to be provided.")
@@ -298,6 +301,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
if strict is set to True.
Note: patch processing would break the continuity of labels (e.g. bbounding boxes, masks).
+
"""
for arg in self.children():
if isinstance(arg, (ImageSequential,)) and not arg.is_intensity_only(strict):
@@ -327,8 +331,8 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
Returns:
Callable: Decorated function with converted input and output types.
- """
+ """
# Wrap the forward method with the decorator
if not self._disable_features:
decorated_forward = self.convert_input_output(
@@ -349,6 +353,7 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Siz
Note:
Augmentations that change the image size must provide the parameter `output_size`.
+
"""
if param.data is None:
return batch_shape
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 5fd71ddb0..fa5d464e5 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -50,6 +50,7 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
module: any torch Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
+
"""
raise NotImplementedError
@@ -63,6 +64,7 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
module: any torch Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
+
"""
raise NotImplementedError
@@ -253,6 +255,7 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
module: any torch Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
+
"""
if extra_args is None:
extra_args = {}
@@ -301,6 +304,7 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
module: any torch Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
+
"""
if extra_args is None:
extra_args = {}
@@ -365,6 +369,7 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
module: any torch Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
+
"""
if extra_args is None:
extra_args = {}
@@ -412,6 +417,7 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
module: any torch Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
+
"""
if extra_args is None:
extra_args = {}
@@ -457,6 +463,7 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
module: any torch Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
+
"""
if extra_args is None:
extra_args = {}
@@ -507,6 +514,7 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
module: any torch Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
+
"""
if extra_args is None:
extra_args = {}
@@ -553,6 +561,7 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
module: any torch Module but only kornia augmentation modules will count
to apply transformations.
param: the corresponding parameters to the module.
+
"""
if extra_args is None:
extra_args = {}
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index 7eae3536a..59d841540 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -107,6 +107,7 @@ class PatchSequential(ImageSequential):
>>> out = seq(input)
>>> out.shape
torch.Size([2, 3, 224, 224])
+
"""
def __init__(
@@ -202,6 +203,7 @@ class PatchSequential(ImageSequential):
<BLANKLINE>
<BLANKLINE>
[[[31, 32, 33]]]]])
+
"""
if pad is not None:
input = fpad(input, list(pad))
@@ -225,6 +227,7 @@ class PatchSequential(ImageSequential):
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]]]])
+
"""
if grid_size is None:
grid_size = self.grid_size
@@ -260,6 +263,7 @@ class PatchSequential(ImageSequential):
Args:
batch_shape: 5-dim shape arranged as :math:``(N, B, C, H, W)``, in which N represents
the number of sequence.
+
"""
if not self.same_on_batch and self.random_apply:
# diff_on_batch and random_apply => patch-wise augmentation
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 3003121cc..52e71f9fd 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -94,6 +94,7 @@ class VideoSequential(ImageSequential):
>>> out = aug_list(input)
>>> out.shape
torch.Size([2, 3, 4, 5, 6])
+
"""
# TODO: implement transform_matrix
@@ -252,6 +253,7 @@ class VideoSequential(ImageSequential):
Args:
input: 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)`.
+
"""
if isinstance(input, Tensor):
batchsize, frame_num = input.size(0), input.size(1)
@@ -270,6 +272,7 @@ class VideoSequential(ImageSequential):
Args:
input: 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)`.
+
"""
if isinstance(input, Tensor):
batchsize, frame_num = input.size(0), input.size(1)
@@ -288,6 +291,7 @@ class VideoSequential(ImageSequential):
Args:
input: tensor with shape :math:`(B, T, N, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`.
+
"""
if isinstance(input, Tensor):
batchsize, frame_num = input.size(0), input.size(1)
@@ -306,6 +310,7 @@ class VideoSequential(ImageSequential):
Args:
input: tensor with shape :math:`(B, T, N, 2)`.
If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`.
+
"""
if isinstance(input, Tensor):
frame_num, batchsize = input.size(0), input.size(1)
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index 8c93e4baf..ea9e1204c 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -42,6 +42,7 @@ class AffineGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/channel_dropout.py b/kornia/augmentation/random_generator/_2d/channel_dropout.py
index 2f093228d..973603742 100644
--- a/kornia/augmentation/random_generator/_2d/channel_dropout.py
+++ b/kornia/augmentation/random_generator/_2d/channel_dropout.py
@@ -21,6 +21,7 @@ class ChannelDropoutGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.py
index 34382fd12..a001fbe3a 100644
--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py
+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py
@@ -34,6 +34,7 @@ class ColorJiggleGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/color_jitter.py b/kornia/augmentation/random_generator/_2d/color_jitter.py
index bed380922..29b5f47d9 100644
--- a/kornia/augmentation/random_generator/_2d/color_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py
@@ -43,6 +43,7 @@ class ColorJitterGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index ab392f1b7..9a5104105 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -29,6 +29,7 @@ class CropGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, size: Union[Tuple[int, int], Tensor], resize_to: Optional[Tuple[int, int]] = None) -> None:
@@ -164,6 +165,7 @@ class ResizedCropGenerator(CropGenerator):
tensor([[3, 3]])
>>> out["output_size"]
tensor([[30, 30]])
+
"""
def __init__(
@@ -270,6 +272,7 @@ def center_crop_generator(
Note:
No random number will be generated.
+
"""
if device is None:
device = torch.device("cpu")
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index 803e4c74d..3209823ee 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -32,6 +32,7 @@ class CutmixGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/gaussian_blur.py b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
index ec162e4f5..07d20995f 100644
--- a/kornia/augmentation/random_generator/_2d/gaussian_blur.py
+++ b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
@@ -30,6 +30,7 @@ class RandomGaussianBlurGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, sigma: Union[Tuple[float, float], Tensor] = (0.1, 2.0)) -> None:
diff --git a/kornia/augmentation/random_generator/_2d/gaussian_illumination.py b/kornia/augmentation/random_generator/_2d/gaussian_illumination.py
index 931f15485..ba57f8b30 100644
--- a/kornia/augmentation/random_generator/_2d/gaussian_illumination.py
+++ b/kornia/augmentation/random_generator/_2d/gaussian_illumination.py
@@ -33,6 +33,7 @@ class GaussianIlluminationGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
@@ -60,7 +61,6 @@ class GaussianIlluminationGenerator(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
r"""Create samplers for generating random gaussian illumination parameters."""
-
gain = _range_bound(self.gain, "gain", device=device, dtype=dtype)
self.gain_sampler = UniformDistribution(gain[0], gain[1], validate_args=False)
diff --git a/kornia/augmentation/random_generator/_2d/jigsaw.py b/kornia/augmentation/random_generator/_2d/jigsaw.py
index 9858cfb3e..fa0247afb 100644
--- a/kornia/augmentation/random_generator/_2d/jigsaw.py
+++ b/kornia/augmentation/random_generator/_2d/jigsaw.py
@@ -24,6 +24,7 @@ class JigsawGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, grid: Tuple[int, int] = (4, 4), ensure_perm: bool = True) -> None:
diff --git a/kornia/augmentation/random_generator/_2d/jpeg.py b/kornia/augmentation/random_generator/_2d/jpeg.py
index 7e508340c..35e5e89e1 100644
--- a/kornia/augmentation/random_generator/_2d/jpeg.py
+++ b/kornia/augmentation/random_generator/_2d/jpeg.py
@@ -24,6 +24,7 @@ class JPEGGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/linear_illumination.py b/kornia/augmentation/random_generator/_2d/linear_illumination.py
index 627eaf3aa..979623552 100644
--- a/kornia/augmentation/random_generator/_2d/linear_illumination.py
+++ b/kornia/augmentation/random_generator/_2d/linear_illumination.py
@@ -24,6 +24,7 @@ class LinearIlluminationGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
@@ -42,7 +43,6 @@ class LinearIlluminationGenerator(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
r"""Create samplers for generating random gaussian illumination parameters."""
-
gain = _range_bound(
self.gain,
"gain",
@@ -107,6 +107,7 @@ class LinearCornerIlluminationGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
@@ -125,7 +126,6 @@ class LinearCornerIlluminationGenerator(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
r"""Create samplers for generating random gaussian illumination parameters."""
-
gain = _range_bound(
self.gain,
"gain",
diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.py
index e6a51544c..f73d506d9 100644
--- a/kornia/augmentation/random_generator/_2d/mixup.py
+++ b/kornia/augmentation/random_generator/_2d/mixup.py
@@ -26,6 +26,7 @@ class MixupGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None, p: float = 1.0) -> None:
diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.py
index ee36e82ec..85bf86ef7 100644
--- a/kornia/augmentation/random_generator/_2d/mosaic.py
+++ b/kornia/augmentation/random_generator/_2d/mosaic.py
@@ -32,6 +32,7 @@ class MosaicGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.py
index 9090d6e33..98599f9ce 100644
--- a/kornia/augmentation/random_generator/_2d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py
@@ -36,6 +36,7 @@ class MotionBlurGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.py
index c832496ec..0d215a653 100644
--- a/kornia/augmentation/random_generator/_2d/perspective.py
+++ b/kornia/augmentation/random_generator/_2d/perspective.py
@@ -30,6 +30,7 @@ class PerspectiveGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, distortion_scale: Union[Tensor, float] = 0.5, sampling_method: str = "basic") -> None:
diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.py
index d8266e8f7..c36c2bd96 100644
--- a/kornia/augmentation/random_generator/_2d/plain_uniform.py
+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py
@@ -40,6 +40,7 @@ class PlainUniformGenerator(RandomGeneratorBase):
... (torch.tensor([-0.5, 0.5]), "factor_2", 0.1, (-1., 1.)),
... )(torch.Size([2]))
{'factor_1': tensor([0.7196, 0.7307]), 'factor_2': tensor([ 0.3278, -0.3657])}
+
"""
def __init__(self, *samplers: ParameterBound) -> None:
diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.py
index 63529d295..3273a04e8 100644
--- a/kornia/augmentation/random_generator/_2d/posterize.py
+++ b/kornia/augmentation/random_generator/_2d/posterize.py
@@ -26,6 +26,7 @@ class PosterizeGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, bits: Union[float, Tuple[float, float], Tensor]) -> None:
diff --git a/kornia/augmentation/random_generator/_2d/probability.py b/kornia/augmentation/random_generator/_2d/probability.py
index fd285f338..95b3a4a87 100644
--- a/kornia/augmentation/random_generator/_2d/probability.py
+++ b/kornia/augmentation/random_generator/_2d/probability.py
@@ -24,6 +24,7 @@ class ProbabilityGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, p: float = 0.5) -> None:
@@ -66,6 +67,7 @@ def random_prob_generator(
Note:
The generated random numbers are not reproducible across different devices and dtypes.
+
"""
if device is None:
device = torch.device("cpu")
diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
index 8c74dc70c..42f06d364 100644
--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py
+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
@@ -30,6 +30,7 @@ class RectangleEraseGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/resize.py b/kornia/augmentation/random_generator/_2d/resize.py
index 89615ee23..b2a2745b4 100644
--- a/kornia/augmentation/random_generator/_2d/resize.py
+++ b/kornia/augmentation/random_generator/_2d/resize.py
@@ -29,6 +29,7 @@ class ResizeGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, resize_to: Union[int, Tuple[int, int]], side: str = "short") -> None:
diff --git a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
index 9aeca2f38..5e041f174 100644
--- a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
+++ b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
@@ -27,6 +27,7 @@ class SaltAndPepperGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.py
index a26144d28..1bc4a438f 100644
--- a/kornia/augmentation/random_generator/_2d/shear.py
+++ b/kornia/augmentation/random_generator/_2d/shear.py
@@ -31,6 +31,7 @@ class ShearGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, shear: Union[Tensor, float, Tuple[float, float], Tuple[float, float, float, float]]) -> None:
diff --git a/kornia/augmentation/random_generator/_2d/translate.py b/kornia/augmentation/random_generator/_2d/translate.py
index 0cee8306f..05716a992 100644
--- a/kornia/augmentation/random_generator/_2d/translate.py
+++ b/kornia/augmentation/random_generator/_2d/translate.py
@@ -27,6 +27,7 @@ class TranslateGenerator(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
index f8a87acee..0609e42e3 100644
--- a/kornia/augmentation/random_generator/_3d/affine.py
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -54,6 +54,7 @@ class AffineGenerator3D(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 5129382b5..0c3b1b3a1 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -27,6 +27,7 @@ class CropGenerator3D(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
@@ -161,6 +162,7 @@ def center_crop_generator3d(
Note:
No random number will be generated.
+
"""
if device is None:
device = torch.device("cpu")
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
index 7edb94fbf..3d6de9183 100644
--- a/kornia/augmentation/random_generator/_3d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -34,6 +34,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.py
index 02f014923..1cf101e84 100644
--- a/kornia/augmentation/random_generator/_3d/perspective.py
+++ b/kornia/augmentation/random_generator/_3d/perspective.py
@@ -24,6 +24,7 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(self, distortion_scale: Union[Tensor, float] = 0.5) -> None:
diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.py
index 447cd426d..52885313e 100644
--- a/kornia/augmentation/random_generator/_3d/rotation.py
+++ b/kornia/augmentation/random_generator/_3d/rotation.py
@@ -31,6 +31,7 @@ class RotationGenerator3D(RandomGeneratorBase):
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU in float32. This can be changed by calling
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
"""
def __init__(
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index ceecee6be..8dd199f81 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -39,6 +39,7 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):
Note:
The generated random numbers are not reproducible across different devices and dtypes.
+
"""
if device is None:
device = torch.device("cpu")
@@ -83,6 +84,7 @@ class DistributionWithMapper(Distribution):
>>> _ = torch.manual_seed(0)
>>> dist.rsample((8,))
tensor([0.8236, 0.4272, 0.1017, 0.6384, 0.2527, 0.1980, 0.5995, 0.6980])
+
"""
def __init__(self, dist: Distribution, map_fn: Optional[Callable[[Tensor], Tensor]] = None) -> None:
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 6137f524f..d707c9108 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -18,6 +18,7 @@ def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:
Returns:
the wrapped function after input is validated.
+
"""
@wraps(f)
@@ -41,6 +42,7 @@ def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:
Returns:
the wrapped function after input is validated.
+
"""
@wraps(f)
@@ -85,10 +87,11 @@ def _infer_batch_shape3d(input: Union[Tensor, Tuple[Tensor, Tensor]]) -> torch.S
def _transform_input_by_shape(input: Tensor, reference_shape: Tensor, match_channel: bool = True) -> Tensor:
"""Reshape an input tensor to have the same dimensions as the reference_shape.
- Arguments
+ Arguments:
input: 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
+
"""
B = reference_shape[-4] if len(reference_shape) >= 4 else None
C = reference_shape[-3] if len(reference_shape) >= 3 else None
@@ -113,10 +116,11 @@ def _transform_input_by_shape(input: Tensor, reference_shape: Tensor, match_chan
def _transform_input3d_by_shape(input: Tensor, reference_shape: Tensor, match_channel: bool = True) -> Tensor:
"""Reshape an input tensor to have the same dimensions as the reference_shape.
- Arguments
+ Arguments:
input: 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
+
"""
B = reference_shape[-5] if len(reference_shape) >= 5 else None
C = reference_shape[-4] if len(reference_shape) >= 4 else None
@@ -140,11 +144,13 @@ def _transform_input3d_by_shape(input: Tensor, reference_shape: Tensor, match_ch
def _transform_input(input: Tensor) -> Tensor:
r"""Reshape an input tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).
+
Args:
input: Tensor
Returns:
Tensor
+
"""
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -163,11 +169,13 @@ def _transform_input(input: Tensor) -> Tensor:
def _transform_input3d(input: Tensor) -> Tensor:
r"""Reshape an input tensor to be (*, C, D, H, W). Accept either (D, H, W), (C, D, H, W) or (*, C, D, H, W).
+
Args:
input: Tensor
Returns:
Tensor
+
"""
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -200,12 +208,14 @@ def _transform_output_shape(
output: Tensor, shape: Tuple[int, ...], *, reference_shape: Optional[Tensor] = None
) -> Tensor:
r"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape.
+
Args:
input: Tensor
shape: List/tuple of int
Returns:
Tensor
+
"""
out_tensor = output.clone()
@@ -241,12 +251,14 @@ def _validate_input_shape(input: Tensor, channel_index: int, number: int) -> boo
e.g. to check if an input is channel first.
If channel first, the second channel of an RGB input shall be fixed to 3. To verify using:
_validate_input_shape(input, 1, 3)
+
Args:
input: Tensor
channel_index: int
number: int
Returns:
bool
+
"""
return input.shape[channel_index] == number
@@ -369,8 +381,8 @@ def override_parameters(
if_none_exist: behaviour if the key in `params_override` does not exist in `params`.
'raise' | 'ignore'.
in_place: if to override in-place or not.
- """
+ """
if params_override is None:
return params
out = params if in_place else deepcopy_dict(params)
@@ -415,6 +427,7 @@ def preprocess_boxes(input: Union[Tensor, Boxes], mode: str = "vertices_plus") -
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
`quadrilaterals <https://en.wikipedia.org/wiki/Quadrilateral>`_ are rectangles, rhombus and trapezoids.
+
"""
# TODO: We may allow list here.
# input is BxNx4x2 or Boxes.
@@ -447,7 +460,8 @@ def preprocess_classes(input: Tensor) -> Tensor:
class MultiprocessWrapper:
"""Utility class which when used as a base class, makes the class work with the 'spawn' multiprocessing
- context."""
+ context.
+ """
def __init__(self, *args: Any, **kwargs: Any) -> None:
args = tuple(arg.clone() if isinstance(arg, torch.Tensor) else arg for arg in args)
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index d453b310f..46b149593 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -113,6 +113,7 @@ def _tuple_range_reader(
tensor([[0.2000, 0.3000],
[0.2000, 0.3000],
[0.2000, 0.3000]])
+
"""
target_shape = torch.Size([target_size, 2])
diff --git a/kornia/color/colormap.py b/kornia/color/colormap.py
index 2f26e46b5..06decb692 100644
--- a/kornia/color/colormap.py
+++ b/kornia/color/colormap.py
@@ -46,6 +46,7 @@ class ColorMapType(Enum):
Returns:
The base colormap.
+
"""
return {
"autumn": cm_data.get_autumn_base,
@@ -75,6 +76,7 @@ class ColorMapType(Enum):
Returns:
A list containing the names of enumeration members.
+
"""
return [c.name for c in cls]
@@ -104,6 +106,7 @@ class ColorMap:
tensor([[0.0000, 0.0000, 0.1250, 0.3750, 0.6250, 0.8750, 1.0000, 1.0000],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
[1.0000, 1.0000, 0.8750, 0.6250, 0.3750, 0.1250, 0.0000, 0.0000]])
+
"""
def __init__(
@@ -145,6 +148,7 @@ class ColorMap:
Returns:
A tensor representing the colormap.
+
"""
tensor_colors = tensor(list(base_colormap), dtype=self._dtype, device=self._device).T
return interpolate(tensor_colors[None, ...], size=num_colors, mode="linear")[0, ...]
@@ -154,6 +158,7 @@ class ColorMap:
Returns:
Number of colors in the colormap.
+
"""
return self.colors.shape[-1]
@@ -191,8 +196,8 @@ def apply_colormap(input_tensor: Tensor, colormap: ColorMap) -> Tensor:
[[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000]]]])
- """
+ """
KORNIA_CHECK(isinstance(input_tensor, Tensor), f"`input_tensor` must be a Tensor. Got: {type(input_tensor)}")
valid_types = [torch.half, torch.float, torch.double, torch.uint8, torch.int, torch.long, torch.short]
KORNIA_CHECK(
@@ -254,6 +259,7 @@ class ApplyColorMap(Module):
[[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000]]]])
+
"""
def __init__(
@@ -274,6 +280,7 @@ class ApplyColorMap(Module):
Returns:
The output 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 f647cfd33..f05b5b642 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -26,6 +26,7 @@ def grayscale_to_rgb(image: Tensor) -> Tensor:
Example:
>>> input = torch.randn(2, 1, 4, 5)
>>> gray = grayscale_to_rgb(input) # 2x3x4x5
+
"""
KORNIA_CHECK_IS_TENSOR(image)
@@ -46,6 +47,7 @@ def rgb_to_grayscale(image: Tensor, rgb_weights: Optional[Tensor] = None) -> Ten
image: RGB image to be converted to grayscale with shape :math:`(*,3,H,W)`.
rgb_weights: Weights that will be applied on each channel (RGB).
The sum of the weights should add up to one.
+
Returns:
grayscale version of the image with shape :math:`(*,1,H,W)`.
@@ -55,6 +57,7 @@ def rgb_to_grayscale(image: Tensor, rgb_weights: Optional[Tensor] = None) -> Ten
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> gray = rgb_to_grayscale(input) # 2x1x4x5
+
"""
KORNIA_CHECK_IS_TENSOR(image)
@@ -97,6 +100,7 @@ def bgr_to_grayscale(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> gray = bgr_to_grayscale(input) # 2x1x4x5
+
"""
KORNIA_CHECK_IS_TENSOR(image)
@@ -123,6 +127,7 @@ class GrayscaleToRgb(Module):
>>> input = torch.rand(2, 1, 4, 5)
>>> rgb = GrayscaleToRgb()
>>> output = rgb(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]
@@ -148,6 +153,7 @@ class RgbToGrayscale(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> gray = RgbToGrayscale()
>>> output = gray(input) # 2x1x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -179,6 +185,7 @@ class BgrToGrayscale(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> gray = BgrToGrayscale()
>>> output = gray(input) # 2x1x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index 05185ac07..26bed6deb 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -28,6 +28,7 @@ def rgb_to_hls(image: Tensor, eps: float = 1e-8) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_hls(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -104,6 +105,7 @@ def hls_to_rgb(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = hls_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -146,6 +148,7 @@ class RgbToHls(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> hls = RgbToHls()
>>> output = hls(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -174,6 +177,7 @@ class HlsToRgb(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgb = HlsToRgb()
>>> output = rgb(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
diff --git a/kornia/color/hsv.py b/kornia/color/hsv.py
index 365e40eb9..79ea8b4cd 100644
--- a/kornia/color/hsv.py
+++ b/kornia/color/hsv.py
@@ -29,6 +29,7 @@ def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_hsv(input) # 2x3x4x5
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
@@ -72,6 +73,7 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = hsv_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
@@ -117,6 +119,7 @@ class RgbToHsv(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> hsv = RgbToHsv()
>>> output = hsv(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -146,6 +149,7 @@ class HsvToRgb(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgb = HsvToRgb()
>>> output = rgb(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
diff --git a/kornia/color/lab.py b/kornia/color/lab.py
index 417b1e1d5..3c26c2a51 100644
--- a/kornia/color/lab.py
+++ b/kornia/color/lab.py
@@ -33,6 +33,7 @@ def rgb_to_lab(image: torch.Tensor) -> torch.Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_lab(input) # 2x3x4x5
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
@@ -84,6 +85,7 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = lab_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
@@ -152,6 +154,7 @@ class RgbToLab(Module):
[2] https://www.easyrgb.com/en/math.php
[3] https://github.com/torch/image/blob/dc061b98fb7e946e00034a5fc73e883a299edc7f/generic/image.c#L1467
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -182,6 +185,7 @@ class LabToRgb(Module):
[2] https://www.easyrgb.com/en/math.php
[3] https://github.com/torch/image/blob/dc061b98fb7e946e00034a5fc73e883a299edc7f/generic/image.c#L1518
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
diff --git a/kornia/color/luv.py b/kornia/color/luv.py
index 7b6756a21..ce25b6716 100644
--- a/kornia/color/luv.py
+++ b/kornia/color/luv.py
@@ -33,6 +33,7 @@ def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_luv(input) # 2x3x4x5
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
@@ -85,6 +86,7 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = luv_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
@@ -145,6 +147,7 @@ class RgbToLuv(Module):
[2] https://www.easyrgb.com/en/math.php
[3] http://www.poynton.com/ColorFAQ.html
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -175,6 +178,7 @@ class LuvToRgb(Module):
[2] https://www.easyrgb.com/en/math.php
[3] http://www.poynton.com/ColorFAQ.html
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
diff --git a/kornia/color/raw.py b/kornia/color/raw.py
index fee2dc2a2..944869f0f 100644
--- a/kornia/color/raw.py
+++ b/kornia/color/raw.py
@@ -45,12 +45,14 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
Args:
image: raw image to be converted to RGB with shape :math:`(*,1,H,W)`.
cfa: The configuration of the color filter.
+
Returns:
RGB version of the image with shape :math:`(*,3,H,W)`.
Example:
>>> rawinput = torch.randn(2, 1, 4, 6)
>>> rgb = raw_to_rgb(rawinput, CFA.RG) # 2x3x4x6
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
@@ -189,6 +191,7 @@ def rgb_to_raw(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
Example:
>>> rgbinput = torch.rand(2, 3, 4, 6)
>>> raw = rgb_to_raw(rgbinput, CFA.BG) # 2x1x4x6
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
@@ -238,6 +241,7 @@ def raw_to_rgb_2x2_downscaled(image: Tensor, cfa: CFA) -> Tensor:
Example:
>>> rawinput = torch.randn(2, 1, 4, 6)
>>> rgb = raw_to_rgb_2x2_downscaled(rawinput, CFA.RG) # 2x3x2x3
+
"""
KORNIA_CHECK(isinstance(image, Tensor), "Input type is not a torch.Tensor")
@@ -289,6 +293,7 @@ class RawToRgb(Module):
>>> rawinput = torch.rand(2, 1, 4, 6)
>>> rgb = RawToRgb(CFA.RG)
>>> output = rgb(rawinput) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]
@@ -318,6 +323,7 @@ class RgbToRaw(Module):
>>> rgbinput = torch.rand(2, 3, 4, 6)
>>> raw = RgbToRaw(CFA.GB)
>>> output = raw(rgbinput) # 2x1x4x6
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -345,6 +351,7 @@ class RawToRgb2x2Downscaled(Module):
>>> rawinput = torch.rand(2, 1, 4, 6)
>>> rgb_downscale = RawToRgb2x2Downscaled(CFA.RG)
>>> output = rgb_downscale(rawinput) # 2x3x2x3
+
"""
def __init__(self, cfa: CFA) -> None:
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index f882f1994..92efb3900 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -23,6 +23,7 @@ def rgb_to_bgr(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_bgr(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -45,6 +46,7 @@ def bgr_to_rgb(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = bgr_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -73,6 +75,7 @@ def rgb_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_rgba(input, 1.) # 2x4x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -110,6 +113,7 @@ def bgr_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = bgr_to_rgba(input, 1.) # 2x4x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -137,6 +141,7 @@ def rgba_to_rgb(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 4, 4, 5)
>>> output = rgba_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -168,6 +173,7 @@ def rgba_to_bgr(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 4, 4, 5)
>>> output = rgba_to_bgr(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -194,6 +200,7 @@ def rgb_to_linear_rgb(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_linear_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -218,6 +225,7 @@ def linear_rgb_to_rgb(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = linear_rgb_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -245,6 +253,7 @@ def normals_to_rgb255(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = normals_to_rgb255(input) # 2x3x4x5
+
"""
KORNIA_CHECK_IS_COLOR(image)
rgb255 = (0.5 * (image + 1.0)).clip(0.0, 1.0) * 255
@@ -263,6 +272,7 @@ def rgb_to_rgb255(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_rgb255(input) # 2x3x4x5
+
"""
KORNIA_CHECK_IS_COLOR(image)
rgb255 = (image * 255).clip(0.0, 255.0)
@@ -281,6 +291,7 @@ def rgb255_to_rgb(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb255_to_rgb(input) # 2x3x4x5
+
"""
KORNIA_CHECK_IS_COLOR(image)
rgb = image / 255.0
@@ -299,6 +310,7 @@ def rgb255_to_normals(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb255_to_normals(input) # 2x3x4x5
+
"""
KORNIA_CHECK_IS_COLOR(image)
normals = normalize((image / 255.0) * 2.0 - 1.0, dim=-3, p=2.0)
@@ -321,6 +333,7 @@ class BgrToRgb(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgb = BgrToRgb()
>>> output = rgb(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -346,6 +359,7 @@ class RgbToBgr(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> bgr = RgbToBgr()
>>> output = bgr(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -377,6 +391,7 @@ class RgbToRgba(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgba = RgbToRgba(1.)
>>> output = rgba(input) # 2x4x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -412,6 +427,7 @@ class BgrToRgba(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgba = BgrToRgba(1.)
>>> output = rgba(input) # 2x4x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -441,6 +457,7 @@ class RgbaToRgb(Module):
>>> input = torch.rand(2, 4, 4, 5)
>>> rgba = RgbaToRgb()
>>> output = rgba(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]
@@ -466,6 +483,7 @@ class RgbaToBgr(Module):
>>> input = torch.rand(2, 4, 4, 5)
>>> rgba = RgbaToBgr()
>>> output = rgba(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]
@@ -499,6 +517,7 @@ class RgbToLinearRgb(Module):
[2] https://www.cambridgeincolour.com/tutorials/gamma-correction.htm
[3] https://en.wikipedia.org/wiki/SRGB
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -531,6 +550,7 @@ class LinearRgbToRgb(Module):
[2] https://www.cambridgeincolour.com/tutorials/gamma-correction.htm
[3] https://en.wikipedia.org/wiki/SRGB
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -554,6 +574,7 @@ class NormalsToRgb255(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgb = NormalsToRgb255()
>>> output = rgb(input) # 2x3x4x5
+
"""
def forward(self, image: Tensor) -> Tensor:
@@ -574,6 +595,7 @@ class RgbToRgb255(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgb = RgbToRgb255()
>>> output = rgb(input) # 2x3x4x5
+
"""
def forward(self, image: Tensor) -> Tensor:
@@ -594,6 +616,7 @@ class Rgb255ToRgb(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgb = Rgb255ToRgb()
>>> output = rgb(input) # 2x3x4x5
+
"""
def forward(self, image: Tensor) -> Tensor:
@@ -614,6 +637,7 @@ class Rgb255ToNormals(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> normals = Rgb255ToNormals()
>>> output = normals(input) # 2x3x4x5
+
"""
def forward(self, image: Tensor) -> Tensor:
diff --git a/kornia/color/sepia.py b/kornia/color/sepia.py
index 49c914940..091b2e893 100644
--- a/kornia/color/sepia.py
+++ b/kornia/color/sepia.py
@@ -24,6 +24,7 @@ def sepia_from_rgb(input: Tensor, rescale: bool = True, eps: float = 1e-6) -> Te
[[1.2030]],
<BLANKLINE>
[[0.9370]]])
+
"""
if len(input.shape) < 3 or input.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {input.shape}")
@@ -66,6 +67,7 @@ class Sepia(Module):
[[1.2030]],
<BLANKLINE>
[[0.9370]]])
+
"""
def __init__(self, rescale: bool = True, eps: float = 1e-6) -> None:
diff --git a/kornia/color/xyz.py b/kornia/color/xyz.py
index 5affc1f72..8c7ed038a 100644
--- a/kornia/color/xyz.py
+++ b/kornia/color/xyz.py
@@ -22,6 +22,7 @@ def rgb_to_xyz(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_xyz(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -54,6 +55,7 @@ def xyz_to_rgb(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = xyz_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -93,6 +95,7 @@ class RgbToXyz(Module):
Reference:
[1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -119,6 +122,7 @@ class XyzToRgb(Module):
Reference:
[1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
diff --git a/kornia/color/ycbcr.py b/kornia/color/ycbcr.py
index 7c3ba1740..904dfc74e 100644
--- a/kornia/color/ycbcr.py
+++ b/kornia/color/ycbcr.py
@@ -27,6 +27,7 @@ def rgb_to_ycbcr(image: Tensor) -> Tensor:
Examples:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_ycbcr(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -57,6 +58,7 @@ def rgb_to_y(image: Tensor) -> Tensor:
Examples:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_y(input) # 2x1x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -86,6 +88,7 @@ def ycbcr_to_rgb(image: Tensor) -> Tensor:
Examples:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = ycbcr_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -123,6 +126,7 @@ class RgbToYcbcr(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> ycbcr = RgbToYcbcr()
>>> output = ycbcr(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -148,6 +152,7 @@ class YcbcrToRgb(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgb = YcbcrToRgb()
>>> output = rgb(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
diff --git a/kornia/color/yuv.py b/kornia/color/yuv.py
index c52ad7707..d490cb5b6 100644
--- a/kornia/color/yuv.py
+++ b/kornia/color/yuv.py
@@ -30,6 +30,7 @@ def rgb_to_yuv(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = rgb_to_yuv(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -72,6 +73,7 @@ def rgb_to_yuv420(image: Tensor) -> tuple[Tensor, Tensor]:
Example:
>>> input = torch.rand(2, 3, 4, 6)
>>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x2x2x3)
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -113,6 +115,7 @@ def rgb_to_yuv422(image: Tensor) -> tuple[Tensor, Tensor]:
Example:
>>> input = torch.rand(2, 3, 4, 6)
>>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x1x4x3)
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -147,6 +150,7 @@ def yuv_to_rgb(image: Tensor) -> Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
>>> output = yuv_to_rgb(input) # 2x3x4x5
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(image)}")
@@ -190,6 +194,7 @@ def yuv420_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:
>>> inputy = torch.rand(2, 1, 4, 6)
>>> inputuv = torch.rand(2, 2, 2, 3)
>>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x6
+
"""
if not isinstance(imagey, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(imagey)}")
@@ -249,6 +254,7 @@ def yuv422_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:
>>> inputy = torch.rand(2, 1, 4, 6)
>>> inputuv = torch.rand(2, 2, 2, 3)
>>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x5
+
"""
if not isinstance(imagey, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(imagey)}")
@@ -299,6 +305,7 @@ class RgbToYuv(Module):
Reference::
[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -333,6 +340,7 @@ class RgbToYuv420(Module):
Reference::
[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV
+
"""
# TODO: Handle multiple inputs and outputs models later
@@ -367,6 +375,7 @@ class RgbToYuv422(Module):
Reference::
[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV
+
"""
# TODO: Handle multiple inputs and outputs models later
@@ -397,6 +406,7 @@ class YuvToRgb(Module):
>>> input = torch.rand(2, 3, 4, 5)
>>> rgb = YuvToRgb()
>>> output = rgb(input) # 2x3x4x5
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -431,6 +441,7 @@ class Yuv420ToRgb(Module):
>>> inputuv = torch.rand(2, 2, 2, 3)
>>> rgb = Yuv420ToRgb()
>>> output = rgb(inputy, inputuv) # 2x3x4x6
+
"""
# TODO: Handle multiple inputs and outputs models later
@@ -465,6 +476,7 @@ class Yuv422ToRgb(Module):
>>> inputuv = torch.rand(2, 2, 4, 3)
>>> rgb = Yuv422ToRgb()
>>> output = rgb(inputy, inputuv) # 2x3x4x6
+
"""
# TODO: Handle multiple inputs and outputs models later
diff --git a/kornia/contrib/classification.py b/kornia/contrib/classification.py
index f0ce44cd8..852b3d865 100644
--- a/kornia/contrib/classification.py
+++ b/kornia/contrib/classification.py
@@ -16,6 +16,7 @@ class ClassificationHead(nn.Module):
>>> head = ClassificationHead(256, 10)
>>> head(feat).shape
torch.Size([1, 10])
+
"""
def __init__(self, embed_size: int = 768, num_classes: int = 10) -> None:
diff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.py
index 6fa1b6ad4..6c645a051 100644
--- a/kornia/contrib/connected_components.py
+++ b/kornia/contrib/connected_components.py
@@ -30,6 +30,7 @@ def connected_components(image: Tensor, num_iterations: int = 100) -> Tensor:
Example:
>>> img = torch.rand(2, 1, 4, 5)
>>> img_labels = connected_components(img, num_iterations=100)
+
"""
if not isinstance(image, Tensor):
raise TypeError(f"Input imagetype is not a Tensor. Got: {type(image)}")
diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.py
index 2bd1b9ef0..0cd7f0594 100644
--- a/kornia/contrib/diamond_square.py
+++ b/kornia/contrib/diamond_square.py
@@ -34,6 +34,7 @@ def _diamond_square_seed(
Return:
the generated image seed of size Bx1xHxW.
+
"""
KORNIA_CHECK(width == 3 or height == 3, "Height or Width must be equal to 3.")
# TODO(anguelos): can we avoid transposing and passing always fixed size. This will cause issues with onnx/jit
@@ -96,6 +97,7 @@ def _one_diamond_one_square(
Return:
A 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"])
# TODO (anguelos) test multi channel and batch size > 1
@@ -162,6 +164,7 @@ def diamond_square(
Returns:
A 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)")
if not isinstance(random_scale, Tensor):
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 1d384f546..0b2693f4a 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -26,6 +26,7 @@ def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.3
>>> tensor = torch.zeros(1, 1, 5, 5)
>>> tensor[:,:, 1, 2] = 1
>>> dt = kornia.contrib.distance_transform(tensor)
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"image type is not a torch.Tensor. Got {type(image)}")
@@ -77,6 +78,7 @@ class DistanceTransform(nn.Module):
Args:
kernel_size: size of the convolution kernel.
h: value that influence the approximation of the min function.
+
"""
def __init__(self, kernel_size: int = 3, h: float = 0.35) -> None:
diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.py
index 061391233..7fd2ac44e 100644
--- a/kornia/contrib/edge_detection.py
+++ b/kornia/contrib/edge_detection.py
@@ -17,6 +17,7 @@ class EdgeDetector(Module):
>>> out = detect(img)
>>> out.shape
torch.Size([1, 1, 320, 320])
+
"""
def __init__(self) -> None:
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 1f7760dea..15ea43357 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -61,6 +61,7 @@ def compute_padding(
.. note::
This function will be implicitly used in :func:`extract_tensor_patches` and :func:`combine_tensor_patches` if
`allow_auto_(un)padding` is set to True.
+
"""
original_size = cast(Tuple[int, int], _pair(original_size))
window_size = cast(Tuple[int, int], _pair(window_size))
@@ -159,6 +160,7 @@ class ExtractTensorPatches(Module):
>>> patches[:, -1]
tensor([[[[3., 4., 5.],
[6., 7., 8.]]]])
+
"""
def __init__(
@@ -249,6 +251,7 @@ class CombineTensorPatches(Module):
.. note::
This function is supposed to be used in conjunction with :class:`ExtractTensorPatches`.
+
"""
def __init__(
@@ -326,8 +329,8 @@ def combine_tensor_patches(
.. note::
This function is supposed to be used in conjunction with :func:`extract_tensor_patches`.
- """
+ """
if patches.ndim != 5:
raise ValueError(f"Invalid input shape, we expect BxNxCxHxW. Got: {patches.shape}")
@@ -442,6 +445,7 @@ def extract_tensor_patches(
>>> patches[:, -1]
tensor([[[[3., 4., 5.],
[6., 7., 8.]]]])
+
"""
if not torch.is_tensor(input):
raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
index d862d3fef..46a0af274 100644
--- a/kornia/contrib/face_detection.py
+++ b/kornia/contrib/face_detection.py
@@ -33,6 +33,7 @@ class FaceDetectorResult:
Args:
data: the encoded results coming from the feature detector with shape :math:`(14,)`.
+
"""
def __init__(self, data: torch.Tensor) -> None:
@@ -70,6 +71,7 @@ class FaceDetectorResult:
Args:
keypoint: the keypoint type to return the position.
+
"""
if keypoint == FaceKeypoint.EYE_LEFT:
out = self._data[..., (4, 5)]
@@ -143,6 +145,7 @@ class FaceDetector(nn.Module):
>>> img = torch.rand(1, 3, 320, 320)
>>> detect = FaceDetector()
>>> res = detect(img)
+
"""
def __init__(
@@ -218,6 +221,7 @@ class FaceDetector(nn.Module):
Return:
List[torch.Tensor]: list with the boxes found on each image. :math:`Bx(N,15)`.
+
"""
img = self.preprocess(image)
out = self.model(img)
@@ -349,6 +353,7 @@ def _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) ->
Return:
Tensor containing decoded bounding box predictions.
+
"""
boxes = torch.cat(
(
diff --git a/kornia/contrib/histogram_matching.py b/kornia/contrib/histogram_matching.py
index 9bf8058a2..c30bb73b4 100644
--- a/kornia/contrib/histogram_matching.py
+++ b/kornia/contrib/histogram_matching.py
@@ -18,6 +18,7 @@ def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Te
Note:
This function does not matches histograms element-wisely if input a batched tensor.
+
"""
oldshape = source.shape
source = source.ravel()
@@ -60,6 +61,7 @@ def interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
Returns:
the interpolated values, same size as `x`.
+
"""
i = torch.clip(torch.searchsorted(xp, x, right=True), 1, len(xp) - 1)
diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.py
index edfa2dbbd..128ee2c15 100644
--- a/kornia/contrib/image_stitching.py
+++ b/kornia/contrib/image_stitching.py
@@ -31,6 +31,7 @@ class ImageStitcher(Module):
out = IS(img_left, img_right)
# Show the result
plt.imshow(K.tensor_to_image(out))
+
"""
def __init__(self, matcher: Module, estimator: str = "ransac", blending_method: str = "naive") -> None:
@@ -49,6 +50,7 @@ class ImageStitcher(Module):
Args:
keypoints1: matched keypoint set from an image, shaped as :math:`(N, 2)`.
keypoints2: matched keypoint set from the other image, shaped as :math:`(N, 2)`.
+
"""
if self.estimator == "vanilla":
homo = find_homography_dlt_iterated(
diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.py
index d86d9c8ff..cb06be99f 100644
--- a/kornia/contrib/kmeans.py
+++ b/kornia/contrib/kmeans.py
@@ -23,6 +23,7 @@ class KMeans:
>>> kmeans = kornia.contrib.KMeans(3, None, 10e-4, 100, 0)
>>> kmeans.fit(torch.rand((1000, 5)))
>>> predictions = kmeans.predict(torch.rand((10, 5)))
+
"""
def __init__(
@@ -75,6 +76,7 @@ class KMeans:
Returns:
2D Tensor with num_cluster rows
+
"""
num_samples: int = len(X)
perm = torch.randperm(num_samples, device=X.device)
@@ -91,6 +93,7 @@ class KMeans:
Returns:
2D tensor of shape N, C
+
"""
# N*1*D
A = data1[:, None, ...]
@@ -105,6 +108,7 @@ class KMeans:
Args:
X: 2D input tensor to be clustered
+
"""
# X should have only 2 dimensions
KORNIA_CHECK_SHAPE(X, ["N", "D"])
@@ -164,8 +168,8 @@ class KMeans:
Returns:
1D tensor containing cluster id assigned to each data point in x
- """
+ """
# x and cluster_centers should have same number of columns
KORNIA_CHECK(
x.shape[1] == self.cluster_centers.shape[1],
diff --git a/kornia/contrib/lambda_module.py b/kornia/contrib/lambda_module.py
index 625fdb61e..8ee7186b8 100644
--- a/kornia/contrib/lambda_module.py
+++ b/kornia/contrib/lambda_module.py
@@ -18,6 +18,7 @@ class Lambda(Module):
>>> f = Lambda(lambda x: kornia.color.rgb_to_grayscale(x))
>>> f(x).shape
torch.Size([1, 1, 5, 5])
+
"""
def __init__(self, func: Callable[..., Tensor]) -> None:
diff --git a/kornia/contrib/models/base.py b/kornia/contrib/models/base.py
index 39f85af97..663a5822f 100644
--- a/kornia/contrib/models/base.py
+++ b/kornia/contrib/models/base.py
@@ -20,8 +20,8 @@ class ModelBase(ABC, Module, Generic[ModelConfig]):
Args:
checkpoint: The url or filepath for the respective checkpoint
device: The desired device to load the weights and move the model
- """
+ """
if os.path.isfile(checkpoint):
with open(checkpoint, "rb") as f:
state_dict = torch.load(f, map_location=device)
@@ -37,6 +37,7 @@ class ModelBase(ABC, Module, Generic[ModelConfig]):
Args:
config: The specifications for the model be build/loaded
+
"""
raise NotImplementedError
diff --git a/kornia/contrib/models/common.py b/kornia/contrib/models/common.py
index b46049f93..fbc108677 100644
--- a/kornia/contrib/models/common.py
+++ b/kornia/contrib/models/common.py
@@ -109,6 +109,7 @@ def window_partition(x: Tensor, window_size: int) -> tuple[Tensor, tuple[int, in
Returns:
windows: windows after partition with [B * num_windows, window_size, window_size, C].
(Hp, Wp): padded height and width before partition
+
"""
B, H, W, C = x.shape
@@ -134,6 +135,7 @@ def window_unpartition(windows: Tensor, window_size: int, pad_hw: tuple[int, int
Returns:
x: unpartitioned sequences with [B, H, W, C].
+
"""
Hp, Wp = pad_hw
H, W = hw
diff --git a/kornia/contrib/models/efficient_vit/model.py b/kornia/contrib/models/efficient_vit/model.py
index 09bdded1a..55346ffb8 100644
--- a/kornia/contrib/models/efficient_vit/model.py
+++ b/kornia/contrib/models/efficient_vit/model.py
@@ -24,6 +24,7 @@ class EfficientViTConfig:
Args:
checkpoint: URL or local path of model weights.
+
"""
checkpoint: str = field(default_factory=_get_base_url)
@@ -37,6 +38,7 @@ class EfficientViTConfig:
Args:
model_type: model type, one of :obj:`"b1"`, :obj:`"b2"`, :obj:`"b3"`.
resolution: input resolution, one of :obj:`224`, :obj:`256`, :obj:`288`.
+
"""
return cls(checkpoint=_get_base_url(model_type=model_type, resolution=resolution))
@@ -57,6 +59,7 @@ class EfficientViT(ModelBase[EfficientViTConfig]):
Returns:
EfficientViT: the EfficientViT model.
+
"""
# load the model from the checkpoint
try:
@@ -85,6 +88,7 @@ class EfficientViT(ModelBase[EfficientViTConfig]):
Returns:
Dict[str, Tensor]: a dictionary containing the features.
+
"""
feats = self.backbone(images)
return feats
diff --git a/kornia/contrib/models/rt_detr/architecture/hgnetv2.py b/kornia/contrib/models/rt_detr/architecture/hgnetv2.py
index db12bf7a8..fa6c5e329 100644
--- a/kornia/contrib/models/rt_detr/architecture/hgnetv2.py
+++ b/kornia/contrib/models/rt_detr/architecture/hgnetv2.py
@@ -1,6 +1,7 @@
"""Based on code from
https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/
-ppdet/modeling/backbones/hgnet_v2.py."""
+ppdet/modeling/backbones/hgnet_v2.py.
+"""
from __future__ import annotations
diff --git a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
index 5e2a8cc98..2d1412d65 100644
--- a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
+++ b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
@@ -1,6 +1,7 @@
"""Based on the code from
https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/
-ppdet/modeling/transformers/hybrid_encoder.py."""
+ppdet/modeling/transformers/hybrid_encoder.py.
+"""
from __future__ import annotations
@@ -135,6 +136,7 @@ class AIFI(Module):
Returns:
positional embeddings, shape :math:`(H * W, 1, C)`
+
"""
xs = torch.arange(w, device=device, dtype=dtype)
ys = torch.arange(h, device=device, dtype=dtype)
diff --git a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
index 61b179c10..d495d16b2 100644
--- a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
+++ b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
@@ -23,6 +23,7 @@ def _inverse_sigmoid(x: torch.Tensor, eps: float = 1e-5) -> torch.Tensor:
Returns:
output tensor
+
"""
out = x.clip(min=0.0, max=1.0)
return torch.log(out.clip(min=eps) / (1.0 - out).clip(min=eps))
@@ -43,6 +44,7 @@ def _deformable_attention_kernel(
Returns:
output, shape (N, Lq, n_head * C)
+
"""
bs, _, n_head, c = value.shape
_, Len_q, _, n_levels, n_points, _ = sampling_locations.shape
@@ -99,8 +101,7 @@ class MultiScaleDeformableAttention(Module):
def forward(
self, query: Tensor, reference_points: Tensor, value: Tensor, value_spatial_shapes: list[tuple[int, int]]
) -> Tensor:
- """
- Args:
+ """Args:
query: shape (N, Lq, C)
reference_points: shape (N, Lq, n_levels, 4)
value: shape (N, Lv, C)
@@ -108,6 +109,7 @@ class MultiScaleDeformableAttention(Module):
Returns:
output, shape (N, Lq, C)
+
"""
N, Lenq, _ = query.shape
_, Len_v, _ = value.shape
@@ -439,6 +441,7 @@ class RTDETRHead(Module):
Returns:
logit of anchors and mask
+
"""
# TODO: might make this (or some parts of it) into a separate reusable function
anchors_list: list[Tensor] = []
diff --git a/kornia/contrib/models/rt_detr/model.py b/kornia/contrib/models/rt_detr/model.py
index f7d040f99..9197ca40d 100644
--- a/kornia/contrib/models/rt_detr/model.py
+++ b/kornia/contrib/models/rt_detr/model.py
@@ -59,6 +59,7 @@ class RTDETRConfig:
head_hidden_dim: hidden dim for head.
head_num_queries: number of queries for Deformable DETR transformer decoder.
head_num_decoder_layers: number of decoder layers for Deformable DETR transformer decoder.
+
"""
model_type: RTDETRModelType | str | int
@@ -80,8 +81,8 @@ class RTDETRConfig:
Args:
model_name: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.
- """
+ """
if model_name == "rtdetr_r18vd":
config = RTDETRConfig(RTDETRModelType.resnet18d, num_classes, input_size=640)
elif model_name == "rtdetr_r34vd":
@@ -108,6 +109,7 @@ class RTDETR(ModelBase[RTDETRConfig]):
backbone: backbone network for feature extraction.
neck: neck network for feature fusion.
head: head network to decode features into detection results.
+
"""
super().__init__()
self.backbone = backbone
@@ -125,6 +127,7 @@ class RTDETR(ModelBase[RTDETRConfig]):
For ``config.neck_hidden_dim``, ``config.neck_dim_feedforward``, ``config.neck_expansion``, and
``config.head_num_decoder_layers``, if they are ``None``, their values will be replaced with the
default values depending on the ``config.model_type``. See the source code for the default values.
+
"""
model_type = config.model_type
if isinstance(model_type, int):
@@ -205,8 +208,8 @@ class RTDETR(ModelBase[RTDETRConfig]):
Args:
model_name: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.
- """
+ """
if model_name not in URLs:
raise ValueError(f"No pretrained model for '{model_name}'. Please select from {list(URLs.keys())}.")
@@ -252,6 +255,7 @@ class RTDETR(ModelBase[RTDETRConfig]):
Args:
model_name: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.
+
"""
model = RTDETR.from_config(RTDETRConfig.from_name(model_name, num_classes))
return model
@@ -266,8 +270,8 @@ class RTDETR(ModelBase[RTDETRConfig]):
- **logits** - Tensor of shape :math:`(N, Q, K)`, where :math:`Q` is the number of queries,
:math:`K` is the number of classes.
- **boxes** - Tensor of shape :math:`(N, Q, 4)`, where :math:`Q` is the number of queries.
- """
+ """
feats = self.backbone(images)
feats_buf = self.encoder(feats)
logits, boxes = self.decoder(feats_buf)
diff --git a/kornia/contrib/models/rt_detr/post_processor.py b/kornia/contrib/models/rt_detr/post_processor.py
index 0df2c1190..45b742ad6 100644
--- a/kornia/contrib/models/rt_detr/post_processor.py
+++ b/kornia/contrib/models/rt_detr/post_processor.py
@@ -26,6 +26,7 @@ def mod(a: Tensor, b: int) -> Tensor:
Example:
>>> mod(7, 3)
1
+
"""
return a - (a // b) * b
@@ -63,6 +64,7 @@ class DETRPostProcessor(Module):
Returns:
Processed detections. For each image, the detections have shape (D, 6), where D is the number of detections
in that image, 6 represent (class_id, confidence_score, x, y, w, h).
+
"""
# NOTE: consider using kornia BoundingBox
# NOTE: consider having a separate function to convert the detections to a list of bounding boxes
diff --git a/kornia/contrib/models/sam/architecture/image_encoder.py b/kornia/contrib/models/sam/architecture/image_encoder.py
index c9da29323..5db27f383 100644
--- a/kornia/contrib/models/sam/architecture/image_encoder.py
+++ b/kornia/contrib/models/sam/architecture/image_encoder.py
@@ -39,23 +39,23 @@ class ImageEncoderViT(Module):
window_size: int = 0,
global_attn_indexes: tuple[int, ...] = (),
) -> None:
- """
- Args:
- img_size: Input image size.
- patch_size: Patch size.
- in_chans: Number of input image channels.
- embed_dim: Patch embedding dimension.
- depth: Depth of ViT.
- num_heads: Number of attention heads in each ViT block.
- mlp_ratio: Ratio of mlp hidden dim to embedding dim.
- qkv_bias: If True, add a learnable bias to query, key, value.
- norm_layer: Normalization layer.
- act_layer: Activation layer.
- use_abs_pos: If True, use absolute positional embeddings.
- use_rel_pos: If True, add relative positional embeddings to the attention map.
- rel_pos_zero_init: If True, zero initialize relative positional parameters.
- window_size: Window size for window attention blocks.
- global_attn_indexes: Indexes for blocks using global attention.
+ """Args:
+ img_size: Input image size.
+ patch_size: Patch size.
+ in_chans: Number of input image channels.
+ embed_dim: Patch embedding dimension.
+ depth: Depth of ViT.
+ num_heads: Number of attention heads in each ViT block.
+ mlp_ratio: Ratio of mlp hidden dim to embedding dim.
+ qkv_bias: If True, add a learnable bias to query, key, value.
+ norm_layer: Normalization layer.
+ act_layer: Activation layer.
+ use_abs_pos: If True, use absolute positional embeddings.
+ use_rel_pos: If True, add relative positional embeddings to the attention map.
+ rel_pos_zero_init: If True, zero initialize relative positional parameters.
+ window_size: Window size for window attention blocks.
+ global_attn_indexes: Indexes for blocks using global attention.
+
"""
super().__init__()
self.img_size = img_size
@@ -124,18 +124,18 @@ class Block(Module):
window_size: int = 0,
input_size: Optional[tuple[int, int]] = None,
) -> None:
- """
- Args:
- dim: Number of input channels.
- num_heads: Number of attention heads in each ViT block.
- mlp_ratio: Ratio of mlp hidden dim to embedding dim.
- qkv_bias: If True, add a learnable bias to query, key, value.
- norm_layer: Normalization layer.
- act_layer: Activation layer.
- use_rel_pos: If True, add relative positional embeddings to the attention map.
- rel_pos_zero_init: If True, zero initialize relative positional parameters.
- window_size: Window size for window attention blocks. If it equals 0, then use global attention.
- input_size: Input resolution for calculating the relative positional parameter size.
+ """Args:
+ dim: Number of input channels.
+ num_heads: Number of attention heads in each ViT block.
+ mlp_ratio: Ratio of mlp hidden dim to embedding dim.
+ qkv_bias: If True, add a learnable bias to query, key, value.
+ norm_layer: Normalization layer.
+ act_layer: Activation layer.
+ use_rel_pos: If True, add relative positional embeddings to the attention map.
+ rel_pos_zero_init: If True, zero initialize relative positional parameters.
+ window_size: Window size for window attention blocks. If it equals 0, then use global attention.
+ input_size: Input resolution for calculating the relative positional parameter size.
+
"""
super().__init__()
self.norm1 = norm_layer(dim)
@@ -184,14 +184,14 @@ class Attention(Module):
rel_pos_zero_init: bool = True,
input_size: Optional[tuple[int, int]] = None,
) -> None:
- """
- Args:
- dim: Number of input channels.
- num_heads: Number of attention heads.
- qkv_bias: If True, add a learnable bias to query, key, value.
- rel_pos: If True, add relative positional embeddings to the attention map.
- rel_pos_zero_init: If True, zero initialize relative positional parameters.
- input_size: Input resolution for calculating the relative positional parameter size.
+ """Args:
+ dim: Number of input channels.
+ num_heads: Number of attention heads.
+ qkv_bias: If True, add a learnable bias to query, key, value.
+ rel_pos: If True, add relative positional embeddings to the attention map.
+ rel_pos_zero_init: If True, zero initialize relative positional parameters.
+ input_size: Input resolution for calculating the relative positional parameter size.
+
"""
super().__init__()
self.num_heads = num_heads
@@ -236,6 +236,7 @@ def get_rel_pos(q_size: int, k_size: int, rel_pos: Tensor) -> Tensor:
Returns:
Extracted positional embeddings according to relative positions.
+
"""
max_rel_dist = int(2 * max(q_size, k_size) - 1)
# Interpolate rel pos if needed.
@@ -275,6 +276,7 @@ def add_decomposed_rel_pos(
Returns:
att: attention map with added relative positional embeddings.
+
"""
q_h, q_w = q_size
k_h, k_w = k_size
@@ -304,13 +306,13 @@ class PatchEmbed(Module):
in_chans: int = 3,
embed_dim: int = 768,
) -> None:
- """
- Args:
- kernel_size: kernel size of the projection layer.
- stride: stride of the projection layer.
- padding: padding size of the projection layer.
- in_chans: Number of input image channels.
- embed_dim: Patch embedding dimension.
+ """Args:
+ kernel_size: kernel size of the projection layer.
+ stride: stride of the projection layer.
+ padding: padding size of the projection layer.
+ in_chans: Number of input image channels.
+ embed_dim: Patch embedding dimension.
+
"""
super().__init__()
diff --git a/kornia/contrib/models/sam/architecture/mask_decoder.py b/kornia/contrib/models/sam/architecture/mask_decoder.py
index c7609ae43..cc3c7c5d5 100644
--- a/kornia/contrib/models/sam/architecture/mask_decoder.py
+++ b/kornia/contrib/models/sam/architecture/mask_decoder.py
@@ -33,6 +33,7 @@ class MaskDecoder(Module):
activation: the type of activation to use when upscaling masks
iou_head_depth: the depth of the MLP used to predict mask quality
iou_head_hidden_dim: the hidden dimension of the MLP used to predict mask quality
+
"""
super().__init__()
self.transformer_dim = transformer_dim
@@ -77,6 +78,7 @@ class MaskDecoder(Module):
Returns:
batched predicted masks
batched predictions of mask quality
+
"""
masks, iou_pred = self.predict_masks(
image_embeddings=image_embeddings,
diff --git a/kornia/contrib/models/sam/architecture/prompt_encoder.py b/kornia/contrib/models/sam/architecture/prompt_encoder.py
index 9e41d20fe..681274079 100644
--- a/kornia/contrib/models/sam/architecture/prompt_encoder.py
+++ b/kornia/contrib/models/sam/architecture/prompt_encoder.py
@@ -33,6 +33,7 @@ class PromptEncoder(Module):
input_image_size: The padded size of the image as input to the image encoder, as (H, W).
mask_in_chans: The number of hidden channels used for encoding input masks.
activation: The activation to use when encoding input masks.
+
"""
super().__init__()
self.embed_dim = embed_dim
@@ -63,6 +64,7 @@ class PromptEncoder(Module):
Returns:
Positional encoding with shape 1x(embed_dim)x(embedding_h)x(embedding_w)
+
"""
return self.pe_layer(self.image_embedding_size)[None, ...]
@@ -125,6 +127,7 @@ class PromptEncoder(Module):
- sparse embeddings for the points and boxes, with shape BxNx(embed_dim), where N is determined by the
number of input points and boxes.
- dense embeddings for the masks, in the shape Bx(embed_dim)x(embed_H)x(embed_W)
+
"""
bs = self._get_batch_size(points, boxes, masks)
sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())
diff --git a/kornia/contrib/models/sam/architecture/transformer.py b/kornia/contrib/models/sam/architecture/transformer.py
index 2fe202547..9838ea232 100644
--- a/kornia/contrib/models/sam/architecture/transformer.py
+++ b/kornia/contrib/models/sam/architecture/transformer.py
@@ -34,6 +34,7 @@ class TwoWayTransformer(Module):
num_heads: the number of heads for multihead attention. Must divide embedding_dim
mlp_dim: the channel dimension internal to the MLP block
activation: the activation to use in the MLP block
+
"""
super().__init__()
self.depth = depth
@@ -58,8 +59,7 @@ class TwoWayTransformer(Module):
self.norm_final_attn = nn.LayerNorm(embedding_dim)
def forward(self, image_embedding: Tensor, image_pe: Tensor, point_embedding: Tensor) -> tuple[Tensor, Tensor]:
- """
- Args:
+ """Args:
image_embedding: image to attend to. Should be shape B x embedding_dim x h x w for any h and w.
image_pe: the positional encoding to add to the image. Must have the same shape as image_embedding.
point_embedding: the embedding to add to the query points. Must have shape B x N_points x embedding_dim
@@ -68,6 +68,7 @@ class TwoWayTransformer(Module):
Returns:
- the processed point_embedding
- the processed image_embedding
+
"""
# BxCxHxW -> BxHWxC == B x N_image_tokens x C
bs, c, h, w = image_embedding.shape
@@ -112,6 +113,7 @@ class TwoWayAttentionBlock(Module):
mlp_dim: the hidden dimension of the mlp block
activation: the activation of the mlp block
skip_first_layer_pe: skip the PE on the first layer
+
"""
super().__init__()
self.self_attn = Attention(embedding_dim, num_heads)
@@ -162,7 +164,8 @@ class TwoWayAttentionBlock(Module):
class Attention(Module):
"""An attention layer that allows for downscaling the size of the embedding after projection to queries, keys,
- and values."""
+ and values.
+ """
def __init__(self, embedding_dim: int, num_heads: int, downsample_rate: int = 1) -> None:
super().__init__()
diff --git a/kornia/contrib/models/sam/model.py b/kornia/contrib/models/sam/model.py
index 1aaaf3b00..f1ca75613 100644
--- a/kornia/contrib/models/sam/model.py
+++ b/kornia/contrib/models/sam/model.py
@@ -54,6 +54,7 @@ class SamConfig:
encoder_depth: Depth of ViT.
encoder_num_heads: Number of attention heads in each ViT block.
encoder_global_attn_indexes: Encoder indexes for blocks using global attention.
+
"""
model_type: Optional[str | int | SamModelType] = None
@@ -79,8 +80,8 @@ class Sam(ModelBase[SamConfig]):
prediction.
prompt_encoder: Encodes various types of input prompts.
mask_decoder: Predicts masks from the image embeddings and encoded prompts.
- """
+ """
super().__init__()
self.image_encoder = image_encoder
self.prompt_encoder = prompt_encoder
@@ -99,6 +100,7 @@ class Sam(ModelBase[SamConfig]):
Returns:
The respective SAM model
+
"""
if name in ["vit_b", "vit_l", "vit_h", "mobile_sam"]:
return Sam.from_config(SamConfig(name))
@@ -112,12 +114,14 @@ class Sam(ModelBase[SamConfig]):
Args:
config: The SamConfig data structure. If the model_type is available, build from it, otherwise will use
the parameters set.
+
Returns:
The respective SAM model
Example:
>>> from kornia.contrib.models.sam import SamConfig
>>> sam_model = Sam.from_config(SamConfig('vit_b'))
+
"""
model_type = config.model_type
@@ -254,8 +258,8 @@ class Sam(ModelBase[SamConfig]):
subsequent iterations of prediction. Where :math:`K` is the number of input prompts,
:math:`C` is determined by multimask_output, and :math:`H=W=256` are the model output size.
- scores: The model's predictions of mask quality (iou prediction), in shape BxC.
- """
+ """
KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])
KORNIA_CHECK(
images.shape[0] == len(batched_prompts),
diff --git a/kornia/contrib/models/structures.py b/kornia/contrib/models/structures.py
index e03c7c9f2..a2b5e2a43 100644
--- a/kornia/contrib/models/structures.py
+++ b/kornia/contrib/models/structures.py
@@ -16,6 +16,7 @@ class SegmentationResults:
logits: Results logits with shape :math:`(B, C, H, W)`, where :math:`C` refers to the number of predicted masks
scores: The scores from the logits. Shape :math:`(B, C)`
mask_threshold: The threshold value to generate the `binary_masks` from the `logits`
+
"""
logits: Tensor
@@ -56,6 +57,7 @@ class SegmentationResults:
Returns:
Batched logits in :math:`(K, C, H, W)` format, where (H, W) is given by original_size.
+
"""
x = self.logits
@@ -87,6 +89,7 @@ class Prompts:
the keypoints, and :math:`(K, N)`
boxes: Batched box inputs, with shape :math:`(K, 4)`. Expected to be into xyxy format.
masks: Batched mask prompts to the model with shape :math:`(K, 1, H, W)`
+
"""
points: Optional[tuple[Tensor, Tensor]] = None
diff --git a/kornia/contrib/models/tiny_vit.py b/kornia/contrib/models/tiny_vit.py
index ee06aa093..129982514 100644
--- a/kornia/contrib/models/tiny_vit.py
+++ b/kornia/contrib/models/tiny_vit.py
@@ -325,6 +325,7 @@ class TinyViT(Module):
local_conv_size: Kernel size of convolution used in TinyViTBlock
activation: activation function.
mobile_same: Whether to use modifications for MobileSAM.
+
"""
def __init__(
@@ -445,6 +446,7 @@ class TinyViT(Module):
When ``img_size`` is different from the pre-trained size, bicubic interpolation will be performed on
attention biases. When using ``pretrained=True``, ImageNet-1k checkpoint (``'in1k'``) is used.
For feature extraction or fine-tuning, ImageNet-22k checkpoint (``'in22k'``) is preferred.
+
"""
KORNIA_CHECK(variant in ("5m", "11m", "21m"), "Only variant 5m, 11m, and 21m are supported")
return {"5m": _tiny_vit_5m, "11m": _tiny_vit_11m, "21m": _tiny_vit_21m}[variant](pretrained, **kwargs)
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 25d7ece0b..48ac1e6dd 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -16,7 +16,7 @@ from kornia.geometry.keypoints import Keypoints
class VisualPrompter:
- """This class allow the user to run multiple query with multiple prompts for a model.
+ r"""This class allow the user to run multiple query with multiple prompts for a model.
At the moment, we just support the SAM model. The model is loaded based on the given config.
@@ -48,6 +48,7 @@ class VisualPrompter:
>>> prediction = prompter.predict(boxes=boxes)
>>> prediction.logits.shape
torch.Size([1, 3, 256, 256])
+
"""
def __init__(
@@ -94,8 +95,8 @@ class VisualPrompter:
Returns:
The image preprocessed (normalized if has mean and str available and padded to encoder size)
- """
+ """
if isinstance(mean, Tensor) and isinstance(std, Tensor):
x = normalize(x, mean, std)
elif isinstance(self.pixel_mean, Tensor) and isinstance(self.pixel_std, Tensor):
@@ -118,6 +119,7 @@ class VisualPrompter:
image: RGB image. Normally images with range of [0-1], the model preprocess normalize the
pixel values with the mean and std defined in its initialization. Expected to be into a float32
dtype. Shape :math:`(3, H, W)`.
+
"""
KORNIA_CHECK_SHAPE(image, ["3", "H", "W"])
@@ -247,10 +249,11 @@ class VisualPrompter:
multimask_output=False can give better results.
output_original_size: If true, the logits of `SegmentationResults` will be post-process to match the
original input image size.
+
Returns:
A prediction with the logits and scores (IoU of each predicted mask)
- """
+ """
KORNIA_CHECK(self.is_image_set, "An image must be set with `self.set_image(...)` before `predict` be called!")
prompts = self.preprocess_prompts(keypoints, keypoints_labels, boxes, masks)
@@ -320,8 +323,8 @@ class VisualPrompter:
>>> # prompter = VisualPrompter()
>>> # prompter.compile() # You should have torch >= 2.0.0 installed
>>> # Use the prompter methods ...
- """
+ """
# self.set_image = torch.compile( # type: ignore[method-assign]
# self.set_image,
# fullgraph=fullgraph,
diff --git a/kornia/contrib/vit.py b/kornia/contrib/vit.py
index 55aef9499..b40edf433 100644
--- a/kornia/contrib/vit.py
+++ b/kornia/contrib/vit.py
@@ -198,6 +198,7 @@ class VisionTransformer(Module):
>>> vit = VisionTransformer(image_size=224, patch_size=16)
>>> vit(img).shape
torch.Size([1, 197, 768])
+
"""
def __init__(
@@ -255,12 +256,14 @@ class VisionTransformer(Module):
variant: ViT model variant e.g. ``vit_b/16``.
pretrained: whether to load pre-trained AugReg weights.
kwargs: other keyword arguments that will be passed to :func:`kornia.contrib.vit.VisionTransformer`.
+
Returns:
The respective ViT model
Example:
>>> from kornia.contrib import VisionTransformer
>>> vit_model = VisionTransformer.from_config("vit_b/16", pretrained=True)
+
"""
model_type, patch_size_str = variant.split("/")
patch_size = int(patch_size_str)
diff --git a/kornia/contrib/vit_mobile.py b/kornia/contrib/vit_mobile.py
index 4c639a345..1776621f2 100644
--- a/kornia/contrib/vit_mobile.py
+++ b/kornia/contrib/vit_mobile.py
@@ -75,6 +75,7 @@ class Transformer(Module):
dim_head: head size.
mlp_dim: dimension of the FeedForward layer.
dropout: dropout ratio, defaults to 0.
+
"""
def __init__(self, dim: int, depth: int, heads: int, dim_head: int, mlp_dim: int, dropout: float = 0.0) -> None:
@@ -108,6 +109,7 @@ class MV2Block(Module):
oup: output channel.
stride: stride for convolution, defaults to 1, set to 2 if down-sample.
expansion: expansion ratio for hidden dimension, defaults to 4.
+
"""
def __init__(self, inp: int, oup: int, stride: int = 1, expansion: int = 4) -> None:
@@ -160,6 +162,7 @@ class MobileViTBlock(Module):
patch_size: patch size for folding and unfloding.
mlp_dim: dimension of the FeedForward layer in Transformer.
dropout: dropout ratio, defaults to 0.
+
"""
def __init__(
@@ -230,6 +233,7 @@ class MobileViT(Module):
>>> mvit = MobileViT(mode='xxs')
>>> mvit(img).shape
torch.Size([1, 320, 8, 8])
+
"""
def __init__(
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 1b69d139c..6742a89a3 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -51,6 +51,7 @@ def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], raises: bool = True) -> bool
>>> x = torch.rand(2, 3, 4, 4)
>>> KORNIA_CHECK_SHAPE(x, ["2", "3", "H", "W"]) # explicit
True
+
"""
if "*" == shape[0]:
shape_to_check = shape[1:]
@@ -98,6 +99,7 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = True
>>> x = torch.rand(2, 3, 3)
>>> KORNIA_CHECK(x.shape[-2:] == (3, 3), "Invalid homography")
True
+
"""
if not condition:
if raises:
@@ -112,6 +114,7 @@ def KORNIA_UNWRAP(maybe_obj: object, typ: Any) -> Any:
Args:
maybe_obj: the object to unwrap.
typ: expected type after unwrap.
+
"""
# TODO: this function will change after kornia/pr#1987
return cast(typ, maybe_obj)
@@ -138,6 +141,7 @@ def KORNIA_CHECK_TYPE(
Example:
>>> KORNIA_CHECK_TYPE("foo", str, "Invalid string")
True
+
"""
# TODO: Move to use typeguard here dropping support for JIT
if not isinstance(x, typ):
@@ -162,6 +166,7 @@ def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool =
>>> x = torch.rand(2, 3, 3)
>>> KORNIA_CHECK_IS_TENSOR(x, "Invalid tensor")
True
+
"""
# TODO: Move to use typeguard here dropping support for JIT
if not isinstance(x, Tensor):
@@ -190,6 +195,7 @@ def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool =
False
>>> KORNIA_CHECK_IS_LIST_OF_TENSOR([x])
True
+
"""
are_tensors = isinstance(x, list) and all(isinstance(d, Tensor) for d in x)
if not are_tensors:
@@ -216,6 +222,7 @@ def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor, raises: bool = True) -> bool:
>>> x2 = torch.rand(1, 3, 1)
>>> KORNIA_CHECK_SAME_DEVICE(x1, x2)
True
+
"""
if x.device != y.device:
if raises:
@@ -240,6 +247,7 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: Optional[str] = None,
>>> x2 = torch.rand(1, 3, 1)
>>> KORNIA_CHECK_SAME_DEVICES([x1, x2], "Tensors not in the same device")
True
+
"""
KORNIA_CHECK(isinstance(tensors, list) and len(tensors) >= 1, "Expected a list with at least one element", raises)
if not all(tensors[0].device == x.device for x in tensors):
@@ -266,6 +274,7 @@ def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor, raises: bool = True) -> bool:
>>> x2 = torch.rand(2, 3, 3)
>>> KORNIA_CHECK_SAME_SHAPE(x1, x2)
True
+
"""
if x.shape != y.shape:
if raises:
@@ -289,6 +298,7 @@ def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None, raises: bool = T
>>> img = torch.rand(2, 3, 4, 4)
>>> KORNIA_CHECK_IS_COLOR(img, "Image is not color")
True
+
"""
if len(x.shape) < 3 or x.shape[-3] != 3:
if raises:
@@ -312,6 +322,7 @@ def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = Tr
>>> img = torch.rand(2, 1, 4, 4)
>>> KORNIA_CHECK_IS_GRAY(img, "Image is not grayscale")
True
+
"""
if len(x.shape) < 2 or (len(x.shape) >= 3 and x.shape[-3] != 1):
if raises:
@@ -335,6 +346,7 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None, raises:
>>> img = torch.rand(2, 3, 4, 4)
>>> KORNIA_CHECK_IS_COLOR_OR_GRAY(img, "Image is not color orgrayscale")
True
+
"""
if len(x.shape) < 3 or x.shape[-3] not in [1, 3]:
if raises:
@@ -361,6 +373,7 @@ def KORNIA_CHECK_IS_IMAGE(x: Tensor, msg: Optional[str] = None, raises: bool = T
>>> img = torch.rand(2, 3, 4, 4)
>>> KORNIA_CHECK_IS_IMAGE(img, "It is not an image")
True
+
"""
res = KORNIA_CHECK_IS_COLOR_OR_GRAY(x, msg, raises=raises)
@@ -400,6 +413,7 @@ def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor, raises: bool
>>> dm = torch.rand(4, 8)
>>> KORNIA_CHECK_DM_DESC(desc1, desc2, dm)
True
+
"""
if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))):
if raises:
@@ -425,5 +439,6 @@ def KORNIA_CHECK_LAF(laf: Tensor, raises: bool = True) -> bool:
>>> lafs = torch.rand(2, 10, 2, 3)
>>> KORNIA_CHECK_LAF(lafs)
True
+
"""
return KORNIA_CHECK_SHAPE(laf, ["B", "N", "2", "3"], raises)
diff --git a/kornia/core/external.py b/kornia/core/external.py
index 47ac3fa92..5f5270a67 100644
--- a/kornia/core/external.py
+++ b/kornia/core/external.py
@@ -20,6 +20,7 @@ class LazyLoader:
Attributes:
module_name: The name of the module to be lazily loaded.
module: The actual module object, initialized to None and loaded upon first access.
+
"""
auto_install: bool = False
@@ -32,6 +33,7 @@ class LazyLoader:
dev_dependency: If the dependency is required in the dev environment.
If True, the module will be loaded in the dev environment.
If False, the module will not be loaded in the dev environment.
+
"""
self.module_name = module_name
self.module: Optional[ModuleType] = None
@@ -107,6 +109,7 @@ class LazyLoader:
Returns:
The requested attribute of the loaded module.
+
"""
self._load()
return getattr(self.module, item)
@@ -119,6 +122,7 @@ class LazyLoader:
Returns:
list: The list of attributes of the loaded module.
+
"""
self._load()
return dir(self.module)
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index b003f4fe6..6138d6c4b 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -31,6 +31,7 @@ class ImageModuleMixIn:
Returns:
Callable: Decorated function with converted input and output types.
+
"""
def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
@@ -85,6 +86,7 @@ class ImageModuleMixIn:
Returns:
bool: True if valid, False otherwise.
+
"""
if isinstance(arg, (str,)) and os.path.exists(arg):
return True
@@ -107,6 +109,7 @@ class ImageModuleMixIn:
Returns:
Tensor: The converted tensor.
+
"""
if isinstance(x, (str,)):
from kornia.io import ImageLoadType, load_image # pylint: disable=C0415
@@ -130,6 +133,7 @@ class ImageModuleMixIn:
Returns:
np.array: The converted numpy array.
+
"""
if isinstance(x, (Tensor,)):
return x.cpu().detach().numpy()
@@ -147,6 +151,7 @@ class ImageModuleMixIn:
Returns:
Image.Image: The converted PIL image.
+
"""
if isinstance(x, (Tensor,)):
x = x.cpu().detach() * 255
@@ -185,6 +190,7 @@ class ImageModuleMixIn:
Args:
n_row: Number of images displayed in each row of the grid.
backend: visualization backend. Only PIL is supported now.
+
"""
if self._output_image is None:
raise ValueError("No pre-computed images found. Needs to execute first.")
@@ -213,6 +219,7 @@ class ImageModuleMixIn:
Args:
name: Directory to save the images.
n_row: Number of images displayed in each row of the grid.
+
"""
from kornia.io import write_image # pylint: disable=C0415
from kornia.utils.image import make_grid # pylint: disable=C0415
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index 9ac1c890e..7a4736c65 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -37,6 +37,7 @@ class ONNXExportMixin:
Note:
- If `ONNX_EXPORTABLE` is False, indicating that the object cannot be exported to ONNX.
+
"""
ONNX_EXPORTABLE: bool = True
@@ -84,6 +85,7 @@ class ONNXExportMixin:
- A dummy input tensor is created based on the provided or default input shape.
- Dynamic axes for input and output tensors are configured where dimensions are marked `-1`.
- The model is exported with `torch.onnx.export`, with constant folding enabled and opset version set to 17.
+
"""
if not self.ONNX_EXPORTABLE:
raise RuntimeError("This object cannot be exported to ONNX.")
@@ -162,6 +164,7 @@ class ONNXRuntimeMixin:
Returns:
ort.InferenceSession: The ONNXRuntime session optimized for inference.
+
"""
if session_options is None:
sess_options = ort.SessionOptions() # type:ignore
@@ -179,6 +182,7 @@ class ONNXRuntimeMixin:
Args:
session: ort.InferenceSession
The custom ONNXRuntime session to be set for inference.
+
"""
self._session = session
@@ -187,6 +191,7 @@ class ONNXRuntimeMixin:
Returns:
ort.InferenceSession: The current ONNXRuntime session.
+
"""
return self._session
@@ -208,6 +213,7 @@ class ONNXRuntimeMixin:
Args:
device_id: Select GPU to execute.
+
"""
self._session.set_providers(["CUDAExecutionProvider"], provider_options=[{"device_id": device_id, **kwargs}])
@@ -220,6 +226,7 @@ class ONNXRuntimeMixin:
Args:
device_id: select GPU to execute.
+
"""
self._session.set_providers(
["TensorrtExecutionProvider"], provider_options=[{"device_id": device_id, **kwargs}]
@@ -235,6 +242,7 @@ class ONNXRuntimeMixin:
Args:
device_type: CPU, NPU, GPU, GPU.0, GPU.1 based on the available GPUs, NPU, Any valid Hetero combination,
Any valid Multi or Auto devices combination.
+
"""
self._session.set_providers(
["OpenVINOExecutionProvider"], provider_options=[{"device_type": device_type, **kwargs}]
@@ -248,6 +256,7 @@ class ONNXRuntimeMixin:
Returns:
list: The outputs from the ONNX model inference.
+
"""
ort_inputs = self._session.get_inputs()
ort_input_values = {ort_inputs[i].name: inputs[i] for i in range(len(ort_inputs))}
@@ -269,6 +278,7 @@ class ONNXMixin:
Returns:
onnx.ModelProto: The loaded ONNX model.
+
"""
if isinstance(arg, str):
return kornia.onnx.utils.ONNXLoader.load_model(arg, cache_dir=cache_dir)
@@ -290,6 +300,7 @@ class ONNXMixin:
Returns:
list[onnx.ModelProto]: The loaded ONNX models as a list of ONNX graphs.
+
"""
op_list = []
for arg in args:
@@ -311,6 +322,7 @@ class ONNXMixin:
Returns:
onnx.ModelProto: The combined ONNX model as a single ONNX graph.
+
"""
if len(args) == 0:
raise ValueError("No operators found.")
@@ -339,6 +351,7 @@ class ONNXMixin:
Args:
file_path:
The file path to export the combined ONNX model.
+
"""
onnx.save(op, file_path, **kwargs) # type:ignore
@@ -353,6 +366,7 @@ class ONNXMixin:
additional_metadata:
A list of tuples representing additional metadata to add to the combined ONNX model.
Example: [("version", 0.1)], [("date", 20240909)].
+
"""
op = kornia.onnx.utils.add_metadata(op, additional_metadata)
return op
@@ -368,6 +382,7 @@ class ONNXMixin:
Args:
target_ir_version: The target IR version to convert to.
target_opset_version: The target OPSET version to convert to.
+
"""
if op.ir_version != target_ir_version or op.opset_import[0].version != target_opset_version:
# Check if all ops are supported in the current IR version
diff --git a/kornia/core/module.py b/kornia/core/module.py
index b8dd6ed9e..63670e3b3 100644
--- a/kornia/core/module.py
+++ b/kornia/core/module.py
@@ -37,6 +37,7 @@ class ImageModuleMixIn:
Returns:
Callable: Decorated function with converted input and output types.
+
"""
def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
@@ -91,6 +92,7 @@ class ImageModuleMixIn:
Returns:
bool: True if valid, False otherwise.
+
"""
if isinstance(arg, (str,)) and os.path.exists(arg):
return True
@@ -113,6 +115,7 @@ class ImageModuleMixIn:
Returns:
Tensor: The converted tensor.
+
"""
if isinstance(x, (str,)):
return kornia.io.load_image(x, kornia.io.ImageLoadType.UNCHANGED) / 255
@@ -132,6 +135,7 @@ class ImageModuleMixIn:
Returns:
np.array: The converted numpy array.
+
"""
if isinstance(x, (Tensor,)):
return x.cpu().detach().numpy()
@@ -149,6 +153,7 @@ class ImageModuleMixIn:
Returns:
Image.Image: The converted PIL image.
+
"""
if isinstance(x, (Tensor,)):
x = x.cpu().detach() * 255
@@ -187,6 +192,7 @@ class ImageModuleMixIn:
Args:
n_row: Number of images displayed in each row of the grid.
backend: visualization backend. Only PIL is supported now.
+
"""
if self._output_image is None:
raise ValueError("No pre-computed images found. Needs to execute first.")
@@ -213,6 +219,7 @@ class ImageModuleMixIn:
Args:
name: Directory to save the images.
n_row: Number of images displayed in each row of the grid.
+
"""
if name is None:
name = f"Kornia-{datetime.datetime.now(tz=datetime.timezone.utc).strftime('%Y%m%d%H%M%S')!s}.jpg"
@@ -235,6 +242,7 @@ class ImageModule(Module, ImageModuleMixIn, ONNXExportMixin):
Note:
The additional add-on features increase the use of memories. To restore the
original behaviour, you may set `disable_features = True`.
+
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
@@ -264,8 +272,8 @@ class ImageModule(Module, ImageModuleMixIn, ONNXExportMixin):
Returns:
Callable: Decorated function with converted input and output types.
- """
+ """
# Wrap the forward method with the decorator
if not self._disable_features:
decorated_forward = self.convert_input_output(
@@ -291,6 +299,7 @@ class ImageSequential(Sequential, ImageModuleMixIn, ONNXExportMixin):
Note:
The additional add-on features increase the use of memories. To restore the
original behaviour, you may set `disable_features = True`.
+
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
@@ -320,8 +329,8 @@ class ImageSequential(Sequential, ImageModuleMixIn, ONNXExportMixin):
Returns:
Callable: Decorated function with converted input and output types.
- """
+ """
# Wrap the forward method with the decorator
if not self._disable_features:
decorated_forward = self.convert_input_output(
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index b5eb5f008..b1469636d 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -74,6 +74,7 @@ def adjust_saturation_with_gray_subtraction(image: Tensor, factor: Union[float,
>>> y = torch.tensor([1., 2.])
>>> adjust_saturation_with_gray_subtraction(x, y).shape
torch.Size([2, 3, 3, 3])
+
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
@@ -131,6 +132,7 @@ def adjust_saturation(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
>>> y = torch.tensor([1., 2.])
>>> adjust_saturation(x, y).shape
torch.Size([2, 3, 3, 3])
+
"""
# convert the rgb image to hsv
x_hsv: Tensor = rgb_to_hsv(image)
@@ -206,6 +208,7 @@ def adjust_hue(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
>>> y = torch.ones(2) * 3.141516
>>> adjust_hue(x, y).shape
torch.Size([2, 3, 3, 3])
+
"""
# convert the rgb image to hsv
x_hsv: Tensor = rgb_to_hsv(image)
@@ -250,6 +253,7 @@ def adjust_gamma(input: Tensor, gamma: Union[float, Tensor], gain: Union[float,
>>> y2 = torch.ones(2) * 2.0
>>> adjust_gamma(x, y1, y2).shape
torch.Size([2, 5, 3, 3])
+
"""
if not isinstance(input, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -331,6 +335,7 @@ def adjust_contrast(image: Tensor, factor: Union[float, Tensor], clip_output: bo
>>> y = torch.tensor([0.65, 0.50])
>>> adjust_contrast(x, y).shape
torch.Size([2, 5, 3, 3])
+
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
@@ -385,6 +390,7 @@ def adjust_contrast_with_mean_subtraction(image: Tensor, factor: Union[float, Te
>>> y = torch.tensor([0.65, 0.50])
>>> adjust_contrast_with_mean_subtraction(x, y).shape
torch.Size([2, 5, 3, 3])
+
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
@@ -455,6 +461,7 @@ def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output:
>>> y = torch.tensor([0.25, 0.50])
>>> adjust_brightness(x, y).shape
torch.Size([2, 5, 3, 3])
+
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
@@ -506,6 +513,7 @@ def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor],
>>> y = torch.tensor([0.25, 0.50])
>>> adjust_brightness_accumulative(x, y).shape
torch.Size([2, 5, 3, 3])
+
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")
@@ -554,6 +562,7 @@ def adjust_sigmoid(image: Tensor, cutoff: float = 0.5, gain: float = 10, inv: bo
>>> adjust_sigmoid(x, gain=0)
tensor([[[[0.5000, 0.5000],
[0.5000, 0.5000]]]])
+
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
@@ -586,6 +595,7 @@ def adjust_log(image: Tensor, gain: float = 1, inv: bool = False, clip_output: b
>>> adjust_log(x, inv=True)
tensor([[[[0., 0.],
[0., 0.]]]])
+
"""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
@@ -613,6 +623,7 @@ def _solarize(input: Tensor, thresholds: Union[float, Tensor] = 0.5) -> Tensor:
Returns:
Solarized images.
+
"""
if not isinstance(input, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -666,6 +677,7 @@ def solarize(
>>> additions = torch.tensor([-0.25, 0.25])
>>> solarize(x, thresholds, additions).shape
torch.Size([2, 4, 3, 3])
+
"""
if not isinstance(input, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -725,6 +737,7 @@ def posterize(input: Tensor, bits: Union[int, Tensor]) -> Tensor:
>>> bits = torch.tensor([4, 2])
>>> posterize(x, bits).shape
torch.Size([2, 6, 3, 3])
+
"""
if not isinstance(input, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -808,6 +821,7 @@ def sharpness(input: Tensor, factor: Union[float, Tensor]) -> Tensor:
>>> x = torch.rand(1, 1, 5, 5)
>>> sharpness(x, 0.5).shape
torch.Size([1, 1, 5, 5])
+
"""
if not isinstance(factor, Tensor):
factor = torch.as_tensor(factor, device=input.device, dtype=input.dtype)
@@ -851,6 +865,7 @@ def _blend_one(input1: Tensor, input2: Tensor, factor: Tensor) -> Tensor:
Returns:
: image tensor with the batch in the zero position.
+
"""
if not isinstance(input1, Tensor):
raise AssertionError(f"`input1` must be a tensor. Got {input1}.")
@@ -891,6 +906,7 @@ def _scale_channel(im: Tensor) -> Tensor:
Returns:
image tensor with the batch in the zero position.
+
"""
min_ = im.min()
max_ = im.max()
@@ -943,6 +959,7 @@ def equalize(input: Tensor) -> Tensor:
>>> x = torch.rand(1, 2, 3, 3)
>>> equalize(x).shape
torch.Size([1, 2, 3, 3])
+
"""
res = []
for image in input:
@@ -965,6 +982,7 @@ def equalize3d(input: Tensor) -> Tensor:
Returns:
Equalized volume with shape :math:`(B, C, D, H, W)`.
+
"""
res = []
for volume in input:
@@ -998,6 +1016,7 @@ def invert(image: Tensor, max_val: Optional[Tensor] = None) -> Tensor:
>>> img = torch.rand(1, 3, 4, 4)
>>> invert(img, torch.as_tensor([[[[1.]]]])).shape
torch.Size([1, 3, 4, 4])
+
"""
if not isinstance(image, Tensor):
raise AssertionError(f"Input is not a Tensor. Got: {type(input)}")
@@ -1046,6 +1065,7 @@ class AdjustSaturation(Module):
>>> out = AdjustSaturation(y)(x)
>>> torch.nn.functional.mse_loss(x, out)
tensor(0.)
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -1096,6 +1116,7 @@ class AdjustSaturationWithGraySubtraction(Module):
>>> out = AdjustSaturationWithGraySubtraction(y)(x)
>>> torch.nn.functional.mse_loss(x, out)
tensor(0.)
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -1146,6 +1167,7 @@ class AdjustHue(Module):
>>> y = torch.ones(2) * 3.141516
>>> AdjustHue(y)(x).shape
torch.Size([2, 3, 3, 3])
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
@@ -1186,6 +1208,7 @@ class AdjustGamma(Module):
>>> y2 = torch.ones(2) * 2.0
>>> AdjustGamma(y1, y2)(x).shape
torch.Size([2, 5, 3, 3])
+
"""
def __init__(self, gamma: Union[float, Tensor], gain: Union[float, Tensor] = 1.0) -> None:
@@ -1224,6 +1247,7 @@ class AdjustContrast(Module):
>>> y = torch.ones(2)
>>> AdjustContrast(y)(x).shape
torch.Size([2, 5, 3, 3])
+
"""
def __init__(self, contrast_factor: Union[float, Tensor]) -> None:
@@ -1262,6 +1286,7 @@ class AdjustContrastWithMeanSubtraction(Module):
>>> y = torch.ones(2)
>>> AdjustContrastWithMeanSubtraction(y)(x).shape
torch.Size([2, 5, 3, 3])
+
"""
def __init__(self, contrast_factor: Union[float, Tensor]) -> None:
@@ -1298,6 +1323,7 @@ class AdjustBrightness(Module):
>>> y = torch.ones(2)
>>> AdjustBrightness(y)(x).shape
torch.Size([2, 5, 3, 3])
+
"""
def __init__(self, brightness_factor: Union[float, Tensor]) -> None:
@@ -1328,6 +1354,7 @@ class AdjustSigmoid(Module):
>>> AdjustSigmoid(gain=0)(x)
tensor([[[[0.5000, 0.5000],
[0.5000, 0.5000]]]])
+
"""
def __init__(self, cutoff: float = 0.5, gain: float = 10, inv: bool = False) -> None:
@@ -1359,6 +1386,7 @@ class AdjustLog(Module):
>>> AdjustLog(inv=True)(x)
tensor([[[[0., 0.],
[0., 0.]]]])
+
"""
def __init__(self, gain: float = 1, inv: bool = False, clip_output: bool = True) -> None:
@@ -1397,6 +1425,7 @@ class AdjustBrightnessAccumulative(Module):
>>> y = torch.ones(2)
>>> AdjustBrightnessAccumulative(y)(x).shape
torch.Size([2, 5, 3, 3])
+
"""
def __init__(self, brightness_factor: Union[float, Tensor]) -> None:
@@ -1427,6 +1456,7 @@ class Invert(Module):
>>> img = torch.rand(1, 3, 4, 4)
>>> Invert(torch.as_tensor([[[[1.]]]]))(img).shape
torch.Size([1, 3, 4, 4])
+
"""
def __init__(self, max_val: Optional[Tensor] = None) -> None:
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 2a2cc375e..bbd82af04 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -36,6 +36,7 @@ def add_weighted(
Notes:
Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes.
+
"""
KORNIA_CHECK_IS_TENSOR(src1)
KORNIA_CHECK_IS_TENSOR(src2)
@@ -86,6 +87,7 @@ class AddWeighted(Module):
Notes:
Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes.
+
"""
def __init__(self, alpha: Union[float, Tensor], beta: Union[float, Tensor], gamma: Union[float, Tensor]) -> None:
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index 957d45c01..b56d22147 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -28,6 +28,7 @@ def _compute_tiles(
Returns:
tensor with tiles (B, GH, GW, C, TH, TW). B = 1 in case of a single image is provided.
tensor with the padded batch of 2D imageswith shape (B, C, H', W').
+
"""
batch: torch.Tensor = imgs # B x C x H x W
@@ -81,6 +82,7 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[int
Returns:
tensor with the interpolation tiles (B, 2GH, 2GW, C, TH/2, TW/2).
+
"""
if padded_imgs.dim() != 4:
raise AssertionError("Images Tensor must be 4D.")
@@ -134,6 +136,7 @@ def _compute_luts(
Returns:
Lut for each tile (B, GH, GW, C, 256).
+
"""
if tiles_x_im.dim() != 6:
raise AssertionError("Tensor must be 6D.")
@@ -181,6 +184,7 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:
Returns:
mapped luts (B, 2GH, 2GW, 4, C, 256)
+
"""
if interp_tiles.dim() != 6:
raise AssertionError("interp_tiles tensor must be 6D.")
@@ -237,6 +241,7 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
Returns:
equalized tiles (B, 2GH, 2GW, C, TH/2, TW/2)
+
"""
if interp_tiles.dim() != 6:
raise AssertionError("interp_tiles tensor must be 6D.")
@@ -338,6 +343,7 @@ def equalize_clahe(
>>> res = equalize_clahe(img)
>>> res.shape
torch.Size([2, 3, 10, 20])
+
"""
if not isinstance(clip_limit, float):
raise TypeError(f"Input clip_limit type is not float. Got {type(clip_limit)}")
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 5a4819a21..6f14fb9a9 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -19,8 +19,8 @@ def marginal_pdf(values: Tensor, bins: Tensor, sigma: Tensor, epsilon: float = 1
Tuple[Tensor, Tensor]:
- Tensor: shape [BxN].
- Tensor: shape [BxNxNUM_BINS].
- """
+ """
if not isinstance(values, Tensor):
raise TypeError(f"Input values type is not a Tensor. Got {type(values)}")
@@ -60,6 +60,7 @@ def joint_pdf(kernel_values1: Tensor, kernel_values2: Tensor, epsilon: float = 1
Returns:
shape [BxNUM_BINSxNUM_BINS].
+
"""
if not isinstance(kernel_values1, Tensor):
raise TypeError(f"Input kernel_values1 type is not a Tensor. Got {type(kernel_values1)}")
@@ -106,6 +107,7 @@ def histogram(x: Tensor, bins: Tensor, bandwidth: Tensor, epsilon: float = 1e-10
>>> hist = histogram(x, bins, bandwidth=torch.tensor(0.9))
>>> hist.shape
torch.Size([1, 128])
+
"""
pdf, _ = marginal_pdf(x.unsqueeze(2), bins, bandwidth, epsilon)
@@ -134,8 +136,8 @@ def histogram2d(x1: Tensor, x2: Tensor, bins: Tensor, bandwidth: Tensor, epsilon
>>> hist = histogram2d(x1, x2, bins, bandwidth=torch.tensor(0.9))
>>> hist.shape
torch.Size([2, 128, 128])
- """
+ """
_, kernel_values1 = marginal_pdf(x1.unsqueeze(2), bins, bandwidth, epsilon)
_, kernel_values2 = marginal_pdf(x2.unsqueeze(2), bins, bandwidth, epsilon)
@@ -183,6 +185,7 @@ def image_histogram2d(
Computed probability densities of shape :math:`(bins)`, :math:`(C, bins)`,
:math:`(B, C, bins)`, if return_pdf is ``True``. Tensor of zeros with shape
of the histogram otherwise.
+
"""
if image is not None and not isinstance(image, Tensor):
raise TypeError(f"Input image type is not a Tensor. Got {type(image)}.")
diff --git a/kornia/enhance/integral.py b/kornia/enhance/integral.py
index f82a077c7..db15a491b 100644
--- a/kornia/enhance/integral.py
+++ b/kornia/enhance/integral.py
@@ -27,6 +27,7 @@ def integral_tensor(input: Tensor, dim: Optional[Tuple[int, ...]] = None) -> Ten
tensor([[ 1., 2., 3., 4., 5.],
[ 2., 4., 6., 8., 10.],
[ 3., 6., 9., 12., 15.]])
+
"""
KORNIA_CHECK_SHAPE(input, ["*", "D"])
@@ -62,6 +63,7 @@ def integral_image(image: Tensor) -> Tensor:
[ 3., 6., 9., 12., 15.],
[ 4., 8., 12., 16., 20.],
[ 5., 10., 15., 20., 25.]]])
+
"""
KORNIA_CHECK_SHAPE(image, ["*", "H", "W"])
@@ -89,6 +91,7 @@ class IntegralTensor(Module):
tensor([[ 1., 2., 3., 4., 5.],
[ 2., 4., 6., 8., 10.],
[ 3., 6., 9., 12., 15.]])
+
"""
def __init__(self, dim: Optional[Tuple[int, ...]] = None) -> None:
@@ -123,6 +126,7 @@ class IntegralImage(Module):
[ 3., 6., 9., 12., 15.],
[ 4., 8., 12., 16., 20.],
[ 5., 10., 15., 20., 25.]]])
+
"""
def forward(self, input: Tensor) -> Tensor:
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index e4fccfa98..b64e5233b 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -69,6 +69,7 @@ def _patchify_8x8(input: Tensor) -> Tensor:
Returns:
output (Tensor): Image patchify of the shape :math:`(B, N, 8, 8)`.
+
"""
# Get input shape
B, H, W = input.shape
@@ -85,6 +86,7 @@ def _unpatchify_8x8(input: Tensor, H: int, W: int) -> Tensor:
Returns:
output (Tensor): Image patchify of the shape :math:`(B, H, W)`.
+
"""
# Get input shape
B, N = input.shape[:2]
@@ -101,6 +103,7 @@ def _dct_8x8(input: Tensor) -> Tensor:
Returns:
output (Tensor): DCT output tensor of the shape :math:`(B, N, 8, 8)`.
+
"""
# Get dtype and device
dtype: Dtype = input.dtype
@@ -125,6 +128,7 @@ def _idct_8x8(input: Tensor) -> Tensor:
Returns:
output (Tensor): DCT output tensor of the shape :math:`(B, N, 8, 8)`.
+
"""
# Get dtype and device
dtype: Dtype = input.dtype
@@ -153,6 +157,7 @@ def _jpeg_quality_to_scale(
Returns:
scale (Tensor): Scaling factor to be applied to quantization matrix. Same shape as input.
+
"""
# Get scale
scale: Tensor = differentiable_polynomial_floor(
@@ -179,6 +184,7 @@ def _quantize(
Returns:
output (Tensor): Quantized output tensor of the shape :math:`(B, N, 8, 8)`.
+
"""
# Scale quantization table
quantization_table_scaled: Tensor = (
@@ -208,6 +214,7 @@ def _dequantize(
Returns:
output (Tensor): Quantized output tensor of the shape :math:`(B, N, 8, 8)`.
+
"""
# Scale quantization table
quantization_table_scaled: Tensor = (
@@ -230,6 +237,7 @@ def _chroma_subsampling(input_ycbcr: Tensor) -> tuple[Tensor, Tensor, Tensor]:
output_y (Tensor): Y component (not-subsampled), shape is :math:`(B, H, W)`.
output_cb (Tensor): Cb component (subsampled), shape is :math:`(B, H // 2, W // 2)`.
output_cr (Tensor): Cr component (subsampled), shape is :math:`(B, H // 2, W // 2)`.
+
"""
# Get components
output_y: Tensor = input_ycbcr[:, 0]
@@ -261,6 +269,7 @@ def _chroma_upsampling(input_c: Tensor) -> Tensor:
Returns:
output_c (Tensor): Upsampled C(b or r) component of the shape :math:`(B, H * 2, W * 2)`.
+
"""
# Upsample component
output_c: Tensor = rescale(
@@ -291,6 +300,7 @@ def _jpeg_encode(
y_encoded (Tensor): Encoded Y component of the shape :math:`(B, N, 8, 8)`.
cb_encoded (Tensor): Encoded Cb component of the shape :math:`(B, N, 8, 8)`.
cr_encoded (Tensor): Encoded Cr component of the shape :math:`(B, N, 8, 8)`.
+
"""
# Convert RGB image to YCbCr.
image_ycbcr: Tensor = rgb_to_ycbcr(image_rgb)
@@ -343,6 +353,7 @@ def _jpeg_decode(
Returns:
rgb_decoded (Tensor): Decompressed RGB image of the shape :math:`(B, 3, H, W)`.
+
"""
# Dequantize inputs
input_y = _dequantize(
@@ -382,6 +393,7 @@ def _perform_padding(image: Tensor) -> tuple[Tensor, int, int]:
image_padded: Padded image of the shape :math:`(*, 3, H_{new}, W_{new})`.
h_pad: Padded pixels along the horizontal axis.
w_pad: Padded pixels along the vertical axis.
+
"""
# Get spatial dimensions of the image
H, W = image.shape[-2:]
@@ -446,7 +458,6 @@ def jpeg_codec_differentiable(
JPEG coded image of the shape :math:`(B, 3, H, W)`
Example:
-
To perform JPEG coding with the standard quantization tables just provide a JPEG quality
>>> img = torch.rand(3, 3, 64, 64, requires_grad=True, dtype=torch.float)
@@ -472,6 +483,7 @@ def jpeg_codec_differentiable(
>>> quantization_table_c = torch.randint(1, 256, size=(3, 8, 8), dtype=torch.float)
>>> img_jpeg = jpeg_codec_differentiable(img, jpeg_quality, quantization_table_y, quantization_table_c)
>>> img_jpeg.sum().backward()
+
"""
# Check that inputs are tensors
KORNIA_CHECK_IS_TENSOR(image_rgb)
@@ -593,7 +605,6 @@ class JPEGCodecDifferentiable(Module):
- jpeg_quality: :math:`(1)` or :math:`(B)` (if used batch dim. needs to match w/ image_rgb).
Example:
-
You can use the differentiable JPEG module with standard quantization tables by
>>> diff_jpeg_module = JPEGCodecDifferentiable()
@@ -621,6 +632,7 @@ class JPEGCodecDifferentiable(Module):
>>> jpeg_quality = torch.tensor((99.0, 1.0), requires_grad=True)
>>> img_jpeg = diff_jpeg_module(img, jpeg_quality)
>>> img_jpeg.sum().backward()
+
"""
def __init__(
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index c2c8713fc..69e1c5f7a 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -38,6 +38,7 @@ class Normalize(Module):
>>> out = Normalize(mean, std)(x)
>>> out.shape
torch.Size([1, 4, 3, 3])
+
"""
def __init__(
@@ -98,6 +99,7 @@ def normalize(data: Tensor, mean: Tensor, std: Tensor) -> Tensor:
>>> out = normalize(x, mean, std)
>>> out.shape
torch.Size([1, 4, 3, 3])
+
"""
shape = data.shape
@@ -165,6 +167,7 @@ class Denormalize(Module):
>>> out = Denormalize(mean, std)(x)
>>> out.shape
torch.Size([1, 4, 3, 3, 3])
+
"""
def __init__(self, mean: Union[Tensor, float], std: Union[Tensor, float]) -> None:
@@ -209,6 +212,7 @@ def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, flo
>>> out = denormalize(x, mean, std)
>>> out.shape
torch.Size([1, 4, 3, 3, 3])
+
"""
shape = data.shape
@@ -271,6 +275,7 @@ def normalize_min_max(x: Tensor, min_val: float = 0.0, max_val: float = 1.0, eps
tensor(-1.)
>>> x_norm.max()
tensor(1.0000)
+
"""
if not isinstance(x, Tensor):
raise TypeError(f"data should be a tensor. Got: {type(x)}.")
diff --git a/kornia/enhance/rescale.py b/kornia/enhance/rescale.py
index add1e3318..fddb21699 100644
--- a/kornia/enhance/rescale.py
+++ b/kornia/enhance/rescale.py
@@ -9,6 +9,7 @@ class Rescale(Module):
Args:
factor: The scaling factor. Could be a float or a 0-d tensor.
+
"""
def __init__(self, factor: Union[float, Tensor]) -> None:
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index afd009a7f..0753a766f 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -25,8 +25,7 @@ class ZCAWhitening(Module):
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:
-
+ Args:
dim: Determines the dimension that represents the samples axis.
eps: a small number used for numerical stability.
unbiased: Whether to use the biased estimate of the covariance matrix.
@@ -53,14 +52,13 @@ class ZCAWhitening(Module):
>>> x_whiten = zca(x, include_fit = True) # Includes the fitting step
Note:
-
This implementation uses :py:meth:`~torch.svd` which yields NaNs in the backwards step
if the singular values are not unique. See `here <https://pytorch.org/docs/stable/torch.html#torch.svd>`_ for
more information.
References:
-
[1] `Stanford PCA & ZCA whitening tutorial <http://ufldl.stanford.edu/tutorial/unsupervised/PCAWhitening/>`_
+
"""
def __init__(
@@ -89,11 +87,11 @@ class ZCAWhitening(Module):
r"""Fit ZCA whitening matrices to the data.
Args:
-
x: Input data.
returns:
Returns a fitted ZCAWhiten object instance.
+
"""
T, mean, T_inv = zca_mean(x, self.dim, self.unbiased, self.eps, self.compute_inv)
@@ -122,6 +120,7 @@ class ZCAWhitening(Module):
Returns:
The transformed data.
+
"""
if include_fit:
self.fit(x)
@@ -141,6 +140,7 @@ class ZCAWhitening(Module):
Returns:
Original data.
+
"""
if not self.fitted:
raise RuntimeError("Needs to be fitted first before running. Please call fit or set include_fit to True.")
@@ -193,8 +193,8 @@ def zca_mean(
>>> x = torch.rand(3,20,2,2)
>>> transform_matrix, mean_vector, inv_transform = zca_mean(x, dim = 1, return_inverse = True)
>>> # transform_matrix.size() equals (12,12) and the mean vector.size equal (1,12)
- """
+ """
if not isinstance(inp, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(inp)}")
@@ -280,6 +280,7 @@ def zca_whiten(inp: Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e
tensor([[ 0.0000, 1.1547],
[ 1.0000, -0.5773],
[-1.0000, -0.5773]])
+
"""
if not isinstance(inp, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(inp)}")
@@ -339,6 +340,7 @@ def linear_transform(inp: Tensor, transform_matrix: Tensor, mean_vector: Tensor,
>>> out = linear_transform(inp, transform_mat, mean)
>>> print(out.shape, out.unique()) # Should a be (10,2) tensor of 2s
torch.Size([10, 2]) tensor([2.])
+
"""
inp_size = inp.size()
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index d8a1d5c04..0045a7b35 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -58,6 +58,7 @@ def match_adalam(
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
where 0 <= B3 <= B1.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -157,6 +158,7 @@ class AdalamFilter:
Returns:
Filtered putative matches.
A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
+
"""
with torch.no_grad():
return adalam_core(
@@ -223,6 +225,7 @@ class AdalamFilter:
Returns:
Filtered putative matches.
A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
+
"""
if s1 is None or s2 is None:
if self.config["scale_rate_threshold"] is not None:
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index 05e81f31d..2341023ec 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -33,6 +33,7 @@ class AdalamConfig(TypedDict):
at the cost of runtime
device: Device to be used for running AdaLAM. Use GPU if available.
mnn: Default None. You can provide a MNN mask in input to skip MNN computation and still get the improvement.
+
"""
area_ratio: NotRequired[int]
@@ -55,6 +56,7 @@ def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(0, 1)`.
- Long 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)
idxs = torch.empty(0, 2, device=dm.device, dtype=torch.long)
@@ -80,6 +82,7 @@ def select_seeds(
im1seeds: Keypoint index of chosen seeds in image I_1
im2seeds: Keypoint index of chosen seeds in image I_2
+
""" # noqa: E501
im1neighmap = dist1 < R1**2 # (n1, n1)
# find out who scores higher than whom
@@ -144,6 +147,7 @@ def extract_neighborhood_sets(
rdims: Number of keypoints included in the neighborhood for each seed
im1seeds: Keypoint index of chosen seeds in image I_1
im2seeds: Keypoint index of chosen seeds in image I_2
+
"""
dst1 = dist1[im1seeds, :]
dst2 = dist_matrix(k2[fnn12[im1seeds]], k2[fnn12])
@@ -213,6 +217,7 @@ def extract_local_patterns(
This allows to distinguish inputs belonging to the same problem.
tokp1: Index of the original keypoint in image I_1 for each RANSAC sample.
tokp2: Index of the original keypoint in image I_2 for each RANSAC sample.
+
"""
# first get an indexing representation of the assignments:
# - ransidx holds the index of the seed for each assignment
@@ -287,6 +292,7 @@ def adalam_core(
Returns:
idxs: A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
dists: inverse confidence ratio.
+
"""
AREA_RATIO = config["area_ratio"]
SEARCH_EXP = config["search_expansion"]
diff --git a/kornia/feature/adalam/utils.py b/kornia/feature/adalam/utils.py
index 4b7afc7ce..8fc354ba0 100644
--- a/kornia/feature/adalam/utils.py
+++ b/kornia/feature/adalam/utils.py
@@ -11,6 +11,7 @@ def arange_sequence(ranges: Tensor) -> Tensor:
Example:
[2, 5, 1, 2] -> [0, 1, 0, 1, 2, 3, 4, 0, 0, 1]
+
"""
maxcnt = torch.max(ranges).item()
numuni = ranges.shape[0]
@@ -38,8 +39,7 @@ def orientation_diff(o1: Tensor, o2: Tensor) -> Tensor:
def piecewise_arange(piecewise_idxer: Tensor) -> Tensor:
- """
- count repeated indices
+ """Count repeated indices
Example:
[0, 0, 0, 3, 3, 3, 3, 1, 1, 2] -> [0, 1, 2, 0, 1, 2, 3, 0, 1, 0]
"""
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index ceb280f6c..8933c8232 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -31,6 +31,7 @@ class PatchAffineShapeEstimator(nn.Module):
Args:
patch_size: the input image patch size.
eps: for safe division.
+
"""
def __init__(self, patch_size: int = 19, eps: float = 1e-10) -> None:
@@ -45,8 +46,7 @@ class PatchAffineShapeEstimator(nn.Module):
return f"{self.__class__.__name__}(patch_size={self.patch_size}, eps={self.eps})"
def forward(self, patch: torch.Tensor) -> torch.Tensor:
- """
- Args:
+ """Args:
patch: :math:`(B, 1, H, W)`
Returns:
@@ -92,6 +92,7 @@ class LAFAffineShapeEstimator(nn.Module):
patch_size: the input image patch size.
affine_shape_detector: Patch affine shape estimator, :class:`~kornia.feature.PatchAffineShapeEstimator`.
preserve_orientation: if True, the original orientation is preserved.
+
""" # pylint: disable
def __init__(
@@ -119,13 +120,13 @@ class LAFAffineShapeEstimator(nn.Module):
)
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
- """
- Args:
+ """Args:
LAF: :math:`(B, N, 2, 3)`
img: :math:`(B, 1, H, W)`
Returns:
LAF_out: :math:`(B, N, 2, 3)`
+
"""
KORNIA_CHECK_LAF(laf)
KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
@@ -157,6 +158,7 @@ class LAFAffNetShapeEstimator(nn.Module):
Args:
pretrained: Download and set pretrained weights to the model.
+
"""
def __init__(self, pretrained: bool = False, preserve_orientation: bool = True) -> None:
@@ -211,13 +213,13 @@ class LAFAffNetShapeEstimator(nn.Module):
return (x - mp.detach()) / (sp.detach() + eps)
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
- """
- Args:
+ """Args:
LAF: :math:`(B, N, 2, 3)`
img: :math:`(B, 1, H, W)`
Returns:
LAF_out: :math:`(B, N, 2, 3)`
+
"""
KORNIA_CHECK_LAF(laf)
KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.py
index c56dda8ca..150c756a3 100644
--- a/kornia/feature/dedode/dedode.py
+++ b/kornia/feature/dedode/dedode.py
@@ -47,6 +47,7 @@ class DeDoDe(Module):
>>> keypoints, scores = dedode.detect(images)
>>> descriptions = dedode.describe(images, keypoints = keypoints)
>>> keypoints, scores, features = dedode(images) # alternatively do both
+
"""
# TODO: implement steerers and mnn matchers
@@ -81,6 +82,7 @@ class DeDoDe(Module):
scores: A tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
descriptions: A tensor of shape :math:`(B, N, DIM)` containing the descriptions of the detected keypoints.
DIM is 256 for B and 512 for G.
+
"""
if apply_imagenet_normalization:
images = self.normalizer(images)
@@ -117,6 +119,7 @@ class DeDoDe(Module):
keypoints: A tensor of shape :math:`(B, N, 2)` containing the detected keypoints,
normalized to the range :math:`[-1, 1]`.
scores: A tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.
+
"""
KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])
self.train(False)
@@ -150,6 +153,7 @@ class DeDoDe(Module):
Returns:
descriptions: A 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)`.
+
"""
KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])
B, C, H, W = images.shape
@@ -190,6 +194,7 @@ class DeDoDe(Module):
Returns:
The pretrained model.
+
"""
model: DeDoDe = cls(
detector_model=detector_weights[0], # type: ignore[arg-type]
diff --git a/kornia/feature/dedode/transformer/dinov2.py b/kornia/feature/dedode/transformer/dinov2.py
index f3782c1c3..c83ab193e 100644
--- a/kornia/feature/dedode/transformer/dinov2.py
+++ b/kornia/feature/dedode/transformer/dinov2.py
@@ -63,27 +63,27 @@ class DinoVisionTransformer(nn.Module):
ffn_layer="mlp",
block_chunks=1,
):
- """
- Args:
- img_size (int, tuple): input image size
- patch_size (int, tuple): patch size
- in_chans (int): number of input channels
- embed_dim (int): embedding dimension
- depth (int): depth of transformer
- num_heads (int): number of attention heads
- mlp_ratio (int): ratio of mlp hidden dim to embedding dim
- qkv_bias (bool): enable bias for qkv if True
- proj_bias (bool): enable bias for proj in attn if True
- 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
- block_fn (nn.Module): transformer block class
- ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
- block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
+ """Args:
+ img_size (int, tuple): input image size
+ patch_size (int, tuple): patch size
+ in_chans (int): number of input channels
+ embed_dim (int): embedding dimension
+ depth (int): depth of transformer
+ num_heads (int): number of attention heads
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
+ qkv_bias (bool): enable bias for qkv if True
+ proj_bias (bool): enable bias for proj in attn if True
+ 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
+ block_fn (nn.Module): transformer block class
+ ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
+ block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
+
"""
super().__init__()
norm_layer = partial(nn.LayerNorm, eps=1e-6)
diff --git a/kornia/feature/dedode/transformer/layers/patch_embed.py b/kornia/feature/dedode/transformer/layers/patch_embed.py
index 1a1402a7a..96b3c011e 100644
--- a/kornia/feature/dedode/transformer/layers/patch_embed.py
+++ b/kornia/feature/dedode/transformer/layers/patch_embed.py
@@ -24,8 +24,7 @@ def make_2tuple(x):
class PatchEmbed(nn.Module):
- """
- 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
+ """2D image to patch embedding: (B,C,H,W) -> (B,N,D)
Args:
img_size: Image size.
@@ -33,6 +32,7 @@ class PatchEmbed(nn.Module):
in_chans: Number of input image channels.
embed_dim: Number of linear projection output channels.
norm_layer: Normalization layer.
+
"""
def __init__(
diff --git a/kornia/feature/dedode/vgg.py b/kornia/feature/dedode/vgg.py
index 25c49a315..f1d82a77e 100644
--- a/kornia/feature/dedode/vgg.py
+++ b/kornia/feature/dedode/vgg.py
@@ -91,8 +91,8 @@ def vgg11(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
.. autoclass:: torchvision.models.VGG11_Weights
:members:
- """
+ """
return _vgg("A", False, weights, **kwargs)
@@ -114,8 +114,8 @@ def vgg11_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
.. autoclass:: torchvision.models.VGG11_BN_Weights
:members:
- """
+ """
return _vgg("A", True, weights, **kwargs)
@@ -137,8 +137,8 @@ def vgg13(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
.. autoclass:: torchvision.models.VGG13_Weights
:members:
- """
+ """
return _vgg("B", False, weights, **kwargs)
@@ -160,8 +160,8 @@ def vgg13_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
.. autoclass:: torchvision.models.VGG13_BN_Weights
:members:
- """
+ """
return _vgg("B", True, weights, **kwargs)
@@ -183,8 +183,8 @@ def vgg16(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
.. autoclass:: torchvision.models.VGG16_Weights
:members:
- """
+ """
return _vgg("D", False, weights, **kwargs)
@@ -206,8 +206,8 @@ def vgg16_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
.. autoclass:: torchvision.models.VGG16_BN_Weights
:members:
- """
+ """
return _vgg("D", True, weights, **kwargs)
@@ -229,8 +229,8 @@ def vgg19(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
.. autoclass:: torchvision.models.VGG19_Weights
:members:
- """
+ """
return _vgg("E", False, weights, **kwargs)
@@ -252,6 +252,6 @@ def vgg19_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:
.. autoclass:: torchvision.models.VGG19_BN_Weights
:members:
- """
+ """
return _vgg("E", True, weights, **kwargs)
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index f2d314090..1ce7a667b 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -266,6 +266,7 @@ class DeFMO(Module):
Args:
pretrained: Download and set pretrained weights to the model. Default: false.
+
Returns:
Temporal super-resolution without background.
Shape:
@@ -277,6 +278,7 @@ class DeFMO(Module):
>>> input = torch.rand(2, 6, 240, 320)
>>> defmo = kornia.feature.DeFMO()
>>> tsr_nobgr = defmo(input) # 2x24x4x240x320
+
"""
def __init__(self, pretrained: bool = False) -> None:
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index 9ab5c4782..632834f0e 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -28,6 +28,7 @@ class DISK(Module):
>>> disk = DISK.from_pretrained('depth')
>>> images = torch.rand(1, 3, 256, 256)
>>> features = disk(images)
+
"""
def __init__(self, desc_dim: int = 128, unet: None | Module = None) -> None:
@@ -51,6 +52,7 @@ class DISK(Module):
A tuple of dense detection scores and descriptors.
Shapes are :math:`(B, 1, H, W)` and :math:`(B, D, H, W)`, where
:math:`D` is the descriptor dimension.
+
"""
unet_output = self.unet(images)
@@ -84,6 +86,7 @@ class DISK(Module):
Returns:
A list of length :math:`B` containing the detected features.
+
"""
B = images.shape[0]
if pad_if_not_divisible:
@@ -120,6 +123,7 @@ class DISK(Module):
Returns:
The pretrained model.
+
"""
urls = {
"depth": "https://raw.githubusercontent.com/cvlab-epfl/disk/master/depth-save.pth",
diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.py
index 59983ebe7..717c5cc7e 100644
--- a/kornia/feature/disk/structs.py
+++ b/kornia/feature/disk/structs.py
@@ -19,6 +19,7 @@ class DISKFeatures:
detection_scores: 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).
+
"""
keypoints: Tensor
@@ -53,6 +54,7 @@ class DISKFeatures:
Returns:
A new DISKFeatures object with tensors of appropriate type and location.
+
"""
return DISKFeatures(
self.keypoints.to(*args, **kwargs),
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 048d58c1d..e8dc49334 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -35,6 +35,7 @@ class HardNet(nn.Module):
>>> input = torch.rand(16, 1, 32, 32)
>>> hardnet = HardNet()
>>> descs = hardnet(input) # 16x128
+
"""
patch_size = 32
@@ -112,6 +113,7 @@ class HardNet8(nn.Module):
>>> input = torch.rand(16, 1, 32, 32)
>>> hardnet = HardNet8()
>>> descs = hardnet(input) # 16x128
+
"""
patch_size = 32
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index e198c2a4d..56cb0a0a1 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -33,6 +33,7 @@ class FilterResponseNorm2d(Module):
Shape:
- Input: :math:`(B, \text{num_features}, H, W)`
- Output: :math:`(B, \text{num_features}, H, W)`
+
"""
def __init__(
@@ -99,6 +100,7 @@ class TLU(Module):
Shape:
- Input: :math:`(B, \text{num_features}, H, W)`
- Output: :math:`(B, \text{num_features}, H, W)`
+
"""
def __init__(self, num_features: int) -> None:
@@ -145,6 +147,7 @@ class HyNet(Module):
>>> input = torch.rand(16, 1, 32, 32)
>>> hynet = HyNet()
>>> descs = hynet(input) # 16x128
+
"""
patch_size = 32
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 7cdbeb946..cbd02722b 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -42,6 +42,7 @@ def get_laf_descriptors(
Returns:
Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.
+
"""
KORNIA_CHECK_LAF(lafs)
patch_descriptor = patch_descriptor.to(img)
@@ -71,6 +72,7 @@ class LAFDescriptor(Module):
or :class:`~kornia.feature.HardNet`. Default: :class:`~kornia.feature.HardNet`.
patch_size: patch size in pixels, which descriptor expects.
grayscale_descriptor: ``True`` if patch_descriptor expects single-channel image.
+
"""
def __init__(
@@ -103,6 +105,7 @@ class LAFDescriptor(Module):
Returns:
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)
@@ -114,6 +117,7 @@ class LocalFeature(Module):
detector: the detection module.
descriptor: the descriptor module.
scaling_coef: multiplier for change default detector scale (e.g. it is too small for KeyNet by default)
+
"""
def __init__(self, detector: Module, descriptor: LAFDescriptor, scaling_coef: float = 1.0) -> None:
@@ -125,8 +129,7 @@ class LocalFeature(Module):
self.scaling_coef = scaling_coef
def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor, Tensor]:
- """
- Args:
+ """Args:
img: image to extract features with shape :math:`(B,C,H,W)`.
mask: a mask with weights where to apply the response function.
The shape must be the same as the input image.
@@ -135,6 +138,7 @@ class LocalFeature(Module):
- 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)` where :math:`D` is descriptor size.
+
"""
lafs, responses = self.detector(img, mask)
lafs = scale_laf(lafs, self.scaling_coef)
@@ -318,6 +322,7 @@ class LocalFeatureMatcher(Module):
... GFTTAffNetHardNet(10), kornia.feature.DescriptorMatcher('snn', 0.8)
... )
>>> out = gftt_hardnet_matcher(input)
+
"""
def __init__(self, local_feature: Module, matcher: Module) -> None:
@@ -342,8 +347,7 @@ class LocalFeatureMatcher(Module):
}
def forward(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
- """
- Args:
+ """Args:
data: dictionary containing the input data in the following format:
Keyword Args:
@@ -359,6 +363,7 @@ class LocalFeatureMatcher(Module):
- ``lafs0``, matching LAFs from image0 :math:`(1, NC, 2, 3)`.
- ``lafs1``, matching LAFs from image1 :math:`(1, NC, 2, 3)`.
- ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`.
+
"""
num_image_pairs: int = data["image0"].shape[0]
@@ -425,6 +430,7 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
Args:
feature_name: type of feature for matching, can be `disk` or `superpoint`.
params: LightGlue params.
+
"""
known_modes: ClassVar[List[str]] = [
@@ -457,8 +463,7 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
hw1: Optional[Tuple[int, int]] = None,
hw2: Optional[Tuple[int, int]] = None,
) -> Tuple[Tensor, Tensor]:
- """
- Args:
+ """Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.
@@ -468,6 +473,7 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
+
"""
if (desc1.shape[0] < 2) or (desc2.shape[0] < 2):
return _no_match(desc1)
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index 483e25deb..333c55138 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -125,6 +125,7 @@ class KeyNet(Module):
Shape:
- Input: :math:`(B, 1, H, W)`
- Output: :math:`(B, 1, H, W)`
+
"""
def __init__(self, pretrained: bool = False, keynet_conf: KeyNet_conf = keynet_default_config) -> None:
@@ -149,9 +150,7 @@ class KeyNet(Module):
self.eval()
def forward(self, x: Tensor) -> Tensor:
- """
- x - input image
- """
+ """X - input image"""
shape_im = x.shape
feats: List[Tensor] = [self.feature_extractor(x)]
for _ in range(1, self.num_levels):
@@ -180,6 +179,7 @@ class KeyNetDetector(MultiResolutionDetector):
which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,
which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
+
"""
def __init__(
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index a7f060baf..c8bb1a520 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -23,6 +23,7 @@ def get_laf_scale(LAF: Tensor) -> Tensor:
Example:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = get_laf_scale(input) # BxNx1x1
+
"""
KORNIA_CHECK_LAF(LAF)
eps = 1e-10
@@ -43,6 +44,7 @@ def get_laf_center(LAF: Tensor) -> Tensor:
Example:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = get_laf_center(input) # BxNx2
+
"""
KORNIA_CHECK_LAF(LAF)
out = LAF[..., 2]
@@ -61,6 +63,7 @@ def get_laf_orientation(LAF: Tensor) -> Tensor:
Example:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = get_laf_orientation(input) # BxNx1
+
"""
KORNIA_CHECK_LAF(LAF)
angle_rad = torch.atan2(LAF[..., 0, 1], LAF[..., 0, 0])
@@ -77,6 +80,7 @@ def rotate_laf(LAF: Tensor, angles_degrees: Tensor) -> Tensor:
Returns:
LAF oriented with angles :math:`(B, N, 2, 3)`
+
"""
KORNIA_CHECK_LAF(LAF)
B, N = LAF.shape[:2]
@@ -95,6 +99,7 @@ def set_laf_orientation(LAF: Tensor, angles_degrees: Tensor) -> Tensor:
Returns:
LAF oriented with angles :math:`(B, N, 2, 3)`
+
"""
KORNIA_CHECK_LAF(LAF)
B, N = LAF.shape[:2]
@@ -114,6 +119,7 @@ def laf_from_center_scale_ori(xy: Tensor, scale: Optional[Tensor] = None, ori: O
Returns:
LAF :math:`(B, N, 2, 3)`
+
"""
KORNIA_CHECK_SHAPE(xy, ["B", "N", "2"])
device = xy.device
@@ -146,6 +152,7 @@ def scale_laf(laf: Tensor, scale_coef: Union[float, Tensor]) -> Tensor:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> scale = 0.5
>>> output = scale_laf(input, scale) # BxNx2x3
+
"""
if not isinstance(scale_coef, (float, Tensor)):
raise TypeError(f"scale_coef should be float or Tensor. Got {type(scale_coef)}")
@@ -167,6 +174,7 @@ def make_upright(laf: Tensor, eps: float = 1e-9) -> Tensor:
Example:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = make_upright(input) # BxNx2x3
+
"""
KORNIA_CHECK_LAF(laf)
det = get_laf_scale(laf)
@@ -203,6 +211,7 @@ def ellipse_to_laf(ells: Tensor) -> Tensor:
Example:
>>> input = torch.ones(1, 10, 5) # BxNx5
>>> output = ellipse_to_laf(input) # BxNx2x3
+
"""
KORNIA_CHECK_SHAPE(ells, ["B", "N", "5"])
B, N, _ = ells.shape
@@ -238,6 +247,7 @@ def laf_to_boundary_points(LAF: Tensor, n_pts: int = 50) -> Tensor:
Returns:
tensor of boundary points LAF: :math:`(B, N, n_pts, 2)`
+
"""
KORNIA_CHECK_LAF(LAF)
B, N, _, _ = LAF.size()
@@ -274,6 +284,7 @@ def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0) -> Tuple[List[int], List[
plt.imshow(kornia.utils.tensor_to_image(img[img_idx]))
plt.plot(x, y, 'r')
plt.show()
+
"""
# TODO: Refactor doctest
KORNIA_CHECK_LAF(LAF)
@@ -300,6 +311,7 @@ def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
Returns:
the denormalized LAF: :math:`(B, N, 2, 3)`, scale in pixels
+
"""
KORNIA_CHECK_LAF(LAF)
_, _, h, w = images.size()
@@ -329,6 +341,7 @@ def normalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
Returns:
the denormalized LAF: :math:`(B, N, 2, 3)`, scale in image percentage (0, 1)
+
"""
KORNIA_CHECK_LAF(LAF)
_, _, h, w = images.size()
@@ -351,6 +364,7 @@ def generate_patch_grid_from_normalized_LAF(img: Tensor, LAF: Tensor, PS: int =
Returns:
grid :math:`(B*N, PS, PS, 2)`
+
"""
KORNIA_CHECK_LAF(LAF)
B, N, _, _ = LAF.size()
@@ -381,6 +395,7 @@ def extract_patches_simple(
Returns:
patches with shape :math:`(B, N, CH, PS,PS)`.
+
"""
KORNIA_CHECK_LAF(laf)
if normalize_lafs_before_extraction:
@@ -416,6 +431,7 @@ def extract_patches_from_pyramid(
Returns:
patches with shape :math:`(B, N, CH, PS,PS)`.
+
"""
KORNIA_CHECK_LAF(laf)
if normalize_lafs_before_extraction:
@@ -464,6 +480,7 @@ def laf_is_inside_image(laf: Tensor, images: Tensor, border: int = 0) -> Tensor:
Returns:
mask with shape :math:`(B, N)`.
+
"""
KORNIA_CHECK_LAF(laf)
_, _, h, w = images.size()
@@ -484,6 +501,7 @@ def laf_to_three_points(laf: Tensor) -> Tensor:
Returns:
threepts :math:`(B, N, 2, 3)`.
+
"""
KORNIA_CHECK_LAF(laf)
three_pts = stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)
@@ -500,6 +518,7 @@ def laf_from_three_points(threepts: Tensor) -> Tensor:
Returns:
laf :math:`(B, N, 2, 3)`.
+
"""
laf = stack([threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1)
return laf
@@ -547,6 +566,7 @@ def perspective_transform_lafs(trans_01: Tensor, lafs_1: Tensor) -> Tensor:
>>> trans_01.shape
torch.Size([2, 3, 3])
>>> lafs_0 = perspective_transform_lafs(trans_01, lafs_1) # BxNx2x3
+
"""
KORNIA_CHECK_LAF(lafs_1)
if not torch.is_tensor(trans_01):
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index cf4913a38..edc08a72d 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -33,6 +33,7 @@ class OnnxLightGlue:
are ``'disk'``, ``'superpoint'``, ``'disk_fp16'``, and ``'superpoint_fp16'``. `Note that FP16 requires CUDA.`
Defaults to ``'disk_fp16'`` if ``device`` is CUDA, and ``'disk'`` if CPU.
device: Device to run inference on.
+
"""
MODEL_URLS: ClassVar[dict[str, str]] = {
@@ -108,6 +109,7 @@ class OnnxLightGlue:
``matches`` (`int64`): :math:`(S, 2)`
``scores`` (`float32`): :math:`(S)`
+
"""
# Input validation.
for key in self.required_data_keys:
diff --git a/kornia/feature/lightglue_onnx/utils/download.py b/kornia/feature/lightglue_onnx/utils/download.py
index ca8fc4267..f12c49fc9 100644
--- a/kornia/feature/lightglue_onnx/utils/download.py
+++ b/kornia/feature/lightglue_onnx/utils/download.py
@@ -39,6 +39,7 @@ def download_onnx_from_url(
Example:
>>> model = download_onnx_from_url('https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/disk_lightglue_fused_fp16.onnx')
+
"""
if model_dir is None:
hub_dir = get_dir()
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 3ad94d124..766f7ac13 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -73,6 +73,7 @@ class LoFTR(Module):
>>> input = {"image0": img1, "image1": img2}
>>> loftr = LoFTR('outdoor')
>>> out = loftr(input)
+
"""
def __init__(self, pretrained: Optional[str] = "outdoor", config: dict[str, Any] = default_cfg) -> None:
@@ -101,8 +102,7 @@ class LoFTR(Module):
self.eval()
def forward(self, data: dict[str, Tensor]) -> dict[str, Tensor]:
- """
- Args:
+ """Args:
data: dictionary containing the input data in the following format:
Keyword Args:
@@ -116,6 +116,7 @@ class LoFTR(Module):
- ``keypoints1``, matching keypoints from image1 :math:`(NC, 2)`.
- ``confidence``, confidence score [0, 1] :math:`(NC)`.
- ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`.
+
"""
# 1. Local Feature CNN
_data: dict[str, Tensor | int | torch.Size] = {
diff --git a/kornia/feature/loftr/loftr_module/linear_attention.py b/kornia/feature/loftr/loftr_module/linear_attention.py
index bf240bdba..118395af4 100644
--- a/kornia/feature/loftr/loftr_module/linear_attention.py
+++ b/kornia/feature/loftr/loftr_module/linear_attention.py
@@ -1,6 +1,7 @@
"""Linear Transformer proposed in "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention"
Modified from: https://github.com/idiap/fast-
-transformers/blob/master/fast_transformers/attention/linear_attention.py."""
+transformers/blob/master/fast_transformers/attention/linear_attention.py.
+"""
from typing import Optional
@@ -35,8 +36,10 @@ class LinearAttention(Module):
values: [N, S, H, D]
q_mask: [N, L]
kv_mask: [N, S]
+
Returns:
queried_values: (N, L, H, D)
+
"""
Q = self.feature_map(queries)
K = self.feature_map(keys)
@@ -79,8 +82,10 @@ class FullAttention(Module):
values: [N, S, H, D]
q_mask: [N, L]
kv_mask: [N, S]
+
Returns:
queried_values: (N, L, H, D)
+
"""
# Compute the unnormalized attention and apply the masks
QK = torch.einsum("nlhd,nshd->nlsh", queries, keys)
diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.py
index d33be6ec1..8a1d24bff 100644
--- a/kornia/feature/loftr/loftr_module/transformer.py
+++ b/kornia/feature/loftr/loftr_module/transformer.py
@@ -37,12 +37,12 @@ class LoFTREncoderLayer(Module):
def forward(
self, x: Tensor, source: Tensor, x_mask: Optional[Tensor] = None, source_mask: Optional[Tensor] = None
) -> Tensor:
- """
- Args:
- x: [N, L, C]
- source: [N, S, C]
- x_mask: [N, L] (optional)
- source_mask: [N, S] (optional)
+ """Args:
+ x: [N, L, C]
+ source: [N, S, C]
+ x_mask: [N, L] (optional)
+ source_mask: [N, S] (optional)
+
"""
bs = x.size(0)
query, key, value = x, source, source
@@ -84,12 +84,12 @@ class LocalFeatureTransformer(Module):
def forward(
self, feat0: Tensor, feat1: Tensor, mask0: None | Tensor = None, mask1: None | Tensor = None
) -> tuple[Tensor, Tensor]:
- """
- Args:
- feat0: [N, L, C]
- feat1: [N, S, C]
- mask0: [N, L] (optional)
- mask1: [N, S] (optional)
+ """Args:
+ feat0: [N, L, C]
+ feat1: [N, S, C]
+ mask0: [N, L] (optional)
+ mask1: [N, S] (optional)
+
"""
if self.d_model != feat0.size(2):
msg = "the feature number of src and transformer must be equal"
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index 404f9b49e..ee0a50922 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -52,6 +52,7 @@ def compute_max_candidates(p_m0: Tensor, p_m1: Tensor) -> Tensor:
Args:
p_m0, p_m1 (torch.Tensor): padded masks
+
"""
h0s, w0s = p_m0.sum(1).max(-1)[0], p_m0.sum(-1).max(-1)[0]
h1s, w1s = p_m1.sum(1).max(-1)[0], p_m1.sum(-1).max(-1)[0]
@@ -94,8 +95,7 @@ class CoarseMatching(Module):
mask_c0: Optional[Tensor] = None,
mask_c1: Optional[Tensor] = None,
) -> None:
- """
- Args:
+ """Args:
feat0 (torch.Tensor): [N, L, C]
feat1 (torch.Tensor): [N, S, C]
data (dict)
@@ -111,6 +111,7 @@ class CoarseMatching(Module):
'mkpts1_c' (torch.Tensor): [M, 2],
'mconf' (torch.Tensor): [M]}
NOTE: M' != M during training.
+
"""
_, L, S, _ = feat_c0.size(0), feat_c0.size(1), feat_c1.size(1), feat_c0.size(2)
@@ -151,10 +152,10 @@ class CoarseMatching(Module):
@torch.no_grad()
def get_coarse_match(self, conf_matrix: Tensor, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
- """
- Args:
+ """Args:
conf_matrix (torch.Tensor): [N, L, S]
data (dict): with keys ['hw0_i', 'hw1_i', 'hw0_c', 'hw1_c']
+
Returns:
coarse_matches (dict): {
'b_ids' (torch.Tensor): [M'],
@@ -165,6 +166,7 @@ class CoarseMatching(Module):
'mkpts0_c' (torch.Tensor): [M, 2],
'mkpts1_c' (torch.Tensor): [M, 2],
'mconf' (torch.Tensor): [M]}
+
"""
axes_lengths = {
"h0c": data["hw0_c"][0],
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index a6638e669..bc02e1642 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -17,8 +17,7 @@ class FineMatching(Module):
super().__init__()
def forward(self, feat_f0: Tensor, feat_f1: Tensor, data: dict[str, Any]) -> None:
- """
- Args:
+ """Args:
feat0 (torch.Tensor): [M, WW, C]
feat1 (torch.Tensor): [M, WW, C]
data (dict)
@@ -27,6 +26,7 @@ class FineMatching(Module):
'expec_f' (torch.Tensor): [M, 3],
'mkpts0_f' (torch.Tensor): [M, 2],
'mkpts1_f' (torch.Tensor): [M, 2]}
+
"""
M, WW, C = feat_f0.shape
W = int(math.sqrt(WW))
diff --git a/kornia/feature/loftr/utils/geometry.py b/kornia/feature/loftr/utils/geometry.py
index 089b6c41c..d5e8ff541 100644
--- a/kornia/feature/loftr/utils/geometry.py
+++ b/kornia/feature/loftr/utils/geometry.py
@@ -19,9 +19,11 @@ def warp_kpts(
T_0to1: [N, 3, 4],
K0: [N, 3, 3],
K1: [N, 3, 3],
+
Returns:
calculable_mask: [N, L]
warped_keypoints0: [N, L, 2] <x0_hat, y1_hat>
+
"""
kpts0_long = kpts0.round().long()
diff --git a/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.py
index 389a3e03d..ea5c7ee72 100644
--- a/kornia/feature/loftr/utils/position_encoding.py
+++ b/kornia/feature/loftr/utils/position_encoding.py
@@ -12,13 +12,13 @@ class PositionEncodingSine(Module):
pe: Tensor
def __init__(self, d_model: int, max_shape: Tuple[int, int] = (256, 256), temp_bug_fix: bool = True) -> None:
- """
- Args:
- max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels
- temp_bug_fix (bool): As noted in this [issue](https://github.com/zju3dv/LoFTR/issues/41),
- the original implementation of LoFTR includes a bug in the pos-enc impl, which has little impact
- on the final performance. For now, we keep both impls for backward compatibility.
- We will remove the buggy impl after re-training all variants of our released models.
+ """Args:
+ max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels
+ temp_bug_fix (bool): As noted in this [issue](https://github.com/zju3dv/LoFTR/issues/41),
+ the original implementation of LoFTR includes a bug in the pos-enc impl, which has little impact
+ on the final performance. For now, we keep both impls for backward compatibility.
+ We will remove the buggy impl after re-training all variants of our released models.
+
"""
super().__init__()
self.d_model = d_model
@@ -60,9 +60,9 @@ class PositionEncodingSine(Module):
self.pe = self._create_position_encoding(max_shape).to(self.pe.device)
def forward(self, x: Tensor) -> Tensor:
- """
- Args:
- x: [N, C, H, W]
+ """Args:
+ x: [N, C, H, W]
+
"""
if x.size(2) > self.pe.size(2) or x.size(3) > self.pe.size(3):
max_shape = (max(x.size(2), self.pe.size(2)), max(x.size(3), self.pe.size(3)))
diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.py
index f8f164bf4..d931e0596 100644
--- a/kornia/feature/loftr/utils/supervision.py
+++ b/kornia/feature/loftr/utils/supervision.py
@@ -24,8 +24,7 @@ def mask_pts_at_padded_regions(grid_pt: Tensor, mask: Tensor) -> Tensor:
@torch.no_grad()
def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
- """
- Update:
+ """Update:
data (dict): {
"conf_matrix_gt": [N, hw0, hw1],
'spv_b_ids': [M]
@@ -35,9 +34,10 @@ def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
'spv_pt1_i': [N, hw1, 2], in original image resolution
}
- NOTE:
+ Note:
- for scannet dataset, there're 3 kinds of resolution {i, c, f}
- for megadepth dataset, there're 4 kinds of resolution {i, i_resize, c, f}
+
"""
# 1. misc
device = data["image0"].device
@@ -119,10 +119,9 @@ def compute_supervision_coarse(data: dict[str, Any], config: dict[str, Any]) ->
# Fine-Level supervision
@torch.no_grad()
def spvs_fine(data: dict[str, Any], config: dict[str, Any]) -> None:
- """
- Update:
- data (dict):{
- "expec_f_gt": [M, 2]}
+ """Update:
+ data (dict):{
+ "expec_f_gt": [M, 2]}
"""
# 1. misc
# w_pt0_i, pt1_i = data.pop('spv_w_pt0_i'), data.pop('spv_pt1_i')
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 4e383ca87..3332ea81c 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -36,6 +36,7 @@ def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
dm: Tensor containing the distances from each descriptor in desc1
to each descriptor in desc2, shape of :math:`(B1, B2)`.
+
"""
if dm_ is None:
dm = _cdist(desc1, desc2)
@@ -51,6 +52,7 @@ def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(0, 1)`.
- Long 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)
idxs = torch.empty(0, 2, device=dm.device, dtype=torch.long)
@@ -71,6 +73,7 @@ def match_nn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple
Returns:
- Descriptor distance of matching descriptors, shape of :math:`(B1, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -98,6 +101,7 @@ def match_mnn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tupl
- Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,
where 0 <= B3 <= min(B1, B2)
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -138,6 +142,7 @@ def match_snn(desc1: Tensor, desc2: Tensor, th: float = 0.8, dm: Optional[Tensor
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
where 0 <= B3 <= B1.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -175,6 +180,7 @@ def match_smnn(desc1: Tensor, desc2: Tensor, th: float = 0.95, dm: Optional[Tens
- Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where 0 <= B3 <= B1.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -245,6 +251,7 @@ def match_fginn(
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
where 0 <= B3 <= B1.
+
"""
KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
@@ -297,6 +304,7 @@ class DescriptorMatcher(Module):
Args:
match_mode: type of matching, can be `nn`, `snn`, `mnn`, `smnn`.
th: threshold on distance ratio, or other quality measure.
+
"""
def __init__(self, match_mode: str = "snn", th: float = 0.8) -> None:
@@ -309,8 +317,7 @@ class DescriptorMatcher(Module):
self.th = th
def forward(self, desc1: Tensor, desc2: Tensor) -> Tuple[Tensor, Tensor]:
- """
- Args:
+ """Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
@@ -318,6 +325,7 @@ class DescriptorMatcher(Module):
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
+
"""
if self.match_mode == "nn":
out = match_nn(desc1, desc2)
@@ -371,6 +379,7 @@ class DescriptorMatcherWithSteerer(Module):
... )
>>> # print(f"{idxs.shape[0]} tentative matches with steered DeDoDe")
>>> # print(f"at rotation of {num_rot * 360 / steerer_order} degrees")
+
"""
def __init__(
@@ -416,8 +425,7 @@ class DescriptorMatcherWithSteerer(Module):
normalize: bool = False,
subset_size: Optional[int] = None,
) -> Tuple[Tensor, Tensor, Optional[int]]:
- """
- Args:
+ """Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
normalize: bool to decide whether to normalize descriptors to unit norm.
@@ -431,6 +439,7 @@ class DescriptorMatcherWithSteerer(Module):
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`).
+
"""
rot1to2 = None
@@ -483,6 +492,7 @@ class GeometryAwareDescriptorMatcher(Module):
Args:
match_mode: type of matching, can be `fginn`.
th: threshold on distance ratio, or other quality measure.
+
"""
known_modes: ClassVar[List[str]] = ["fginn", "adalam"]
@@ -496,8 +506,7 @@ class GeometryAwareDescriptorMatcher(Module):
self.params = params or {}
def forward(self, desc1: Tensor, desc2: Tensor, lafs1: Tensor, lafs2: Tensor) -> Tuple[Tensor, Tensor]:
- """
- Args:
+ """Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
desc2: Batch of descriptors of a shape :math:`(B2, D)`.
lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.
@@ -507,6 +516,7 @@ class GeometryAwareDescriptorMatcher(Module):
- Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
+
"""
if self.match_mode == "fginn":
params = _get_default_fginn_params()
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 271304dfb..669dd31a3 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -64,6 +64,7 @@ class MKDGradients(nn.Module):
>>> patches = torch.rand(23, 1, 32, 32)
>>> gradient = MKDGradients()
>>> g = gradient(patches) # 23x2x32x32
+
"""
def __init__(self) -> None:
@@ -109,6 +110,7 @@ class VonMisesKernel(nn.Module):
... 0.268285,
... 0.21979234])
>>> emb = vm(oris) # 23x7x32x32
+
"""
def __init__(self, patch_size: int, coeffs: Union[List[Union[float, int]], Tuple[Union[float, int], ...]]) -> None:
@@ -176,6 +178,7 @@ class EmbedGradients(nn.Module):
>>> emb_grads = EmbedGradients(patch_size=32,
... relative=False)
>>> emb = emb_grads(grads) # 23x7x32x32
+
"""
def __init__(self, patch_size: int = 32, relative: bool = False) -> None:
@@ -269,6 +272,7 @@ class ExplicitSpacialEncoding(nn.Module):
... do_gmask=True,
... do_l2=True)
>>> desc = ese(emb_ori) # 23x175x32x32
+
"""
def __init__(
@@ -382,6 +386,7 @@ class Whitening(nn.Module):
... keval=40,
... t=0.7)
>>> wdescs = whitening(descs) # 23x128
+
"""
def __init__(
@@ -490,6 +495,7 @@ class MKDDescriptor(nn.Module):
... training_set='liberty',
... output_dims=128)
>>> desc = mkd(patches) # 23x128
+
"""
def __init__(
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index d56f7f447..951e84685 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -19,13 +19,13 @@ class PassLAF(nn.Module):
"""Dummy module to use instead of local feature orientation or affine shape estimator."""
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
- """
- Args:
+ """Args:
laf: :math:`(B, N, 2, 3)`
img: :math:`(B, 1, H, W)`
Returns:
LAF, unchanged :math:`(B, N, 2, 3)`
+
"""
return laf
@@ -39,6 +39,7 @@ class PatchDominantGradientOrientation(nn.Module):
patch_size: size of the (square) input patch.
num_angular_bins: number of histogram bins.
eps: for safe division, and arctan.
+
"""
def __init__(self, patch_size: int = 32, num_angular_bins: int = 36, eps: float = 1e-8) -> None:
@@ -59,12 +60,12 @@ class PatchDominantGradientOrientation(nn.Module):
)
def forward(self, patch: torch.Tensor) -> torch.Tensor:
- """
- Args:
+ """Args:
patch: :math:`(B, 1, H, W)`
Returns:
angle in radians: :math:`(B)`
+
"""
KORNIA_CHECK_SHAPE(patch, ["B", "1", "H", "W"])
_, CH, W, H = patch.size()
@@ -130,6 +131,7 @@ class OriNet(nn.Module):
>>> input = torch.rand(16, 1, 32, 32)
>>> orinet = OriNet()
>>> angle = orinet(input) # 16
+
"""
def __init__(self, pretrained: bool = False, eps: float = 1e-8) -> None:
@@ -175,12 +177,12 @@ class OriNet(nn.Module):
return (x - mp.detach()) / (sp.detach() + eps)
def forward(self, patch: torch.Tensor) -> torch.Tensor:
- """
- Args:
+ """Args:
patch: :math:`(B, 1, H, W)`
Returns:
angle in radians: :math:`(B)`
+
"""
xy = self.features(self._normalize_input(patch)).view(-1, 2)
angle = torch.atan2(xy[:, 0] + 1e-8, xy[:, 1] + self.eps)
@@ -198,6 +200,7 @@ class LAFOrienter(nn.Module):
num_angular_bins:
angle_detector: Patch orientation estimator, e.g. :class:`~kornia.feature.PatchDominantGradientOrientation`
or OriNet.
+
""" # pylint: disable
def __init__(
@@ -216,13 +219,13 @@ class LAFOrienter(nn.Module):
return f"{self.__class__.__name__}(patch_size={self.patch_size}, angle_detector={self.angle_detector})"
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
- """
- Args:
+ """Args:
laf: :math:`(B, N, 2, 3)`
img: :math:`(B, 1, H, W)`
Returns:
LAF_out: :math:`(B, N, 2, 3)`
+
"""
KORNIA_CHECK_LAF(laf)
KORNIA_CHECK_SHAPE(img, ["B", "C", "H", "W"])
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 7f263182e..0724d023c 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -73,6 +73,7 @@ def harris_response(
[0.0020, 0.0040, 0.0029, 0.0000, 0.0029, 0.0040, 0.0020],
[0.0039, 0.0065, 0.0040, 0.0000, 0.0040, 0.0065, 0.0039],
[0.0012, 0.0039, 0.0020, 0.0000, 0.0020, 0.0039, 0.0012]]]])
+
"""
# TODO: Recompute doctest
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -153,6 +154,7 @@ def gftt_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[Ten
[0.0194, 0.0339, 0.0497, 0.0000, 0.0497, 0.0339, 0.0194],
[0.0334, 0.0575, 0.0339, 0.0000, 0.0339, 0.0575, 0.0334],
[0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155]]]])
+
"""
# TODO: Recompute doctest
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -231,6 +233,7 @@ def hessian_response(input: Tensor, grads_mode: str = "sobel", sigmas: Optional[
[0.0194, 0.0339, 0.0497, 0.0000, 0.0497, 0.0339, 0.0194],
[0.0334, 0.0575, 0.0339, 0.0000, 0.0339, 0.0575, 0.0334],
[0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155]]]])
+
"""
# TODO: Recompute doctest
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -263,6 +266,7 @@ def dog_response(input: Tensor) -> Tensor:
Return:
the response map per channel with shape :math:`(B, C, D-1, H, W)`.
+
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "L", "H", "W"])
@@ -281,6 +285,7 @@ def dog_response_single(input: Tensor, sigma1: float = 1.0, sigma2: float = 1.6)
Return:
the response map per channel with shape :math:`(B, C, H, W)`.
+
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
ks1 = _get_kernel_size(sigma1)
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index e3fcefaa3..84553cd8e 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -25,6 +25,7 @@ def _scale_index_to_scale(max_coords: Tensor, sigmas: Tensor, num_levels: int) -
Returns:
tensor [BxNx3].
+
"""
# depth (scale) in coord_max is represented as (float) index, not the scale yet.
# we will interpolate the scale using pytorch.grid_sample function
@@ -73,6 +74,7 @@ class ScaleSpaceDetector(Module):
which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
minima_are_also_good: if True, then both response function minima and maxima are detected
Useful for symmetric response functions like DoG or Hessian. Default is False
+
"""
def __init__(
@@ -228,6 +230,7 @@ class ScaleSpaceDetector(Module):
Returns:
lafs: shape [BxNx2x3]. Detected local affine frames.
responses: shape [BxNx1]. Response function values for corresponding lafs
+
"""
responses, lafs = self.detect(img, self.num_features, mask)
lafs = self.aff(lafs, img)
@@ -269,6 +272,7 @@ class MultiResolutionDetector(Module):
which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,
which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
+
"""
def __init__(
@@ -399,6 +403,7 @@ class MultiResolutionDetector(Module):
Returns:
lafs: shape [1xNx2x3]. Detected local affine frames.
responses: shape [1xNx1]. Response function values for corresponding lafs
+
"""
KORNIA_CHECK_SHAPE(img, ["1", "C", "H", "W"])
responses, lafs = self.detect(img, mask)
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index d9deccb78..fa5d77300 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -25,6 +25,7 @@ def get_sift_pooling_kernel(ksize: int = 25) -> Tensor:
Returns:
the pooling kernel with shape :math:`(ksize, ksize)`.
+
"""
ks_2: float = float(ksize) / 2.0
xc2 = ks_2 - (torch.arange(ksize).float() + 0.5 - ks_2).abs()
@@ -41,6 +42,7 @@ def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tup
Returns:
ksize, stride, pad.
+
"""
ksize: int = 2 * int(patch_size / (num_spatial_bins + 1))
stride: int = patch_size // num_spatial_bins
@@ -76,6 +78,7 @@ class SIFTDescriptor(Module):
>>> input = torch.rand(23, 1, 32, 32)
>>> SIFT = SIFTDescriptor(32, 8, 4)
>>> descs = SIFT(input) # 23x128
+
"""
def __repr__(self) -> str:
@@ -205,6 +208,7 @@ class DenseSIFTDescriptor(Module):
>>> input = torch.rand(2, 1, 200, 300)
>>> SIFT = DenseSIFTDescriptor()
>>> descs = SIFT(input) # 2x128x194x294
+
"""
def __repr__(self) -> str:
diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.py
index a2721fd25..7508bd086 100644
--- a/kornia/feature/sold2/backbones.py
+++ b/kornia/feature/sold2/backbones.py
@@ -31,6 +31,7 @@ class HourglassBackbone(Module):
num_stacks: number of hourglass modules stacked together.
num_blocks: number of layers in each residual block.
num_classes: number of heads for the output of a hourglass module.
+
"""
def __init__(
@@ -257,8 +258,10 @@ class SuperpointDecoder(Module):
Args:
input_feat_dim: channel size of the input features.
+
Returns:
the junction heatmap, with shape (B, H, W).
+
"""
def __init__(self, input_feat_dim: int = 128, grid_size: int = 8) -> None:
@@ -286,8 +289,10 @@ class PixelShuffleDecoder(Module):
input_feat_dim: channel size of the input features.
num_upsample: how many upsamples are performed.
output_channel: number of output channels.
+
Returns:
the (B, 1, H, W) line heatmap.
+
"""
def __init__(self, input_feat_dim: int = 128, num_upsample: int = 2, output_channel: int = 2) -> None:
@@ -350,8 +355,10 @@ class SuperpointDescriptor(Module):
Args:
input_feat_dim: channel size of the input features.
+
Returns:
the semi-dense descriptors with shape (B, 128, H/4, W/4).
+
"""
def __init__(self, input_feat_dim: int = 128) -> None:
@@ -375,11 +382,13 @@ class SOLD2Net(Module):
Args:
model_cfg: the configuration as a Dict.
+
Returns:
a Dict with the following values:
junctions: heatmap of junctions.
heatmap: line heatmap.
descriptors: semi-dense descriptors.
+
"""
def __init__(self, model_cfg: Dict[str, Any]) -> None:
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index 1b0ca798b..f47e5aefb 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -41,6 +41,7 @@ class SOLD2(Module):
>>> desc1 = outputs["dense_desc"][0]
>>> desc2 = outputs["dense_desc"][1]
>>> matches = sold2.match(line_seg1, line_seg2, desc1[None], desc2[None])
+
"""
def __init__(self, pretrained: bool = True, config: Optional[DetectorCfg] = None) -> None:
@@ -76,8 +77,7 @@ class SOLD2(Module):
self.line_matcher = WunschLineMatcher(self.config.line_matcher_cfg)
def forward(self, img: Tensor) -> Dict[str, Any]:
- """
- Args:
+ """Args:
img: batched images with shape :math:`(B, 1, H, W)`.
Return:
@@ -85,6 +85,7 @@ class SOLD2(Module):
- ``junction_heatmap``: raw junction heatmap of shape :math:`(B, H, W)`.
- ``line_heatmap``: raw line heatmap of shape :math:`(B, H, W)`.
- ``dense_desc``: the semi-dense descriptor map of shape :math:`(B, 128, H/4, W/4)`.
+
"""
KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
outputs = {}
@@ -114,9 +115,11 @@ class SOLD2(Module):
Args:
line_seg1, line_seg2: list of line segments in two images, with shape [num_lines, 2, 2].
desc1, desc2: semi-dense descriptor maps of the images, with shape [1, 128, H/4, W/4].
+
Returns:
A np.array of size [num_lines1] indicating the index in line_seg2 of the matched line,
for each line in line_seg1. -1 means that the line is not matched.
+
"""
return self.line_matcher(line_seg1, line_seg2, desc1, desc2)
@@ -308,6 +311,7 @@ def keypoints_to_grid(keypoints: Tensor, img_size: Tuple[int, int]) -> Tensor:
Args:
keypoints: a tensor [N, 2] of N keypoints (ij coordinates convention).
img_size: the original image size (H, W)
+
"""
KORNIA_CHECK_SHAPE(keypoints, ["N", "2"])
n_points = len(keypoints)
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index e826fce9d..27c9e0599 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -35,6 +35,7 @@ class SOLD2_detector(Module):
>>> img = torch.rand(1, 1, 512, 512)
>>> sold2_detector = SOLD2_detector()
>>> line_segments = sold2_detector(img)["line_segments"]
+
"""
def __init__(self, pretrained: bool = True, config: Optional[DetectorCfg] = None) -> None:
@@ -77,14 +78,14 @@ class SOLD2_detector(Module):
return state_dict
def forward(self, img: Tensor) -> Dict[str, Any]:
- """
- Args:
+ """Args:
img: batched images with shape :math:`(B, 1, H, W)`.
Return:
- ``line_segments``: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`.
- ``junction_heatmap``: raw junction heatmap of shape :math:`(B, H, W)`.
- ``line_heatmap``: raw line heatmap of shape :math:`(B, H, W)`.
+
"""
KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
outputs = {}
@@ -132,6 +133,7 @@ class LineSegmentDetectionModule:
>>> module = LineSegmentDetectionModule(config)
>>> junctions, heatmap = torch.rand(10, 2), torch.rand(256, 256)
>>> line_map, junctions, _ = module.detect(junctions, heatmap)
+
"""
def __init__(self, config: Optional[LineDetectorCfg] = None) -> None:
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 9a1b15ab6..dbf9ae988 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -27,6 +27,7 @@ class SOSNet(nn.Module):
>>> input = torch.rand(8, 1, 32, 32)
>>> sosnet = SOSNet()
>>> descs = sosnet(input) # 8x128
+
"""
patch_size = 32
diff --git a/kornia/feature/steerers.py b/kornia/feature/steerers.py
index e2cca1254..ac7150ad0 100644
--- a/kornia/feature/steerers.py
+++ b/kornia/feature/steerers.py
@@ -17,6 +17,7 @@ class DiscreteSteerer(Module):
>>> steerer = DiscreteSteerer(generator)
>>> # steer 3 times:
>>> steered_desc = steerer.steer_descriptions(desc, steerer_power=3, normalize=True)
+
"""
def __init__(self, generator: Tensor) -> None:
@@ -57,6 +58,7 @@ class DiscreteSteerer(Module):
Returns:
The pretrained model.
+
"""
descriptor_dim = 256
if generator_type == "C4":
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index b70548c9e..9485fa324 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -32,6 +32,7 @@ class TFeat(nn.Module):
>>> input = torch.rand(16, 1, 32, 32)
>>> tfeat = TFeat()
>>> descs = tfeat(input) # 16x128
+
"""
patch_size = 32
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index 9caaef0c0..00c354e02 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -19,8 +19,7 @@ def _bilateral_blur(
border_type: str = "reflect",
color_distance_type: str = "l1",
) -> Tensor:
- "Single implementation for both Bilateral Filter and Joint Bilateral Filter"
-
+ """Single implementation for both Bilateral Filter and Joint Bilateral Filter"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
if guidance is not None:
@@ -105,6 +104,7 @@ def bilateral_blur(
>>> output = bilateral_blur(input, (3, 3), 0.1, (1.5, 1.5))
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
return _bilateral_blur(input, None, kernel_size, sigma_color, sigma_space, border_type, color_distance_type)
@@ -150,6 +150,7 @@ def joint_bilateral_blur(
>>> output = joint_bilateral_blur(input, guidance, (3, 3), 0.1, (1.5, 1.5))
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
return _bilateral_blur(input, guidance, kernel_size, sigma_color, sigma_space, border_type, color_distance_type)
@@ -216,6 +217,7 @@ class BilateralBlur(_BilateralBlur):
>>> output = blur(input)
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
def forward(self, input: Tensor) -> Tensor:
@@ -258,6 +260,7 @@ class JointBilateralBlur(_BilateralBlur):
>>> output = blur(input, guidance)
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
def forward(self, input: Tensor, guidance: Tensor) -> Tensor:
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index 10e77a8af..c9a81022c 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -44,6 +44,7 @@ def box_blur(
>>> output = box_blur(input, (3, 3)) # 2x4x5x7
>>> output.shape
torch.Size([2, 4, 5, 7])
+
"""
KORNIA_CHECK_IS_TENSOR(input)
@@ -93,6 +94,7 @@ class BoxBlur(Module):
>>> output = blur(input) # 2x4x5x7
>>> output.shape
torch.Size([2, 4, 5, 7])
+
"""
def __init__(
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index 9e9e38d0d..76dd21d37 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -48,6 +48,7 @@ class BlurPool2D(Module):
tensor([[[[0.3125, 0.0625, 0.0000],
[0.0625, 0.3750, 0.0625],
[0.0000, 0.0625, 0.3125]]]])
+
"""
def __init__(self, kernel_size: tuple[int, int] | int, stride: int = 2) -> None:
@@ -93,6 +94,7 @@ class MaxBlurPool2D(Module):
>>> seq(input)
tensor([[[[0.5625, 0.3125],
[0.3125, 0.8750]]]])
+
"""
def __init__(
@@ -167,6 +169,7 @@ def blur_pool2d(input: Tensor, kernel_size: tuple[int, int] | int, stride: int =
tensor([[[[0.3125, 0.0625, 0.0000],
[0.0625, 0.3750, 0.0625],
[0.0000, 0.0625, 0.3125]]]])
+
"""
kernel = get_pascal_kernel_2d(kernel_size, norm=True, device=input.device, dtype=input.dtype).repeat(
(input.size(1), 1, 1, 1)
@@ -200,6 +203,7 @@ def max_blur_pool2d(
>>> max_blur_pool2d(input, 3)
tensor([[[[0.5625, 0.3125],
[0.3125, 0.8750]]]])
+
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -253,6 +257,7 @@ def edge_aware_blur_pool2d(
Returns:
The blurred tensor of shape :math:`(B, C, H, W)`.
+
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(edge_threshold > 0.0, f"edge threshold should be positive, but got '{edge_threshold}'")
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index ff4f315b7..75afef4ac 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -52,6 +52,7 @@ def canny(
torch.Size([5, 1, 4, 4])
>>> edges.shape
torch.Size([5, 1, 4, 4])
+
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -168,6 +169,7 @@ class Canny(Module):
torch.Size([5, 1, 4, 4])
>>> edges.shape
torch.Size([5, 1, 4, 4])
+
"""
# TODO: Handle multiple inputs and outputs models later
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 44063febb..36ced0e68 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -177,6 +177,7 @@ class DexiNed(Module):
>>> out = net(img)
>>> out.shape
torch.Size([1, 1, 320, 320])
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]
diff --git a/kornia/filters/dissolving.py b/kornia/filters/dissolving.py
index 154ac8240..2a3047a2e 100644
--- a/kornia/filters/dissolving.py
+++ b/kornia/filters/dissolving.py
@@ -98,6 +98,7 @@ class StableDiffusionDissolving(ImageModule):
Args:
version: the version of the stable diffusion model.
**kwargs: additional arguments for `.from_pretrained`.
+
"""
def __init__(self, version: str = "2.1", **kwargs: Any):
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index bf7372e43..470297efd 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -83,6 +83,7 @@ def filter2d(
[0., 5., 5., 5., 0.],
[0., 5., 5., 5., 0.],
[0., 0., 0., 0., 0.]]]])
+
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -184,6 +185,7 @@ def filter2d_separable(
[0., 5., 5., 5., 0.],
[0., 5., 5., 5., 0.],
[0., 0., 0., 0., 0.]]]])
+
"""
out_x = filter2d(input, kernel_x[..., None, :], border_type, normalized, padding)
out = filter2d(out_x, kernel_y[..., None], border_type, normalized, padding)
@@ -249,6 +251,7 @@ def filter3d(input: Tensor, kernel: Tensor, border_type: str = "replicate", norm
[0., 5., 5., 5., 0.],
[0., 5., 5., 5., 0.],
[0., 0., 0., 0., 0.]]]]])
+
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "D", "H", "W"])
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index e4b0737aa..17e4af560 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -49,6 +49,7 @@ def gaussian_blur2d(
>>> output = gaussian_blur2d(input, (3, 3), torch.tensor([[1.5, 1.5]]))
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
KORNIA_CHECK_IS_TENSOR(input)
@@ -99,6 +100,7 @@ class GaussianBlur2d(Module):
>>> output = gauss(input) # 2x4x5x5
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
def __init__(
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index b9a2570ac..0e4d40f72 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -144,8 +144,8 @@ def guided_blur(
>>> output = guided_blur(guidance, input, 3, 0.1)
>>> output.shape
torch.Size([2, 4, 5, 5])
- """
+ """
KORNIA_CHECK_IS_TENSOR(guidance)
KORNIA_CHECK_SHAPE(guidance, ["B", "C", "H", "W"])
if input is not guidance:
@@ -190,6 +190,7 @@ class GuidedBlur(Module):
>>> output = blur(guidance, input)
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
def __init__(
diff --git a/kornia/filters/in_range.py b/kornia/filters/in_range.py
index 3c8a67265..cd6c2480d 100644
--- a/kornia/filters/in_range.py
+++ b/kornia/filters/in_range.py
@@ -44,7 +44,7 @@ def in_range(
A binary mask :math:`(*, 1, H, W)` of input indicating whether elements are within the range
or filtered input image :math:`(*, *, H, W)`.
- Raises
+ Raises:
ValueError: If the shape of `lower`, `upper`, and `input` image channels do not match.
.. note::
@@ -88,6 +88,7 @@ def in_range(
[[[0., 0., 0.],
[1., 0., 0.],
[0., 0., 1.]]]])
+
"""
input_shape = input.shape
@@ -160,6 +161,7 @@ class InRange(Module):
tensor([[[[1., 1., 0.],
[0., 0., 0.],
[0., 1., 1.]]]])
+
"""
def __init__(
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 6b24568b2..5f339b7e2 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -67,7 +67,7 @@ def gaussian(
device: Optional[Device] = None,
dtype: Optional[Dtype] = None,
) -> Tensor:
- """Compute the gaussian values based on the window and sigma values.
+ r"""Compute the gaussian values based on the window and sigma values.
Args:
window_size: the size which drives the filter amount.
@@ -76,10 +76,11 @@ def gaussian(
If a tensor, should be in a shape :math:`(B, 1)`
device: This value will be used if sigma is a float. Device desired to compute.
dtype: This value will be used if sigma is a float. Dtype desired for compute.
+
Returns:
A tensor withshape :math:`(B, \text{kernel_size})`, with Gaussian values.
- """
+ """
if isinstance(sigma, float):
sigma = tensor([[sigma]], device=device, dtype=dtype)
@@ -115,9 +116,11 @@ def gaussian_discrete_erf(
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
device: This value will be used if sigma is a float. Device desired to compute.
dtype: This value will be used if sigma is a float. Dtype desired for compute.
+
Returns:
A tensor withshape :math:`(B, \text{kernel_size})`, with discrete Gaussian values computed by approximation of
the error function.
+
"""
if isinstance(sigma, float):
sigma = tensor([[sigma]], device=device, dtype=dtype)
@@ -242,9 +245,11 @@ def gaussian_discrete(
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
device: This value will be used if sigma is a float. Device desired to compute.
dtype: This value will be used if sigma is a float. Dtype desired for compute.
+
Returns:
A tensor withshape :math:`(B, \text{kernel_size})`, with discrete Gaussian values computed by modified Bessel
function.
+
"""
if isinstance(sigma, float):
sigma = tensor([[sigma]], device=device, dtype=dtype)
@@ -281,9 +286,11 @@ def get_box_kernel1d(kernel_size: int, *, device: Optional[Device] = None, dtype
kernel_size: the size of the kernel.
device: the desired device of returned tensor.
dtype: the desired data type of returned tensor.
+
Returns:
A tensor with shape :math:`(1, \text{kernel\_size})`, filled with the value
:math:`\frac{1}{\text{kernel\_size}}`.
+
"""
scale = tensor(1.0 / kernel_size, device=device, dtype=dtype)
return scale.expand(1, kernel_size)
@@ -298,9 +305,11 @@ def get_box_kernel2d(
kernel_size: the size of the kernel.
device: the desired device of returned tensor.
dtype: the desired data type of returned tensor.
+
Returns:
A tensor with shape :math:`(1, \text{kernel\_size}[0], \text{kernel\_size}[1])`,
filled with the value :math:`\frac{1}{\text{kernel\_size}[0] \times \text{kernel\_size}[1]}`.
+
"""
ky, kx = _unpack_2d_ks(kernel_size)
scale = tensor(1.0 / (kx * ky), device=device, dtype=dtype)
@@ -487,7 +496,8 @@ def get_spatial_gradient_kernel3d(
mode: str, order: int, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients, using one of the following
- operators: sobel, diff."""
+ operators: sobel, diff.
+ """
KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
@@ -529,6 +539,7 @@ def get_gaussian_kernel1d(
>>> get_gaussian_kernel1d(5, torch.tensor([[1.5], [0.7]]))
tensor([[0.1201, 0.2339, 0.2921, 0.2339, 0.1201],
[0.0096, 0.2054, 0.5699, 0.2054, 0.0096]])
+
"""
_check_kernel_size(kernel_size, allow_even=force_even)
@@ -543,7 +554,7 @@ def get_gaussian_discrete_kernel1d(
device: Optional[Device] = None,
dtype: Optional[Dtype] = None,
) -> Tensor:
- """Function that returns Gaussian filter coefficients based on the modified Bessel functions.
+ r"""Function that returns Gaussian filter coefficients based on the modified Bessel functions.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
@@ -565,6 +576,7 @@ def get_gaussian_discrete_kernel1d(
>>> get_gaussian_discrete_kernel1d(5, torch.tensor([[1.5],[2.4]]))
tensor([[0.1096, 0.2323, 0.3161, 0.2323, 0.1096],
[0.1635, 0.2170, 0.2389, 0.2170, 0.1635]])
+
"""
_check_kernel_size(kernel_size, allow_even=force_even)
@@ -579,7 +591,7 @@ def get_gaussian_erf_kernel1d(
device: Optional[Device] = None,
dtype: Optional[Dtype] = None,
) -> Tensor:
- """Function that returns Gaussian filter coefficients by interpolating the error function.
+ r"""Function that returns Gaussian filter coefficients by interpolating the error function.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
@@ -601,6 +613,7 @@ def get_gaussian_erf_kernel1d(
>>> get_gaussian_erf_kernel1d(5, torch.tensor([[1.5], [2.1]]))
tensor([[0.1226, 0.2331, 0.2887, 0.2331, 0.1226],
[0.1574, 0.2198, 0.2456, 0.2198, 0.1574]])
+
"""
_check_kernel_size(kernel_size, allow_even=force_even)
@@ -647,6 +660,7 @@ def get_gaussian_kernel2d(
[0.0351, 0.0683, 0.0853, 0.0683, 0.0351],
[0.0281, 0.0547, 0.0683, 0.0547, 0.0281],
[0.0144, 0.0281, 0.0351, 0.0281, 0.0144]]])
+
"""
if isinstance(sigma, tuple):
sigma = tensor([sigma], device=device, dtype=dtype)
@@ -705,6 +719,7 @@ def get_gaussian_kernel3d(
torch.Size([1, 3, 3, 3])
>>> get_gaussian_kernel3d((3, 7, 5), torch.tensor([[1.5, 1.5, 1.5]])).shape
torch.Size([1, 3, 7, 5])
+
"""
if isinstance(sigma, tuple):
sigma = tensor([sigma], device=device, dtype=dtype)
@@ -743,6 +758,7 @@ def get_laplacian_kernel1d(
tensor([ 1., -2., 1.])
>>> get_laplacian_kernel1d(5)
tensor([ 1., 1., -4., 1., 1.])
+
"""
# TODO: add default dtype as None when kornia relies on torch > 1.12
@@ -778,6 +794,7 @@ def get_laplacian_kernel2d(
[ 1., 1., -24., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
+
"""
# TODO: add default dtype as None when kornia relies on torch > 1.12
@@ -824,6 +841,7 @@ def get_pascal_kernel_2d(
[3., 9., 9., 3.],
[3., 9., 9., 3.],
[1., 3., 3., 1.]])
+
"""
ky, kx = _unpack_2d_ks(kernel_size)
ax = get_pascal_kernel_1d(kx, device=device, dtype=dtype)
@@ -862,6 +880,7 @@ def get_pascal_kernel_1d(
tensor([1., 4., 6., 4., 1.])
>>> get_pascal_kernel_1d(6)
tensor([ 1., 5., 10., 10., 5., 1.])
+
"""
pre: list[float] = []
cur: list[float] = []
@@ -920,7 +939,7 @@ def get_hysteresis_kernel(device: Optional[Device] = None, dtype: Optional[Dtype
def get_hanning_kernel1d(kernel_size: int, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
- """Returns Hanning (also known as Hann) kernel, used in signal processing and KCF tracker.
+ r"""Returns Hanning (also known as Hann) kernel, used in signal processing and KCF tracker.
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
\\qquad 0 \\leq n \\leq M-1
@@ -939,6 +958,7 @@ def get_hanning_kernel1d(kernel_size: int, device: Optional[Device] = None, dtyp
Examples:
>>> get_hanning_kernel1d(4)
tensor([0.0000, 0.7500, 0.7500, 0.0000])
+
"""
_check_kernel_size(kernel_size, 2, allow_even=True)
@@ -950,7 +970,7 @@ def get_hanning_kernel1d(kernel_size: int, device: Optional[Device] = None, dtyp
def get_hanning_kernel2d(
kernel_size: tuple[int, int] | int, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
- """Returns 2d Hanning kernel, used in signal processing and KCF tracker.
+ r"""Returns 2d Hanning kernel, used in signal processing and KCF tracker.
Args:
kernel_size: The size of the kernel for the filter. It should be positive.
@@ -960,6 +980,7 @@ def get_hanning_kernel2d(
Returns:
2D tensor with Hanning filter coefficients. Shape: math:`(\text{kernel_size[0], kernel_size[1]})`
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
+
"""
kernel_size = _unpack_2d_ks(kernel_size)
_check_kernel_size(kernel_size, 2, allow_even=True)
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index e334dcece..02b4bda10 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -39,6 +39,7 @@ def get_motion_kernel2d(
tensor([[[0.0000, 0.0000, 0.1667],
[0.0000, 0.3333, 0.0000],
[0.5000, 0.0000, 0.0000]]])
+
"""
device, dtype = _extract_device_dtype(
[angle if isinstance(angle, Tensor) else None, direction if isinstance(direction, Tensor) else None]
@@ -137,6 +138,7 @@ def get_motion_kernel3d(
[[0.0000, 0.1667, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000]]]])
+
"""
device, dtype = _extract_device_dtype(
[angle if isinstance(angle, Tensor) else None, direction if isinstance(direction, Tensor) else None]
diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.py
index ad102af50..d3578930f 100644
--- a/kornia/filters/laplacian.py
+++ b/kornia/filters/laplacian.py
@@ -35,6 +35,7 @@ def laplacian(
>>> output = laplacian(input, 3)
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
kernel = get_laplacian_kernel2d(kernel_size, device=input.device, dtype=input.dtype)[None, ...]
@@ -67,6 +68,7 @@ class Laplacian(Module):
>>> output = laplace(input)
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
def __init__(
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 0a41d3086..0dd7852f5 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -35,6 +35,7 @@ def median_blur(input: Tensor, kernel_size: tuple[int, int] | int) -> Tensor:
>>> output = median_blur(input, (3, 3))
>>> output.shape
torch.Size([2, 4, 5, 7])
+
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -72,6 +73,7 @@ class MedianBlur(Module):
>>> output = blur(input)
>>> output.shape
torch.Size([2, 4, 5, 7])
+
"""
def __init__(self, kernel_size: tuple[int, int] | int) -> None:
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index f084036eb..f984e02cb 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -37,6 +37,7 @@ class MotionBlur(Module):
>>> input = torch.rand(2, 4, 5, 7)
>>> motion_blur = MotionBlur(3, 35., 0.5)
>>> output = motion_blur(input) # 2x4x5x7
+
"""
def __init__(
@@ -84,6 +85,7 @@ class MotionBlur3D(Module):
>>> input = torch.rand(2, 4, 5, 7, 9)
>>> motion_blur = MotionBlur3D(3, 35., 0.5)
>>> output = motion_blur(input) # 2x4x5x7x9
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1, -1]
@@ -162,6 +164,7 @@ def motion_blur(
>>> out_1 = motion_blur(input, 5, torch.tensor([90., 180,]), torch.tensor([1., -1.]))
>>> torch.allclose(out_1[0], out_1[1])
False
+
"""
kernel = get_motion_kernel2d(kernel_size, angle, direction, mode)
return filter2d(input, kernel, border_type)
@@ -204,6 +207,7 @@ def motion_blur3d(
>>> out_1 = motion_blur3d(input, 5, torch.tensor([[0., 90., 90.], [90., 180., 0.]]), torch.tensor([1., -1.]))
>>> torch.allclose(out_1[0], out_1[1])
False
+
"""
kernel = get_motion_kernel3d(kernel_size, angle, direction, mode)
return filter3d(input, kernel, border_type)
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 6b7a04879..fc6de0bcc 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -34,6 +34,7 @@ def spatial_gradient(input: Tensor, mode: str = "sobel", order: int = 1, normali
>>> output = spatial_gradient(input) # 1x3x2x4x4
>>> output.shape
torch.Size([1, 3, 2, 4, 4])
+
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -72,6 +73,7 @@ def spatial_gradient3d(input: Tensor, mode: str = "diff", order: int = 1) -> Ten
>>> output = spatial_gradient3d(input)
>>> output.shape
torch.Size([1, 4, 3, 2, 4, 4])
+
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "D", "H", "W"])
@@ -137,6 +139,7 @@ def sobel(input: Tensor, normalized: bool = True, eps: float = 1e-6) -> Tensor:
>>> output = sobel(input) # 1x3x4x4
>>> output.shape
torch.Size([1, 3, 4, 4])
+
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -172,6 +175,7 @@ class SpatialGradient(Module):
Examples:
>>> input = torch.rand(1, 3, 4, 4)
>>> output = SpatialGradient()(input) # 1x3x2x4x4
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1]
@@ -209,6 +213,7 @@ class SpatialGradient3d(Module):
>>> output = SpatialGradient3d()(input)
>>> output.shape
torch.Size([1, 4, 3, 2, 4, 4])
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1, -1]
@@ -244,6 +249,7 @@ class Sobel(Module):
Examples:
>>> input = torch.rand(1, 3, 4, 4)
>>> output = Sobel()(input) # 1x3x4x4
+
"""
def __init__(self, normalized: bool = True, eps: float = 1e-6) -> None:
diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.py
index 71419a4cd..b61e6e58a 100644
--- a/kornia/filters/unsharp.py
+++ b/kornia/filters/unsharp.py
@@ -29,6 +29,7 @@ def unsharp_mask(
>>> output = unsharp_mask(input, (3, 3), (1.5, 1.5))
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
data_blur: Tensor = gaussian_blur2d(input, kernel_size, sigma, border_type)
data_sharpened: Tensor = input + (input - data_blur)
@@ -61,6 +62,7 @@ class UnsharpMask(Module):
>>> output = sharpen(input)
>>> output.shape
torch.Size([2, 4, 5, 5])
+
"""
def __init__(
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 927eec2ea..d0e2f9d81 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -30,6 +30,7 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape
of Bx4x2, where each box is defined in the following ``clockwise`` order: top-left, top-right, bottom-right,
bottom-left. The coordinates must be in the x, y order.
+
"""
if not (len(boxes.shape) in [3, 4] and boxes.shape[-2:] == torch.Size([4, 2])):
return False
@@ -62,6 +63,7 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
of Bx8x3, where each box is defined in the following ``clockwise`` order: front-top-left, front-top-right,
front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right, back-bottom-left.
The coordinates must be in the x, y, z order.
+
"""
if not (len(boxes.shape) in [3, 4] and boxes.shape[-2:] == torch.Size([8, 3])):
raise AssertionError(f"Box shape must be (B, 8, 3) or (B, N, 8, 3). Got {boxes.shape}.")
@@ -114,6 +116,7 @@ def infer_bbox_shape(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
... ]]) # 2x4x2
>>> infer_bbox_shape(boxes)
(tensor([2., 2.]), tensor([2., 3.]))
+
"""
validate_bbox(boxes)
width: torch.Tensor = boxes[:, 1, 0] - boxes[:, 0, 0] + 1
@@ -154,6 +157,7 @@ def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor,
... [ 3, 54, 65]]]) # 2x8x3
>>> infer_bbox_shape3d(boxes)
(tensor([31, 61]), tensor([21, 51]), tensor([11, 41]))
+
"""
validate_bbox3d(boxes)
@@ -198,6 +202,7 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
[0., 1., 1., 1., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]])
+
"""
validate_bbox(boxes)
# zero padding the surroundings
@@ -259,6 +264,7 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Ten
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]]]])
+
"""
validate_bbox3d(boxes)
mask = zeros((len(boxes), *size))
@@ -322,6 +328,7 @@ def bbox_generator(
[3, 0],
[3, 3],
[1, 3]]])
+
"""
if not (x_start.shape == y_start.shape and x_start.dim() in [0, 1]):
raise AssertionError(f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}.")
@@ -402,6 +409,7 @@ def bbox_generator3d(
[43, 4, 65],
[43, 54, 65],
[ 3, 54, 65]]])
+
"""
if not (x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [0, 1]):
raise AssertionError(
@@ -461,8 +469,8 @@ def transform_bbox(
Returns:
The set of transformed points in the specified mode
- """
+ """
if not isinstance(mode, str):
raise TypeError(f"Mode must be a string. Got {type(mode)}")
@@ -524,6 +532,7 @@ def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torc
>>> scores = torch.tensor([0.9, 0.8, 0.7, 0.9])
>>> nms(boxes, scores, iou_threshold=0.8)
tensor([0, 3, 1])
+
"""
if len(boxes.shape) != 2 and boxes.shape[-1] != 4:
raise ValueError(f"boxes expected as Nx4. Got: {boxes.shape}.")
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index a9bd12ae5..afc17ad27 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -40,6 +40,7 @@ def _transform_boxes(boxes: torch.Tensor, M: torch.Tensor) -> torch.Tensor:
boxes: 2D quadrilaterals or 3D hexahedrons in kornia format.
M: the transformation matrix of shape :math:`(3, 3)` or :math:`(B, 3, 3)` for 2D and :math:`(4, 4)` or
:math:`(B, 4, 4)` for 3D hexahedron.
+
"""
M = M if M.is_floating_point() else M.float()
@@ -184,6 +185,7 @@ class Boxes:
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
`quadrilaterals <https://en.wikipedia.org/wiki/Quadrilateral>`_ are rectangles, rhombus and trapezoids.
+
"""
def __init__(
@@ -242,6 +244,7 @@ class Boxes:
>>> boxes = Boxes.from_tensor(boxes_xyxy)
>>> boxes.get_boxes_shape()
(tensor([[1., 1.]]), tensor([[1., 2.]]))
+
"""
boxes_xywh = cast(torch.Tensor, self.to_tensor("xywh", as_padded_sequence=True))
widths, heights = boxes_xywh[..., 2], boxes_xywh[..., 3]
@@ -256,6 +259,7 @@ class Boxes:
Args:
boxes: 2D boxes.
inplace: do transform in-place and return self.
+
"""
data = torch.cat([self._data, boxes.data], dim=1)
if inplace:
@@ -291,6 +295,7 @@ class Boxes:
Args:
padding_size: (B, 4)
+
"""
if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
@@ -303,6 +308,7 @@ class Boxes:
Args:
padding_size: (B, 4)
+
"""
if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
@@ -316,7 +322,6 @@ class Boxes:
botright: Optional[Tensor | tuple[int, int]] = None,
inplace: bool = False,
) -> Boxes:
- """"""
if not (isinstance(topleft, Tensor) and isinstance(botright, Tensor)):
raise NotImplementedError
if inplace:
@@ -450,6 +455,7 @@ class Boxes:
[7., 1.],
[7., 3.],
[5., 3.]]])
+
"""
quadrilaterals: torch.Tensor | list[torch.Tensor]
if isinstance(boxes, torch.Tensor):
@@ -492,6 +498,7 @@ class Boxes:
>>> boxes_xyxy = torch.as_tensor([[0, 3, 1, 4], [5, 1, 8, 4]])
>>> boxes = Boxes.from_tensor(boxes_xyxy)
>>> assert (boxes_xyxy == boxes.to_tensor(mode='xyxy')).all()
+
"""
batched_boxes = self._data if self._is_batched else self._data.unsqueeze(0)
@@ -556,6 +563,7 @@ class Boxes:
[0., 1., 1., 1., 1.],
[0., 1., 1., 1., 1.],
[0., 0., 0., 0., 0.]]])
+
"""
if self._data.requires_grad:
raise RuntimeError(
@@ -591,6 +599,7 @@ class Boxes:
Returns:
The transformed boxes.
+
"""
if not 2 <= M.ndim <= 3 or M.shape[-2:] != (3, 3):
raise ValueError(f"The transformation matrix shape must be (3, 3) or (B, 3, 3). Got {M.shape}.")
@@ -618,6 +627,7 @@ class Boxes:
Returns:
The transformed boxes.
+
"""
if method == "fast":
raise NotImplementedError
@@ -719,6 +729,7 @@ class Boxes3D:
Coordinates must be in ``x, y, z`` order. The height, width and depth of a box is defined as
``width = xmax - xmin + 1``, ``height = ymax - ymin + 1`` and ``depth = zmax - zmin + 1``. Examples of
`hexahedrons <https://en.wikipedia.org/wiki/Hexahedron>`_ are cubes and rhombohedrons.
+
"""
def __init__(
@@ -770,6 +781,7 @@ class Boxes3D:
>>> boxes3d = Boxes3D.from_tensor(boxes_xyzxyz)
>>> boxes3d.get_boxes_shape()
(tensor([30., 60.]), tensor([20., 50.]), tensor([10., 40.]))
+
"""
boxes_xyzwhd = self.to_tensor(mode="xyzwhd")
widths, heights, depths = boxes_xyzwhd[..., 3], boxes_xyzwhd[..., 4], boxes_xyzwhd[..., 5]
@@ -817,6 +829,7 @@ class Boxes3D:
[7., 1., 8.],
[7., 3., 8.],
[5., 3., 8.]]])
+
"""
if not (2 <= boxes.ndim <= 3 and boxes.shape[-1] == 6):
raise ValueError(f"BBox shape must be (N, 6) or (B, N, 6). Got {boxes.shape}.")
@@ -887,6 +900,7 @@ class Boxes3D:
>>> boxes_xyzxyz = torch.as_tensor([[0, 3, 6, 1, 4, 8], [5, 1, 3, 8, 4, 9]])
>>> boxes = Boxes3D.from_tensor(boxes_xyzxyz, mode='xyzxyz')
>>> assert (boxes.to_tensor(mode='xyzxyz') == boxes_xyzxyz).all()
+
"""
if self._data.requires_grad:
raise RuntimeError(
@@ -979,6 +993,7 @@ class Boxes3D:
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]]])
+
"""
if self._data.requires_grad:
raise RuntimeError(
@@ -1021,6 +1036,7 @@ class Boxes3D:
Returns:
The transformed boxes.
+
"""
if not 2 <= M.ndim <= 3 or M.shape[-2:] != (4, 4):
raise ValueError(f"The transformation matrix shape must be (4, 4) or (B, 4, 4). Got {M.shape}.")
diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.py
index f2a0fda11..b2f6db8c7 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -16,6 +16,7 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
Returns:
torch.Tensor: Inverse tilt projection matrix with shape :math:`(*, 3, 3)`.
+
"""
if taux.shape != tauy.shape:
raise ValueError(f"Shape of taux {taux.shape} and tauy {tauy.shape} do not match.")
@@ -84,6 +85,7 @@ def distort_points(
>>> K = torch.eye(3)[None]
>>> dist_coeff = torch.rand(1, 4)
>>> points_dist = distort_points(points, K, dist_coeff)
+
"""
if points.dim() < 2 and points.shape[-1] != 2:
raise ValueError(f"points shape is invalid. Got {points.shape}.")
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index 910aa7e3e..d7ad8f9e8 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -21,6 +21,7 @@ def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) ->
Returns:
Tuple containing the normalized points in the shape :math:`(B, N, D)` and the transformation matrix
in the shape :math:`(B, D+1, D+1)`.
+
"""
KORNIA_CHECK_SHAPE(points, ["B", "N", "D"])
x_mean = torch.mean(points, dim=1, keepdim=True) # Bx1xD
@@ -113,6 +114,7 @@ def solve_pnp_dlt(
tensor([[[ 0.9392, -0.3432, -0.0130, 1.6734],
[ 0.3390, 0.9324, -0.1254, -4.3634],
[ 0.0552, 0.1134, 0.9920, 3.7785]]], dtype=torch.float64)
+
"""
# This function was implemented based on ideas inspired from multiple references.
# ============
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 3084a2645..ebdb1719c 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -32,6 +32,7 @@ def undistort_points(
new_K: Intrinsic camera matrix of the distorted image. By default, it is the same as K but you may additionally
scale and shift the result by using a different matrix. Shape: :math:`(*, 3, 3)`. Default: None.
num_iters: Number of undistortion iterations. Default: 5.
+
Returns:
Undistorted 2D points with shape :math:`(*, N, 2)`.
@@ -45,6 +46,7 @@ def undistort_points(
[ 0.0711, 0.1100],
[-0.0697, 0.0228],
[-0.1843, -0.1606]]])
+
"""
KORNIA_CHECK_SHAPE(points, ["*", "N", "2"])
KORNIA_CHECK_SHAPE(K, ["*", "3", "3"])
@@ -140,6 +142,7 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
>>> out = undistort_image(img, K, dist_coeff)
>>> out.shape
torch.Size([1, 3, 5, 5])
+
"""
if len(image.shape) < 3:
raise ValueError(f"Image shape is invalid. Got: {image.shape}.")
diff --git a/kornia/geometry/camera/distortion_affine.py b/kornia/geometry/camera/distortion_affine.py
index 537dfcc00..2c8a6bda9 100644
--- a/kornia/geometry/camera/distortion_affine.py
+++ b/kornia/geometry/camera/distortion_affine.py
@@ -27,6 +27,7 @@ def distort_points_affine(projected_points_in_camera_z1_plane: Tensor, params: T
>>> params = torch.tensor([600., 600., 319.5, 239.5])
>>> distort_points_affine(points, params)
tensor([192019.5000, 143939.5000])
+
"""
KORNIA_CHECK_SHAPE(projected_points_in_camera_z1_plane, ["*", "2"])
KORNIA_CHECK_SHAPE(params, ["*", "4"])
@@ -64,6 +65,7 @@ def undistort_points_affine(distorted_points_in_camera: Tensor, params: Tensor)
>>> params = torch.tensor([600., 600., 319.5, 239.5])
>>> undistort_points_affine(points, params)
tensor([0., 0.])
+
"""
KORNIA_CHECK_SHAPE(distorted_points_in_camera, ["*", "2"])
KORNIA_CHECK_SHAPE(params, ["*", "4"])
@@ -100,6 +102,7 @@ def dx_distort_points_affine(projected_points_in_camera_z1_plane: Tensor, params
>>> dx_distort_points_affine(points, params)
tensor([[600., 0.],
[ 0., 600.]])
+
"""
KORNIA_CHECK_SHAPE(projected_points_in_camera_z1_plane, ["*", "2"])
KORNIA_CHECK_SHAPE(params, ["*", "4"])
diff --git a/kornia/geometry/camera/distortion_kannala_brandt.py b/kornia/geometry/camera/distortion_kannala_brandt.py
index 323ce07e5..9c2a3778d 100644
--- a/kornia/geometry/camera/distortion_kannala_brandt.py
+++ b/kornia/geometry/camera/distortion_kannala_brandt.py
@@ -57,6 +57,7 @@ def distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor, p
>>> params = torch.tensor([1000.0, 1000.0, 320.0, 280.0, 0.1, 0.01, 0.001, 0.0001])
>>> distort_points_kannala_brandt(points, params)
tensor([1982.6832, 1526.3619])
+
"""
KORNIA_CHECK_SHAPE(projected_points_in_camera_z1_plane, ["*", "2"])
KORNIA_CHECK_SHAPE(params, ["*", "8"])
@@ -95,6 +96,7 @@ def undistort_points_kannala_brandt(distorted_points_in_camera: Tensor, params:
>>> params = torch.tensor([1000.0, 1000.0, 320.0, 280.0, 0.1, 0.01, 0.001, 0.0001])
>>> undistort_points_kannala_brandt(points, params).shape
torch.Size([2])
+
"""
KORNIA_CHECK_SHAPE(distorted_points_in_camera, ["*", "2"])
KORNIA_CHECK_SHAPE(params, ["*", "8"])
@@ -196,6 +198,7 @@ def dx_distort_points_kannala_brandt(projected_points_in_camera_z1_plane: Tensor
>>> dx_distort_points_kannala_brandt(points, params)
tensor([[ 486.0507, -213.5573],
[-213.5573, 165.7147]])
+
"""
KORNIA_CHECK_SHAPE(projected_points_in_camera_z1_plane, ["*", "2"])
KORNIA_CHECK_SHAPE(params, ["*", "8"])
diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.py
index 9a542b358..8f010d0bf 100644
--- a/kornia/geometry/camera/perspective.py
+++ b/kornia/geometry/camera/perspective.py
@@ -27,6 +27,7 @@ def project_points(point_3d: torch.Tensor, camera_matrix: torch.Tensor) -> torch
>>> K = torch.eye(3)[None]
>>> project_points(X, K)
tensor([[5.6088, 8.6827]])
+
"""
# projection eq. [u, v, w]' = K * [x y z 1]'
# u = fx * X / Z + cx
@@ -64,6 +65,7 @@ def unproject_points(
>>> K = torch.eye(3)[None]
>>> unproject_points(x, depth, K)
tensor([[0.4963, 0.7682, 1.0000]])
+
"""
if not isinstance(depth, torch.Tensor):
raise TypeError(f"Input depth type is not a torch.Tensor. Got {type(depth)}")
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index b810dbd1c..09306df0c 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -23,6 +23,7 @@ class PinholeCamera:
.. note::
We assume that the class attributes are in batch form in order to take
advantage of PyTorch parallelism to boost computing performance.
+
"""
def __init__(self, intrinsics: Tensor, extrinsics: Tensor, height: Tensor, width: Tensor) -> None:
@@ -70,6 +71,7 @@ class PinholeCamera:
Returns:
Device type
+
"""
return self._intrinsics.device
@@ -79,6 +81,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B, 4, 4)`.
+
"""
if not self._check_valid_params(self._intrinsics, "intrinsics"):
raise AssertionError
@@ -90,6 +93,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B, 4, 4)`.
+
"""
if not self._check_valid_params(self._extrinsics, "extrinsics"):
raise AssertionError
@@ -101,6 +105,7 @@ class PinholeCamera:
Returns:
scalar with the batch size.
+
"""
return self.intrinsics.shape[0]
@@ -110,6 +115,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B)`.
+
"""
return self.intrinsics[..., 0, 0]
@@ -119,6 +125,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B)`.
+
"""
return self.intrinsics[..., 1, 1]
@@ -128,6 +135,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B)`.
+
"""
return self.intrinsics[..., 0, 2]
@@ -137,6 +145,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B)`.
+
"""
return self.intrinsics[..., 1, 2]
@@ -146,6 +155,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B)`.
+
"""
return self.extrinsics[..., 0, -1]
@@ -161,6 +171,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B)`.
+
"""
return self.extrinsics[..., 1, -1]
@@ -176,6 +187,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B)`.
+
"""
return self.extrinsics[..., 2, -1]
@@ -191,6 +203,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B, 3, 4)`.
+
"""
return self.extrinsics[..., :3, :4]
@@ -200,6 +213,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B, 3, 3)`.
+
"""
return self.intrinsics[..., :3, :3]
@@ -209,6 +223,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B, 3, 3)`.
+
"""
return self.extrinsics[..., :3, :3]
@@ -218,6 +233,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B, 3, 1)`.
+
"""
return self.extrinsics[..., :3, -1:]
@@ -234,6 +250,7 @@ class PinholeCamera:
Returns:
tensor of shape :math:`(B, 4, 4)`.
+
"""
return self.intrinsics.inverse()
@@ -247,6 +264,7 @@ class PinholeCamera:
Returns:
the camera model with scaled parameters.
+
"""
# scale the intrinsic parameters
intrinsics: Tensor = self.intrinsics.clone()
@@ -269,6 +287,7 @@ class PinholeCamera:
Returns:
the camera model with scaled parameters.
+
"""
# scale the intrinsic parameters
self.intrinsics[..., 0, 0] *= scale_factor
@@ -300,6 +319,7 @@ class PinholeCamera:
>>> pinhole = kornia.geometry.camera.PinholeCamera(K, E, h, w)
>>> pinhole.project(X)
tensor([[5.6088, 8.6827]])
+
"""
P = self.intrinsics @ self.extrinsics
return convert_points_from_homogeneous(transform_points(P, point_3d))
@@ -332,6 +352,7 @@ class PinholeCamera:
>>> pinhole = kornia.geometry.camera.PinholeCamera(K, E, h, w)
>>> pinhole.unproject(x, depth)
tensor([[0.4963, 0.7682, 1.0000]])
+
"""
P = self.intrinsics @ self.extrinsics
P_inv = _torch_inverse_cast(P)
@@ -389,6 +410,7 @@ class PinholeCamerasList(PinholeCamera):
Args:
pinholes_list: a python tuple or list containing a set of `PinholeCamera` instances.
+
"""
def __init__(self, pinholes_list: Iterable[PinholeCamera]) -> None:
@@ -456,6 +478,7 @@ def pinhole_matrix(pinholes: Tensor, eps: float = 1e-6) -> Tensor:
[1.0000e-06, 7.6822e-01, 1.3203e-01, 1.0000e-06],
[1.0000e-06, 1.0000e-06, 1.0000e+00, 1.0000e-06],
[1.0000e-06, 1.0000e-06, 1.0000e-06, 1.0000e+00]]])
+
"""
# warnings.warn("pinhole_matrix will be deprecated in version 0.2, "
# "use PinholeCamera.camera_matrix instead",
@@ -500,6 +523,7 @@ def inverse_pinhole_matrix(pinhole: Tensor, eps: float = 1e-6) -> Tensor:
[ 0.0000, 1.3017, -0.1719, 0.0000],
[ 0.0000, 0.0000, 1.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000, 1.0000]]])
+
"""
# warnings.warn("inverse_pinhole_matrix will be deprecated in version 0.2, "
# "use PinholeCamera.intrinsics_inverse() instead",
@@ -544,6 +568,7 @@ def scale_pinhole(pinholes: Tensor, scale: Tensor) -> Tensor:
>>> scale_pinhole(pinhole_i, scales) # Nx12
tensor([[0.9925, 1.5364, 0.1770, 0.2641, 0.6148, 1.2682, 0.4901, 0.8964, 0.4556,
0.6323, 0.3489, 0.4017]])
+
"""
# warnings.warn("scale_pinhole will be deprecated in version 0.2, "
# "use PinholeCamera.scale() instead",
@@ -566,6 +591,7 @@ def get_optical_pose_base(pinholes: Tensor) -> Tensor:
Returns:
tensor of extrinsic transformation matrices of size (N, 4, 4).
+
"""
if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):
raise AssertionError(pinholes.shape)
@@ -613,6 +639,7 @@ def homography_i_H_ref(pinhole_i: Tensor, pinhole_ref: Tensor) -> Tensor:
pinhole_i = torch.rand(1, 12) # Nx12
pinhole_ref = torch.rand(1, 12) # Nx12
homography_i_H_ref(pinhole_i, pinhole_ref) # Nx4x4
+
"""
# TODO: Add doctest once having `rtvec_to_pose`.
if not (len(pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12):
@@ -639,6 +666,7 @@ def pixel2cam(depth: Tensor, intrinsics_inv: Tensor, pixel_coords: Tensor) -> Te
Returns:
tensor of shape BxHxWx3 with (x, y, z) cam coordinates.
+
"""
if not len(depth.shape) == 4 and depth.shape[1] == 1:
raise ValueError(f"Input depth has to be in the shape of Bx1xHxW. Got {depth.shape}")
@@ -665,6 +693,7 @@ def cam2pixel(cam_coords_src: Tensor, dst_proj_src: Tensor, eps: float = 1e-12)
Returns:
tensor of shape BxHxWx2 with (u, v) pixel coordinates.
+
"""
if not len(cam_coords_src.shape) == 4 and cam_coords_src.shape[3] == 3:
raise ValueError(f"Input cam_coords_src has to be in the shape of BxHxWx3. Got {cam_coords_src.shape}")
diff --git a/kornia/geometry/camera/projection_orthographic.py b/kornia/geometry/camera/projection_orthographic.py
index 244035fa6..48ae0c07e 100644
--- a/kornia/geometry/camera/projection_orthographic.py
+++ b/kornia/geometry/camera/projection_orthographic.py
@@ -25,6 +25,7 @@ def project_points_orthographic(points_in_camera: Tensor) -> Tensor:
>>> points = torch.tensor([1., 2., 3.])
>>> project_points_orthographic(points)
tensor([1., 2.])
+
"""
KORNIA_CHECK_SHAPE(points_in_camera, ["*", "3"])
return points_in_camera[..., :2]
@@ -49,6 +50,7 @@ def unproject_points_orthographic(points_in_camera: Tensor, extension: Tensor) -
>>> extension = torch.tensor([3.])
>>> unproject_points_orthographic(points, extension)
tensor([1., 2., 3.])
+
"""
KORNIA_CHECK_SHAPE(points_in_camera, ["*", "2"])
@@ -74,6 +76,7 @@ def dx_project_points_orthographic(points_in_camera: Tensor) -> Tensor:
>>> points = torch.tensor([1., 2., 3.])
>>> dx_project_points_orthographic(points)
tensor([1.])
+
"""
KORNIA_CHECK_SHAPE(points_in_camera, ["*", "3"])
return ops.ones_like(points_in_camera[..., 0:1])
diff --git a/kornia/geometry/camera/projection_z1.py b/kornia/geometry/camera/projection_z1.py
index adbc05da2..152f362a4 100644
--- a/kornia/geometry/camera/projection_z1.py
+++ b/kornia/geometry/camera/projection_z1.py
@@ -34,6 +34,7 @@ def project_points_z1(points_in_camera: Tensor) -> Tensor:
>>> points = torch.tensor([1., 2., 3.])
>>> project_points_z1(points)
tensor([0.3333, 0.6667])
+
"""
KORNIA_CHECK_SHAPE(points_in_camera, ["*", "3"])
return points_in_camera[..., :2] / points_in_camera[..., 2:3]
@@ -58,6 +59,7 @@ def unproject_points_z1(points_in_cam_canonical: Tensor, extension: Optional[Ten
>>> extension = torch.tensor([3.])
>>> unproject_points_z1(points, extension)
tensor([3., 6., 3.])
+
"""
KORNIA_CHECK_SHAPE(points_in_cam_canonical, ["*", "2"])
@@ -101,6 +103,7 @@ def dx_project_points_z1(points_in_camera: Tensor) -> Tensor:
>>> dx_project_points_z1(points)
tensor([[ 0.3333, 0.0000, -0.1111],
[ 0.0000, 0.3333, -0.2222]])
+
"""
KORNIA_CHECK_SHAPE(points_in_camera, ["*", "3"])
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index 912cc5d33..e5a8d501c 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -17,6 +17,7 @@ class StereoException(Exception):
msg: Custom message to add to the general message.
*args:
**kwargs:
+
"""
doc_help = (
"\n Please check documents here: "
@@ -37,6 +38,7 @@ class StereoCamera:
of shape :math:`(B, 3, 4)`
rectified_right_camera: The rectified right camera projection matrix
of shape :math:`(B, 3, 4)`
+
"""
self._check_stereo_camera(rectified_left_camera, rectified_right_camera)
self.rectified_left_camera: Tensor = rectified_left_camera
@@ -56,6 +58,7 @@ class StereoCamera:
of shape :math:`(B, 3, 4)`
rectified_right_camera: The rectified right camera projection matrix
of shape :math:`(B, 3, 4)`
+
"""
# Ensure correct shapes
if len(rectified_left_camera.shape) != 3:
@@ -113,6 +116,7 @@ class StereoCamera:
Returns:
scalar with the batch size
+
"""
return self.rectified_left_camera.shape[0]
@@ -125,6 +129,7 @@ class StereoCamera:
Returns:
tensor of shape :math:`(B)`
+
"""
return self.rectified_left_camera[..., 0, 0]
@@ -137,6 +142,7 @@ class StereoCamera:
Returns:
tensor of shape :math:`(B)`
+
"""
return self.rectified_left_camera[..., 1, 1]
@@ -146,6 +152,7 @@ class StereoCamera:
Returns:
tensor of shape :math:`(B)`
+
"""
return self.rectified_left_camera[..., 0, 2]
@@ -155,6 +162,7 @@ class StereoCamera:
Returns:
tensor of shape :math:`(B)`
+
"""
return self.rectified_right_camera[..., 0, 2]
@@ -167,6 +175,7 @@ class StereoCamera:
Returns:
tensor of shape :math:`(B)`
+
"""
return self.rectified_left_camera[..., 1, 2]
@@ -176,6 +185,7 @@ class StereoCamera:
Returns:
Tensor of shape :math:`(B)`
+
"""
return -self.rectified_right_camera[..., 0, 3] / self.fx
@@ -189,6 +199,7 @@ class StereoCamera:
Return:
The Q matrix of shape :math:`(B, 4, 4)`.
+
"""
return self._Q_matrix
@@ -197,6 +208,7 @@ class StereoCamera:
Returns:
The Q matrix of shape :math:`(B, 4, 4)`.
+
"""
Q = zeros((self.batch_size, 4, 4), device=self.device, dtype=self.dtype)
baseline: Tensor = -self.tx
@@ -217,6 +229,7 @@ class StereoCamera:
Returns:
The 3D point cloud of shape :math:`(B, H, W, 3)`
+
"""
return reproject_disparity_to_3D(disparity_tensor, self.Q)
@@ -226,6 +239,7 @@ def _check_disparity_tensor(disparity_tensor: Tensor) -> None:
Args:
disparity_tensor: The disparity tensor of shape :math:`(B, 1, H, W)`.
+
"""
if not isinstance(disparity_tensor, Tensor):
raise StereoException(
@@ -253,6 +267,7 @@ def _check_Q_matrix(Q_matrix: Tensor) -> None:
Args:
Q_matrix: The Q matrix for reprojecting disparity to a point cloud of shape :math:`(B, 4, 4)`
+
"""
if not isinstance(Q_matrix, Tensor):
raise StereoException(f"Expected 'Q_matrix' to be an instance of Tensor but got {type(Q_matrix)}.")
@@ -278,6 +293,7 @@ def reproject_disparity_to_3D(disparity_tensor: Tensor, Q_matrix: Tensor) -> Ten
Returns:
The 3D point cloud of shape :math:`(B, H, W, 3)`
+
"""
_check_Q_matrix(Q_matrix)
_check_disparity_tensor(disparity_tensor)
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 2204ada53..9f648d667 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -73,6 +73,7 @@ def rad2deg(tensor: Tensor) -> Tensor:
>>> input = tensor(3.1415926535)
>>> rad2deg(input)
tensor(180.)
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
@@ -93,6 +94,7 @@ def deg2rad(tensor: Tensor) -> Tensor:
>>> input = tensor(180.)
>>> deg2rad(input)
tensor(3.1416)
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
@@ -115,6 +117,7 @@ def pol2cart(rho: Tensor, phi: Tensor) -> tuple[Tensor, Tensor]:
>>> rho = torch.rand(1, 3, 3)
>>> phi = torch.rand(1, 3, 3)
>>> x, y = pol2cart(rho, phi)
+
"""
if not (isinstance(rho, Tensor) & isinstance(phi, Tensor)):
raise TypeError(f"Input type is not a Tensor. Got {type(rho)}, {type(phi)}")
@@ -140,6 +143,7 @@ def cart2pol(x: Tensor, y: Tensor, eps: float = 1.0e-8) -> tuple[Tensor, Tensor]
>>> x = torch.rand(1, 3, 3)
>>> y = torch.rand(1, 3, 3)
>>> rho, phi = cart2pol(x, y)
+
"""
if not (isinstance(x, Tensor) & isinstance(y, Tensor)):
raise TypeError(f"Input type is not a Tensor. Got {type(x)}, {type(y)}")
@@ -163,6 +167,7 @@ def convert_points_from_homogeneous(points: Tensor, eps: float = 1e-8) -> Tensor
>>> input = tensor([[0., 0., 1.]])
>>> convert_points_from_homogeneous(input)
tensor([[0., 0.]])
+
"""
if not isinstance(points, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(points)}")
@@ -195,6 +200,7 @@ def convert_points_to_homogeneous(points: Tensor) -> Tensor:
>>> input = tensor([[0., 0.]])
>>> convert_points_to_homogeneous(input)
tensor([[0., 0., 1.]])
+
"""
if not isinstance(points, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(points)}")
@@ -226,6 +232,7 @@ def convert_affinematrix_to_homography(A: Tensor) -> Tensor:
tensor([[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]])
+
"""
if not isinstance(A, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(A)}")
@@ -254,6 +261,7 @@ def convert_affinematrix_to_homography3d(A: Tensor) -> Tensor:
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]]])
+
"""
if not isinstance(A, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(A)}")
@@ -285,6 +293,7 @@ def axis_angle_to_rotation_matrix(axis_angle: Tensor) -> Tensor:
tensor([[[ 1.0000e+00, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, -3.6200e-06, -1.0000e+00],
[ 0.0000e+00, 1.0000e+00, -3.6200e-06]]])
+
"""
if not isinstance(axis_angle, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(axis_angle)}")
@@ -368,6 +377,7 @@ def rotation_matrix_to_axis_angle(rotation_matrix: Tensor) -> Tensor:
... [0., 1., 0.]])
>>> rotation_matrix_to_axis_angle(input)
tensor([1.5708, 0.0000, 0.0000])
+
"""
if not isinstance(rotation_matrix, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(rotation_matrix)}")
@@ -401,6 +411,7 @@ def rotation_matrix_to_quaternion(rotation_matrix: Tensor, eps: float = 1.0e-8)
... [0., 0., 1.]])
>>> rotation_matrix_to_quaternion(input, eps=torch.finfo(input.dtype).eps)
tensor([1., 0., 0., 0.])
+
"""
if not isinstance(rotation_matrix, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(rotation_matrix)}")
@@ -474,6 +485,7 @@ def normalize_quaternion(quaternion: Tensor, eps: float = 1.0e-12) -> Tensor:
>>> quaternion = tensor((1., 0., 1., 0.))
>>> normalize_quaternion(quaternion)
tensor([0.7071, 0.0000, 0.7071, 0.0000])
+
"""
if not isinstance(quaternion, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
@@ -506,6 +518,7 @@ def quaternion_to_rotation_matrix(quaternion: Tensor) -> Tensor:
tensor([[-1., 0., 0.],
[ 0., -1., 0.],
[ 0., 0., 1.]])
+
"""
if not isinstance(quaternion, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
@@ -580,6 +593,7 @@ def quaternion_to_axis_angle(quaternion: Tensor) -> Tensor:
>>> quaternion = tensor((1., 0., 0., 0.))
>>> quaternion_to_axis_angle(quaternion)
tensor([0., 0., 0.])
+
"""
if not torch.is_tensor(quaternion):
raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
@@ -638,6 +652,7 @@ def quaternion_log_to_exp(quaternion: Tensor, eps: float = 1.0e-8) -> Tensor:
>>> quaternion = tensor((0., 0., 0.))
>>> quaternion_log_to_exp(quaternion, eps=torch.finfo(quaternion.dtype).eps)
tensor([1., 0., 0., 0.])
+
"""
if not isinstance(quaternion, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
@@ -676,6 +691,7 @@ def quaternion_exp_to_log(quaternion: Tensor, eps: float = 1.0e-8) -> Tensor:
>>> quaternion = tensor((1., 0., 0., 0.))
>>> quaternion_exp_to_log(quaternion, eps=torch.finfo(quaternion.dtype).eps)
tensor([0., 0., 0.])
+
"""
if not isinstance(quaternion, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(quaternion)}")
@@ -724,6 +740,7 @@ def axis_angle_to_quaternion(axis_angle: Tensor) -> Tensor:
>>> axis_angle = tensor((0., 1., 0.))
>>> axis_angle_to_quaternion(axis_angle)
tensor([0.8776, 0.0000, 0.4794, 0.0000])
+
"""
if not torch.is_tensor(axis_angle):
raise TypeError(f"Input type is not a Tensor. Got {type(axis_angle)}")
@@ -777,6 +794,7 @@ def euler_from_quaternion(w: Tensor, x: Tensor, y: Tensor, z: Tensor) -> tuple[T
Return:
A tuple with euler angles`roll`, `pitch`, `yaw`.
+
"""
KORNIA_CHECK(w.shape == x.shape)
KORNIA_CHECK(x.shape == y.shape)
@@ -811,6 +829,7 @@ def quaternion_from_euler(roll: Tensor, pitch: Tensor, yaw: Tensor) -> tuple[Ten
Return:
A tuple with quaternion coefficients in order of `wxyz`.
+
"""
KORNIA_CHECK(roll.shape == pitch.shape)
KORNIA_CHECK(pitch.shape == yaw.shape)
@@ -856,6 +875,7 @@ def normalize_pixel_coordinates(pixel_coordinates: Tensor, height: int, width: i
>>> coords = tensor([[50., 100.]])
>>> normalize_pixel_coordinates(coords, 100, 50)
tensor([[1.0408, 1.0202]])
+
"""
if pixel_coordinates.shape[-1] != 2:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 2). Got {pixel_coordinates.shape}")
@@ -891,6 +911,7 @@ def denormalize_pixel_coordinates(pixel_coordinates: Tensor, height: int, width:
>>> coords = tensor([[-1., -1.]])
>>> denormalize_pixel_coordinates(coords, 100, 50)
tensor([[0., 0.]])
+
"""
if pixel_coordinates.shape[-1] != 2:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 2). Got {pixel_coordinates.shape}")
@@ -918,6 +939,7 @@ def normalize_pixel_coordinates3d(
Return:
the normalized pixel coordinates.
+
"""
if pixel_coordinates.shape[-1] != 3:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 3). Got {pixel_coordinates.shape}")
@@ -947,6 +969,7 @@ def denormalize_pixel_coordinates3d(
Return:
the denormalized pixel coordinates.
+
"""
if pixel_coordinates.shape[-1] != 3:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 3). Got {pixel_coordinates.shape}")
@@ -972,6 +995,7 @@ def angle_to_rotation_matrix(angle: Tensor) -> Tensor:
Example:
>>> input = torch.rand(1, 3) # Nx3
>>> output = angle_to_rotation_matrix(input) # Nx3x2x2
+
"""
ang_rad = deg2rad(angle)
cos_a: Tensor = cos(ang_rad)
@@ -992,6 +1016,7 @@ def normalize_homography(
Returns:
the normalized homography of shape :math:`(B, 3, 3)`.
+
"""
if not isinstance(dst_pix_trans_src_pix, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(dst_pix_trans_src_pix)}")
@@ -1030,6 +1055,7 @@ def normal_transform_pixel(
Returns:
normalized transform with shape :math:`(1, 3, 3)`.
+
"""
tr_mat = tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype) # 3x3
@@ -1061,6 +1087,7 @@ def normal_transform_pixel3d(
Returns:
normalized transform with shape :math:`(1, 4, 4)`.
+
"""
tr_mat = tensor(
[[1.0, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, -1.0], [0.0, 0.0, 1.0, -1.0], [0.0, 0.0, 0.0, 1.0]],
@@ -1093,6 +1120,7 @@ def denormalize_homography(
Returns:
the denormalized homography of shape :math:`(B, 3, 3)`.
+
"""
if not isinstance(dst_pix_trans_src_pix, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(dst_pix_trans_src_pix)}")
@@ -1130,6 +1158,7 @@ def normalize_homography3d(
Shape:
Output: :math:`(B, 4, 4)`
+
"""
if not isinstance(dst_pix_trans_src_pix, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(dst_pix_trans_src_pix)}")
@@ -1167,6 +1196,7 @@ def normalize_points_with_intrinsics(point_2d: Tensor, camera_matrix: Tensor) ->
>>> K = torch.eye(3)[None]
>>> normalize_points_with_intrinsics(X, K)
tensor([[0.4963, 0.7682]])
+
"""
KORNIA_CHECK_SHAPE(point_2d, ["*", "2"])
KORNIA_CHECK_SHAPE(camera_matrix, ["*", "3", "3"])
@@ -1200,6 +1230,7 @@ def denormalize_points_with_intrinsics(point_2d_norm: Tensor, camera_matrix: Ten
>>> K = torch.eye(3)[None]
>>> denormalize_points_with_intrinsics(X, K)
tensor([[0.4963, 0.7682]])
+
"""
KORNIA_CHECK_SHAPE(point_2d_norm, ["*", "2"])
KORNIA_CHECK_SHAPE(camera_matrix, ["*", "3", "3"])
@@ -1244,6 +1275,7 @@ def Rt_to_matrix4x4(R: Tensor, t: Tensor) -> Tensor:
[0., 1., 0., 1.],
[0., 0., 1., 1.],
[0., 0., 0., 1.]]])
+
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
@@ -1269,6 +1301,7 @@ def matrix4x4_to_Rt(extrinsics: Tensor) -> tuple[Tensor, Tensor]:
[0., 0., 1.]]]), tensor([[[0.],
[0.],
[0.]]]))
+
"""
KORNIA_CHECK_SHAPE(extrinsics, ["B", "4", "4"])
R, t = extrinsics[:, :3, :3], extrinsics[:, :3, 3:]
@@ -1294,6 +1327,7 @@ def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: Tensor) -> Tensor:
[ 0., -1., 0., 0.],
[ 0., 0., -1., 0.],
[ 0., 0., 0., 1.]]])
+
"""
KORNIA_CHECK_SHAPE(extrinsics_graphics, ["B", "4", "4"])
invert_yz = tensor(
@@ -1326,6 +1360,7 @@ def camtoworld_graphics_to_vision_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tens
[ 0., 0., -1.]]]), tensor([[[1.],
[1.],
[1.]]]))
+
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
@@ -1351,6 +1386,7 @@ def camtoworld_vision_to_graphics_4x4(extrinsics_vision: Tensor) -> Tensor:
[ 0., -1., 0., 0.],
[ 0., 0., -1., 0.],
[ 0., 0., 0., 1.]]])
+
"""
KORNIA_CHECK_SHAPE(extrinsics_vision, ["B", "4", "4"])
invert_yz = tensor(
@@ -1383,6 +1419,7 @@ def camtoworld_vision_to_graphics_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tens
[ 0., 0., -1.]]]), tensor([[[1.],
[1.],
[1.]]]))
+
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
@@ -1412,6 +1449,7 @@ def camtoworld_to_worldtocam_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
[0., 0., 1.]]]), tensor([[[-1.],
[-1.],
[-1.]]]))
+
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
@@ -1442,6 +1480,7 @@ def worldtocam_to_camtoworld_Rt(R: Tensor, t: Tensor) -> tuple[Tensor, Tensor]:
[0., 0., 1.]]]), tensor([[[-1.],
[-1.],
[-1.]]]))
+
"""
KORNIA_CHECK_SHAPE(R, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])
@@ -1470,6 +1509,7 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: Tensor, tvec: Tensor) -> tuple[Tensor, Ten
(tensor([[0.7071, 0.0000, 0.7071, 0.0000]]), tensor([[[-1.0000],
[-1.0000],
[ 1.0000]]]))
+
"""
# ToDo: integrate QuaterniaonAPI
@@ -1503,6 +1543,7 @@ def vector_to_skew_symmetric_matrix(vec: Tensor) -> Tensor:
tensor([[ 0., -3., 2.],
[ 3., 0., -1.],
[-2., 1., 0.]])
+
"""
# KORNIA_CHECK_SHAPE(vec, ["B", "3"])
if vec.shape[-1] != 3 or len(vec.shape) > 2:
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 7bdb05dc8..ceb94640b 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -52,6 +52,7 @@ def unproject_meshgrid(
Return:
tensor with a 3d point per pixel of the same resolution as the input :math:`(*, H, W, 3)`.
+
"""
KORNIA_CHECK_SHAPE(camera_matrix, ["3", "3"])
@@ -97,6 +98,7 @@ def depth_to_3d_v2(
>>> K = torch.eye(3)
>>> depth_to_3d_v2(depth, K).shape
torch.Size([4, 4, 3])
+
"""
KORNIA_CHECK_SHAPE(depth, ["*", "H", "W"])
KORNIA_CHECK_SHAPE(camera_matrix, ["*", "3", "3"])
@@ -142,6 +144,7 @@ def depth_to_3d(depth: Tensor, camera_matrix: Tensor, normalize_points: bool = F
>>> K = torch.eye(3)[None]
>>> depth_to_3d(depth, K).shape
torch.Size([1, 3, 4, 4])
+
"""
KORNIA_CHECK_IS_TENSOR(depth)
KORNIA_CHECK_IS_TENSOR(camera_matrix)
@@ -182,6 +185,7 @@ def depth_to_normals(depth: Tensor, camera_matrix: Tensor, normalize_points: boo
>>> K = torch.eye(3)[None]
>>> depth_to_normals(depth, K).shape
torch.Size([1, 3, 4, 4])
+
"""
KORNIA_CHECK_IS_TENSOR(depth)
KORNIA_CHECK_IS_TENSOR(camera_matrix)
@@ -214,6 +218,7 @@ def depth_from_plane_equation(
Returns:
Tensor: Computed depth values at the given pixels, shape (B, N).
+
"""
KORNIA_CHECK_SHAPE(plane_normals, ["B", "3"])
KORNIA_CHECK_SHAPE(plane_offsets, ["B", "1"])
@@ -257,6 +262,7 @@ def warp_frame_depth(
Return:
the warped tensor in the source frame with shape :math:`(B,3,H,W)`.
+
"""
KORNIA_CHECK_SHAPE(image_src, ["B", "D", "H", "W"])
KORNIA_CHECK_SHAPE(depth_dst, ["B", "1", "H", "W"])
@@ -298,6 +304,7 @@ class DepthWarper(Module):
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
+
"""
def __init__(
@@ -441,6 +448,7 @@ class DepthWarper(Module):
>>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW
>>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
>>> image_src = warper(depth_src, image_dst) # NxCxHxW
+
"""
return kornia_ops.map_coordinates(
patch_dst,
@@ -474,6 +482,7 @@ def depth_warp(
>>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW
>>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
>>> image_src = depth_warp(pinhole_dst, pinhole_src, depth_src, image_dst, 32, 32) # NxCxHxW
+
"""
warper = DepthWarper(pinhole_dst, height, width, align_corners=align_corners)
warper.compute_projection_matrix(pinhole_src)
@@ -497,6 +506,7 @@ def depth_from_disparity(disparity: Tensor, baseline: float | Tensor, focal: flo
>>> focal = torch.rand(1)
>>> depth_from_disparity(disparity, baseline, focal).shape
torch.Size([4, 1, 4, 4])
+
"""
KORNIA_CHECK_IS_TENSOR(disparity, f"Input disparity type is not a Tensor. Got {type(disparity)}.")
KORNIA_CHECK_SHAPE(disparity, ["*", "H", "W"])
diff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.py
index dcf698bfd..5ef2233d8 100644
--- a/kornia/geometry/epipolar/_metrics.py
+++ b/kornia/geometry/epipolar/_metrics.py
@@ -23,6 +23,7 @@ def sampson_epipolar_distance(
Returns:
the computed Sampson distance with shape :math:`(*, N)`.
+
"""
if not isinstance(Fm, Tensor):
raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")
@@ -74,6 +75,7 @@ def symmetrical_epipolar_distance(
Returns:
the computed Symmetrical distance with shape :math:`(*, N)`.
+
"""
if not isinstance(Fm, Tensor):
raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")
@@ -127,6 +129,7 @@ def left_to_right_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> T
Returns:
the computed Symmetrical distance with shape :math:`(*, N)`.
+
"""
KORNIA_CHECK_IS_TENSOR(pts1)
KORNIA_CHECK_IS_TENSOR(pts2)
@@ -160,6 +163,7 @@ def right_to_left_epipolar_distance(pts1: Tensor, pts2: Tensor, Fm: Tensor) -> T
Returns:
the computed Symmetrical distance with shape :math:`(*, N)`.
+
"""
KORNIA_CHECK_IS_TENSOR(pts1)
KORNIA_CHECK_IS_TENSOR(pts2)
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 6fcd9984e..8cc54154d 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -39,6 +39,7 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[t
Returns:
the computed essential matrix with shape :math:`(B, 3, 3)`.
+
"""
KORNIA_CHECK_SHAPE(points1, ["B", "N", "2"])
KORNIA_CHECK_SAME_SHAPE(points1, points2)
@@ -87,8 +88,8 @@ def null_to_Nister_solution(X: torch.Tensor, batch_size: int) -> torch.Tensor:
Returns:
the computed essential matrix with shape :math:`(B, 3, 3)`.
Note that the returned E matrices should be the same batch size with the input.
- """
+ """
# compute eigenvectors and retrieve the one with the smallest eigenvalue, using SVD
# turn off the grad check due to the unstable gradients from SVD.
# several close to zero values of eigenvalues.
@@ -272,6 +273,7 @@ def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
Returns:
The essential matrix with shape :math:`(*, 3, 3)`.
+
"""
KORNIA_CHECK_SHAPE(F_mat, ["*", "3", "3"])
KORNIA_CHECK_SHAPE(K1, ["*", "3", "3"])
@@ -291,6 +293,7 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch
Returns:
A tuple containing the first and second possible rotation matrices and the translation vector.
The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`.
+
"""
KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])
@@ -328,12 +331,13 @@ def decompose_essential_matrix_no_svd(E_mat: torch.Tensor) -> Tuple[torch.Tensor
reference: Horn, Berthold KP. Recovering baseline and orientation from essential matrix[J].
J. Opt. Soc. Am, 1990, 110.
- Args:
+ Args:
E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.
Returns:
A tuple containing the first and second possible rotation matrices and the translation vector.
The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`.
+
"""
KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])
if len(E_mat.shape) != 3:
@@ -398,6 +402,7 @@ def essential_from_Rt(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2:
Returns:
The Essential matrix with the shape :math:`(*, 3, 3)`.
+
"""
KORNIA_CHECK_SHAPE(R1, ["*", "3", "3"])
KORNIA_CHECK_SHAPE(R2, ["*", "3", "3"])
@@ -425,6 +430,7 @@ def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tens
Returns:
The rotation and translation containing the four possible combination for the retrieved motion.
The tuple is as following :math:`[(*, 4, 3, 3), (*, 4, 3, 1)]`.
+
"""
KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])
@@ -469,6 +475,7 @@ def motion_from_essential_choose_solution(
Returns:
The rotation and translation plus the 3d triangulated points.
The tuple is as following :math:`[(*, 3, 3), (*, 3, 1), (*, N, 3)]`.
+
"""
KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])
KORNIA_CHECK_SHAPE(K1, ["*", "3", "3"])
@@ -560,6 +567,7 @@ def relative_camera_motion(
Returns:
A tuple with the relative rotation matrix and
translation vector with the shape of :math:`[(*, 3, 3), (*, 3, 1)]`.
+
"""
KORNIA_CHECK_SHAPE(R1, ["*", "3", "3"])
KORNIA_CHECK_SHAPE(R2, ["*", "3", "3"])
@@ -578,8 +586,7 @@ def relative_camera_motion(
def find_essential(
points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None
) -> torch.Tensor:
- r"""
- Args:
+ r"""Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=5`.
points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=5`.
weights: Tensor containing the weights per point correspondence with a shape of :math:`(5, N)`.
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 0450c76fb..2c04ad314 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -29,6 +29,7 @@ def normalize_points(points: Tensor, eps: float = 1e-8) -> Tuple[Tensor, Tensor]
Returns:
tuple containing the normalized points in the shape :math:`(B, N, 2)` and the transformation matrix
in the shape :math:`(B, 3, 3)`.
+
"""
if len(points.shape) != 3:
raise AssertionError(points.shape)
@@ -64,6 +65,7 @@ def normalize_transformation(M: Tensor, eps: float = 1e-8) -> Tensor:
Returns:
the normalized transformation matrix with same shape as the input.
+
"""
if len(M.shape) < 2:
raise AssertionError(M.shape)
@@ -82,6 +84,7 @@ def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
Returns:
the computed fundamental matrix with shape :math:`(B, 3*m, 3), Valid values of m are 1, 2 or 3`
+
"""
KORNIA_CHECK_SHAPE(points1, ["B", "7", "2"])
KORNIA_CHECK_SHAPE(points2, ["B", "7", "2"])
@@ -178,6 +181,7 @@ def run_8point(points1: Tensor, points2: Tensor, weights: Optional[Tensor] = Non
Returns:
the computed fundamental matrix with shape :math:`(B, 3, 3)`.
+
"""
KORNIA_CHECK_SHAPE(points1, ["B", "N", "2"])
KORNIA_CHECK_SHAPE(points2, ["B", "N", "2"])
@@ -227,8 +231,7 @@ def run_8point(points1: Tensor, points2: Tensor, weights: Optional[Tensor] = Non
def find_fundamental(
points1: Tensor, points2: Tensor, weights: Optional[Tensor] = None, method: Literal["8POINT", "7POINT"] = "8POINT"
) -> Tensor:
- r"""
- Args:
+ r"""Args:
points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.
points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.
weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
@@ -261,6 +264,7 @@ def compute_correspond_epilines(points: Tensor, F_mat: Tensor) -> Tensor:
a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar
lines corresponding to the points to the other image. Each line is described as
:math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.
+
"""
KORNIA_CHECK_SHAPE(points, ["*", "N", "DIM"])
if points.shape[-1] == 2:
@@ -293,6 +297,7 @@ def get_perpendicular(lines: Tensor, points: Tensor) -> Tensor:
a tensor with shape :math:`(*, N, 3)` containing a vector of the epipolar
perpendicular lines. Each line is described as
:math:`ax + by + c = 0` and encoding the vectors as :math:`(a, b, c)`.
+
"""
KORNIA_CHECK_SHAPE(lines, ["*", "N", "3"])
KORNIA_CHECK_SHAPE(points, ["*", "N", "two"])
@@ -319,6 +324,7 @@ def get_closest_point_on_epipolar_line(pts1: Tensor, pts2: Tensor, Fm: Tensor) -
Returns:
point on epipolar line :math:`(*, N, 2)`.
+
"""
if not isinstance(Fm, Tensor):
raise TypeError(f"Fm type is not a torch.Tensor. Got {type(Fm)}")
@@ -346,6 +352,7 @@ def fundamental_from_essential(E_mat: Tensor, K1: Tensor, K2: Tensor) -> Tensor:
Returns:
The fundamental matrix with shape :math:`(*, 3, 3)`.
+
"""
KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])
KORNIA_CHECK_SHAPE(K1, ["*", "3", "3"])
@@ -370,6 +377,7 @@ def fundamental_from_projections(P1: Tensor, P2: Tensor) -> Tensor:
Returns:
The fundamental matrix with shape :math:`(*, 3, 3)`.
+
"""
KORNIA_CHECK_SHAPE(P1, ["*", "3", "4"])
KORNIA_CHECK_SHAPE(P2, ["*", "3", "4"])
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
index 6b17b7826..44bb36c7c 100644
--- a/kornia/geometry/epipolar/numeric.py
+++ b/kornia/geometry/epipolar/numeric.py
@@ -13,6 +13,7 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
Returns:
The constructed cross_product_matrix symmetric matrix with shape :math:`(*, 3, 3)`.
+
"""
if not x.shape[-1] == 3:
raise AssertionError(x.shape)
@@ -33,6 +34,7 @@ def matrix_cofactor_tensor(matrix: torch.Tensor) -> torch.Tensor:
Args:
matrix: The input matrix in the shape :math:`(*, 3, 3)`.
+
"""
det = torch.det(matrix)
singular_mask = det != 0
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index cec8da7cd..5184b5d52 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -25,6 +25,7 @@ def intrinsics_like(focal: float, input: Tensor) -> Tensor:
Returns:
The camera matrix with the shape of :math:`(B, 3, 3)`.
+
"""
if len(input.shape) != 4:
raise AssertionError(input.shape)
@@ -50,6 +51,7 @@ def random_intrinsics(low: Union[float, Tensor], high: Union[float, Tensor]) ->
Returns:
the random camera matrix with the shape of :math:`(1, 3, 3)`.
+
"""
sampler = torch.distributions.Uniform(low, high)
fx, fy, cx, cy = (sampler.sample(torch.Size((1,))) for _ in range(4))
@@ -70,6 +72,7 @@ def scale_intrinsics(camera_matrix: Tensor, scale_factor: Union[float, Tensor])
Returns:
The scaled camera matrix with shame shape as input :math:`(B, 3, 3)`.
+
"""
K_scale = camera_matrix.clone()
K_scale[..., 0, 0] *= scale_factor
@@ -91,6 +94,7 @@ def projection_from_KRt(K: Tensor, R: Tensor, t: Tensor) -> Tensor:
Returns:
The projection matrix P with shape :math:`(B, 4, 4)`.
+
"""
KORNIA_CHECK_SHAPE(K, ["*", "3", "3"])
KORNIA_CHECK_SHAPE(R, ["*", "3", "3"])
@@ -118,6 +122,7 @@ def KRt_from_projection(P: Tensor, eps: float = 1e-6) -> Tuple[Tensor, Tensor, T
- The Camera matrix with shape :math:`(B, 3, 3)`.
- The Rotation matrix with shape :math:`(B, 3, 3)`.
- The Translation vector with shape :math:`(B, 3)`.
+
"""
KORNIA_CHECK_SHAPE(P, ["*", "3", "4"])
submat_3x3 = P[:, 0:3, 0:3]
@@ -152,6 +157,7 @@ def depth_from_point(R: Tensor, t: Tensor, X: Tensor) -> Tensor:
Returns:
The depth value per point with shape :math:`(*, 1)`.
+
"""
X_tmp = R @ X.transpose(-2, -1)
X_out = X_tmp[..., 2, :] + t[..., 2, :]
@@ -178,6 +184,7 @@ def projections_from_fundamental(F_mat: Tensor) -> Tensor:
Returns:
The projection matrices with shape :math:`(B, 3, 4, 2)`.
+
"""
KORNIA_CHECK_SHAPE(F_mat, ["*", "3", "3"])
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index d81302e06..9521eecab 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -31,6 +31,7 @@ def triangulate_points(
Returns:
The reconstructed 3d points in the world frame with shape :math:`(*, N, 3)`.
+
"""
KORNIA_CHECK_SHAPE(P1, ["*", "3", "4"])
KORNIA_CHECK_SHAPE(P2, ["*", "3", "4"])
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 55cc331b9..91b49d195 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -29,6 +29,7 @@ def oneway_transfer_error(pts1: Tensor, pts2: Tensor, H: Tensor, squared: bool =
Returns:
the computed distance with shape :math:`(B, N)`.
+
"""
KORNIA_CHECK_SHAPE(H, ["B", "3", "3"])
@@ -61,6 +62,7 @@ def symmetric_transfer_error(pts1: Tensor, pts2: Tensor, H: Tensor, squared: boo
Returns:
the computed distance with shape :math:`(B, N)`.
+
"""
KORNIA_CHECK_SHAPE(H, ["B", "3", "3"])
if pts1.size(-1) == 3:
@@ -99,6 +101,7 @@ def line_segment_transfer_error_one_way(ls1: Tensor, ls2: Tensor, H: Tensor, squ
Returns:
the computed distance with shape :math:`(B, N)`.
+
"""
KORNIA_CHECK_SHAPE(H, ["B", "3", "3"])
KORNIA_CHECK_SHAPE(ls1, ["B", "N", "2", "2"])
@@ -135,6 +138,7 @@ def find_homography_dlt(
Returns:
the computed homography matrix with shape :math:`(B, 3, 3)`.
+
"""
if points1.shape != points2.shape:
raise AssertionError(points1.shape)
@@ -203,6 +207,7 @@ def find_homography_dlt_iterated(
Returns:
the computed homography matrix with shape :math:`(B, 3, 3)`.
+
"""
H: Tensor = find_homography_dlt(points1, points2, weights)
for _ in range(n_iter - 1):
@@ -223,6 +228,7 @@ def sample_is_valid_for_homography(points1: Tensor, points2: Tensor) -> Tensor:
Returns:
Mask with the minimal sample is good for homography estimation:math:`(B, 3, 3)`.
+
"""
if points1.shape != points2.shape:
raise AssertionError(points1.shape)
@@ -259,6 +265,7 @@ def find_homography_lines_dlt(ls1: Tensor, ls2: Tensor, weights: Optional[Tensor
Returns:
the computed homography matrix with shape :math:`(B, 3, 3)`.
+
"""
if len(ls1.shape) == 3:
ls1 = ls1[None]
@@ -331,6 +338,7 @@ def find_homography_lines_dlt_iterated(
Returns:
the computed homography matrix with shape :math:`(B, 3, 3)`.
+
"""
H: Tensor = find_homography_lines_dlt(ls1, ls2, weights)
for _ in range(n_iter - 1):
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index 623deacfc..39fb8060c 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -19,6 +19,7 @@ class Keypoints:
Args:
keypoints: Raw tensor or a list of Tensors with the Nx2 coordinates
raise_if_not_floating_point: will raise if the Tensor isn't float
+
"""
def __init__(self, keypoints: Union[Tensor, List[Tensor]], raise_if_not_floating_point: bool = True) -> None:
@@ -102,6 +103,7 @@ class Keypoints:
Args:
padding_size: (B, 4)
+
"""
if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
@@ -114,6 +116,7 @@ class Keypoints:
Args:
padding_size: (B, 4)
+
"""
if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
@@ -130,6 +133,7 @@ class Keypoints:
Returns:
The transformed keypoints.
+
"""
if not 2 <= M.ndim <= 3 or M.shape[-2:] != (3, 3):
raise ValueError(f"The transformation matrix shape must be (3, 3) or (B, 3, 3). Got {M.shape}.")
@@ -159,6 +163,7 @@ class Keypoints:
Returns:
Keypoints tensor :math:`(B, N, 2)`
+
"""
if as_padded_sequence:
raise NotImplementedError
@@ -213,6 +218,7 @@ class Keypoints3D:
Args:
keypoints: Raw tensor or a list of Tensors with the Nx3 coordinates
raise_if_not_floating_point: will raise if the Tensor isn't float
+
"""
def __init__(self, keypoints: Union[Tensor, List[Tensor]], raise_if_not_floating_point: bool = True) -> None:
@@ -263,6 +269,7 @@ class Keypoints3D:
Args:
padding_size: (B, 6)
+
"""
raise NotImplementedError
@@ -271,6 +278,7 @@ class Keypoints3D:
Args:
padding_size: (B, 6)
+
"""
raise NotImplementedError
@@ -283,6 +291,7 @@ class Keypoints3D:
Returns:
The transformed keypoints.
+
"""
raise NotImplementedError
@@ -304,6 +313,7 @@ class Keypoints3D:
Returns:
Keypoints tensor :math:`(B, N, 3)`
+
"""
if as_padded_sequence:
raise NotImplementedError
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 1d5e07e4a..5ca558cf9 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -50,6 +50,7 @@ class Se2(Module):
tensor([1.+0.j], requires_grad=True)
translation: Parameter containing:
tensor([[1., 1.]], requires_grad=True)
+
"""
def __init__(self, rotation: So2, translation: Vector2 | Tensor) -> None:
@@ -70,6 +71,7 @@ class Se2(Module):
tensor([1.+0.j], requires_grad=True)
translation: Parameter containing:
tensor([[1., 1.]], requires_grad=True)
+
"""
super().__init__()
KORNIA_CHECK_TYPE(rotation, So2)
@@ -112,6 +114,7 @@ class Se2(Module):
Return:
The resulting Se2 transformation.
+
"""
so2 = self.so2
t = self.t
@@ -127,12 +130,12 @@ class Se2(Module):
@property
def so2(self) -> So2:
- """Return the underlying rotation(So2)."""
+ """Return the underlying `rotation(So2)`."""
return self._rotation
@property
def r(self) -> So2:
- """Return the underlying rotation(So2)."""
+ """Return the underlying `rotation(So2)`."""
return self._rotation
@property
@@ -142,7 +145,7 @@ class Se2(Module):
@property
def rotation(self) -> So2:
- """Return the underlying rotation(So2)."""
+ """Return the underlying `rotation(So2)`."""
return self._rotation
@property
@@ -166,6 +169,7 @@ class Se2(Module):
>>> s.t
Parameter containing:
tensor([[0.3818, 1.3012]], requires_grad=True)
+
"""
check_v_shape(v)
theta = v[..., 2]
@@ -187,6 +191,7 @@ class Se2(Module):
>>> s = Se2.exp(v).log()
>>> s
tensor([[1.0000, 1.0000, 1.0000]], grad_fn=<StackBackward0>)
+
"""
theta = self.so2.log()
half_theta = 0.5 * theta
@@ -212,6 +217,7 @@ class Se2(Module):
>>> So2.hat(theta)
tensor([[0.0000, 1.5707],
[1.5707, 0.0000]])
+
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_v_shape(v)
@@ -235,6 +241,7 @@ class Se2(Module):
>>> omega_hat = Se2.hat(v)
>>> Se2.vee(omega_hat)
tensor([1., 1., 1.])
+
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_se2_omega_shape(omega)
@@ -257,6 +264,7 @@ class Se2(Module):
>>> s.t
x: tensor([0.])
y: tensor([0.])
+
"""
t: Tensor = tensor([0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
@@ -273,6 +281,7 @@ class Se2(Module):
tensor([[[1., -0., 1.],
[0., 1., 1.],
[0., 0., 1.]]], grad_fn=<CopySlices>)
+
"""
rt = concatenate((self.r.matrix(), self.t.data[..., None]), -1)
rt_3x3 = pad(rt, (0, 0, 0, 1)) # add last row zeros
@@ -295,6 +304,7 @@ class Se2(Module):
Parameter containing:
tensor([[0., 0.],
[0., 0.]], requires_grad=True)
+
"""
# KORNIA_CHECK_SHAPE(matrix, ["B", "3", "3"]) # FIXME: resolve shape bugs. @edgarriba
r = So2.from_matrix(matrix[..., :2, :2])
@@ -313,6 +323,7 @@ class Se2(Module):
>>> s_inv.t
Parameter containing:
tensor([[-1., -1.]], requires_grad=True)
+
"""
r_inv: So2 = self.r.inverse()
_t = -1 * self.t
@@ -331,6 +342,7 @@ class Se2(Module):
Example:
>>> s = Se2.random()
>>> s = Se2.random(batch_size=3)
+
"""
r = So2.random(batch_size, device, dtype)
shape: tuple[int, ...]
@@ -348,6 +360,7 @@ class Se2(Module):
Args:
x: the x-axis translation.
y: the y-axis translation.
+
"""
KORNIA_CHECK(x.shape == y.shape)
KORNIA_CHECK_SAME_DEVICES([x, y])
@@ -361,6 +374,7 @@ class Se2(Module):
Args:
x: the x-axis translation.
+
"""
zs = zeros_like(x)
return cls.trans(x, zs)
@@ -371,6 +385,7 @@ class Se2(Module):
Args:
y: the y-axis translation.
+
"""
zs = zeros_like(y)
return cls.trans(zs, y)
@@ -384,6 +399,7 @@ class Se2(Module):
tensor([[1., -0., 0.],
[0., 1., -0.],
[0., 0., 1.]], grad_fn=<CopySlices>)
+
"""
rt = self.matrix()
rt[..., 0:2, 2] = stack((self.t.data[..., 1], -self.t.data[..., 0]), -1)
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index a4d2912ec..bf883cb7b 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -41,6 +41,7 @@ class Se3(Module):
>>> s.t
Parameter containing:
tensor([1., 1., 1.], requires_grad=True)
+
"""
def __init__(self, rotation: Quaternion | So3, translation: Vector3 | Tensor) -> None:
@@ -62,6 +63,7 @@ class Se3(Module):
>>> s.t
Parameter containing:
tensor([[1., 1., 1.]], requires_grad=True)
+
"""
super().__init__()
# KORNIA_CHECK_TYPE(rotation, (Quaternion, So3))
@@ -101,6 +103,7 @@ class Se3(Module):
Return:
The resulting Se3 transformation.
+
"""
so3 = self.so3
t = self.t
@@ -135,7 +138,7 @@ class Se3(Module):
@property
def rotation(self) -> So3:
- """Return the underlying rotation(So3)."""
+ """Return the underlying `rotation(So3)`."""
return self._rotation
@property
@@ -159,6 +162,7 @@ class Se3(Module):
>>> s.t
Parameter containing:
tensor([[0., 0., 0.]], requires_grad=True)
+
"""
# KORNIA_CHECK_SHAPE(v, ["B", "6"]) # FIXME: resolve shape bugs. @edgarriba
upsilon = v[..., :3]
@@ -183,6 +187,7 @@ class Se3(Module):
>>> q = Quaternion.identity()
>>> Se3(q, torch.zeros(3)).log()
tensor([0., 0., 0., 0., 0., 0.], grad_fn=<CatBackward0>)
+
"""
omega = self.r.log()
theta = batched_dot_product(omega, omega).sqrt()
@@ -215,6 +220,7 @@ class Se3(Module):
[ 1., 0., -1., 1.],
[-1., 1., 0., 1.],
[ 0., 0., 0., 0.]]])
+
"""
# KORNIA_CHECK_SHAPE(v, ["B", "6"]) # FIXME: resolve shape bugs. @edgarriba
upsilon, omega = v[..., :3], v[..., 3:]
@@ -236,6 +242,7 @@ class Se3(Module):
>>> omega_hat = Se3.hat(v)
>>> Se3.vee(omega_hat)
tensor([[1., 1., 1., 1., 1., 1.]])
+
"""
# KORNIA_CHECK_SHAPE(omega, ["B", "4", "4"]) # FIXME: resolve shape bugs. @edgarriba
head = omega[..., :3, -1]
@@ -258,6 +265,7 @@ class Se3(Module):
x: 0.0
y: 0.0
z: 0.0
+
"""
t = tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
@@ -275,6 +283,7 @@ class Se3(Module):
[0., 1., 0., 1.],
[0., 0., 1., 1.],
[0., 0., 0., 1.]], grad_fn=<CopySlices>)
+
"""
rt = concatenate((self.r.matrix(), self.t.data[..., None]), -1)
rt_4x4 = pad(rt, (0, 0, 0, 1)) # add last row zeros
@@ -296,6 +305,7 @@ class Se3(Module):
>>> s.t
Parameter containing:
tensor([0., 0., 0.], requires_grad=True)
+
"""
# KORNIA_CHECK_SHAPE(matrix, ["B", "4", "4"]) # FIXME: resolve shape bugs. @edgarriba
r = So3.from_matrix(matrix[..., :3, :3])
@@ -319,6 +329,7 @@ class Se3(Module):
x: 0.0
y: 0.0
z: 1.0
+
"""
# KORNIA_CHECK_SHAPE(qxyz, ["B", "7"]) # FIXME: resolve shape bugs. @edgarriba
q, xyz = qxyz[..., :4], qxyz[..., 4:]
@@ -336,6 +347,7 @@ class Se3(Module):
>>> s_inv.t
Parameter containing:
tensor([-1., -1., -1.], requires_grad=True)
+
"""
r_inv = self.r.inverse()
_t = -1 * self.t
@@ -354,6 +366,7 @@ class Se3(Module):
Example:
>>> s = Se3.random()
>>> s = Se3.random(batch_size=3)
+
"""
shape: tuple[int, ...]
if batch_size is None:
@@ -371,6 +384,7 @@ class Se3(Module):
Args:
x: the x-axis rotation angle.
+
"""
zs = zeros_like(x)
return cls(So3.rot_x(x), stack((zs, zs, zs), -1))
@@ -381,6 +395,7 @@ class Se3(Module):
Args:
y: the y-axis rotation angle.
+
"""
zs = zeros_like(y)
return cls(So3.rot_y(y), stack((zs, zs, zs), -1))
@@ -391,6 +406,7 @@ class Se3(Module):
Args:
z: the z-axis rotation angle.
+
"""
zs = zeros_like(z)
return cls(So3.rot_z(z), stack((zs, zs, zs), -1))
@@ -403,6 +419,7 @@ class Se3(Module):
x: the x-axis translation.
y: the y-axis translation.
z: the z-axis translation.
+
"""
KORNIA_CHECK(x.shape == y.shape)
KORNIA_CHECK(y.shape == z.shape)
@@ -417,6 +434,7 @@ class Se3(Module):
Args:
x: the x-axis translation.
+
"""
zs = zeros_like(x)
return cls.trans(x, zs, zs)
@@ -427,6 +445,7 @@ class Se3(Module):
Args:
y: the y-axis translation.
+
"""
zs = zeros_like(y)
return cls.trans(zs, y, zs)
@@ -437,6 +456,7 @@ class Se3(Module):
Args:
z: the z-axis translation.
+
"""
zs = zeros_like(z)
return cls.trans(zs, zs, z)
@@ -453,6 +473,7 @@ class Se3(Module):
[0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 1.]], grad_fn=<CatBackward0>)
+
"""
R = self.so3.matrix()
z = zeros_like(R)
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index cfce67a69..ef8bb08d0 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -31,6 +31,7 @@ class So2(Module):
>>> So2(torch.complex(real, imag))
Parameter containing:
tensor([1.+2.j], requires_grad=True)
+
"""
def __init__(self, z: Tensor) -> None:
@@ -47,6 +48,7 @@ class So2(Module):
>>> So2(torch.complex(real, imag)).z
Parameter containing:
tensor(1.+2.j, requires_grad=True)
+
"""
super().__init__()
KORNIA_CHECK_IS_TENSOR(z)
@@ -74,6 +76,7 @@ class So2(Module):
Return:
The resulting So2 transformation.
+
"""
z = self.z
if isinstance(right, So2):
@@ -112,6 +115,7 @@ class So2(Module):
>>> s
Parameter containing:
tensor([4.6329e-05+1.j], requires_grad=True)
+
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_so2_theta_shape(theta)
@@ -125,6 +129,7 @@ class So2(Module):
>>> imag = torch.tensor([3.0])
>>> So2(torch.complex(real, imag)).log()
tensor([1.2490], grad_fn=<Atan2Backward0>)
+
"""
return self.z.imag.atan2(self.z.real)
@@ -140,6 +145,7 @@ class So2(Module):
>>> So2.hat(theta)
tensor([[0.0000, 1.5707],
[1.5707, 0.0000]])
+
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_so2_theta_shape(theta)
@@ -160,6 +166,7 @@ class So2(Module):
>>> omega = So2.hat(v)
>>> So2.vee(omega)
tensor([1., 1., 1.])
+
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_so2_matrix_shape(omega)
@@ -174,6 +181,7 @@ class So2(Module):
>>> m
tensor([[1., -0.],
[0., 1.]], grad_fn=<StackBackward0>)
+
"""
row0 = stack((self.z.real, -self.z.imag), -1)
row1 = stack((self.z.imag, self.z.real), -1)
@@ -192,6 +200,7 @@ class So2(Module):
>>> s.z
Parameter containing:
tensor(1.+0.j, requires_grad=True)
+
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
check_so2_matrix_shape(matrix)
@@ -213,6 +222,7 @@ class So2(Module):
>>> s
Parameter containing:
tensor([1.+0.j, 1.+0.j], requires_grad=True)
+
"""
real_data = tensor(1.0, device=device, dtype=dtype)
imag_data = tensor(0.0, device=device, dtype=dtype)
@@ -230,6 +240,7 @@ class So2(Module):
>>> s.inverse().z
Parameter containing:
tensor(1.+0.j, requires_grad=True)
+
"""
return So2(1 / self.z)
@@ -245,6 +256,7 @@ class So2(Module):
Example:
>>> s = So2.random()
>>> s = So2.random(batch_size=3)
+
"""
if batch_size is not None:
KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")
@@ -263,6 +275,7 @@ class So2(Module):
>>> s.adjoint()
tensor([[1., -0.],
[0., 1.]], grad_fn=<StackBackward0>)
+
"""
batch_size = len(self.z) if len(self.z.shape) > 0 else None
return self.identity(batch_size, self.z.device, self.z.real.dtype).matrix()
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 6c46b9327..0a27d805d 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -27,6 +27,7 @@ class So3(Module):
>>> s.q
Parameter containing:
tensor([1., 0., 0., 0.], requires_grad=True)
+
"""
def __init__(self, q: Quaternion) -> None:
@@ -44,6 +45,7 @@ class So3(Module):
Parameter containing:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.]], requires_grad=True)
+
"""
super().__init__()
KORNIA_CHECK_TYPE(q, Quaternion)
@@ -63,6 +65,7 @@ class So3(Module):
Return:
The resulting So3 transformation.
+
"""
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L98
if isinstance(right, So3):
@@ -100,6 +103,7 @@ class So3(Module):
Parameter containing:
tensor([[1., 0., 0., 0.],
[1., 0., 0., 0.]], requires_grad=True)
+
"""
# KORNIA_CHECK_SHAPE(v, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
theta = batched_dot_product(v, v).sqrt()[..., None]
@@ -122,6 +126,7 @@ class So3(Module):
>>> So3(q).log()
tensor([[0., 0., 0.],
[0., 0., 0.]], grad_fn=<WhereBackward0>)
+
"""
theta = batched_dot_product(self.q.vec, self.q.vec).sqrt()
# NOTE: this differs from https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L33
@@ -146,6 +151,7 @@ class So3(Module):
tensor([[[ 0., -1., 1.],
[ 1., 0., -1.],
[-1., 1., 0.]]])
+
"""
# KORNIA_CHECK_SHAPE(v, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
if isinstance(v, Tensor):
@@ -176,6 +182,7 @@ class So3(Module):
>>> omega = So3.hat(v)
>>> So3.vee(omega)
tensor([[1., 1., 1.]])
+
"""
# KORNIA_CHECK_SHAPE(omega, ["B", "3", "3"]) # FIXME: resolve shape bugs. @edgarriba
a, b, c = omega[..., 2, 1], omega[..., 0, 2], omega[..., 1, 0]
@@ -198,6 +205,7 @@ class So3(Module):
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]], grad_fn=<StackBackward0>)
+
"""
w = self.q.w[..., None]
x, y, z = self.q.x[..., None], self.q.y[..., None], self.q.z[..., None]
@@ -228,6 +236,7 @@ class So3(Module):
>>> s
Parameter containing:
tensor([1., 0., 0., 0.], requires_grad=True)
+
"""
return cls(Quaternion.from_matrix(matrix))
@@ -244,6 +253,7 @@ class So3(Module):
>>> s
Parameter containing:
tensor([1., 0., 0., 0.], requires_grad=True)
+
"""
# KORNIA_CHECK_SHAPE(wxyz, ["B", "4"]) # FIXME: resolve shape bugs. @edgarriba
return cls(Quaternion(wxyz))
@@ -268,6 +278,7 @@ class So3(Module):
Parameter containing:
tensor([[1., 0., 0., 0.],
[1., 0., 0., 0.]], requires_grad=True)
+
"""
return cls(Quaternion.identity(batch_size, device, dtype))
@@ -279,6 +290,7 @@ class So3(Module):
>>> s.inverse()
Parameter containing:
tensor([1., -0., -0., -0.], requires_grad=True)
+
"""
return So3(self.q.conj())
@@ -294,6 +306,7 @@ class So3(Module):
Example:
>>> s = So3.random()
>>> s = So3.random(batch_size=3)
+
"""
return cls(Quaternion.random(batch_size, device, dtype))
@@ -303,6 +316,7 @@ class So3(Module):
Args:
x: the x-axis rotation angle.
+
"""
zs = zeros_like(x)
return cls.exp(stack((x, zs, zs), -1))
@@ -313,6 +327,7 @@ class So3(Module):
Args:
y: the y-axis rotation angle.
+
"""
zs = zeros_like(y)
return cls.exp(stack((zs, y, zs), -1))
@@ -323,6 +338,7 @@ class So3(Module):
Args:
z: the z-axis rotation angle.
+
"""
zs = zeros_like(z)
return cls.exp(stack((zs, zs, z), -1))
@@ -336,6 +352,7 @@ class So3(Module):
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]], grad_fn=<StackBackward0>)
+
"""
return self.matrix()
@@ -352,6 +369,7 @@ class So3(Module):
tensor([[-0.0687, 0.5556, -0.0141],
[-0.2267, 0.1779, 0.6236],
[ 0.5074, 0.3629, 0.5890]])
+
"""
# KORNIA_CHECK_SHAPE(vec, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
R_skew = vector_to_skew_symmetric_matrix(vec)
@@ -366,6 +384,7 @@ class So3(Module):
Args:
vec: the input point of shape :math:`(B, 3)`.
+
"""
return So3.right_jacobian(vec)
@@ -382,6 +401,7 @@ class So3(Module):
tensor([[-0.0687, -0.2267, 0.5074],
[ 0.5556, 0.1779, 0.3629],
[-0.0141, 0.6236, 0.5890]])
+
"""
# KORNIA_CHECK_SHAPE(vec, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
R_skew = vector_to_skew_symmetric_matrix(vec)
@@ -396,5 +416,6 @@ class So3(Module):
Args:
vec: the input point of shape :math:`(B, 3)`.
+
"""
return So3.left_jacobian(vec)
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 066817be8..4c4ae5d5f 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -41,6 +41,7 @@ def compose_transformations(trans_01: Tensor, trans_12: Tensor) -> Tensor:
>>> trans_01 = torch.eye(4) # 4x4
>>> trans_12 = torch.eye(4) # 4x4
>>> trans_02 = compose_transformations(trans_01, trans_12) # 4x4
+
"""
KORNIA_CHECK_IS_TENSOR(trans_01)
KORNIA_CHECK_IS_TENSOR(trans_12)
@@ -93,6 +94,7 @@ def inverse_transformation(trans_12: Tensor) -> Tensor:
Example:
>>> trans_12 = torch.rand(1, 4, 4) # Nx4x4
>>> trans_21 = inverse_transformation(trans_12) # Nx4x4
+
"""
KORNIA_CHECK_IS_TENSOR(trans_12)
@@ -137,6 +139,7 @@ def relative_transformation(trans_01: Tensor, trans_02: Tensor) -> Tensor:
>>> trans_01 = torch.eye(4) # 4x4
>>> trans_02 = torch.eye(4) # 4x4
>>> trans_12 = relative_transformation(trans_01, trans_02) # 4x4
+
"""
KORNIA_CHECK_IS_TENSOR(trans_01)
KORNIA_CHECK_IS_TENSOR(trans_02)
@@ -159,6 +162,7 @@ def transform_points(trans_01: Tensor, points_1: Tensor) -> Tensor:
trans_01: tensor for transformations of shape
:math:`(B, D+1, D+1)`.
points_1: tensor of points of shape :math:`(B, N, D)`.
+
Returns:
a tensor of N-dimensional points.
@@ -166,10 +170,10 @@ def transform_points(trans_01: Tensor, points_1: Tensor) -> Tensor:
- Output: :math:`(B, N, D)`
Examples:
-
>>> points_1 = torch.rand(2, 4, 3) # BxNx3
>>> trans_01 = torch.eye(4).view(1, 4, 4) # Bx4x4
>>> points_0 = transform_points(trans_01, points_1) # BxNx3
+
"""
KORNIA_CHECK_IS_TENSOR(trans_01)
KORNIA_CHECK_IS_TENSOR(points_1)
@@ -211,6 +215,7 @@ def point_line_distance(point: Tensor, line: Tensor, eps: float = 1e-9) -> Tenso
Returns:
the computed distance with shape :math:`(*, N)`.
+
"""
KORNIA_CHECK_IS_TENSOR(point)
KORNIA_CHECK_IS_TENSOR(line)
@@ -249,6 +254,7 @@ def euclidean_distance(x: Tensor, y: Tensor, keepdim: bool = False, eps: float =
y: second set of points of shape :math:`(*, N)`.
keepdim: whether to keep the dimension after reduction.
eps: small value to have numerical stability.
+
"""
KORNIA_CHECK_SHAPE(x, ["*", "N"])
KORNIA_CHECK_SHAPE(y, ["*", "N"])
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index d2ee95b63..6f1b930f1 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -35,6 +35,7 @@ class ParametrizedLine(Module):
>>> o = torch.tensor([0.0, 0.0])
>>> d = torch.tensor([1.0, 1.0])
>>> l = ParametrizedLine(o, d)
+
"""
super().__init__()
self._origin = Parameter(origin)
@@ -78,6 +79,7 @@ class ParametrizedLine(Module):
>>> p0 = torch.tensor([0.0, 0.0])
>>> p1 = torch.tensor([1.0, 1.0])
>>> l = ParametrizedLine.through(p0, p1)
+
"""
return ParametrizedLine(p0, normalize((p1 - p0), p=2, dim=-1))
@@ -95,6 +97,7 @@ class ParametrizedLine(Module):
>>> p1 = torch.tensor([1.0, 1.0])
>>> l = ParametrizedLine.through(p0, p1)
>>> p2 = l.point_at(0.1)
+
"""
return self.origin + self.direction * t
@@ -103,6 +106,7 @@ class ParametrizedLine(Module):
Args:
point: the point to be projected.
+
"""
return self.origin + (self.direction @ (point - self.origin)) * self.direction
@@ -112,6 +116,7 @@ class ParametrizedLine(Module):
Args:
point: the point to calculate the distance onto the line.
+
"""
diff: Tensor = point - self.origin
return squared_norm(diff - (self.direction @ diff) * self.direction)
@@ -122,6 +127,7 @@ class ParametrizedLine(Module):
Args:
point: the point to calculate the distance into the line.
+
"""
return self.squared_distance(point).sqrt()
@@ -140,6 +146,7 @@ class ParametrizedLine(Module):
Return:
- the lambda value used to compute the look at point.
- the intersected point.
+
"""
dot_prod = batched_dot_product(plane.normal.data, self.direction.data)
dot_prod_mask = dot_prod.abs() >= eps
@@ -173,6 +180,7 @@ def fit_line(points: Tensor, weights: Optional[Tensor] = None) -> ParametrizedLi
>>> line = fit_line(points, weights)
>>> line.direction.shape
torch.Size([2, 3])
+
"""
KORNIA_CHECK_IS_TENSOR(points, "points must be a tensor")
KORNIA_CHECK_SHAPE(points, ["B", "N", "D"])
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 59d11bef7..64b46fb50 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -113,6 +113,7 @@ def fit_plane(points: Vector3) -> Hyperplane:
Return:
The computed hyperplane object.
+
"""
# TODO: fix to support more type check here
# KORNIA_CHECK_SHAPE(points, ["N", "D"])
diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.py
index 0f753fb54..2559bb9a3 100644
--- a/kornia/geometry/pose.py
+++ b/kornia/geometry/pose.py
@@ -34,6 +34,7 @@ class NamedPose:
y: 0.0
z: 0.0,
frame_src: frame_a -> frame_dst: frame_b)
+
"""
def __init__(self, dst_from_src: Se2 | Se3, frame_src: str | None = None, frame_dst: str | None = None) -> None:
@@ -43,6 +44,7 @@ class NamedPose:
dst_from_src: Pose from source frame to destination frame.
src: Name of frame a.
dst: Name of frame b.
+
"""
self._dst_from_src = dst_from_src
self._frame_src = frame_src or uuid.uuid4().hex
@@ -73,6 +75,7 @@ class NamedPose:
y: 0.0
z: 0.0,
frame_src: frame_a -> frame_dst: frame_c)
+
"""
if self._frame_src != other._frame_dst:
raise ValueError(f"Cannot compose {self} with {other}")
@@ -137,6 +140,7 @@ class NamedPose:
translation: Parameter containing:
tensor([1., 2., 3.], requires_grad=True),
frame_src: frame_a -> frame_dst: frame_b)
+
"""
if isinstance(rotation, (So3, Quaternion)):
return cls(Se3(rotation, translation), frame_src, frame_dst)
@@ -179,6 +183,7 @@ class NamedPose:
translation: Parameter containing:
tensor([0., 0., 0.], requires_grad=True),
frame_src: frame_a -> frame_dst: frame_b)
+
"""
check_matrix_shape(matrix, matrix_type="RT")
dim = matrix.shape[-1]
@@ -203,6 +208,7 @@ class NamedPose:
y: 0.0
z: 0.0,
frame_src: frame_b -> frame_dst: frame_a)
+
"""
return NamedPose(self._dst_from_src.inverse(), self._frame_dst, self._frame_src)
@@ -219,5 +225,6 @@ class NamedPose:
>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")
>>> b_from_a.transform_points(torch.tensor([1., 2., 3.]))
tensor([1., 2., 3.], grad_fn=<AddBackward0>)
+
"""
return self._dst_from_src * points_in_src
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index 30b6b5a6d..f9c8387b3 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -53,6 +53,7 @@ class Quaternion(Module):
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], grad_fn=<SliceBackward0>)
+
"""
def __init__(self, data: Tensor) -> None:
@@ -66,6 +67,7 @@ class Quaternion(Module):
>>> q = Quaternion(data)
>>> q.shape
(2, 4)
+
"""
super().__init__()
# KORNIA_CHECK_SHAPE(data, ["B", "4"]) # FIXME: resolve shape bugs. @edgarriba
@@ -84,6 +86,7 @@ class Quaternion(Module):
>>> q = Quaternion.identity()
>>> -q.data
tensor([-1., -0., -0., -0.], grad_fn=<NegBackward0>)
+
"""
return Quaternion(-self.data)
@@ -100,6 +103,7 @@ class Quaternion(Module):
>>> q3.data
Parameter containing:
tensor([3., 0., 1., 1.], requires_grad=True)
+
"""
KORNIA_CHECK_TYPE(right, Quaternion)
return Quaternion(self.data + right.data)
@@ -117,6 +121,7 @@ class Quaternion(Module):
>>> q3.data
Parameter containing:
tensor([1., 0., 1., 1.], requires_grad=True)
+
"""
KORNIA_CHECK_TYPE(right, Quaternion)
return Quaternion(self.data - right.data)
@@ -147,6 +152,7 @@ class Quaternion(Module):
Example:
>>> q = Quaternion(tensor([1., .5, 0., 0.]))
>>> q_pow = q**2
+
"""
theta = self.polar_angle[..., None]
vec_norm = self.vec.norm(dim=-1, keepdim=True)
@@ -229,6 +235,7 @@ class Quaternion(Module):
>>> q = Quaternion.identity()
>>> q.polar_angle
tensor(0., grad_fn=<AcosBackward0>)
+
"""
return (self.scalar / self.norm()).acos()
@@ -242,6 +249,7 @@ class Quaternion(Module):
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]], grad_fn=<ViewBackward0>)
+
"""
return quaternion_to_rotation_matrix(self.data)
@@ -258,6 +266,7 @@ class Quaternion(Module):
>>> q.data
Parameter containing:
tensor([[1., 0., 0., 0.]], requires_grad=True)
+
"""
return cls(rotation_matrix_to_quaternion(matrix))
@@ -276,6 +285,7 @@ class Quaternion(Module):
>>> q.data
Parameter containing:
tensor([0.8776, 0.0000, 0.4794, 0.0000], requires_grad=True)
+
"""
w, x, y, z = quaternion_from_euler(roll=roll, pitch=pitch, yaw=yaw)
q = stack((w, x, y, z), -1)
@@ -293,6 +303,7 @@ class Quaternion(Module):
tensor(1.5708, grad_fn=<AsinBackward0>)
>>> yaw
tensor(2.2143, grad_fn=<Atan2Backward0>)
+
"""
return euler_from_quaternion(self.w, self.x, self.y, self.z)
@@ -309,6 +320,7 @@ class Quaternion(Module):
>>> q.data
Parameter containing:
tensor([[0.8776, 0.4794, 0.0000, 0.0000]], requires_grad=True)
+
"""
return cls(axis_angle_to_quaternion(axis_angle))
@@ -320,6 +332,7 @@ class Quaternion(Module):
>>> axis_angle = q.to_axis_angle()
>>> axis_angle
tensor([0., 0., 0.], grad_fn=<AsStridedBackward0>)
+
"""
return quaternion_to_axis_angle(self.data)
@@ -337,6 +350,7 @@ class Quaternion(Module):
>>> q.data
Parameter containing:
tensor([1., 0., 0., 0.], requires_grad=True)
+
"""
data = tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
@@ -358,6 +372,7 @@ class Quaternion(Module):
>>> q.data
Parameter containing:
tensor([1., 0., 0., 0.], requires_grad=True)
+
"""
return cls(tensor([w, x, y, z]))
@@ -377,6 +392,7 @@ class Quaternion(Module):
Example:
>>> q = Quaternion.random()
>>> q = Quaternion.random(batch_size=2)
+
"""
rand_shape = (batch_size,) if batch_size is not None else ()
@@ -400,6 +416,7 @@ class Quaternion(Module):
>>> q0 = Quaternion.identity()
>>> q1 = Quaternion(torch.tensor([1., .5, 0., 0.]))
>>> q2 = q0.slerp(q1, .3)
+
"""
KORNIA_CHECK_TYPE(q1, Quaternion)
q0 = self.normalize()
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 39bcd5d0c..905b86bbe 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -36,6 +36,7 @@ class RANSAC(Module):
max_iterations: maximum batches to generate. Actual number of models to try is ``batch_size * max_iterations``.
confidence: desired confidence of the result, used for the early stopping.
max_local_iterations: number of local optimization (polishing) iterations.
+
"""
def __init__(
@@ -99,7 +100,8 @@ class RANSAC(Module):
@staticmethod
def max_samples_by_conf(n_inl: int, num_tc: int, sample_size: int, conf: float) -> float:
"""Formula to update max_iter in order to stop iterations earlier
- https://en.wikipedia.org/wiki/Random_sample_consensus."""
+ https://en.wikipedia.org/wiki/Random_sample_consensus.
+ """
eps = 1e-9
if num_tc <= sample_size:
return 1.0
@@ -131,7 +133,6 @@ class RANSAC(Module):
return model_best, inliers_best, best_model_score
def remove_bad_samples(self, kp1: Tensor, kp2: Tensor) -> Tuple[Tensor, Tensor]:
- """"""
# ToDo: add (model-specific) verification of the samples,
# E.g. constraints on not to be a degenerate sample
if self.model_type == "homography":
@@ -186,6 +187,7 @@ class RANSAC(Module):
Returns:
- Estimated model, shape of :math:`(1, 3, 3)`.
- The inlier/outlier mask, shape of :math:`(1, N)`, where N is number of input correspondences.
+
"""
self.validate_inputs(kp1, kp2, weights)
best_score_total: float = float(self.minimal_sample_size)
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index 1bb4417af..e2dfae389 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -30,8 +30,8 @@ def solve_quadratic(coeffs: Tensor) -> Tensor:
In cases where a quadratic polynomial has only one real root, the output will be in the format
[real_root, 0]. And for the complex roots should be represented as 0. This is done to maintain
a consistent output shape for all cases.
- """
+ """
KORNIA_CHECK_SHAPE(coeffs, ["B", "3"])
# Coefficients of quadratic equation
@@ -92,6 +92,7 @@ def solve_cubic(coeffs: Tensor) -> Tensor:
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].
+
"""
KORNIA_CHECK_SHAPE(coeffs, ["B", "4"])
@@ -215,8 +216,8 @@ def multiply_deg_one_poly(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
Returns:
degree 2 poly with the order :math:`(x^2, x*y, x*z, x, y^2, y*z, y, z^2, z, 1)`.
- """
+ """
return stack(
[
a[:, 0] * b[:, 0],
@@ -250,8 +251,8 @@ def multiply_deg_two_one_poly(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
a third degree poly for variables,
:math:`(x^3, y^3, x^2*y, x*y^2, x^2*z, x^2, y^2*z, y^2,
x*y*z, x*y, x*z^2, x*z, x, y*z^2, y*z, y, z^3, z^2, z, 1)`.
- """
+ """
return stack(
[
a[:, 0] * b[:, 0],
@@ -290,8 +291,8 @@ def determinant_to_polynomial(A: Tensor) -> Tensor:
Returns:
a degree 10 poly, representing determinant (Eqn. 14 in the paper).
- """
+ """
cs = zeros(A.shape[0], 11, device=A.device, dtype=A.dtype)
cs[:, 0] = (
A[:, 0, 12] * A[:, 1, 3] * A[:, 2, 7]
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 833c4fa07..41d23bbb6 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -1,5 +1,6 @@
r"""Implementation of "differentiable spatial to numerical" (soft-argmax) operations, as described in the paper
-"Numerical Coordinate Regression with Convolutional Neural Networks" by Nibali et al."""
+"Numerical Coordinate Regression with Convolutional Neural Networks" by Nibali et al.
+"""
from __future__ import annotations
@@ -39,6 +40,7 @@ def spatial_softmax2d(input: Tensor, temperature: Optional[Tensor] = None) -> Te
tensor([[[[0.0585, 0.0585, 0.0585],
[0.0585, 0.0585, 0.0585],
[0.0585, 0.1589, 0.4319]]]])
+
"""
_validate_batched_image_tensor_input(input)
@@ -74,6 +76,7 @@ def spatial_expectation2d(input: Tensor, normalized_coordinates: bool = True) ->
... [0., 1., 0.]]]])
>>> spatial_expectation2d(heatmaps, False)
tensor([[[1., 2.]]])
+
"""
_validate_batched_image_tensor_input(input)
@@ -114,6 +117,7 @@ def render_gaussian2d(mean: Tensor, std: Tensor, size: tuple[int, int], normaliz
Returns:
tensor including rendered points with shape :math:`(*, H, W)`.
+
"""
if not (std.dtype == mean.dtype and std.device == mean.device):
raise TypeError("Expected inputs to have the same dtype and device")
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index d8994b148..2391f4c89 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -26,6 +26,7 @@ def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = N
Returns:
conv_kernel [2x1xhxw]
+
"""
if device is None:
device = torch.device("cpu")
@@ -46,6 +47,7 @@ def _get_center_kernel2d(h: int, w: int, device: Optional[torch.device] = None)
Returns:
conv_kernel [2x2xhxw].
+
"""
if device is None:
device = torch.device("cpu")
@@ -80,6 +82,7 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: Optional[torch.device]
Returns:
conv_kernel [3x3xdxhxw].
+
"""
if device is None:
torch.device("cpu")
@@ -119,6 +122,7 @@ def _get_window_grid_kernel3d(d: int, h: int, w: int, device: Optional[torch.dev
Returns:
conv_kernel [3x1xdxhxw]
+
"""
if device is None:
device = torch.device("cpu")
@@ -287,6 +291,7 @@ def conv_soft_argmax2d(
Examples:
>>> input = torch.randn(20, 16, 50, 32)
>>> nms_coords, nms_val = conv_soft_argmax2d(input, (3,3), (2,2), (1,1), output_value=True)
+
"""
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -407,6 +412,7 @@ def conv_soft_argmax3d(
Examples:
>>> input = torch.randn(20, 16, 3, 50, 32)
>>> nms_coords, nms_val = conv_soft_argmax3d(input, (3, 3, 3), (1, 2, 2), (0, 1, 1))
+
"""
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -501,6 +507,7 @@ def spatial_soft_argmax2d(
... [0., 0., 0.]]]])
>>> spatial_soft_argmax2d(input, normalized_coordinates=False)
tensor([[[1.0000, 1.0000]]])
+
"""
if temperature is None:
temperature = tensor(1.0)
@@ -563,6 +570,7 @@ def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: fl
Examples:
>>> input = torch.randn(20, 16, 3, 50, 32)
>>> nms_coords, nms_val = conv_quad_interp3d(input, 1.0)
+
"""
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index ccf58bfb4..7b85907df 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -146,6 +146,7 @@ def affine(
>>> out = affine(img, aff)
>>> print(out.shape)
torch.Size([1, 2, 3, 5])
+
"""
# warping needs data in the shape of BCHW
is_unbatched: bool = tensor.ndimension() == 3
@@ -196,6 +197,7 @@ def affine3d(
>>> out = affine3d(img, aff)
>>> print(out.shape)
torch.Size([1, 2, 4, 3, 5])
+
"""
# warping needs data in the shape of BCDHW
is_unbatched: bool = tensor.ndimension() == 4
@@ -260,6 +262,7 @@ def rotate(
>>> out = rotate(img, angle)
>>> print(out.shape)
torch.Size([1, 3, 4, 4])
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
@@ -318,6 +321,7 @@ def rotate3d(
Returns:
Tensor: The rotated tensor with shape as input.
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
@@ -384,6 +388,7 @@ def translate(
>>> out = translate(img, translation)
>>> print(out.shape)
torch.Size([1, 3, 4, 4])
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
@@ -437,6 +442,7 @@ def scale(
>>> out = scale(img, scale_factor)
>>> print(out.shape)
torch.Size([1, 3, 4, 4])
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
@@ -493,6 +499,7 @@ def shear(
>>> out = shear(img, shear_factor)
>>> print(out.shape)
torch.Size([1, 3, 4, 4])
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")
@@ -558,6 +565,7 @@ def resize(
>>> out = resize(img, (6, 8))
>>> print(out.shape)
torch.Size([1, 3, 6, 8])
+
"""
if not isinstance(input, Tensor):
raise TypeError(f"Input tensor type is not a Tensor. Got {type(input)}")
@@ -629,8 +637,8 @@ def resize_to_be_divisible(
Returns:
Tensor: The resized tensor.
- """
+ """
if isinstance(input, Tensor) and len(input.shape) == 4:
height, width = input.shape[2], input.shape[3]
if isinstance(input, Tensor) and len(input.shape) == 3:
@@ -672,6 +680,7 @@ def rescale(
>>> out = rescale(img, (2, 3))
>>> print(out.shape)
torch.Size([1, 3, 8, 12])
+
"""
if isinstance(factor, float):
factor_vert = factor_horz = factor
@@ -711,6 +720,7 @@ class Resize(Module):
.. raw:: html
<gradio-app src="kornia/kornia-resize-antialias"></gradio-app>
+
"""
def __init__(
@@ -772,6 +782,7 @@ class Affine(Module):
>>> out = Affine(angle)(img)
>>> print(out.shape)
torch.Size([1, 2, 3, 5])
+
"""
def __init__(
@@ -857,6 +868,7 @@ class Rescale(Module):
>>> out = Rescale((2, 3))(img)
>>> print(out.shape)
torch.Size([1, 3, 8, 12])
+
"""
def __init__(
@@ -902,6 +914,7 @@ class Rotate(Module):
>>> out = Rotate(angle)(img)
>>> print(out.shape)
torch.Size([1, 3, 4, 4])
+
"""
def __init__(
@@ -945,6 +958,7 @@ class Translate(Module):
>>> out = Translate(translation)(img)
>>> print(out.shape)
torch.Size([1, 3, 4, 4])
+
"""
def __init__(
@@ -986,6 +1000,7 @@ class Scale(Module):
>>> out = Scale(scale_factor)(img)
>>> print(out.shape)
torch.Size([1, 3, 4, 4])
+
"""
def __init__(
@@ -1029,6 +1044,7 @@ class Shear(Module):
>>> out = Shear(shear_factor)(img)
>>> print(out.shape)
torch.Size([1, 3, 4, 4])
+
"""
def __init__(
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 828f9bd63..a6652430b 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -55,6 +55,7 @@ def crop_and_resize(
>>> crop_and_resize(input, boxes, (2, 2), mode='nearest', align_corners=True)
tensor([[[[ 6., 7.],
[10., 11.]]]])
+
"""
if not isinstance(input_tensor, Tensor):
raise TypeError(f"Input tensor type is not a Tensor. Got {type(input_tensor)}")
@@ -118,6 +119,7 @@ def center_crop(
>>> center_crop(input, (2, 4), mode='nearest', align_corners=True)
tensor([[[[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.]]]])
+
"""
if not isinstance(input_tensor, Tensor):
raise TypeError(f"Input tensor type is not a Tensor. Got {type(input_tensor)}")
@@ -218,6 +220,7 @@ def crop_by_boxes(
Note:
If the src_box is smaller than dst_box, the following error will be thrown.
RuntimeError: solve_cpu: For batch 0: U(2,2) is zero, singular U.
+
"""
if validate_boxes:
validate_bbox(src_box)
@@ -266,6 +269,7 @@ def crop_by_transform_mat(
Returns:
the output tensor with patches.
+
"""
# simulate broadcasting
dst_trans_src = as_tensor(
@@ -310,6 +314,7 @@ def crop_by_indices(
No effect for upscaling.
shape_compensation: if the cropped slice sizes are not exactly align `size`, the image can either be padded
or resized.
+
"""
KORNIA_CHECK_SHAPE(input_tensor, ["B", "C", "H", "W"])
KORNIA_CHECK_SHAPE(src_box, ["B", "4", "2"])
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index db5199805..dd3e52b56 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -70,6 +70,7 @@ def crop_and_resize3d(
<BLANKLINE>
[[37.0000, 39.0000],
[45.0000, 47.0000]]]]])
+
"""
if not isinstance(tensor, (torch.Tensor)):
raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
@@ -153,6 +154,7 @@ def center_crop3d(
<BLANKLINE>
[[37.0000, 38.0000],
[41.0000, 42.0000]]]]])
+
"""
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
@@ -297,6 +299,7 @@ def crop_by_boxes3d(
[[37., 38., 39.],
[41., 42., 43.],
[45., 46., 47.]]]]])
+
"""
validate_bbox3d(src_box)
validate_bbox3d(dst_box)
@@ -350,6 +353,7 @@ def crop_by_transform_mat3d(
Returns:
the output tensor with patches.
+
"""
# simulate broadcasting
dst_trans_src = transform.expand(tensor.shape[0], -1, -1)
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index a15dcb61d..854841d37 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -59,6 +59,7 @@ def elastic_transform2d(
>>> alpha = torch.tensor([16., 32.], requires_grad=True)
>>> image_hat = elastic_transform2d(image, noise, (3, 3), alpha=alpha)
>>> image_hat.mean().backward()
+
"""
KORNIA_CHECK_IS_TENSOR(image)
KORNIA_CHECK_IS_TENSOR(noise)
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index 6016f24bd..52bc2b1f1 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -28,6 +28,7 @@ class Vflip(Module):
tensor([[[[0., 1., 1.],
[0., 0., 0.],
[0., 0., 0.]]]])
+
"""
def forward(self, input: Tensor) -> Tensor:
@@ -59,6 +60,7 @@ class Hflip(Module):
tensor([[[[0., 0., 0.],
[0., 0., 0.],
[1., 1., 0.]]]])
+
"""
def forward(self, input: Tensor) -> Tensor:
@@ -87,6 +89,7 @@ class Rot180(Module):
tensor([[[[1., 1., 0.],
[0., 0., 0.],
[0., 0., 0.]]]])
+
"""
def forward(self, input: Tensor) -> Tensor:
@@ -108,6 +111,7 @@ def rot180(input: Tensor) -> Tensor:
Returns:
The rotated image tensor.
+
"""
return torch.flip(input, [-2, -1])
@@ -124,6 +128,7 @@ def hflip(input: Tensor) -> Tensor:
Returns:
The horizontally flipped image tensor.
+
"""
return input.flip(-1).contiguous()
@@ -140,5 +145,6 @@ def vflip(input: Tensor) -> Tensor:
Returns:
The vertically flipped image tensor.
+
"""
return input.flip(-2).contiguous()
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 0ca400154..eb49e7d3c 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -41,6 +41,7 @@ class HomographyWarper(BaseWarper):
``'zeros'`` | ``'border'`` | ``'reflection'``.
normalized_coordinates: whether to use a grid with normalized coordinates.
align_corners: interpolation flag.
+
"""
_warped_grid: Optional[Tensor]
@@ -76,6 +77,7 @@ class HomographyWarper(BaseWarper):
has to be :math:`(1, 3, 3)` or :math:`(N, 1, 3, 3)`.
The homography assumes normalized coordinates [-1, 1] if
normalized_coordinates is True.
+
"""
self._warped_grid = warp_grid(self.grid, src_homo_dst)
@@ -104,6 +106,7 @@ class HomographyWarper(BaseWarper):
>>> # precomputing the warp
>>> warper.precompute_warp_grid(homography)
>>> output = warper(input) # NxCxHxW
+
"""
_warped_grid = self._warped_grid
if src_homo_dst is not None:
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 5005e03a8..5d3f9829d 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -27,7 +27,8 @@ class BaseModel(Module):
class Homography(BaseModel):
r"""Homography geometric model to be used together with ImageRegistrator module for the optimization-based
- image registration."""
+ image registration.
+ """
def __init__(self) -> None:
super().__init__()
@@ -46,6 +47,7 @@ class Homography(BaseModel):
Returns:
Homography matrix with shape :math:`(1, 3, 3)`.
+
"""
return torch.unsqueeze(self.model / self.model[2, 2], dim=0) # 1x3x3
@@ -54,6 +56,7 @@ class Homography(BaseModel):
Returns:
Homography martix with shape :math:`(1, 3, 3)`.
+
"""
return torch.unsqueeze(torch.inverse(self.model), dim=0)
@@ -66,6 +69,7 @@ class Similarity(BaseModel):
rotation: if True, the rotation is optimizable, else constant zero.
scale: if True, the scale is optimizable, else constant zero.
shift: if True, the shift is optimizable, else constant one.
+
"""
def __init__(self, rotation: bool = True, scale: bool = True, shift: bool = True) -> None:
@@ -100,6 +104,7 @@ class Similarity(BaseModel):
Returns:
Similarity with shape :math:`(1, 3, 3)`
+
"""
rot = self.scale * angle_to_rotation_matrix(self.rot)
out = convert_affinematrix_to_homography(torch.cat([rot, self.shift], dim=2))
@@ -110,6 +115,7 @@ class Similarity(BaseModel):
Returns:
Similarity with shape :math:`(1, 3, 3)`
+
"""
return torch.inverse(self.forward())
@@ -133,6 +139,7 @@ class ImageRegistrator(Module):
>>> img_dst = torch.rand(1, 1, 32, 32)
>>> registrator = ImageRegistrator('similarity')
>>> homo = registrator.register(img_src, img_dst)
+
"""
# TODO: resolve better type, potentially using factory.
@@ -216,6 +223,7 @@ class ImageRegistrator(Module):
Returns:
the transformation between two images, shape depends on the model,
typically [1x3x3] tensor for string model_types.
+
"""
self.reset_model()
# ToDo: better parameter passing to optimizer
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 0cd8ab758..ff87c9bc7 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -89,6 +89,7 @@ def warp_perspective(
.. note::
See a working example `here <https://kornia.github.io/tutorials/nbs/warp_perspective.html>`_.
+
"""
if not isinstance(src, Tensor):
raise TypeError(f"Input src type is not a Tensor. Got {type(src)}")
@@ -175,6 +176,7 @@ def warp_affine(
>>> out = warp_affine(img, A, (4, 2), align_corners=True)
>>> print(out.shape)
torch.Size([1, 4, 4, 2])
+
"""
if not isinstance(src, Tensor):
raise TypeError(f"Input src type is not a Tensor. Got {type(src)}")
@@ -219,6 +221,7 @@ def _fill_and_warp(src: Tensor, grid: Tensor, mode: str, align_corners: bool, fi
Returns:
the warped and filled tensor with shape :math:`(B, 3, H, W)`.
+
"""
ones_mask = ones_like(src)
fill_value = fill_value.to(ones_mask)[None, :, None, None] # cast and add dimensions for broadcasting
@@ -238,6 +241,7 @@ def warp_grid(grid: Tensor, src_homo_dst: Tensor) -> Tensor:
Returns:
the transformed grid of shape :math:`(N, H, W, 2)`.
+
"""
batch_size: int = src_homo_dst.size(0)
_, height, width, _ = grid.size()
@@ -262,6 +266,7 @@ def warp_grid3d(grid: Tensor, src_homo_dst: Tensor) -> Tensor:
Returns:
the transformed grid of shape :math:`(N, H, W, 3)`.
+
"""
batch_size: int = src_homo_dst.size(0)
_, depth, height, width, _ = grid.size()
@@ -326,6 +331,7 @@ def get_perspective_transform(points_src: Tensor, points_dst: Tensor) -> Tensor:
>>> x1 = torch.tensor([[[0., 0.], [1., 0.], [1., 1.], [0., 1.]]])
>>> x2 = torch.tensor([[[1., 0.], [0., 0.], [0., 1.], [1., 1.]]])
>>> x2_trans_x1 = get_perspective_transform(x1, x2)
+
"""
KORNIA_CHECK_SHAPE(points_src, ["B", "4", "2"])
KORNIA_CHECK_SHAPE(points_dst, ["B", "4", "2"])
@@ -409,6 +415,7 @@ def get_rotation_matrix2d(center: Tensor, angle: Tensor, scale: Tensor) -> Tenso
.. note::
This function is often used in conjunction with :func:`warp_affine`.
+
"""
if not isinstance(center, Tensor):
raise TypeError(f"Input center type is not a Tensor. Got {type(center)}")
@@ -505,6 +512,7 @@ def remap(
.. note::
This function is often used in conjunction with :func:`kornia.utils.create_meshgrid`.
+
"""
KORNIA_CHECK_SHAPE(image, ["B", "C", "H", "W"])
KORNIA_CHECK_SHAPE(map_x, ["B", "H", "W"])
@@ -549,6 +557,7 @@ def invert_affine_transform(matrix: Tensor) -> Tensor:
.. note::
This function is often used in conjunction with :func:`warp_affine`.
+
"""
if not isinstance(matrix, Tensor):
raise TypeError(f"Input matrix type is not a Tensor. Got {type(matrix)}")
@@ -585,6 +594,7 @@ def get_affine_matrix2d(
.. note::
This function is often used in conjunction with :func:`warp_affine`, :func:`warp_perspective`.
+
"""
transform: Tensor = get_rotation_matrix2d(center, -angle, scale)
transform[..., 2] += translations # tx/ty
@@ -610,6 +620,7 @@ def get_translation_matrix2d(translations: Tensor) -> Tensor:
.. note::
This function is often used in conjunction with :func:`warp_affine`, :func:`warp_perspective`.
+
"""
transform: Tensor = eye_like(3, translations)[:, :2, :]
transform[..., 2] += translations # tx/ty
@@ -652,6 +663,7 @@ def get_shear_matrix2d(center: Tensor, sx: Optional[Tensor] = None, sy: Optional
.. note::
This function is often used in conjunction with :func:`warp_affine`, :func:`warp_perspective`.
+
"""
sx = tensor([0.0]).repeat(center.size(0)) if sx is None else sx
sy = tensor([0.0]).repeat(center.size(0)) if sy is None else sy
@@ -703,6 +715,7 @@ def get_affine_matrix3d(
.. note::
This function is often used in conjunction with :func:`warp_perspective`.
+
"""
transform: Tensor = get_projective_transform(center, -angles, scale)
transform[..., 3] += translations # tx/ty/tz
@@ -771,6 +784,7 @@ def get_shear_matrix3d(
.. note::
This function is often used in conjunction with :func:`warp_perspective3d`.
+
"""
sxy = tensor([0.0]).repeat(center.size(0)) if sxy is None else sxy
sxz = tensor([0.0]).repeat(center.size(0)) if sxz is None else sxz
@@ -851,6 +865,7 @@ def warp_affine3d(
.. note::
This function is often used in conjunction with :func:`get_perspective_transform3d`.
+
"""
if len(src.shape) != 5:
raise AssertionError(src.shape)
@@ -891,6 +906,7 @@ def projection_from_Rt(rmat: Tensor, tvec: Tensor) -> Tensor:
Returns:
the projection matrix with shape :math:`(*, 3, 4)`.
+
"""
if not (len(rmat.shape) >= 2 and rmat.shape[-2:] == (3, 3)):
raise AssertionError(rmat.shape)
@@ -920,6 +936,7 @@ def get_projective_transform(center: Tensor, angles: Tensor, scales: Tensor) ->
.. note::
This function is often used in conjunction with :func:`warp_affine3d`.
+
"""
if not (len(center.shape) == 2 and center.shape[-1] == 3):
raise AssertionError(center.shape)
@@ -1022,6 +1039,7 @@ def get_perspective_transform3d(src: Tensor, dst: Tensor) -> Tensor:
.. note::
This function is often used in conjunction with :func:`warp_perspective3d`.
+
"""
if not isinstance(src, (Tensor)):
raise TypeError(f"Input type is not a Tensor. Got {type(src)}")
@@ -1202,6 +1220,7 @@ def warp_perspective3d(
.. note::
This function is often used in conjunction with :func:`get_perspective_transform3d`.
+
"""
if not isinstance(src, Tensor):
raise TypeError(f"Input src type is not a Tensor. Got {type(src)}")
@@ -1254,12 +1273,13 @@ def homography_warp(
>>> homography = torch.eye(3).view(1, 3, 3)
>>> output = homography_warp(input, homography, (32, 32))
- Example
+ Example:
>>> img = torch.rand(1, 4, 5, 6)
>>> H = torch.eye(3)[None]
>>> out = homography_warp(img, H, (4, 2), align_corners=True, normalized_homography=False)
>>> print(out.shape)
torch.Size([1, 4, 4, 2])
+
"""
if not src_homo_dst.device == patch_src.device:
raise TypeError(
@@ -1323,6 +1343,7 @@ def homography_warp3d(
>>> input = torch.rand(1, 3, 32, 32)
>>> homography = torch.eye(3).view(1, 3, 3)
>>> output = homography_warp(input, homography, (32, 32))
+
"""
if not src_homo_dst.device == patch_src.device:
raise TypeError(
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 46fd8b446..c231bc6e9 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -59,6 +59,7 @@ class PyrDown(Module):
Examples:
>>> input = torch.rand(1, 2, 4, 4)
>>> output = PyrDown()(input) # 1x2x2x2
+
"""
def __init__(self, border_type: str = "reflect", align_corners: bool = False, factor: float = 2.0) -> None:
@@ -90,6 +91,7 @@ class PyrUp(Module):
Examples:
>>> input = torch.rand(1, 2, 4, 4)
>>> output = PyrUp()(input) # 1x2x8x8
+
"""
def __init__(self, border_type: str = "reflect", align_corners: bool = False) -> None:
@@ -126,6 +128,7 @@ class ScalePyramid(Module):
Examples:
>>> input = torch.rand(2, 4, 100, 100)
>>> sp, sigmas, pds = ScalePyramid(3, 15)(input)
+
"""
def __init__(
@@ -248,6 +251,7 @@ def pyrdown(input: Tensor, border_type: str = "reflect", align_corners: bool = F
>>> pyrdown(input, align_corners=True)
tensor([[[[ 3.7500, 5.2500],
[ 9.7500, 11.2500]]]])
+
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -288,6 +292,7 @@ def pyrup(input: Tensor, border_type: str = "reflect", align_corners: bool = Fal
[1.0000, 1.1250, 1.3750, 1.5000],
[1.5000, 1.6250, 1.8750, 2.0000],
[1.7500, 1.8750, 2.1250, 2.2500]]]])
+
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -324,6 +329,7 @@ def build_pyramid(
Shape:
- Input: :math:`(B, C, H, W)`
- Output :math:`[(B, C, H, W), (B, C, H/2, W/2), ...]`
+
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(
@@ -377,8 +383,8 @@ def build_laplacian_pyramid(
Return:
Output: :math:`[(B, C, H, W), (B, C, H/2, W/2), ...]`
- """
+ """
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(
isinstance(max_level, int) or max_level < 0,
@@ -420,6 +426,7 @@ def upscale_double(x: Tensor) -> Tensor:
Shape:
- Input: :math:`(*, H, W)`
- Output :math:`(*, H, W)`
+
"""
KORNIA_CHECK_IS_TENSOR(x)
KORNIA_CHECK_SHAPE(x, ["*", "H", "W"])
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index c38ba3e1e..aa1a858b6 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -14,7 +14,8 @@ __all__ = ["get_tps_transform", "warp_image_tps", "warp_points_tps"]
def _pair_square_euclidean(tensor1: torch.Tensor, tensor2: torch.Tensor) -> torch.Tensor:
r"""Compute the pairwise squared euclidean distance matrices :math:`(B, N, M)` between two tensors with shapes
- (B, N, C) and (B, M, C)."""
+ (B, N, C) and (B, M, C).
+ """
# ||t1-t2||^2 = (t1-t2)^T(t1-t2) = t1^T*t1 + t2^T*t2 - 2*t1^T*t2
t1_sq: torch.Tensor = tensor1.mul(tensor1).sum(dim=-1, keepdim=True)
t2_sq: torch.Tensor = tensor2.mul(tensor2).sum(dim=-1, keepdim=True).transpose(1, 2)
@@ -57,6 +58,7 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tup
.. note::
This function is often used in conjunction with :func:`warp_points_tps`, :func:`warp_image_tps`.
+
"""
if not isinstance(points_src, torch.Tensor):
raise TypeError(f"Input points_src is not torch.Tensor. Got {type(points_src)}")
@@ -123,6 +125,7 @@ def warp_points_tps(
.. note::
This function is often used in conjunction with :func:`get_tps_transform`.
+
"""
if not isinstance(points_src, torch.Tensor):
raise TypeError(f"Input points_src is not torch.Tensor. Got {type(points_src)}")
@@ -200,6 +203,7 @@ def warp_image_tps(
.. note::
This function is often used in conjunction with :func:`get_tps_transform`.
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input image is not torch.Tensor. Got {type(image)}")
diff --git a/kornia/grad_estimator/ste.py b/kornia/grad_estimator/ste.py
index c8ab23189..63a7b96a9 100644
--- a/kornia/grad_estimator/ste.py
+++ b/kornia/grad_estimator/ste.py
@@ -32,6 +32,7 @@ class STEFunction(Function):
>>> loss.backward()
>>> input.grad
tensor([0.2500, 0.2500, 0.2500, 0.2500])
+
"""
@staticmethod
@@ -100,6 +101,7 @@ class StraightThroughEstimator(nn.Module):
[0.0566, 0.0626, 0.0626, 0.0626],
[0.0626, 0.0626, 0.0626, 0.0566],
[0.0422, 0.0566, 0.0626, 0.0422]]]])
+
"""
def __init__(self, target_fn: nn.Module, grad_fn: Optional[Callable[..., Any]] = None) -> None:
diff --git a/kornia/image/base.py b/kornia/image/base.py
index 98c7c94f3..b4de124c4 100644
--- a/kornia/image/base.py
+++ b/kornia/image/base.py
@@ -20,6 +20,7 @@ class ImageSize:
3
>>> size.width
4
+
"""
height: int | Tensor
@@ -49,6 +50,7 @@ class PixelFormat:
<ColorSpace.RGB: 2>
>>> pixel_format.bit_depth
8
+
"""
color_space: ColorSpace
@@ -79,6 +81,7 @@ class ImageLayout:
3
>>> layout.channels_order
<ChannelsOrder.CHANNELS_LAST: 1>
+
"""
image_size: ImageSize
diff --git a/kornia/image/image.py b/kornia/image/image.py
index 6f80d04b9..5c03b0cfe 100644
--- a/kornia/image/image.py
+++ b/kornia/image/image.py
@@ -55,6 +55,7 @@ class Image:
>>> assert img.channels == 3
>>> assert img.width == 5
>>> assert img.height == 4
+
"""
def __init__(self, data: Tensor, pixel_format: PixelFormat, layout: ImageLayout) -> None:
@@ -64,6 +65,7 @@ class Image:
data: a torch tensor containing the image data.
pixel_format: the pixel format of the image.
layout: a dataclass containing the image layout information.
+
"""
# TODO: move this to a function KORNIA_CHECK_IMAGE_LAYOUT
if layout.channels_order == ChannelsOrder.CHANNELS_FIRST:
@@ -93,6 +95,7 @@ class Image:
Returns:
Image: the image moved to the given device and dtype.
+
"""
if device is not None and isinstance(device, torch.dtype):
dtype, device = device, None
@@ -191,6 +194,7 @@ class Image:
>>> assert img.channels == 3
>>> assert img.width == 5
>>> assert img.height == 4
+
"""
if channels_order == ChannelsOrder.CHANNELS_LAST:
image_size = ImageSize(height=data.shape[0], width=data.shape[1])
@@ -224,6 +228,7 @@ class Image:
Example:
>>> x = np.ones((4, 5, 3))
>>> img = Image.from_dlpack(x.__dlpack__())
+
"""
_data: Tensor = from_dlpack(data)
@@ -248,6 +253,7 @@ class Image:
Args:
file_path: the path to the file to read the image from.
+
"""
# TODO: allow user to specify the desired type and device
data: Tensor = load_image(file_path, desired_type=ImageLoadType.RGB8, device="cpu")
@@ -273,6 +279,7 @@ class Image:
>>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC
>>> img = Image.from_numpy(data)
>>> img.write("test.jpg")
+
"""
data = self.data
if self.channels_order == ChannelsOrder.CHANNELS_LAST:
@@ -291,5 +298,6 @@ class Image:
img.print()
.. image:: https://github.com/kornia/data/blob/main/print_image.png?raw=true
+
"""
print(image_to_string(self.data, max_width))
diff --git a/kornia/io/io.py b/kornia/io/io.py
index a0bb81cfe..6e5e24c80 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -34,8 +34,8 @@ def _load_image_to_tensor(path_file: Path, device: Device) -> Tensor:
Return:
Image tensor with shape :math:`(3,H,W)`.
- """
+ """
# read image and return as `np.ndarray` with shape HxWxC
if path_file.suffix.lower() in [".jpg", ".jpeg"]:
img = kornia_rs.read_image_jpeg(str(path_file))
@@ -75,6 +75,7 @@ def load_image(
Return:
Image tensor with shape :math:`(3,H,W)`.
+
"""
if not isinstance(path_file, Path):
path_file = Path(path_file)
@@ -137,6 +138,7 @@ def write_image(path_file: str | Path, image: Tensor) -> None:
Return:
None.
+
"""
if not isinstance(path_file, Path):
path_file = Path(path_file)
diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.py
index 09b6b93c0..f587409b5 100644
--- a/kornia/losses/cauchy.py
+++ b/kornia/losses/cauchy.py
@@ -40,6 +40,7 @@ def cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
>>> img2 = torch.randn(2, 3, 32, 32)
>>> output = cauchy_loss(img1, img2, reduction="mean")
>>> output.backward()
+
"""
KORNIA_CHECK_IS_TENSOR(img1)
@@ -103,6 +104,7 @@ class CauchyLoss(Module):
>>> img2 = torch.randn(2, 3, 32, 2107)
>>> output = criterion(img1, img2)
>>> output.backward()
+
"""
def __init__(self, reduction: str = "none") -> None:
diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.py
index 95a8e260c..5ce3568e9 100644
--- a/kornia/losses/charbonnier.py
+++ b/kornia/losses/charbonnier.py
@@ -46,6 +46,7 @@ def charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Ten
>>> img2 = torch.randn(2, 3, 32, 32)
>>> output = charbonnier_loss(img1, img2, reduction="sum")
>>> output.backward()
+
"""
KORNIA_CHECK_IS_TENSOR(img1)
@@ -115,6 +116,7 @@ class CharbonnierLoss(Module):
>>> img2 = torch.randn(2, 3, 32, 2107)
>>> output = criterion(img1, img2)
>>> output.backward()
+
"""
def __init__(self, reduction: str = "none") -> None:
diff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.py
index f8594f65a..2b9b6ef9b 100644
--- a/kornia/losses/depth_smooth.py
+++ b/kornia/losses/depth_smooth.py
@@ -39,6 +39,7 @@ def inverse_depth_smoothness_loss(idepth: torch.Tensor, image: torch.Tensor) ->
>>> idepth = torch.rand(1, 1, 4, 5)
>>> image = torch.rand(1, 3, 4, 5)
>>> loss = inverse_depth_smoothness_loss(idepth, image)
+
"""
if not isinstance(idepth, torch.Tensor):
raise TypeError(f"Input idepth type is not a torch.Tensor. Got {type(idepth)}")
@@ -97,6 +98,7 @@ class InverseDepthSmoothnessLoss(nn.Module):
>>> image = torch.rand(1, 3, 4, 5)
>>> smooth = InverseDepthSmoothnessLoss()
>>> loss = smooth(idepth, image)
+
"""
def forward(self, idepth: torch.Tensor, image: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 63f49612e..63e5f2fd2 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -65,6 +65,7 @@ def dice_loss(
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = dice_loss(pred, target)
>>> output.backward()
+
"""
KORNIA_CHECK_IS_TENSOR(pred)
@@ -176,6 +177,7 @@ class DiceLoss(nn.Module):
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = criterion(pred, target)
>>> output.backward()
+
"""
def __init__(
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index b7bb7d56e..66b762ec1 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -48,6 +48,7 @@ def js_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = "mean") -> Ten
>>> loss = js_div_loss_2d(pred, pred)
>>> loss.item()
0.0
+
"""
return _reduce_loss(_js_div_2d(target, pred), reduction)
@@ -69,5 +70,6 @@ def kl_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = "mean") -> Ten
>>> loss = kl_div_loss_2d(pred, pred)
>>> loss.item()
0.0
+
"""
return _reduce_loss(_kl_div_2d(target, pred), reduction)
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index d73f02b55..3f98f603c 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -58,8 +58,8 @@ def focal_loss(
>>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
>>> output = focal_loss(pred, target, **kwargs)
>>> output.backward()
- """
+ """
KORNIA_CHECK_SHAPE(pred, ["B", "C", "*"])
out_size = (pred.shape[0],) + pred.shape[2:]
KORNIA_CHECK(
@@ -155,6 +155,7 @@ class FocalLoss(nn.Module):
>>> criterion = FocalLoss(**kwargs)
>>> output = criterion(pred, target)
>>> output.backward()
+
"""
def __init__(
@@ -223,8 +224,8 @@ def binary_focal_loss_with_logits(
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> output = binary_focal_loss_with_logits(pred, target, **kwargs)
>>> output.backward()
- """
+ """
KORNIA_CHECK_SHAPE(pred, ["B", "C", "*"])
KORNIA_CHECK(pred.shape == target.shape, f"Expected target size {pred.shape}, got {target.shape}")
KORNIA_CHECK(
@@ -328,6 +329,7 @@ class BinaryFocalLossWithLogits(nn.Module):
>>> criterion = BinaryFocalLossWithLogits(**kwargs)
>>> output = criterion(pred, target)
>>> output.backward()
+
"""
def __init__(
diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.py
index 28a768b71..ca708215e 100644
--- a/kornia/losses/geman_mcclure.py
+++ b/kornia/losses/geman_mcclure.py
@@ -40,6 +40,7 @@ def geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> T
>>> img2 = torch.randn(2, 3, 32, 32)
>>> output = geman_mcclure_loss(img1, img2, reduction="mean")
>>> output.backward()
+
"""
KORNIA_CHECK_IS_TENSOR(img1)
@@ -103,6 +104,7 @@ class GemanMcclureLoss(Module):
>>> img2 = torch.randn(2, 3, 32, 2107)
>>> output = criterion(img1, img2)
>>> output.backward()
+
"""
def __init__(self, reduction: str = "none") -> None:
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index 7c9f3f80c..3987d7968 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -25,6 +25,7 @@ class _HausdorffERLossBase(Module):
Returns:
Estimated Hausdorff Loss.
+
"""
conv: Callable[..., Tensor]
@@ -86,6 +87,7 @@ class _HausdorffERLossBase(Module):
Returns:
Estimated Hausdorff Loss.
+
"""
if not (pred.shape[2:] == target.shape[2:] and pred.size(0) == target.size(0) and target.size(1) == 1):
raise ValueError(
@@ -156,6 +158,7 @@ class HausdorffERLoss(_HausdorffERLossBase):
>>> input = torch.randn(5, 3, 20, 20)
>>> target = (torch.rand(5, 1, 20, 20) * 2).long()
>>> res = hdloss(input, target)
+
"""
conv = torch.conv2d
@@ -177,6 +180,7 @@ class HausdorffERLoss(_HausdorffERLossBase):
Returns:
Estimated Hausdorff Loss.
+
"""
if pred.dim() != 4:
raise ValueError(f"Only 2D images supported. Got {pred.dim()}.")
@@ -222,6 +226,7 @@ class HausdorffERLoss3D(_HausdorffERLossBase):
>>> input = torch.randn(5, 3, 20, 20, 20)
>>> target = (torch.rand(5, 1, 20, 20, 20) * 2).long()
>>> res = hdloss(input, target)
+
"""
conv = torch.conv3d
@@ -247,6 +252,7 @@ class HausdorffERLoss3D(_HausdorffERLossBase):
Returns:
Estimated Hausdorff Loss.
+
"""
if pred.dim() != 5:
raise ValueError(f"Only 3D images supported. Got {pred.dim()}.")
diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.py
index 7f34ba779..74aaccf56 100644
--- a/kornia/losses/lovasz_hinge.py
+++ b/kornia/losses/lovasz_hinge.py
@@ -51,6 +51,7 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = lovasz_hinge_loss(pred, target)
>>> output.backward()
+
"""
KORNIA_CHECK_SHAPE(pred, ["B", "1", "H", "W"])
@@ -129,6 +130,7 @@ class LovaszHingeLoss(nn.Module):
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = criterion(pred, target)
>>> output.backward()
+
"""
def __init__(self) -> None:
diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.py
index 92acc2d8b..966fafaca 100644
--- a/kornia/losses/lovasz_softmax.py
+++ b/kornia/losses/lovasz_softmax.py
@@ -54,6 +54,7 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = lovasz_softmax_loss(pred, target)
>>> output.backward()
+
"""
KORNIA_CHECK_SHAPE(pred, ["B", "N", "H", "W"])
@@ -157,6 +158,7 @@ class LovaszSoftmaxLoss(nn.Module):
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = criterion(pred, target)
>>> output.backward()
+
"""
def __init__(self, weight: Optional[Tensor] = None) -> None:
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.py
index b9989adbb..2008a53a7 100644
--- a/kornia/losses/ms_ssim.py
+++ b/kornia/losses/ms_ssim.py
@@ -52,6 +52,7 @@ class MS_SSIMLoss(nn.Module):
>>> input2 = torch.rand(1, 3, 5, 5)
>>> criterion = kornia.losses.MS_SSIMLoss()
>>> loss = criterion(input1, input2)
+
"""
def __init__(
@@ -95,6 +96,7 @@ class MS_SSIMLoss(nn.Module):
Returns:
1D kernel (size).
+
"""
coords = torch.arange(size, device=device, dtype=dtype)
coords -= size // 2
@@ -113,6 +115,7 @@ class MS_SSIMLoss(nn.Module):
Returns:
2D kernel (size x size).
+
"""
gaussian_vec = self._fspecial_gauss_1d(size, sigma, device, dtype)
return torch.outer(gaussian_vec, gaussian_vec)
@@ -126,6 +129,7 @@ class MS_SSIMLoss(nn.Module):
Returns:
Estimated MS-SSIM_L1 loss.
+
"""
if not isinstance(img1, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(img1)}")
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
index 6ab148a81..fdf57331a 100644
--- a/kornia/losses/psnr.py
+++ b/kornia/losses/psnr.py
@@ -29,6 +29,7 @@ def psnr_loss(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torc
>>> ones = torch.ones(1)
>>> psnr_loss(ones, 1.2 * ones, 2.) # 10 * log(4/((1.2-1)**2)) / log(10)
tensor(-20.0000)
+
"""
return -1.0 * metrics.psnr(image, target, max_val)
@@ -57,6 +58,7 @@ class PSNRLoss(nn.Module):
>>> criterion = PSNRLoss(2.)
>>> criterion(ones, 1.2 * ones) # 10 * log(4/((1.2-1)**2)) / log(10)
tensor(-20.0000)
+
"""
def __init__(self, max_val: float) -> None:
diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.py
index 2abc1bcdc..3fedf7a7a 100644
--- a/kornia/losses/ssim.py
+++ b/kornia/losses/ssim.py
@@ -45,6 +45,7 @@ def ssim_loss(
>>> input1 = torch.rand(1, 4, 5, 5)
>>> input2 = torch.rand(1, 4, 5, 5)
>>> loss = ssim_loss(input1, input2, 5)
+
"""
# compute the ssim map
ssim_map: torch.Tensor = metrics.ssim(img1, img2, window_size, max_val, eps, padding)
@@ -94,6 +95,7 @@ class SSIMLoss(nn.Module):
>>> input2 = torch.rand(1, 4, 5, 5)
>>> criterion = SSIMLoss(5)
>>> loss = criterion(input1, input2)
+
"""
def __init__(
diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.py
index 7d8a9860d..75283151c 100644
--- a/kornia/losses/ssim3d.py
+++ b/kornia/losses/ssim3d.py
@@ -43,6 +43,7 @@ def ssim3d_loss(
>>> input1 = torch.rand(1, 4, 5, 5, 5)
>>> input2 = torch.rand(1, 4, 5, 5, 5)
>>> loss = ssim3d_loss(input1, input2, 5)
+
"""
# compute the ssim map
ssim_map: Tensor = metrics.ssim3d(img1, img2, window_size, max_val, eps, padding)
@@ -92,6 +93,7 @@ class SSIM3DLoss(Module):
>>> input2 = torch.rand(1, 4, 5, 5, 5)
>>> criterion = SSIM3DLoss(5)
>>> loss = criterion(input1, input2)
+
"""
def __init__(
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index 9a2e8626a..a58453b22 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -29,6 +29,7 @@ def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:
Reference:
[1] https://en.wikipedia.org/wiki/Total_variation
+
"""
# TODO: here torchscript doesn't like KORNIA_CHECK_TYPE
if not isinstance(img, Tensor):
@@ -77,6 +78,7 @@ class TotalVariation(Module):
Reference:
[1] https://en.wikipedia.org/wiki/Total_variation
+
"""
def forward(self, img: Tensor) -> Tensor:
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index 8782c9ffd..4622b5697 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -59,6 +59,7 @@ def tversky_loss(
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = tversky_loss(pred, target, alpha=0.5, beta=0.5)
>>> output.backward()
+
"""
if not isinstance(pred, torch.Tensor):
raise TypeError(f"pred type is not a torch.Tensor. Got {type(pred)}")
@@ -138,6 +139,7 @@ class TverskyLoss(nn.Module):
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = criterion(pred, target)
>>> output.backward()
+
"""
def __init__(self, alpha: float, beta: float, eps: float = 1e-8, ignore_index: Optional[int] = -100) -> None:
diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.py
index 869bd99c9..9ff70334a 100644
--- a/kornia/losses/welsch.py
+++ b/kornia/losses/welsch.py
@@ -41,6 +41,7 @@ def welsch_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
>>> img2 = torch.randn(2, 3, 32, 32)
>>> output = welsch_loss(img1, img2, reduction="mean")
>>> output.backward()
+
"""
KORNIA_CHECK_IS_TENSOR(img1)
@@ -103,6 +104,7 @@ class WelschLoss(Module):
>>> img2 = torch.randn(2, 3, 32, 1904)
>>> output = criterion(img1, img2)
>>> output.backward()
+
"""
def __init__(self, reduction: str = "none") -> None:
diff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.py
index 05e1293f0..48ca33424 100644
--- a/kornia/metrics/accuracy.py
+++ b/kornia/metrics/accuracy.py
@@ -16,6 +16,7 @@ def accuracy(pred: Tensor, target: Tensor, topk: Tuple[int, ...] = (1,)) -> List
>>> target = torch.tensor([[1]])
>>> accuracy(logits, target)
[tensor(100.)]
+
"""
maxk = min(max(topk), pred.size()[1])
batch_size = target.size(0)
diff --git a/kornia/metrics/average_meter.py b/kornia/metrics/average_meter.py
index 752c7c12f..4aa1f260b 100644
--- a/kornia/metrics/average_meter.py
+++ b/kornia/metrics/average_meter.py
@@ -12,6 +12,7 @@ class AverageMeter:
>>> stats.update(acc1, n=1) # where n is batch size usually
>>> round(stats.avg, 2)
0.99
+
"""
val: Union[float, bool, Tensor]
diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.py
index 697a8aef0..b75956369 100644
--- a/kornia/metrics/confusion_matrix.py
+++ b/kornia/metrics/confusion_matrix.py
@@ -31,6 +31,7 @@ def confusion_matrix(
tensor([[[2., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]]])
+
"""
if not torch.is_tensor(pred) and pred.dtype is not torch.int64:
raise TypeError(f"Input pred type is not a torch.Tensor with torch.int64 dtype. Got {type(pred)}")
diff --git a/kornia/metrics/endpoint_error.py b/kornia/metrics/endpoint_error.py
index d8d01a6b3..d0daa507d 100644
--- a/kornia/metrics/endpoint_error.py
+++ b/kornia/metrics/endpoint_error.py
@@ -32,6 +32,7 @@ def aepe(input: torch.Tensor, target: torch.Tensor, reduction: str = "mean") ->
Reference:
https://link.springer.com/content/pdf/10.1007/s11263-010-0390-2.pdf
+
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_IS_TENSOR(target)
@@ -81,6 +82,7 @@ class AEPE(nn.Module):
>>> input2 = torch.rand(1, 4, 5, 2)
>>> epe = AEPE(reduction="mean")
>>> epe = epe(input1, input2)
+
"""
def __init__(self, reduction: str = "mean") -> None:
diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.py
index f0f06e2e6..cc1616f83 100644
--- a/kornia/metrics/mean_average_precision.py
+++ b/kornia/metrics/mean_average_precision.py
@@ -38,6 +38,7 @@ def mean_average_precision(
>>> gt_boxes, gt_labels = torch.tensor([[100, 50, 150, 100.]]), torch.tensor([1])
>>> mean_average_precision([boxes], [labels], [scores], [gt_boxes], [gt_labels], 2)
(tensor(1.), {1: 1.0})
+
"""
# these are all lists of tensors of the same length, i.e. number of images
if not len(pred_boxes) == len(pred_labels) == len(pred_scores) == len(gt_boxes) == len(gt_labels):
diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.py
index a668f09d5..3d573a691 100644
--- a/kornia/metrics/mean_iou.py
+++ b/kornia/metrics/mean_iou.py
@@ -27,6 +27,7 @@ def mean_iou(pred: torch.Tensor, target: torch.Tensor, num_classes: int, eps: fl
>>> target = torch.tensor([[0, 1, 0]])
>>> mean_iou(logits, target, num_classes=3)
tensor([[1., 1., 1.]])
+
"""
if not torch.is_tensor(pred) and pred.dtype is not torch.int64:
raise TypeError(f"Input pred type is not a torch.Tensor with torch.int64 dtype. Got {type(pred)}")
@@ -75,6 +76,7 @@ def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor) -> torch.Tensor:
>>> mean_iou_bbox(boxes_1, boxes_2)
tensor([[0.3333, 0.0000],
[0.1429, 0.2500]])
+
"""
# TODO: support more box types. e.g. xywh,
if not (((boxes_1[:, 2] - boxes_1[:, 0]) > 0).all() or ((boxes_1[:, 3] - boxes_1[:, 1]) > 0).all()):
diff --git a/kornia/metrics/psnr.py b/kornia/metrics/psnr.py
index a006bd0f9..84ef5b36b 100644
--- a/kornia/metrics/psnr.py
+++ b/kornia/metrics/psnr.py
@@ -36,6 +36,7 @@ def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten
Reference:
https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio#Definition
+
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Expected torch.Tensor but got {type(image)}.")
diff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.py
index 3887d2dac..c3cd5fa22 100644
--- a/kornia/metrics/ssim.py
+++ b/kornia/metrics/ssim.py
@@ -55,6 +55,7 @@ def ssim(
>>> input1 = torch.rand(1, 4, 5, 5)
>>> input2 = torch.rand(1, 4, 5, 5)
>>> ssim_map = ssim(input1, input2, 5) # 1x4x5x5
+
"""
if not isinstance(img1, torch.Tensor):
raise TypeError(f"Input img1 type is not a torch.Tensor. Got {type(img1)}")
@@ -156,6 +157,7 @@ class SSIM(nn.Module):
>>> input2 = torch.rand(1, 4, 5, 5)
>>> ssim = SSIM(5)
>>> ssim_map = ssim(input1, input2) # 1x4x5x5
+
"""
def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = "same") -> None:
diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.py
index 840338f47..b47f2f16c 100644
--- a/kornia/metrics/ssim3d.py
+++ b/kornia/metrics/ssim3d.py
@@ -57,6 +57,7 @@ def ssim3d(
>>> input1 = torch.rand(1, 4, 5, 5, 5)
>>> input2 = torch.rand(1, 4, 5, 5, 5)
>>> ssim_map = ssim3d(input1, input2, 5) # 1x4x5x5x5
+
"""
KORNIA_CHECK_IS_TENSOR(img1)
KORNIA_CHECK_IS_TENSOR(img2)
@@ -149,6 +150,7 @@ class SSIM3D(Module):
>>> input2 = torch.rand(1, 4, 5, 5, 5)
>>> ssim = SSIM3D(5)
>>> ssim_map = ssim(input1, input2) # 1x4x5x5x5
+
"""
def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = "same") -> None:
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.py
index f377cca8d..488af7320 100644
--- a/kornia/models/_hf_models/hf_onnx_community.py
+++ b/kornia/models/_hf_models/hf_onnx_community.py
@@ -23,6 +23,7 @@ class HFONNXComunnityModelLoader:
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`.
+
"""
def __init__(
@@ -106,6 +107,7 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
Returns:
The resized images.
+
"""
if isinstance(target_images, Tensor):
return resize(images, target_images.shape[-2:])
@@ -131,6 +133,7 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
If to save the model or load it.
additional_metadata:
Additional metadata to add to the ONNX model.
+
"""
if onnx_name is None:
onnx_name = f"kornia_{self.name}.onnx"
diff --git a/kornia/models/base.py b/kornia/models/base.py
index 7fa741054..6ba69f91e 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -31,6 +31,7 @@ class ModelBaseMixin:
Raises:
RuntimeError: If the output type is not supported.
+
"""
if output_type == "torch":
if is_batch and not isinstance(output, Tensor):
@@ -56,6 +57,7 @@ class ModelBaseMixin:
Args:
outputs: output tensor.
directory: directory to save the images.
+
"""
if directory is None:
name = f"{self.name}_{datetime.datetime.now(tz=datetime.timezone.utc).strftime('%Y%m%d%H%M%S')!s}"
@@ -82,6 +84,7 @@ class ModelBase(Module, ONNXExportMixin, ModelBaseMixin):
model: an object detection model.
pre_processor: a pre-processing module
post_processor: a post-processing module.
+
"""
super().__init__()
self.model = model.eval()
diff --git a/kornia/models/depth_estimation/base.py b/kornia/models/depth_estimation/base.py
index 5bac1c7c4..ea77f40d0 100644
--- a/kornia/models/depth_estimation/base.py
+++ b/kornia/models/depth_estimation/base.py
@@ -23,6 +23,7 @@ class DepthEstimation(HFONNXComunnityModel):
Returns:
list of detections found in each image. For item in a batch, shape is :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.
+
"""
if isinstance(
images,
@@ -60,6 +61,7 @@ class DepthEstimation(HFONNXComunnityModel):
Returns:
output tensor.
+
"""
if depth_maps is None:
depth_maps = self(images)
@@ -94,6 +96,7 @@ class DepthEstimation(HFONNXComunnityModel):
Returns:
output tensor.
+
"""
outputs = self.visualize(images, depth_maps, output_type, depth_type=depth_type, max_depth=max_depth)
self._save_outputs(images, directory, suffix="_src")
diff --git a/kornia/models/depth_estimation/depth_anything.py b/kornia/models/depth_estimation/depth_anything.py
index 7cde1eacb..6c09ce177 100644
--- a/kornia/models/depth_estimation/depth_anything.py
+++ b/kornia/models/depth_estimation/depth_anything.py
@@ -39,6 +39,7 @@ class DepthAnythingONNXBuilder:
images = kornia.utils.sample.get_sample_images()
model = DepthAnythingONNXBuilder.build()
model.save(images)
+
"""
if model_name not in [
"depth-anything-v2-small",
diff --git a/kornia/models/detection/base.py b/kornia/models/detection/base.py
index ce727e3b3..1a24abaf7 100644
--- a/kornia/models/detection/base.py
+++ b/kornia/models/detection/base.py
@@ -46,6 +46,7 @@ class BoundingBox:
Args:
data: tuple of bounding box data. The length of the tuple depends on the data format.
data_format: bounding box data format.
+
"""
data: tuple[float, float, float, float]
@@ -60,6 +61,7 @@ class ObjectDetectorResult:
class_id: class id of the detected object.
confidence: confidence score of the detected object.
bbox: bounding box of the detected object in xywh format.
+
"""
class_id: int
@@ -76,6 +78,7 @@ def results_from_detections(detections: Tensor, format: str | BoundingBoxDataFor
Returns:
list of :py:class:`ObjectDetectorResult`.
+
"""
KORNIA_CHECK_SHAPE(detections, ["D", "6"])
@@ -113,6 +116,7 @@ class ObjectDetector(ModelBase):
Returns:
list of detections found in each image. For item in a batch, shape is :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.
+
"""
images, images_sizes = self.pre_processor(images)
logits, boxes = self.model(images)
@@ -148,6 +152,7 @@ class ObjectDetector(ModelBase):
images: input tensor.
detections: detection tensor.
directory: directory to save the images.
+
"""
outputs = self.visualize(images, detections)
self._save_outputs(outputs, directory)
@@ -180,6 +185,7 @@ class ObjectDetector(ModelBase):
If to save the model or load it.
additional_metadata:
Additional metadata to add to the ONNX model.
+
"""
if onnx_name is None:
onnx_name = f"kornia_{self.name}_{image_size}.onnx"
diff --git a/kornia/models/detection/rtdetr.py b/kornia/models/detection/rtdetr.py
index 2884f0ee6..025c605d4 100644
--- a/kornia/models/detection/rtdetr.py
+++ b/kornia/models/detection/rtdetr.py
@@ -55,6 +55,7 @@ class RTDETRDetectorBuilder:
Returns:
ObjectDetector
An object detector instance initialized with the specified model, preprocessor, and post-processor.
+
"""
if model_name is not None and config is not None:
raise ValueError("Either `model_name` or `config` should be `None`.")
diff --git a/kornia/models/detection/utils.py b/kornia/models/detection/utils.py
index 5699c45d7..262053709 100644
--- a/kornia/models/detection/utils.py
+++ b/kornia/models/detection/utils.py
@@ -13,6 +13,7 @@ class BoxFiltering(Module, ONNXExportMixin):
confidence_threshold: an 0-d scalar that represents the desired threshold.
classes_to_keep: a 1-d list of classes to keep. If None, keep all classes.
filter_as_zero: whether to filter boxes as zero.
+
"""
ONNX_DEFAULT_INPUTSHAPE: ClassVar[List[int]] = [-1, -1, 6]
@@ -57,6 +58,7 @@ class BoxFiltering(Module, ONNXExportMixin):
detections as input.
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.
+
"""
# Apply confidence filtering
zero_tensor = tensor(0.0, device=boxes.device, dtype=boxes.dtype)
diff --git a/kornia/models/edge_detection/base.py b/kornia/models/edge_detection/base.py
index 589865d5b..d27c817e0 100644
--- a/kornia/models/edge_detection/base.py
+++ b/kornia/models/edge_detection/base.py
@@ -28,6 +28,7 @@ class EdgeDetector(ModelBase):
Returns:
output tensor.
+
"""
images, image_sizes = self.pre_processor(images)
out_images = self.model(images)
@@ -47,6 +48,7 @@ class EdgeDetector(ModelBase):
Returns:
output tensor.
+
"""
if edge_maps is None:
edge_maps = self.forward(images)
@@ -71,6 +73,7 @@ class EdgeDetector(ModelBase):
Returns:
output tensor.
+
"""
outputs = self.visualize(images, edge_maps, output_type)
self._save_outputs(images, directory, suffix="_src")
@@ -100,6 +103,7 @@ class EdgeDetector(ModelBase):
If to save the model or load it.
additional_metadata:
Additional metadata to add to the ONNX model.
+
"""
if onnx_name is None:
onnx_name = f"kornia_{self.name}_{image_size}.onnx"
diff --git a/kornia/models/segmentation/base.py b/kornia/models/segmentation/base.py
index ecb7e809c..f78174364 100644
--- a/kornia/models/segmentation/base.py
+++ b/kornia/models/segmentation/base.py
@@ -31,6 +31,7 @@ class SemanticSegmentation(ModelBase):
Returns:
output tensor.
+
"""
outputs: Union[Tensor, list[Tensor]]
@@ -64,6 +65,7 @@ class SemanticSegmentation(ModelBase):
Returns:
A tensor of shape (num_classes, 3) representing the color map.
+
"""
if colormap == "random":
# Generate a color for each class
@@ -90,6 +92,7 @@ class SemanticSegmentation(ModelBase):
ValueError: If the shape of the semantic mask is not of shape (C, H, W) or (B, C, H, W).
ValueError: If the shape of the colors is not of shape (num_classes, 3).
ValueError: If only muliclass segmentation is supported. Please ensure a softmax is used, or submit a PR.
+
"""
if semantic_mask.dim() == 3:
channel_dim = 0
@@ -138,6 +141,7 @@ class SemanticSegmentation(ModelBase):
output_type: The type of output, can be "torch" or "PIL".
colormap: The colormap to use, can be "random" or a custom color map.
manual_seed: The manual seed to use for the colormap.
+
"""
if semantic_masks is None:
semantic_masks = self.forward(images)
@@ -185,8 +189,8 @@ class SemanticSegmentation(ModelBase):
output_type: The type of output, can be "torch" or "PIL".
colormap: The colormap to use, can be "random" or a custom color map.
manual_seed: The manual seed to use for the colormap.
- """
+ """
colored_masks = self.visualize(images, semantic_masks, output_type, colormap=colormap, manual_seed=manual_seed)
overlaid: Union[Tensor, list[Tensor]]
if isinstance(images, Tensor) and isinstance(colored_masks, Tensor):
diff --git a/kornia/models/segmentation/segmentation_models.py b/kornia/models/segmentation/segmentation_models.py
index 7cfc811f4..3a4cdf25c 100644
--- a/kornia/models/segmentation/segmentation_models.py
+++ b/kornia/models/segmentation/segmentation_models.py
@@ -43,8 +43,8 @@ class SegmentationModelsBuilder:
Note:
Only encoder weights are available.
Pretrained weights for the whole model are not available.
- """
+ """
preproc_params = smp.encoders.get_preprocessing_params(encoder_name) # type: ignore
preprocessor = SegmentationModelsBuilder.get_preprocessing_pipeline(preproc_params)
segmentation_model = getattr(smp, model_name)(
diff --git a/kornia/models/super_resolution/base.py b/kornia/models/super_resolution/base.py
index bfd896120..d1b5518a6 100644
--- a/kornia/models/super_resolution/base.py
+++ b/kornia/models/super_resolution/base.py
@@ -29,6 +29,7 @@ class SuperResolution(ModelBase):
Returns:
output tensor.
+
"""
output = self.pre_processor(images)
if isinstance(
@@ -61,6 +62,7 @@ class SuperResolution(ModelBase):
Returns:
output tensor.
+
"""
if edge_maps is None:
edge_maps = self.forward(images)
@@ -85,6 +87,7 @@ class SuperResolution(ModelBase):
Returns:
output tensor.
+
"""
outputs = self.visualize(images, edge_maps, output_type)
self._save_outputs(images, directory, suffix="_src")
@@ -113,6 +116,7 @@ class SuperResolution(ModelBase):
If to save the model or load it.
additional_metadata:
Additional metadata to add to the ONNX model.
+
"""
if onnx_name is None:
onnx_name = f"kornia_{self.name}.onnx"
diff --git a/kornia/models/tracking/boxmot_tracker.py b/kornia/models/tracking/boxmot_tracker.py
index fe73c02d9..2731d32a7 100644
--- a/kornia/models/tracking/boxmot_tracker.py
+++ b/kornia/models/tracking/boxmot_tracker.py
@@ -65,6 +65,7 @@ class BoxMotTracker:
.. note::
At least 4 frames are needed to initialize the tracking position.
+
"""
name: str = "boxmot_tracker"
@@ -100,8 +101,8 @@ class BoxMotTracker:
Args:
image: The input image.
- """
+ """
if not (image.ndim == 4 and image.shape[0] == 1) and not image.ndim == 3:
raise ValueError(f"Input tensor must be of shape (1, 3, H, W) or (3, H, W). Got {image.shape}")
@@ -140,6 +141,7 @@ class BoxMotTracker:
Returns:
The image with the results of the tracker.
+
"""
frame_raw = (tensor_to_image(image) * 255).astype(np.uint8)
self.tracker.plot_results(frame_raw, show_trajectories=show_trajectories)
@@ -151,6 +153,7 @@ class BoxMotTracker:
Args:
image: The input image.
+
"""
if directory is None:
name = f"{self.name}_{datetime.datetime.now(tz=datetime.timezone.utc).strftime('%Y%m%d%H%M%S')!s}"
diff --git a/kornia/models/utils.py b/kornia/models/utils.py
index 70aac895d..962ca238b 100644
--- a/kornia/models/utils.py
+++ b/kornia/models/utils.py
@@ -17,22 +17,22 @@ class ResizePreProcessor(Module):
"""
def __init__(self, height: int, width: int, interpolation_mode: str = "bilinear") -> None:
- """
- Args:
- height: height of the resized image.
- width: width of the resized image.
- interpolation_mode: interpolation mode for image resizing. Supported values: ``nearest``, ``bilinear``,
- ``bicubic``, ``area``, and ``nearest-exact``.
+ """Args:
+ height: height of the resized image.
+ width: width of the resized image.
+ interpolation_mode: interpolation mode for image resizing. Supported values: ``nearest``, ``bilinear``,
+ ``bicubic``, ``area``, and ``nearest-exact``.
+
"""
super().__init__()
self.size = (height, width)
self.interpolation_mode = interpolation_mode
def forward(self, imgs: Union[Tensor, List[Tensor]]) -> Tuple[Tensor, Tensor]:
- """
- Returns:
- resized_imgs: resized images in a batch.
- original_sizes: the original image sizes of (height, width).
+ """Returns:
+ resized_imgs: resized images in a batch.
+ original_sizes: the original image sizes of (height, width).
+
"""
# TODO: support other input formats e.g. file path, numpy
resized_imgs: list[Tensor] = []
@@ -53,10 +53,10 @@ class ResizePostProcessor(Module):
self.interpolation_mode = interpolation_mode
def forward(self, imgs: Union[Tensor, List[Tensor]], original_sizes: Tensor) -> Union[Tensor, List[Tensor]]:
- """
- Returns:
- resized_imgs: resized images in a batch.
- original_sizes: the original image sizes of (height, width).
+ """Returns:
+ resized_imgs: resized images in a batch.
+ original_sizes: the original image sizes of (height, width).
+
"""
# TODO: support other input formats e.g. file path, numpy
resized_imgs: list[Tensor] = []
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index 5940dae22..d258ce9fb 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -54,8 +54,8 @@ def dilation(
>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> dilated_img = dilation(tensor, kernel)
- """
+ """
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
@@ -147,8 +147,8 @@ def erosion(
>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(5, 5)
>>> output = erosion(tensor, kernel)
- """
+ """
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
@@ -241,8 +241,8 @@ def opening(
>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> opened_img = opening(tensor, kernel)
- """
+ """
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
@@ -318,8 +318,8 @@ def closing(
>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> closed_img = closing(tensor, kernel)
- """
+ """
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
@@ -397,8 +397,8 @@ def gradient(
>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> gradient_img = gradient(tensor, kernel)
- """
+ """
return dilation(
tensor,
kernel=kernel,
@@ -465,8 +465,8 @@ def top_hat(
>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> top_hat_img = top_hat(tensor, kernel)
- """
+ """
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
@@ -536,8 +536,8 @@ def bottom_hat(
>>> tensor = torch.rand(1, 3, 5, 5)
>>> kernel = torch.ones(3, 3)
>>> bottom_hat_img = bottom_hat(tensor, kernel)
- """
+ """
if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
diff --git a/kornia/nerf/camera_utils.py b/kornia/nerf/camera_utils.py
index 55d641c14..8d6f3f6d1 100755
--- a/kornia/nerf/camera_utils.py
+++ b/kornia/nerf/camera_utils.py
@@ -21,8 +21,8 @@ def parse_colmap_output(
Returns:
image names: List[str]
scene camera object: PinholeCamera
- """
+ """
# Parse camera intrinsics
with open(cameras_path) as f:
lines = f.readlines()
@@ -120,6 +120,7 @@ def cameras_for_ids(cameras: PinholeCamera, camera_ids: Union[List[int], Tensor]
Return:
A new PinholeCamera object with a sub-set of cameras: PinholeCamera
+
"""
intrinsics = cameras.intrinsics[camera_ids]
extrinsics = cameras.extrinsics[camera_ids]
@@ -137,6 +138,7 @@ def create_spiral_path(cameras: PinholeCamera, rad: float, num_views: int, num_c
rad: Spiral radius: float
num_views: Number of created cameras: int
num_circles: Number of spiral circles: int
+
"""
# Average locations over all cameras
mean_center = cameras.translation_vector.mean(0, False).squeeze(-1)
diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.py
index cca6aceb9..f6124b92c 100755
--- a/kornia/nerf/data_utils.py
+++ b/kornia/nerf/data_utils.py
@@ -31,6 +31,7 @@ class RayDataset(Dataset[RayGroup]):
ndc: convert ray parameters to normalized device coordinates: bool
device: device for ray tensors: Union[str, torch.device]
dtype: type of ray tensors: torch.dtype
+
"""
def __init__(
@@ -51,6 +52,7 @@ class RayDataset(Dataset[RayGroup]):
Args:
num_img_rays: If not None, number of rays to randomly cast from each camera: math: `(B)`.
+
"""
if num_img_rays is None:
self._init_uniform_ray_dataset()
@@ -63,6 +65,7 @@ class RayDataset(Dataset[RayGroup]):
Args:
imgs: List of image tensors or image paths: Images
+
"""
self._check_image_type_consistency(imgs)
@@ -83,6 +86,7 @@ class RayDataset(Dataset[RayGroup]):
Args:
num_img_rays: If not None, number of rays to randomly cast from each camers: math: `(B)`.
+
"""
self._ray_sampler = RandomRaySampler(
self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
@@ -135,6 +139,7 @@ class RayDataset(Dataset[RayGroup]):
Return:
A ray parameter object that includes ray origins, directions, and rgb values at the ray 2d pixel
coordinates: RayGroup
+
"""
if not isinstance(self._ray_sampler, RaySampler):
raise TypeError("Ray sampler is not initiate yet, please run self.init_ray_dataset() before use it.")
@@ -160,6 +165,7 @@ def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shuffle
dataset: A ray dataset: RayDataset
batch_size: Number of rays to sample in a batch: int
shuffle: Whether to shuffle rays or sample then sequentially: bool
+
"""
def collate_rays(items: List[RayGroup]) -> RayGroup:
diff --git a/kornia/nerf/nerf_model.py b/kornia/nerf/nerf_model.py
index 9f3406b11..aaf16d975 100755
--- a/kornia/nerf/nerf_model.py
+++ b/kornia/nerf/nerf_model.py
@@ -32,6 +32,7 @@ class MLP(Module):
num_units: Number of sub-units.
num_unit_layers: Number of fully connected layers in each sub-unit.
num_hidden: Layer hidden dimensions.
+
"""
super().__init__()
self._num_unit_layers = num_unit_layers
@@ -66,6 +67,7 @@ class NerfModel(Module):
num_unit_layers: Number of fully connected layers in each sub-unit.
num_hidden: Layer hidden dimensions.
log_space_encoding: Whether to apply log spacing for encoding.
+
"""
def __init__(
@@ -108,6 +110,7 @@ class NerfModel(Module):
Returns:
Rendered image pixels :math:`(B, 3)`.
+
"""
# Sample xyz for ray parameters
batch_size = origins.shape[0]
@@ -158,6 +161,7 @@ class NerfModelRenderer:
image_size: image size.
device: device to run the model on.
dtype: dtype to run the model on.
+
"""
self._nerf_model = nerf_model
self._image_size = image_size
@@ -175,6 +179,7 @@ class NerfModelRenderer:
Returns:
- Pixels grid: Tensor (1, H, W, 2)
- Ones: Tensor (H*W, 1)
+
"""
height, width = self._image_size
pixels_grid: Tensor = create_meshgrid(
@@ -194,6 +199,7 @@ class NerfModelRenderer:
Returns:
Rendered image with shape :math:`(H, W, 3)`.
+
"""
# create ray for this camera
rays: Ray = self._create_rays(camera)
@@ -211,6 +217,7 @@ class NerfModelRenderer:
Args:
camera: camera for image rendering: PinholeCamera.
+
"""
height, width = self._image_size
diff --git a/kornia/nerf/nerf_solver.py b/kornia/nerf/nerf_solver.py
index 835c63d8b..cf7c5ee1a 100755
--- a/kornia/nerf/nerf_solver.py
+++ b/kornia/nerf/nerf_solver.py
@@ -26,6 +26,7 @@ class NerfSolver:
Args:
device: device for class tensors: Union[str, Device]
dtype: type for all floating point calculations: torch.dtype
+
"""
def __init__(self, device: torch.device, dtype: torch.dtype) -> None:
@@ -87,6 +88,7 @@ class NerfSolver:
irregular_ray_sampling: Whether to sample ray points irregularly.
log_space: Whether frequency sampling should be log spaced.
lr: Learning rate.
+
"""
self._cameras = cameras
self._min_depth = min_depth
@@ -179,6 +181,7 @@ class NerfSolver:
Returns:
Average psnr over all epoch rays.
+
"""
KORNIA_CHECK(self._nerf_model is not None, "The model should be a NeRF model.")
KORNIA_CHECK(self._nerf_optimizer is not None, "The optimizer should be an Adam optimizer.")
@@ -226,6 +229,7 @@ class NerfSolver:
Args:
num_epochs: number of epochs to run. Default: 1.
+
"""
for i_epoch in range(num_epochs):
# train one epoch
diff --git a/kornia/nerf/positional_encoder.py b/kornia/nerf/positional_encoder.py
index a71aa71e5..13b3e14f4 100755
--- a/kornia/nerf/positional_encoder.py
+++ b/kornia/nerf/positional_encoder.py
@@ -24,6 +24,7 @@ class PositionalEncoder(nn.Module):
num_dims: Number of input dimensions (channels): int
num_freqs: Number of frequency bands for encoding span: int
log_space: Whether frequency sampling should be log spaced: bool
+
"""
super().__init__()
self._num_dims = num_dims
@@ -56,6 +57,7 @@ class PositionalEncoder(nn.Module):
Returns:
Tensor with encoded position/direction: Tensor
+
"""
if x.ndim < 1:
raise ValueError("Input tensor represents a scalar")
diff --git a/kornia/nerf/samplers.py b/kornia/nerf/samplers.py
index 720b2942f..1197d82df 100755
--- a/kornia/nerf/samplers.py
+++ b/kornia/nerf/samplers.py
@@ -18,6 +18,7 @@ class RaySampler:
max_depth: sampled rays maximal depth from cameras: float
ndc: convert ray parameters to normalized device coordinates: bool
device: device for ray tensors: Union[str, torch.device]
+
"""
_origins: Tensor # Ray origins in world coordinates (*, 3)
@@ -75,6 +76,7 @@ class RaySampler:
points_2d: tensor with ray pixel coordinates (the coordinates in the image plane that correspond to the
ray):math:`(B, 2)`
camera_ids: list of camera ids for each pixel coordinates: List[int]
+
"""
def __init__(self, points_2d: Tensor, camera_ids: List[int]) -> None:
@@ -96,6 +98,7 @@ class RaySampler:
Args:
cameras: scene cameras: PinholeCamera
points_2d_camera: a dictionary that groups Point2D objects by total number of casted rays
+
"""
# Unproject 2d points in image plane to 3d world for two depths
origins = []
@@ -141,6 +144,7 @@ class RaySampler:
Args:
cameras: scene cameras: PinholeCamera
+
"""
cams = cameras_for_ids(cameras, self._camera_ids)
fx = cams.fx
@@ -201,7 +205,8 @@ class RaySampler:
n: int, x: Tensor, y: Tensor, camera_id: int, points2d_as_flat_tensors: Dict[int, Points2D_FlatTensors]
) -> None:
r"""Adds x/y pixel coordinates for all rays casted by a scene camera to dictionary of pixel coordinates
- grouped by total number of rays."""
+ grouped by total number of rays.
+ """
if n not in points2d_as_flat_tensors:
points2d_as_flat_tensors[n] = RaySampler.Points2D_FlatTensors()
points2d_as_flat_tensors[n]._x = x.flatten()
@@ -225,6 +230,7 @@ class RaySampler:
Returns:
dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
id it was casted by: Dict[int, Points2D]
+
"""
num_ray_dict_of_points2d: Dict[int, RaySampler.Points2D] = {}
for n, points2d_as_flat_tensor in points2d_as_flat_tensors.items():
@@ -246,6 +252,7 @@ class RandomRaySampler(RaySampler):
max_depth: sampled rays maximal depth from cameras: float
ndc: convert to normalized device coordinates: bool
device: device for ray tensors: Union[str, torch.device]
+
"""
def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
@@ -262,6 +269,7 @@ class RandomRaySampler(RaySampler):
Returns:
dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
id it was casted by: Dict[int, Points2D]
+
"""
num_img_rays = num_img_rays.int()
points2d_as_flat_tensors: Dict[int, RaySampler.Points2D_FlatTensors] = {}
@@ -280,6 +288,7 @@ class RandomRaySampler(RaySampler):
Args:
cameras: scene cameras: PinholeCamera
num_img_rays: tensor that holds the number of rays to randomly cast from each scene camera: int math: `(B)`.
+
"""
num_cams = cameras.batch_size
if num_cams != num_img_rays.shape[0]:
@@ -302,6 +311,7 @@ class RandomGridRaySampler(RandomRaySampler):
max_depth: sampled rays maximal depth from cameras: float
ndc: convert to normalized device coordinates: bool
device: device for ray tensors: Union[str, torch.device]
+
"""
def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
@@ -319,6 +329,7 @@ class RandomGridRaySampler(RandomRaySampler):
Returns:
dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
id it was casted by: Dict[int, Points2D]
+
"""
num_img_rays = num_img_rays.int()
points2d_as_flat_tensors: Dict[int, RaySampler.Points2D_FlatTensors] = {}
@@ -341,6 +352,7 @@ class UniformRaySampler(RaySampler):
max_depth: sampled rays maximal depth from cameras: float
ndc: convert to normalized device coordinates: bool
device: device for ray tensors: Union[str, torch.device]
+
"""
def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
@@ -359,6 +371,7 @@ class UniformRaySampler(RaySampler):
Returns:
dictionary of Points2D objects that holds information on pixel 2d coordinates of each ray and the camera
id it was casted by: Dict[int, Points2D]
+
"""
heights = heights.int()
widths = widths.int()
@@ -402,14 +415,14 @@ def sample_lengths(
def sample_ray_points(
origins: Tensor, directions: Tensor, lengths: Tensor
) -> Tensor: # FIXME: Test by projecting to points_2d and compare with sampler 2d points
- r"""
- Args:
+ r"""Args:
origins: tensor containing ray origins in 3d world coordinates. Tensor shape :math:`(*, 3)`.
directions: tensor containing ray directions in 3d world coordinates. Tensor shape :math:`(*, 3)`.
lengths: tensor containing sampled distances along each ray. Tensor shape :math:`(*, num_ray_points)`.
Returns:
points_3d: Points along rays :math:`(*, num_ray_points, 3)`
+
"""
points_3d = origins[..., None, :] + lengths[..., None] * directions[..., None, :]
return points_3d
@@ -423,6 +436,7 @@ def calc_ray_t_vals(points_3d: Tensor) -> Tensor:
Returns:
t values along rays :math:`(*, num_ray_points)`
+
"""
t_vals = torch.linalg.norm(points_3d - points_3d[..., 0, :].unsqueeze(-2), dim=-1)
return t_vals
diff --git a/kornia/nerf/volume_renderer.py b/kornia/nerf/volume_renderer.py
index 1fbd0ea20..7f8c4b1a4 100755
--- a/kornia/nerf/volume_renderer.py
+++ b/kornia/nerf/volume_renderer.py
@@ -19,6 +19,7 @@ class VolumeRenderer(torch.nn.Module):
Args:
shift: Size of far-field layer: int
+
"""
super().__init__()
self._shift = shift
@@ -51,6 +52,7 @@ class IrregularRenderer(VolumeRenderer):
Returns:
Rendered RGB values for each ray :math:`(*, 3)`
+
"""
t_vals = calc_ray_t_vals(points_3d)
deltas = t_vals[..., 1:] - t_vals[..., :-1] # (*, N - 1)
@@ -75,6 +77,7 @@ class RegularRenderer(VolumeRenderer):
Returns:
Rendered RGB values for each ray :math:`(*, 3)`
+
"""
KORNIA_CHECK_SHAPE(rgbs, ["*", "N", "3"])
KORNIA_CHECK_SHAPE(densities, ["*", "N"])
diff --git a/kornia/onnx/module.py b/kornia/onnx/module.py
index 8231f6be8..26eb6090b 100644
--- a/kornia/onnx/module.py
+++ b/kornia/onnx/module.py
@@ -23,6 +23,7 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
target_ir_version: The target IR version to convert to.
target_opset_version: The target OPSET version to convert to.
+
"""
def __init__(
@@ -64,5 +65,6 @@ def load(model_name: Union[onnx.ModelProto, str]) -> ONNXModule: # type:ignore
model_name: The name of the model to load. For Hugging Face-hosted models,
use the format 'hf://model_name'. Valid `model_name` can be found on
https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.
+
"""
return ONNXModule(model_name)
diff --git a/kornia/onnx/sequential.py b/kornia/onnx/sequential.py
index 949a2ecf7..44d628eb3 100644
--- a/kornia/onnx/sequential.py
+++ b/kornia/onnx/sequential.py
@@ -29,6 +29,7 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
Other versions may be pointed to by `target_ir_version` and `target_opset_version`.
target_ir_version: The target IR version to convert to.
target_opset_version: The target OPSET version to convert to.
+
"""
def __init__(
@@ -65,6 +66,7 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
Args:
target_ir_version: The target IR version to convert to.
target_opset_version: The target OPSET version to convert to.
+
"""
# TODO: maybe another logic for versioning.
if target_ir_version is None:
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index 5cd497416..4c74308ec 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -30,6 +30,7 @@ class ONNXLoader(CachedDownloader):
Returns:
dict[str, Any]: The loaded preprocessor config.
+
"""
if url.startswith(("http:", "https:")):
file_path = cls.download_to_cache(
@@ -65,6 +66,7 @@ class ONNXLoader(CachedDownloader):
Returns:
onnx.ModelProto: The loaded ONNX model.
+
"""
if model_name.startswith("hf://"):
model_name = model_name[len("hf://") :]
@@ -115,6 +117,7 @@ class ONNXLoader(CachedDownloader):
Returns:
A list of all files in the repository as dictionaries containing file details.
+
"""
url = f"https://huggingface.co/api/models/kornia/ONNX_models/tree/main/{folder}"
@@ -155,6 +158,7 @@ def io_name_conversion(
Args:
onnx_model: The ONNX model to convert.
io_name_mapping: A dictionary mapping the original input and output names to the new ones.
+
"""
# Convert I/O nodes
for i in range(len(onnx_model.graph.input)):
@@ -196,6 +200,7 @@ def add_metadata(
Returns:
The ONNX model with the added metadata.
+
"""
if additional_metadata is None:
additional_metadata = []
diff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.py
index fa9763606..5c348ad3e 100644
--- a/kornia/sensors/camera/camera_model.py
+++ b/kornia/sensors/camera/camera_model.py
@@ -51,6 +51,7 @@ class CameraModelBase:
>>> cam = CameraModelBase(BrownConradyTransform(), Z1Projection(), ImageSize(480, 640), params)
>>> cam.params
tensor([328., 328., 320., 240.])
+
"""
def __init__(
@@ -66,6 +67,7 @@ class CameraModelBase:
for PINHOLE Camera, :math:`(B, 12)`
for Brown Conrady, :math:`(B, 8)`
for Kannala Brandt K3.
+
"""
self.distortion = distortion
self.projection = projection
@@ -137,6 +139,7 @@ class CameraModelBase:
>>> cam.project(points)
x: 648.0
y: 568.0
+
"""
return self.distortion.distort(self.params, self.projection.project(points))
@@ -157,6 +160,7 @@ class CameraModelBase:
x: tensor([-0.9726])
y: tensor([-0.7287])
z: tensor([1.])
+
"""
return self.projection.unproject(self.distortion.undistort(self.params, points), depth)
@@ -174,6 +178,7 @@ class PinholeModel(CameraModelBase):
>>> cam = CameraModel(ImageSize(480, 640), CameraModelType.PINHOLE, torch.Tensor([328., 328., 320., 240.]))
>>> cam
CameraModel(ImageSize(height=480, width=640), PinholeModel, tensor([328., 328., 320., 240.]))
+
"""
def __init__(self, image_size: ImageSize, params: Tensor) -> None:
@@ -182,6 +187,7 @@ class PinholeModel(CameraModelBase):
Args:
image_size: Image size
params: Camera parameters of shape :math:`(B, 4)` of the form :math:`(fx, fy, cx, cy)`.
+
"""
if params.shape[-1] != 4 or len(params.shape) > 2:
raise ValueError("params must be of shape (B, 4) for PINHOLE Camera")
@@ -203,6 +209,7 @@ class PinholeModel(CameraModelBase):
tensor([[1., 0., 3.],
[0., 2., 4.],
[0., 0., 1.]])
+
"""
z = zeros_like(self.fx)
row1 = stack((self.fx, z, self.cx), -1)
@@ -226,6 +233,7 @@ class PinholeModel(CameraModelBase):
>>> cam_scaled = cam.scale(2)
>>> cam_scaled.params
tensor([656., 656., 640., 480.])
+
"""
fx = self.fx * scale_factor
fy = self.fy * scale_factor
@@ -246,6 +254,7 @@ class BrownConradyModel(CameraModelBase):
image_size: Image size
params: Camera parameters of shape :math:`(B, 12)` of the form :math:`(fx, fy, cx, cy, kb0, kb1, kb2, kb3,
k1, k2, k3, k4)`.
+
"""
if params.shape[-1] != 12 or len(params.shape) > 2:
raise ValueError("params must be of shape (B, 12) for BROWN_CONRADY Camera")
@@ -261,6 +270,7 @@ class KannalaBrandtK3(CameraModelBase):
Args:
image_size: Image size
params: Camera parameters of shape :math:`(B, 8)` of the form :math:`(fx, fy, cx, cy, kb0, kb1, kb2, kb3)`.
+
"""
if params.shape[-1] != 8 or len(params.shape) > 2:
raise ValueError("params must be of shape B, 8 for KANNALA_BRANDT_K3 Camera")
@@ -276,6 +286,7 @@ class Orthographic(CameraModelBase):
Args:
image_size: Image size
params: Camera parameters of shape :math:`(B, 4)` of the form :math:`(fx, fy, cx, cy)`.
+
"""
super().__init__(AffineTransform(), OrthographicProjection(), image_size, params)
if params.shape[-1] != 4 or len(params.shape) > 2:
@@ -301,6 +312,7 @@ class CameraModel:
>>> cam = CameraModel(ImageSize(480, 640), CameraModelType.ORTHOGRAPHIC, torch.Tensor([328., 328., 320., 240.]))
>>> cam.params
tensor([328., 328., 320., 240.])
+
"""
def __init__(self, image_size: ImageSize, model_type: CameraModelType, params: Tensor) -> None:
@@ -310,6 +322,7 @@ class CameraModel:
image_size: Image size
model_type: Camera model type
params: Camera parameters of shape :math:`(B, N)`.
+
"""
self._model = get_model_from_type(model_type, image_size, params)
diff --git a/kornia/sensors/camera/distortion_model.py b/kornia/sensors/camera/distortion_model.py
index 9282a2d00..dc7682bd0 100644
--- a/kornia/sensors/camera/distortion_model.py
+++ b/kornia/sensors/camera/distortion_model.py
@@ -19,6 +19,7 @@ class AffineTransform:
>>> AffineTransform().distort(params, points)
x: 4.0
y: 8.0
+
"""
fx, fy, cx, cy = params[..., 0], params[..., 1], params[..., 2], params[..., 3]
u = points.x * fx + cx
@@ -41,6 +42,7 @@ class AffineTransform:
>>> AffineTransform().undistort(params, points)
x: -2.0
y: -1.0
+
"""
fx, fy, cx, cy = params[..., 0], params[..., 1], params[..., 2], params[..., 3]
x = (points.x - cx) / fx
diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.py
index a7850cc06..17fc80c63 100644
--- a/kornia/sensors/camera/projection_model.py
+++ b/kornia/sensors/camera/projection_model.py
@@ -20,6 +20,7 @@ class Z1Projection:
>>> Z1Projection().project(points)
x: 0.3333333432674408
y: 0.6666666865348816
+
"""
xy = points.data[..., :2]
z = points.z
@@ -42,6 +43,7 @@ class Z1Projection:
x: tensor([3.])
y: tensor([6.])
z: tensor([3.])
+
"""
if isinstance(depth, (float, int)):
depth = Tensor([depth])
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 2714e619c..b9467e079 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -164,6 +164,7 @@ class BaseTester(ABC):
low_tolerance:
This parameter allows to reduce tolerance. Half the decimal places.
Example, 1e-4 -> 1e-2 or 1e-6 -> 1e-3
+
"""
if hasattr(actual, "data"):
actual = actual.data
diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.py
index 70f976e02..91fed5b92 100644
--- a/kornia/tracking/planar_tracker.py
+++ b/kornia/tracking/planar_tracker.py
@@ -21,6 +21,7 @@ class HomographyTracker(Module):
or :class:`~kornia.feature.LoFTR`. Default: :class:`~kornia.feature.DescriptorMatcher`.
ransac: homography estimation module. Default: :class:`~kornia.geometry.RANSAC`.
minimum_inliers_num: threshold for number inliers for matching to be successful.
+
"""
def __init__(
@@ -107,7 +108,8 @@ class HomographyTracker(Module):
def track_next_frame(self, x: Tensor) -> Tuple[Tensor, bool]:
"""The frame `x` is prewarped according to the previous frame homography, matched with fast_matcher
- verified with ransac."""
+ verified with ransac.
+ """
if self.previous_homography is not None: # mypy, shut up
Hwarp = self.previous_homography.clone()[None]
# make a bit of border for safety
diff --git a/kornia/transpiler/transpiler.py b/kornia/transpiler/transpiler.py
index 12c1af034..c24089b85 100644
--- a/kornia/transpiler/transpiler.py
+++ b/kornia/transpiler/transpiler.py
@@ -27,6 +27,7 @@ def to_jax() -> ModuleType:
import jax
input = jax.random.normal(jax.random.key(42), shape=(2, 3, 4, 5))
gray = jax_kornia.color.gray.rgb_to_grayscale(input)
+
"""
return ivy.transpile(
kornia,
@@ -59,6 +60,7 @@ def to_numpy() -> ModuleType:
Note:
Ivy does not currently support transpiling trainable modules to NumPy.
+
"""
return ivy.transpile(
kornia,
@@ -88,6 +90,7 @@ def to_tensorflow() -> ModuleType:
import tensorflow as tf
input = tf.random.normal((2, 3, 4, 5))
gray = tf_kornia.color.gray.rgb_to_grayscale(input)
+
"""
return ivy.transpile(
kornia,
diff --git a/kornia/utils/download.py b/kornia/utils/download.py
index 153493cc7..9b6506c7f 100644
--- a/kornia/utils/download.py
+++ b/kornia/utils/download.py
@@ -26,6 +26,7 @@ class CachedDownloader:
Returns:
str: The full local path where the model should be stored or loaded from.
+
"""
# Determine the local file path
if cache_dir is None:
@@ -62,6 +63,7 @@ class CachedDownloader:
url: The URL of the ONNX model to download.
file_path: The local path where the downloaded model should be saved.
download_if_not_exists: If True, the file will be downloaded if it's not already downloaded.
+
"""
if os.path.exists(file_path):
logger.info(f"Loading `{url}` from `{file_path}`.")
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
index 6ad6b0671..681d3b3ef 100644
--- a/kornia/utils/draw.py
+++ b/kornia/utils/draw.py
@@ -18,6 +18,7 @@ def draw_point2d(image: Tensor, points: Tensor, color: Tensor) -> Tensor:
Return:
The image with points set to the color.
+
"""
KORNIA_CHECK(
(len(image.shape) == 2 and len(color.shape) == 1) or (image.shape[0] == color.shape[0]),
@@ -46,6 +47,7 @@ def _draw_pixel(image: torch.Tensor, x: int, y: int, color: torch.Tensor) -> Non
Return:
Nothing is returned.
+
"""
image[:, y, x] = color
@@ -58,6 +60,7 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
p1: the start point [x y] of the line with shape (2, ) or (B, 2).
p2: the end point [x y] of the line with shape (2, ) or (B, 2).
color: the color of the line with shape :math`(C)` where :math`C` is the number of channels of the image.
+
Return:
the image with containing the line.
@@ -72,6 +75,7 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.]]])
+
"""
if (p1.shape[0] != p2.shape[0]) or (p1.shape[-1] != 2 or p2.shape[-1] != 2):
raise ValueError(
@@ -197,8 +201,8 @@ def draw_rectangle(
>>> img = torch.rand(2, 3, 10, 12)
>>> rect = torch.tensor([[[0, 0, 4, 4]], [[4, 4, 10, 10]]])
>>> out = draw_rectangle(img, rect)
- """
+ """
batch, c, h, w = image.shape
batch_rect, num_rectangle, num_points = rectangle.shape
if batch != batch_rect:
@@ -254,14 +258,17 @@ def draw_rectangle(
def _get_convex_edges(polygon: Tensor, h: int, w: int) -> Tuple[Tensor, Tensor]:
r"""Gets the left and right edges of a polygon for each y-coordinate y \in [0, h)
+
Args:
polygons: represents polygons to draw in BxNx2
N is the number of points
2 is (x, y).
h: bottom most coordinate (top coordinate is assumed to be 0)
w: right most coordinate (left coordinate is assumed to be 0)
+
Returns:
The left and right edges of the polygon of shape (B,B).
+
"""
dtype = polygon.dtype
@@ -296,13 +303,16 @@ def _batch_polygons(polygons: List[Tensor]) -> Tensor:
r"""Converts a List of variable length polygons into a fixed size tensor.
Works by repeating the last element in the tensor.
+
Args:
polygon: List of variable length polygons of shape [N_1 x 2, N_2 x 2, ..., N_B x 2].
B is the batch size,
N_i is the number of points,
2 is (x, y).
+
Returns:
A fixed size tensor of shape (B, N, 2) where N = max_i(N_i)
+
"""
B, N = len(polygons), len(max(polygons, key=len))
batched_polygons = torch.zeros(B, N, 2, dtype=polygons[0].dtype, device=polygons[0].device)
@@ -334,6 +344,7 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], c
>>> poly = torch.tensor([[[4, 4], [12, 4], [12, 8], [4, 8]]])
>>> color = torch.tensor([[0.5, 0.5, 0.5]])
>>> out = draw_convex_polygon(img, poly, color)
+
"""
# TODO: implement optional linetypes for smooth edges
KORNIA_CHECK_SHAPE(images, ["B", "C", "H", "W"])
diff --git a/kornia/utils/grid.py b/kornia/utils/grid.py
index ca4235b4a..b03fbf832 100644
--- a/kornia/utils/grid.py
+++ b/kornia/utils/grid.py
@@ -45,6 +45,7 @@ def create_meshgrid(
<BLANKLINE>
[[0., 1.],
[1., 1.]]]])
+
"""
xs: Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
ys: Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
@@ -95,6 +96,7 @@ def create_meshgrid3d(
Return:
grid tensor with shape :math:`(1, D, H, W, 3)`.
+
"""
xs: Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
ys: Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index e1ccd9b22..e81dc41eb 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -34,6 +34,7 @@ def get_cuda_device_if_available(index: int = 0) -> torch.device:
Returns:
torch.device
+
"""
if torch.cuda.is_available():
return torch.device(f"cuda:{index}")
@@ -46,6 +47,7 @@ def get_mps_device_if_available() -> torch.device:
Returns:
torch.device
+
"""
dev = "cpu"
if hasattr(torch.backends, "mps"):
@@ -59,6 +61,7 @@ def get_cuda_or_mps_device_if_available() -> torch.device:
Returns:
torch.device
+
"""
if sys.platform == "darwin" and platform.machine() == "arm64":
return get_mps_device_if_available()
@@ -120,6 +123,7 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
Returns:
[torch.device, torch.dtype]
+
"""
device, dtype = None, None
for tensor in tensor_list:
@@ -237,7 +241,8 @@ def _torch_solve_cast(A: Tensor, B: Tensor) -> Tensor:
def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
r"""Helper function, which avoids crashing because of singular matrix input and outputs the mask of valid
- solution."""
+ solution.
+ """
if not torch_version_ge(1, 10):
sol = _torch_solve_cast(A, B)
warnings.warn("PyTorch version < 1.10, solve validness mask maybe not correct", RuntimeWarning, stacklevel=1)
@@ -280,8 +285,8 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
def safe_inverse_with_mask(A: Tensor) -> Tuple[Tensor, Tensor]:
r"""Helper function, which avoids crashing because of non-invertable matrix input and outputs the mask of valid
- solution."""
-
+ solution.
+ """
if not isinstance(A, Tensor):
raise AssertionError(f"A must be Tensor. Got: {type(A)}.")
@@ -307,6 +312,7 @@ def is_autocast_enabled(both: bool = True) -> bool:
will always return False for a torch without support, otherwise will be: if both is True
`torch.is_autocast_enabled() or torch.is_autocast_enabled('cpu')`. If both is False will return just
`torch.is_autocast_enabled()`.
+
"""
if TYPE_CHECKING:
# TODO: remove this branch when kornia relies on torch >= 1.10.2
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 05293e757..f22eacaba 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -32,6 +32,7 @@ def image_to_tensor(image: Any, keepdim: bool = True) -> Tensor:
>>> img = np.ones((4, 4, 3))
>>> image_to_tensor(img, keepdim=False).shape
torch.Size([1, 3, 4, 4])
+
"""
if len(image.shape) > 4 or len(image.shape) < 2:
raise ValueError("Input size must be a two, three or four dimensional array")
@@ -69,6 +70,7 @@ def image_list_to_tensor(images: List[Any]) -> Tensor:
>>> imgs = [np.ones((4, 4, 1)), np.zeros((4, 4, 1))]
>>> image_list_to_tensor(imgs).shape
torch.Size([2, 1, 4, 4])
+
"""
if not images:
raise ValueError("Input list of numpy images is empty")
@@ -90,6 +92,7 @@ def _to_bchw(tensor: Tensor) -> Tensor:
Returns:
input tensor of the form :math:`(B, C, H, W)`.
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
@@ -117,6 +120,7 @@ def _to_bcdhw(tensor: Tensor) -> Tensor:
Returns:
input tensor of the form :math:`(B, C, D, H, W)`.
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
@@ -159,6 +163,7 @@ def tensor_to_image(tensor: Tensor, keepdim: bool = False, force_contiguous: boo
>>> img = torch.ones(3, 4, 4)
>>> tensor_to_image(img).shape
(4, 4, 3)
+
"""
if not isinstance(tensor, Tensor):
raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
@@ -201,6 +206,7 @@ class ImageToTensor(nn.Module):
Args:
keepdim: If ``False`` unsqueeze the input image to match the shape :math:`(B, H, W, C)`.
+
"""
def __init__(self, keepdim: bool = False) -> None:
@@ -221,6 +227,7 @@ def make_grid(tensor: Tensor, n_row: Optional[int] = None, padding: int = 2) ->
Returns:
Tensor: The combined image grid.
+
"""
if not isinstance(tensor, torch.Tensor):
raise TypeError("Input tensor must be a PyTorch tensor.")
diff --git a/kornia/utils/image_print.py b/kornia/utils/image_print.py
index f90fd7a3c..edac398fc 100644
--- a/kornia/utils/image_print.py
+++ b/kornia/utils/image_print.py
@@ -314,6 +314,7 @@ def rgb2short(rgb: str) -> Tuple[str, str]:
('231', 'ffffff')
>>> rgb2short('0DADD6') # vimeo logo
('38', '00afd7')
+
"""
rgb = _strip_hash(rgb)
incs = (0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF)
@@ -347,6 +348,7 @@ def image_to_string(image: Tensor, max_width: int = 256) -> str:
Args:
image: an RGB image with shape :math:`3HW`.
max_width: maximum width of the input image.
+
"""
KORNIA_CHECK_IS_IMAGE(image, None, raises=True)
KORNIA_CHECK_SHAPE(image, ["C", "H", "W"])
@@ -381,6 +383,7 @@ def print_image(image: Union[str, Tensor], max_width: int = 96) -> None:
Note:
Need to use `print_image(...)`.
+
"""
if isinstance(image, str):
img = kornia.io.load_image(image, ImageLoadType.RGB8)
diff --git a/kornia/utils/memory.py b/kornia/utils/memory.py
index 77489be25..2ddfc279c 100644
--- a/kornia/utils/memory.py
+++ b/kornia/utils/memory.py
@@ -28,6 +28,7 @@ def batched_forward(
>>> desc_batched = batched_forward(sift, patches, torch.device('cpu'), 128)
>>> desc = sift(patches)
>>> assert torch.allclose(desc, desc_batched)
+
"""
model_dev = model.to(device)
B: int = len(data)
diff --git a/kornia/utils/misc.py b/kornia/utils/misc.py
index 3efa3000a..761183e41 100644
--- a/kornia/utils/misc.py
+++ b/kornia/utils/misc.py
@@ -21,6 +21,7 @@ def eye_like(n: int, input: Tensor, shared_memory: bool = False) -> Tensor:
When the dimension to expand is of size 1, using torch.expand(...) yields the same tensor as torch.repeat(...)
without using extra memory. Thus, when the tensor obtained by this method will be later assigned -
use this method with shared_memory=False, otherwise, prefer using it with shared_memory=True.
+
"""
if n <= 0:
raise AssertionError(type(n), n)
@@ -48,6 +49,7 @@ def vec_like(n: int, tensor: Tensor, shared_memory: bool = False) -> Tensor:
When the dimension to expand is of size 1, using torch.expand(...) yields the same tensor as torch.repeat(...)
without using extra memory. Thus, when the tensor obtained by this method will be later assigned -
use this method with shared_memory=False, otherwise, prefer using it with shared_memory=True.
+
"""
if n <= 0:
raise AssertionError(type(n), n)
@@ -66,6 +68,7 @@ def differentiable_polynomial_rounding(input: Tensor) -> Tensor:
Returns:
output (Tensor): Pseudo rounded tensor of the same shape as input tensor.
+
"""
# Perform differentiable rounding
input_round = input.round()
@@ -81,6 +84,7 @@ def differentiable_polynomial_floor(input: Tensor) -> Tensor:
Returns:
output (Tensor): Pseudo rounded tensor of the same shape as input tensor.
+
"""
# Perform differentiable rounding
input_floor = input.floor()
@@ -104,6 +108,7 @@ def differentiable_clipping(
Returns:
output (Tensor): Clipped output tensor of the same shape as the input tensor.
+
"""
# Make a copy of the input tensor
output: Tensor = input.clone()
diff --git a/kornia/utils/one_hot.py b/kornia/utils/one_hot.py
index 4507e7222..d406f7bea 100644
--- a/kornia/utils/one_hot.py
+++ b/kornia/utils/one_hot.py
@@ -27,6 +27,7 @@ def one_hot(labels: Tensor, num_classes: int, device: torch.device, dtype: torch
<BLANKLINE>
[[1.0000e-06, 1.0000e-06],
[1.0000e+00, 1.0000e-06]]]])
+
"""
if not isinstance(labels, Tensor):
raise TypeError(f"Input labels type is not a Tensor. Got {type(labels)}")
diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.py
index 529060503..a559b2cc2 100644
--- a/kornia/utils/pointcloud_io.py
+++ b/kornia/utils/pointcloud_io.py
@@ -11,6 +11,7 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
pointcloud: tensor containing the pointcloud to save.
The tensor must be in the shape of :math:`(*, 3)` where the last
component is assumed to be a 3d point coordinate :math:`(X, Y, Z)`.
+
"""
if not isinstance(filename, str) and filename[-3:] == ".ply":
raise TypeError(f"Input filename must be a string in with the .ply extension. Got {filename}")
@@ -59,6 +60,7 @@ def load_pointcloud_ply(filename: str, header_size: int = 8) -> torch.Tensor:
Return:
tensor containing the loaded point with shape :math:`(*, 3)` where
:math:`*` represents the number of points.
+
"""
if not isinstance(filename, str) and filename[-3:] == ".ply":
raise TypeError(f"Input filename must be a string in with the .ply extension. Got {filename}")
diff --git a/kornia/utils/sample.py b/kornia/utils/sample.py
index c2fdce4af..3745067f4 100644
--- a/kornia/utils/sample.py
+++ b/kornia/utils/sample.py
@@ -28,6 +28,7 @@ def download_image(url: str, save_to: str) -> None:
Args:
url: The URL of the image to download.
save_to: The file path where the downloaded image will be saved.
+
"""
im = Image.open(requests.get(url, stream=True, timeout=30).raw) # type:ignore
im.save(save_to)
@@ -64,6 +65,7 @@ def get_sample_images(
torch.Tensor | list[torch.Tensor]:
If `resize` is provided, returns a single stacked tensor with shape (B, C, H, W).
Otherwise, returns a list of tensors, each with its original shape (C, H, W).
+
"""
if cache_dir is None:
cache_dir = ".kornia_hub/images"
diff --git a/kornia/x/callbacks.py b/kornia/x/callbacks.py
index bb67235a9..6b2ae3b69 100644
--- a/kornia/x/callbacks.py
+++ b/kornia/x/callbacks.py
@@ -38,6 +38,7 @@ class EarlyStopping:
trainer = ImageClassifierTrainer(
callbacks={"on_epoch_end", early_stop}
)
+
"""
def __init__(
@@ -105,6 +106,7 @@ class ModelCheckpoint:
trainer = ImageClassifierTrainer(...,
callbacks={"on_checkpoint", model_checkpoint}
)
+
"""
def __init__(
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
index f78896eca..a6863c05c 100644
--- a/kornia/x/trainer.py
+++ b/kornia/x/trainer.py
@@ -58,6 +58,7 @@ class Trainer:
.. seealso::
Learn how to use the API in our documentation
`here <https://kornia.readthedocs.io/en/latest/get-started/training.html>`_.
+
"""
def __init__(
diff --git a/kornia/x/utils.py b/kornia/x/utils.py
index bcc2c2213..714f69fc3 100644
--- a/kornia/x/utils.py
+++ b/kornia/x/utils.py
@@ -50,6 +50,7 @@ class Lambda(Module):
>>> fcn = Lambda(lambda x: K.geometry.resize(x, (32, 16)))
>>> fcn(torch.rand(1, 4, 64, 32)).shape
torch.Size([1, 4, 32, 16])
+
"""
def __init__(self, fcn: Callable[..., Any]) -> None:
diff --git a/pyproject.toml b/pyproject.toml
index 470df5e37..d039e8c88 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -105,7 +105,7 @@ select = [
# "ANN", # flake8-annotations
# "ARG", # flake8-unused-arguments
# "COM", # flake8-commas
- # "D", # pydocstyle
+ "D", # pydocstyle
# "DJ", # flake8-django
# "EM", # flake8-errmsg
# "ERA", # eradicate
@@ -138,6 +138,7 @@ ignore = [
"UP007", # Prefer Optional[], Union[] over | due to torch jit scripting
"UP006", # Prefer List[], over list due to torch jit scripting
"UP035", # Ignore deprecated typing because of jit scripting
+ 'D100', 'D101', 'D102','D103', 'D104', 'D105', 'D107', 'D203', 'D204', 'D205', 'D213', 'D400', 'D401', 'D404', 'D406', 'D407', 'D415', 'D417'# docs -- TODO: unconment some of these rules..
]
[tool.ruff.lint.isort]
@@ -252,5 +253,4 @@ module = "kornia.feature.dedode.transformer.*"
ignore_errors = true
[tool.pydocstyle]
-ignore = ['D105', 'D107', 'D203', 'D204', 'D213', 'D406', 'D407']
match = '.*\.py'
diff --git a/testing/base.py b/testing/base.py
index 74e99e953..327f42e26 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -83,6 +83,7 @@ class BaseTester:
low_tolerance:
This parameter allows to reduce tolerance. Half the decimal places.
Example, 1e-4 -> 1e-2 or 1e-6 -> 1e-3
+
"""
if hasattr(actual, "data"):
actual = actual.data
diff --git a/tests/feature/test_disk.py b/tests/feature/test_disk.py
index bc1275b85..6b11802e8 100644
--- a/tests/feature/test_disk.py
+++ b/tests/feature/test_disk.py
@@ -20,7 +20,8 @@ class TestDisk(BaseTester):
def test_smoke_n_detections(self, dtype, device):
"""Unless we give it an actual image and use pretrained weights, we can't expect the number of detections
- to really match the limit."""
+ to really match the limit.
+ """
disk = DISK().to(device, dtype)
inp = torch.ones(1, 3, 64, 64, device=device, dtype=dtype)
output = disk(inp, n=100)