Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add kornia.testing api in docs (#1954)

Edgar Ribaffc8a5d04617
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 6f7f87f6f..acc5c54a6 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -94,6 +94,7 @@ Join the community
metrics
morphology
tracking
+ testing
utils
x
diff --git a/docs/source/testing.rst b/docs/source/testing.rst
new file mode 100644
index 000000000..68a9ecfb1
--- /dev/null
+++ b/docs/source/testing.rst
@@ -0,0 +1,5 @@
+kornia.testing
+==============
+
+.. automodule:: kornia.testing
+ :members:
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 8a41cbc37..8daafe048 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -5,13 +5,31 @@ import math
from abc import ABC, abstractmethod
from copy import deepcopy
from itertools import product
-from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, TypeVar, Union, cast
+from typing import Any, Dict, List, Optional, cast
import torch
-from torch import Tensor
from torch.nn import Parameter
-__all__ = ['tensor_to_gradcheck_var', 'create_eye_batch', 'xla_is_available', 'assert_close']
+from kornia.core import Tensor
+
+__all__ = [
+ "tensor_to_gradcheck_var",
+ "create_eye_batch",
+ "xla_is_available",
+ "assert_close",
+ "KORNIA_CHECK_SHAPE",
+ "KORNIA_CHECK",
+ "KORNIA_UNWRAP",
+ "KORNIA_CHECK_TYPE",
+ "KORNIA_CHECK_IS_TENSOR",
+ "KORNIA_CHECK_SAME_DEVICE",
+ "KORNIA_CHECK_SAME_DEVICES",
+ "KORNIA_CHECK_IS_COLOR",
+ "KORNIA_CHECK_IS_GRAY",
+ "KORNIA_CHECK_IS_COLR_OR_GRAY",
+ "KORNIA_CHECK_DM_DESC",
+ "KORNIA_CHECK_LAF",
+]
def xla_is_available() -> bool:
@@ -271,7 +289,28 @@ except ImportError:
# Logger api
+
+
def KORNIA_CHECK_SHAPE(x, shape: List[str]) -> None:
+ """Check whether a tensor has a specified shape.
+
+ The shape can be specified with a implicit or explicit list of strings.
+ The guard also check whether the variable is a type `Tensor`.
+
+ Args:
+ x: the tensor to evaluate.
+ shape: a list with strings with the expected shape.
+
+ Raises:
+ Exception: if the input tensor is has not the expected shape.
+
+ Example:
+ >>> x = torch.rand(2, 3, 4, 4)
+ >>> KORNIA_CHECK_SHAPE(x, ["B","C", "H", "W"]) # implicit
+
+ >>> x = torch.rand(2, 3, 4, 4)
+ >>> KORNIA_CHECK_SHAPE(x, ["2","3", "H", "W"]) # explicit
+ """
# Desired shape here is list and not tuple, because torch.jit
# does not like variable-length tuples
KORNIA_CHECK_IS_TENSOR(x)
@@ -296,52 +335,181 @@ def KORNIA_CHECK_SHAPE(x, shape: List[str]) -> None:
raise TypeError(f"{x} shape should be must be [{shape}]. Got {x.shape}")
-def KORNIA_CHECK(condition: bool, msg: Optional[str] = None):
+def KORNIA_CHECK(condition: bool, msg: Optional[str] = None) -> None:
+ """Check any arbitrary boolean condition.
+
+ Args:
+ condition: the condition to evaluate.
+ msg: message to show in the exception.
+
+ Raises:
+ Exception: if the confition is met.
+
+ Example:
+ >>> x = torch.rand(2, 3, 3)
+ >>> KORNIA_CHECK(x.shape[-2:] == (3, 3), "Invalid homography")
+ """
if not condition:
raise Exception(f"{condition} not true.\n{msg}")
def KORNIA_UNWRAP(maybe_obj, typ):
+ """Unwraps an optional contained value that may or not be present.
+
+ Args:
+ maybe_obj: the object to unwrap.
+ typ: expected type after unwrap.
+ """
return cast(typ, maybe_obj)
def KORNIA_CHECK_TYPE(x, typ, msg: Optional[str] = None):
+ """Check the type of an aribratry variable.
+
+ Args:
+ x: any input variable.
+ typ: the expected type of the variable.
+ msg: message to show in the exception.
+
+ Raises:
+ TypeException: if the input variable does not match with the expected.
+
+ Example:
+ >>> KORNIA_CHECK_TYPE("foo", str, "Invalid string")
+ """
if not isinstance(x, typ):
raise TypeError(f"Invalid type: {type(x)}.\n{msg}")
def KORNIA_CHECK_IS_TENSOR(x, msg: Optional[str] = None):
+ """Check the input variable is a Tensor.
+
+ Args:
+ x: any input variable.
+ msg: message to show in the exception.
+
+ Raises:
+ TypeException: if the input variable does not match with the expected.
+
+ Example:
+ >>> x = torch.rand(2, 3, 3)
+ >>> KORNIA_CHECK_IS_TENSOR(x, "Invalid tensor")
+ """
if not isinstance(x, Tensor):
raise TypeError(f"Not a Tensor type. Got: {type(x)}.\n{msg}")
+def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor):
+ """Check whether two tensor in the same device.
+
+ Args:
+ x: first tensor to evaluate.
+ y: sencod tensor to evaluate.
+ msg: message to show in the exception.
+
+ Raises:
+ TypeException: if the two tensors are not in the same device.
+
+ Example:
+ >>> x1 = torch.rand(2, 3, 3)
+ >>> x2 = torch.rand(1, 3, 1)
+ >>> KORNIA_CHECK_SAME_DEVICE(x1, x2)
+ """
+ if x.device != y.device:
+ raise TypeError(f"Not same device for tensors. Got: {x.device} and {y.device}")
+
+
def KORNIA_CHECK_SAME_DEVICES(tensors: List[Tensor], msg: Optional[str] = None):
+ """Check whether a list provided tensors live in the same device.
+
+ Args:
+ x: a list of tensors.
+ msg: message to show in the exception.
+
+ Raises:
+ Exception: if all the tensors are not in the same device.
+
+ Example:
+ >>> x1 = torch.rand(2, 3, 3)
+ >>> x2 = torch.rand(1, 3, 1)
+ >>> KORNIA_CHECK_SAME_DEVICES([x1, x2], "Tensors not in the same device")
+ """
KORNIA_CHECK(isinstance(tensors, list) and len(tensors) >= 1, "Expected a list with at least one element")
if not all(tensors[0].device == x.device for x in tensors):
raise Exception(f"Not same device for tensors. Got: {[x.device for x in tensors]}.\n{msg}")
def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None):
+ """Check whether an image tensor is a color images.
+
+ Args:
+ x: image tensor to evaluate.
+ msg: message to show in the exception.
+
+ Raises:
+ TypeException: if all the input tensor has not a shape :math:`(3,H,W)`.
+
+ Example:
+ >>> img = torch.rand(2, 3, 4, 4)
+ >>> KORNIA_CHECK_IS_COLOR(img, "Image is not color")
+ """
if len(x.shape) < 3 or x.shape[-3] != 3:
raise TypeError(f"Not a color tensor. Got: {type(x)}.\n{msg}")
def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None):
+ """Check whether an image tensor is grayscale.
+
+ Args:
+ x: image tensor to evaluate.
+ msg: message to show in the exception.
+
+ Raises:
+ TypeException: if the tensor has not a shape :math:`(1,H,W)` or :math:`(H,W)`.
+
+ Example:
+ >>> img = torch.rand(2, 1, 4, 4)
+ >>> KORNIA_CHECK_IS_GRAY(img, "Image is not grayscale")
+ """
if len(x.shape) < 2 or (len(x.shape) >= 3 and x.shape[-3] != 1):
raise TypeError(f"Not a gray tensor. Got: {type(x)}.\n{msg}")
def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None):
- if len(x.shape) < 3 or x.shape[-3] not in [1, 3]:
- raise TypeError(f"Not a color or gray tensor. Got: {type(x)}.\n{msg}")
+ """Check whether an image tensor is grayscale or color.
+
+ Args:
+ x: image tensor to evaluate.
+ msg: message to show in the exception.
+ Raises:
+ TypeException: if the tensor has not a shape :math:`(1,H,W)` or :math:`(3,H,W)`.
-def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor):
- if x.device != y.device:
- raise TypeError(f"Not same device for tensors. Got: {x.device} and {y.device}")
+ Example:
+ >>> img = torch.rand(2, 3, 4, 4)
+ >>> KORNIA_CHECK_IS_COLOR_OR_GRAY(img, "Image is not color or grayscale")
+ """
+ if len(x.shape) < 3 or x.shape[-3] not in [1, 3]:
+ raise TypeError(f"Not a color or gray tensor. Got: {type(x)}.\n{msg}")
def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor):
+ """Check whether the provided descriptors match with a distance matrix.
+
+ Args:
+ desc1: first descriptor tensor to evaluate.
+ desc2: second descriptor tensor to evaluate.
+ dm: distance matrix tensor to evaluate.
+
+ Raises:
+ TypeException: if the descriptors shape do not match with the distance matrix.
+
+ Example:
+ >>> desc1 = torch.rand(4)
+ >>> desc2 = torch.rand(8)
+ >>> dm = torch.rand(4, 8)
+ >>> KORNIA_CHECK_DM_DESC(desc1, desc2, dm)
+ """
if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))):
message = f"""distance matrix shape {dm.shape} is not
consistent with descriptors shape: desc1 {desc1.shape}
@@ -350,9 +518,16 @@ def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor):
def KORNIA_CHECK_LAF(laf: Tensor) -> None:
- """Auxiliary function, which verifies that input.
+ """Check whether a Local Affine Frame (laf) has a valid shape.
Args:
- laf: [BxNx2x3] shape.
+ laf: local affine frame tensor to evaluate.
+
+ Raises:
+ Exception: if the input laf does not have a shape :math:`(B,N,2,3)`.
+
+ Example:
+ >>> lafs = torch.rand(2, 10, 2, 3)
+ >>> KORNIA_CHECK_LAF(lafs)
"""
KORNIA_CHECK_SHAPE(laf, ["B", "N", "2", "3"])