Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

move kornia check api to kornia.core.logger (#2143)

Edgar Riba565122c8fb90
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 613c4008a..ec0b37448 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -6,8 +6,8 @@ from kornia.augmentation.base import _BasicAugmentationBase
from kornia.augmentation.utils import _transform_input, _transform_output_shape, _validate_input_dtype
from kornia.constants import DataKey, DType
from kornia.core import Tensor, tensor
+from kornia.core.check import KORNIA_UNWRAP
from kornia.geometry.boxes import Boxes
-from kornia.testing import KORNIA_UNWRAP
class MixAugmentationBaseV2(_BasicAugmentationBase):
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 1393cfb0c..aa1b3b22c 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -6,9 +6,9 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey, Resample
from kornia.core import Tensor, as_tensor, concatenate, pad, zeros
+from kornia.core.check import KORNIA_UNWRAP
from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
-from kornia.testing import KORNIA_UNWRAP
from kornia.utils import eye_like
__all__ = ["RandomMosaic"]
diff --git a/kornia/color/colormap.py b/kornia/color/colormap.py
index 341ad616c..d6c9f51f2 100644
--- a/kornia/color/colormap.py
+++ b/kornia/color/colormap.py
@@ -5,7 +5,7 @@ import torch
from torch.nn.functional import interpolate
from kornia.core import Module, Tensor, tensor
-from kornia.testing import KORNIA_CHECK_IS_GRAY
+from kornia.core.check import KORNIA_CHECK_IS_GRAY
RGBColor = List[float]
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index 317e21219..578180fb0 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -4,7 +4,7 @@ import torch
from kornia.color.rgb import bgr_to_rgb
from kornia.core import Module, Tensor, concatenate
-from kornia.testing import KORNIA_CHECK_IS_TENSOR
+from kornia.core.check import KORNIA_CHECK_IS_TENSOR
def grayscale_to_rgb(image: Tensor) -> Tensor:
diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.py
index 29833ac24..8baa7447c 100644
--- a/kornia/contrib/diamond_square.py
+++ b/kornia/contrib/diamond_square.py
@@ -5,9 +5,9 @@ from typing import Callable, List, Optional, Tuple, Union
import torch
from kornia.core import Tensor
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.enhance import normalize_min_max
from kornia.filters import filter2d
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
# the default kernels for the diamond square
default_diamond_kernel: List[List[float]] = [[0.25, 0.0, 0.25], [0.0, 0.0, 0.0], [0.25, 0.0, 0.25]]
diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.py
index 9ad220816..a8d674043 100644
--- a/kornia/contrib/edge_detection.py
+++ b/kornia/contrib/edge_detection.py
@@ -1,8 +1,8 @@
from typing import List
from kornia.core import Module, Tensor
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.filters.dexined import DexiNed
-from kornia.testing import KORNIA_CHECK_SHAPE
class EdgeDetector(Module):
diff --git a/kornia/core/check.py b/kornia/core/check.py
new file mode 100644
index 000000000..26219b93f
--- /dev/null
+++ b/kornia/core/check.py
@@ -0,0 +1,308 @@
+"""The testing package contains testing-specific utilities."""
+from typing import List, Optional, Sequence, cast
+
+from typing_extensions import TypeGuard
+
+from kornia.core import Tensor
+
+__all__ = [
+ "KORNIA_CHECK_SHAPE",
+ "KORNIA_CHECK",
+ "KORNIA_UNWRAP",
+ "KORNIA_CHECK_TYPE",
+ "KORNIA_CHECK_IS_TENSOR",
+ "KORNIA_CHECK_IS_LIST_OF_TENSOR",
+ "KORNIA_CHECK_SAME_DEVICE",
+ "KORNIA_CHECK_SAME_DEVICES",
+ "KORNIA_CHECK_IS_COLOR",
+ "KORNIA_CHECK_IS_GRAY",
+ "KORNIA_CHECK_DM_DESC",
+ "KORNIA_CHECK_LAF",
+]
+
+# Logger api
+
+# TODO: add somehow type check, or enforce to do it before
+# TODO: get rid of torchscript test because prevents us to have type safe code
+
+
+def KORNIA_CHECK_SHAPE(x: Tensor, 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
+ """
+
+ if '*' == shape[0]:
+ shape_to_check = shape[1:]
+ x_shape_to_check = x.shape[-len(shape) + 1 :]
+ elif '*' == shape[-1]:
+ shape_to_check = shape[:-1]
+ x_shape_to_check = x.shape[: len(shape) - 1]
+ else:
+ shape_to_check = shape
+ x_shape_to_check = x.shape
+
+ if len(x_shape_to_check) != len(shape_to_check):
+ raise TypeError(f"{x} shape must be [{shape}]. Got {x.shape}")
+
+ for i in range(len(x_shape_to_check)):
+ # The voodoo below is because torchscript does not like
+ # that dim can be both int and str
+ dim_: str = shape_to_check[i]
+ if not dim_.isnumeric():
+ continue
+ dim = int(dim_)
+ if x_shape_to_check[i] != dim:
+ raise TypeError(f"{x} shape must be [{shape}]. Got {x.shape}")
+
+
+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) # type: ignore # TODO: this function will change after kornia/pr#1987
+
+
+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_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]]) -> TypeGuard[List[Tensor]]:
+ """Check the input variable is a List of Tensors.
+
+ Args:
+ x: Any sequence of objects
+
+ Return:
+ True if the input is a list of Tensors, otherwise return False.
+
+ Example:
+ >>> x = torch.rand(2, 3, 3)
+ >>> KORNIA_CHECK_IS_LIST_OF_TENSOR(x)
+ False
+ >>> KORNIA_CHECK_IS_LIST_OF_TENSOR([x])
+ True
+ """
+ return isinstance(x, list) and all(isinstance(d, Tensor) for d in x)
+
+
+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_SAME_SHAPE(x: Tensor, y: Tensor) -> None:
+ """Check whether two tensor have the same shape.
+
+ Args:
+ x: first tensor to evaluate.
+ y: sencod tensor to evaluate.
+ msg: message to show in the exception.
+
+ Raises:
+ TypeException: if the two tensors have not the same shape.
+
+ Example:
+ >>> x1 = torch.rand(2, 3, 3)
+ >>> x2 = torch.rand(2, 3, 3)
+ >>> KORNIA_CHECK_SAME_SHAPE(x1, x2)
+ """
+ if x.shape != y.shape:
+ raise TypeError(f"Not same shape for tensors. Got: {x.shape} and {y.shape}")
+
+
+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):
+ """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)`.
+
+ 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}
+ desc2 {desc2.shape}"""
+ raise TypeError(message)
+
+
+def KORNIA_CHECK_LAF(laf: Tensor) -> None:
+ """Check whether a Local Affine Frame (laf) has a valid shape.
+
+ Args:
+ 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"])
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 6a2de22a7..01503b1da 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -6,7 +6,7 @@ from torch import Tensor
from torch.nn import Module, Parameter
from kornia.color import hsv_to_rgb, rgb_to_grayscale, rgb_to_hsv
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_COLOR_OR_GRAY, KORNIA_CHECK_IS_TENSOR
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_COLOR_OR_GRAY, KORNIA_CHECK_IS_TENSOR
from kornia.utils.helpers import _torch_histc_cast
from kornia.utils.image import perform_keep_shape_image, perform_keep_shape_video
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 037673fdd..31f577bd6 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -1,7 +1,7 @@
from typing import Union
from kornia.core import Module, Tensor, tensor
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
def add_weighted(
diff --git a/kornia/enhance/integral.py b/kornia/enhance/integral.py
index 9d74ccec1..4216ad480 100644
--- a/kornia/enhance/integral.py
+++ b/kornia/enhance/integral.py
@@ -1,7 +1,7 @@
from typing import Optional, Tuple
from kornia.core import Module, Tensor
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
def integral_tensor(input: Tensor, dim: Optional[Tuple[int, ...]] = None) -> Tensor:
diff --git a/kornia/enhance/shift_rgb.py b/kornia/enhance/shift_rgb.py
index 7f4c43a6c..31ae55524 100644
--- a/kornia/enhance/shift_rgb.py
+++ b/kornia/enhance/shift_rgb.py
@@ -1,6 +1,6 @@
import torch
-from kornia.testing import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSOR
+from kornia.core.check import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSOR
def shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor, b_shift: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index 4af2f47c4..cd1ecda35 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -7,8 +7,8 @@ from typing import Optional, Tuple, Union
import torch
from kornia.core import Tensor
+from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.feature.laf import get_laf_center, get_laf_orientation, get_laf_scale
-from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from .core import AdalamConfig, _no_match, adalam_core
from .utils import dist_matrix
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 3f1d8fbd3..87b149feb 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -5,9 +5,9 @@ from typing import Dict, Optional
import torch
import torch.nn as nn
+from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.filters.kernels import get_gaussian_kernel2d
from kornia.filters.sobel import SpatialGradient
-from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.utils.helpers import map_location_to_cpu
from .laf import (
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index df0311c62..2df949353 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -4,7 +4,8 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from kornia.testing import KORNIA_CHECK_SHAPE, is_mps_tensor_safe
+from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.testing import is_mps_tensor_safe
from kornia.utils.helpers import map_location_to_cpu
urls: Dict[str, str] = {}
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 3ea67722e..35d3da090 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -5,9 +5,9 @@ import torch
from kornia.color import rgb_to_grayscale
from kornia.core import Device, Module, Tensor, concatenate
+from kornia.core.check import KORNIA_CHECK_LAF
from kornia.geometry.subpix import ConvQuadInterp3d
from kornia.geometry.transform import ScalePyramid
-from kornia.testing import KORNIA_CHECK_LAF
from .affine_shape import LAFAffNetShapeEstimator
from .hardnet import HardNet
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 89f6e5467..4bf828273 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -5,10 +5,10 @@ import torch
import torch.nn.functional as F
from kornia.core import Tensor, concatenate, stack, tensor, zeros
+from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous, rad2deg
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import pyrdown
-from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
def get_laf_scale(LAF: Tensor) -> Tensor:
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 430fc4712..b737e89d1 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -3,8 +3,10 @@ from typing import Dict, Optional, Tuple
import torch
import torch.nn as nn
+from kornia.core import Tensor
+from kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE
from kornia.feature.laf import get_laf_center
-from kornia.testing import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE, Tensor, is_mps_tensor_safe
+from kornia.testing import is_mps_tensor_safe
from .adalam import get_adalam_default_config, match_adalam
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 2456feb23..98df0c13a 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -6,9 +6,9 @@ import torch.nn as nn
import torch.nn.functional as F
from kornia.constants import pi
+from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.filters import SpatialGradient, get_gaussian_kernel2d
from kornia.geometry import rad2deg
-from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.utils.helpers import map_location_to_cpu
from .laf import extract_patches_from_pyramid, get_laf_orientation, set_laf_orientation
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index a474176db..4a3e916ab 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -3,8 +3,8 @@ from typing import Optional, Union
import torch
from kornia.core import Module, Tensor, tensor
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.filters import gaussian_blur2d, spatial_gradient
-from kornia.testing import KORNIA_CHECK_SHAPE
def _get_kernel_size(sigma: float):
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 2e78ac26e..c2db83658 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -6,9 +6,9 @@ import torch.nn.functional as F
from typing_extensions import TypedDict
from kornia.core import Device, Module, Tensor, concatenate, eye, tensor, where, zeros
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.subpix import ConvSoftArgmax3d, NonMaximaSuppression2d
from kornia.geometry.transform import ScalePyramid, pyrdown, resize
-from kornia.testing import KORNIA_CHECK_SHAPE
from .laf import laf_from_center_scale_ori, laf_is_inside_image
from .orientation import PassLAF
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index df88383fb..be02d31a5 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -5,9 +5,9 @@ import torch
import torch.nn as nn
from kornia.core import Module, Tensor, concatenate, eye, normalize
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.filters import get_gaussian_kernel2d, spatial_gradient
from kornia.geometry.conversions import pi
-from kornia.testing import KORNIA_CHECK_SHAPE
def _get_reshape_kernel(kd: int, ky: int, kx: int) -> Tensor:
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index bb92e241f..d94ab76bc 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -4,8 +4,8 @@ import torch
import torch.nn.functional as F
from kornia.core import Module, Tensor, concatenate, pad, stack
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import normalize_pixel_coordinates
-from kornia.testing import KORNIA_CHECK_SHAPE
from kornia.utils import map_location_to_cpu
from .backbones import SOLD2Net
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index c4a3bfd7d..533c58368 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -4,8 +4,8 @@ from typing import Any, Dict, Optional, Tuple
import torch
from kornia.core import Module, Tensor, concatenate, stack, tensor, where, zeros
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.bbox import nms
-from kornia.testing import KORNIA_CHECK_SHAPE
from kornia.utils import map_location_to_cpu, torch_meshgrid
from .backbones import SOLD2Net
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 0be734ecc..173f050f8 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -3,7 +3,7 @@ from typing import Dict
import torch
import torch.nn as nn
-from kornia.testing import KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.utils.helpers import map_location_to_cpu
urls: Dict[str, str] = {}
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index 42c938ec9..eabce3e0b 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -3,7 +3,7 @@ from typing import Dict
import torch
import torch.nn as nn
-from kornia.testing import KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.utils.helpers import map_location_to_cpu
urls: Dict[str, str] = {}
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index 8a0c3ca84..d7cfabcc7 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import torch.nn.functional as F
from kornia.core import Module, Tensor, as_tensor, pad, tensor
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from .kernels import get_pascal_kernel_2d
from .median import _compute_zero_padding # TODO: Move to proper place
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index d9756561b..05b810a3c 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -7,7 +7,7 @@ import torch.nn.functional as F
from kornia.color import rgb_to_grayscale
from kornia.core import Module, Tensor
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .gaussian import gaussian_blur2d
from .kernels import get_canny_nms_kernel, get_hysteresis_kernel
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 72d42e2c4..6338e0fd5 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -9,7 +9,7 @@ import torch.nn as nn
import torch.nn.functional as F
from kornia.core import Module, Tensor, concatenate
-from kornia.testing import KORNIA_CHECK
+from kornia.core.check import KORNIA_CHECK
from kornia.utils import map_location_to_cpu
url: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 15c8b44dc..755368999 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import torch.nn.functional as F
from kornia.core import Tensor, pad
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .kernels import normalize_kernel2d
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 1fe9fafa0..2e52c64b2 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from typing import Any
from kornia.core import Module, Tensor, tensor
-from kornia.testing import KORNIA_CHECK_IS_TENSOR
+from kornia.core.check import KORNIA_CHECK_IS_TENSOR
from kornia.utils import deprecated
from .filter import filter2d, filter2d_separable
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 973aecca2..c09cb68ec 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -7,7 +7,7 @@ from typing import Any
import torch
from kornia.core import Device, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
from kornia.utils import deprecated
@@ -70,7 +70,6 @@ def gaussian(
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 Gaussian values.
"""
@@ -98,13 +97,11 @@ def gaussian_discrete_erf(
r"""Discrete Gaussian by interpolating the error function.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
-
Args:
window_size: the size which drives the filter amount.
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.
@@ -227,13 +224,11 @@ def gaussian_discrete(
r"""Discrete Gaussian kernel based on the modified Bessel functions.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
-
Args:
window_size: the size which drives the filter amount.
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.
@@ -478,28 +473,21 @@ def get_gaussian_kernel1d(
dtype: torch.dtype | None = None,
) -> Tensor:
r"""Function that returns Gaussian filter coefficients.
-
Args:
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation.
force_even: overrides requirement for odd kernel size.
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:
gaussian filter coefficients
-
Shape:
- Output: :math:`(B, \text{kernel_size})`.
-
Examples:
-
>>> get_gaussian_kernel1d(3, 2.5)
tensor([[0.3243, 0.3513, 0.3243]])
-
>>> get_gaussian_kernel1d(5, 1.5)
tensor([[0.1201, 0.2339, 0.2921, 0.2339, 0.1201]])
-
>>> 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]])
@@ -519,25 +507,19 @@ def get_gaussian_discrete_kernel1d(
) -> Tensor:
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.
-
Args:
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
force_even: overrides requirement for odd kernel size.
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:
1D tensor with gaussian filter coefficients.
-
Shape:
- Output: :math:`(B, \text{kernel_size})`
-
Examples:
-
>>> get_gaussian_discrete_kernel1d(3, 2.5)
tensor([[0.3235, 0.3531, 0.3235]])
-
>>> get_gaussian_discrete_kernel1d(5, 1.5)
tensor([[0.1096, 0.2323, 0.3161, 0.2323, 0.1096]])
>>> get_gaussian_discrete_kernel1d(5, torch.tensor([[1.5],[2.4]]))
@@ -559,28 +541,21 @@ def get_gaussian_erf_kernel1d(
) -> Tensor:
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.
-
Args:
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
force_even: overrides requirement for odd kernel size.
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:
1D tensor with gaussian filter coefficients.
-
Shape:
- Output: :math:`(B, \text{kernel_size})`
-
Examples:
-
>>> get_gaussian_erf_kernel1d(3, 2.5)
tensor([[0.3245, 0.3511, 0.3245]])
-
>>> get_gaussian_erf_kernel1d(5, 1.5)
tensor([[0.1226, 0.2331, 0.2887, 0.2331, 0.1226]])
-
>>> 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]])
@@ -599,34 +574,27 @@ def get_gaussian_kernel2d(
dtype: torch.dtype | None = None,
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
-
Args:
kernel_size: filter sizes in the x and y direction. Sizes should be odd and positive.
sigma: gaussian standard deviation in the x and y.
force_even: overrides requirement for odd kernel size.
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:
2D tensor with gaussian filter matrix coefficients.
-
Shape:
- Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y)`
-
Examples:
-
>>> get_gaussian_kernel2d((5, 5), (1.5, 1.5))
tensor([[[0.0144, 0.0281, 0.0351, 0.0281, 0.0144],
[0.0281, 0.0547, 0.0683, 0.0547, 0.0281],
[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]]])
-
>>> get_gaussian_kernel2d((3, 5), (1.5, 1.5))
tensor([[[0.0370, 0.0720, 0.0899, 0.0720, 0.0370],
[0.0462, 0.0899, 0.1123, 0.0899, 0.0462],
[0.0370, 0.0720, 0.0899, 0.0720, 0.0370]]])
-
>>> get_gaussian_kernel2d((5, 5), torch.tensor([[1.5, 1.5]]))
tensor([[[0.0144, 0.0281, 0.0351, 0.0281, 0.0144],
[0.0281, 0.0547, 0.0683, 0.0547, 0.0281],
@@ -658,20 +626,16 @@ def get_gaussian_kernel3d(
dtype: torch.dtype | None = None,
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
-
Args:
kernel_size: filter sizes in the x, y and z direction. Sizes should be odd and positive.
sigma: gaussian standard deviation in the x, y and z direction.
force_even: overrides requirement for odd kernel size.
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:
3D tensor with gaussian filter matrix coefficients.
-
Shape:
- Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y, \text{kernel_size}_z)`
-
Examples:
>>> get_gaussian_kernel3d((3, 3, 3), (1.5, 1.5, 1.5))
tensor([[[[0.0292, 0.0364, 0.0292],
@@ -715,18 +679,14 @@ def get_laplacian_kernel1d(
kernel_size: int, *, device: Device | None = None, dtype: torch.dtype = torch.float32
) -> Tensor:
r"""Function that returns the coefficients of a 1D Laplacian filter.
-
Args:
kernel_size: filter size. It should be odd and positive.
device: tensor device desired to create the kernel
dtype: tensor dtype desired to create the kernel
-
Returns:
1D tensor with laplacian filter coefficients.
-
Shape:
- Output: math:`(\text{kernel_size})`
-
Examples:
>>> get_laplacian_kernel1d(3)
tensor([ 1., -2., 1.])
@@ -744,18 +704,14 @@ def get_laplacian_kernel2d(
kernel_size: tuple[int, int] | int, *, device: Device | None = None, dtype: torch.dtype = torch.float32
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
-
Args:
kernel_size: filter size should be odd.
device: tensor device desired to create the kernel
dtype: tensor dtype desired to create the kernel
-
Returns:
2D tensor with laplacian filter matrix coefficients.
-
Shape:
- Output: :math:`(\text{kernel_size}_x, \text{kernel_size}_y)`
-
Examples:
>>> get_laplacian_kernel2d(3)
tensor([[ 1., 1., 1.],
@@ -789,17 +745,14 @@ def get_pascal_kernel_2d(
dtype: torch.dtype | None = None,
) -> Tensor:
"""Generate pascal filter kernel by kernel size.
-
Args:
kernel_size: height and width of the kernel.
norm: if to normalize the kernel or not. Default: True.
device: tensor device desired to create the kernel
dtype: tensor dtype desired to create the kernel
-
Returns:
if kernel_size is an integer the kernel will be shaped as :math:`(kernel_size, kernel_size)`
otherwise the kernel will be shaped as :math: `kernel_size`
-
Examples:
>>> get_pascal_kernel_2d(1)
tensor([[1.]])
@@ -828,16 +781,13 @@ def get_pascal_kernel_1d(
kernel_size: int, norm: bool = False, *, device: Device | None = None, dtype: torch.dtype | None = None
) -> Tensor:
"""Generate Yang Hui triangle (Pascal's triangle) by a given number.
-
Args:
kernel_size: height and width of the kernel.
norm: if to normalize the kernel or not. Default: False.
device: tensor device desired to create the kernel
dtype: tensor dtype desired to create the kernel
-
Returns:
kernel shaped as :math:`(kernel_size,)`
-
Examples:
>>> get_pascal_kernel_1d(1)
tensor([1.])
@@ -913,21 +863,16 @@ def get_hanning_kernel1d(kernel_size: int, device: Device | None = None, dtype:
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
\\qquad 0 \\leq n \\leq M-1
-
See further in numpy docs https://numpy.org/doc/stable/reference/generated/numpy.hanning.html
-
Args:
kernel_size: The size the of the kernel. It should be positive.
device: tensor device desired to create the kernel
dtype: tensor dtype desired to create the kernel
-
Returns:
1D tensor with Hanning filter coefficients.
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
-
Shape:
- Output: math:`(\text{kernel_size})`
-
Examples:
>>> get_hanning_kernel1d(4)
tensor([0.0000, 0.7500, 0.7500, 0.0000])
@@ -943,16 +888,13 @@ def get_hanning_kernel2d(
kernel_size: tuple[int, int] | int, device: Device | None = None, dtype: torch.dtype | None = None
) -> Tensor:
"""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.
device: tensor device desired to create the kernel
dtype: tensor dtype desired to create the kernel
-
Returns:
2D tensor with Hanning filter coefficients.
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
-
Shape:
- Output: math:`(\text{kernel_size[0], kernel_size[1]})`
"""
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index 21c9c9ea4..0bdb45378 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -3,8 +3,8 @@ from __future__ import annotations
import torch
from kornia.core import Tensor, pad, stack, tensor, zeros
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.geometry.transform import rotate, rotate3d
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.utils import _extract_device_dtype
from .kernels import _check_kernel_size, _unpack_2d_ks, _unpack_3d_ks
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 6782d8c41..5deacd78c 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import torch.nn.functional as F
from kornia.core import Module, Tensor
-from kornia.testing import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .kernels import _unpack_2d_ks, get_binary_kernel2d
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index 96dafea0f..1c979403f 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from kornia.core import Module, Tensor
-from kornia.testing import KORNIA_CHECK
+from kornia.core.check import KORNIA_CHECK
from .filter import filter2d, filter3d
from .kernels_geometry import get_motion_kernel2d, get_motion_kernel3d
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 2f1ad69ad..1b9780509 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -4,7 +4,7 @@ import torch
import torch.nn.functional as F
from kornia.core import Module, Tensor, pad
-from kornia.testing import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 72a60ea07..b065354e4 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -3,9 +3,9 @@ from typing import Iterable, List
import torch
from kornia.core import Device, Tensor
+from kornia.core.check import KORNIA_CHECK_SAME_DEVICE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import inverse_transformation, transform_points
-from kornia.testing import KORNIA_CHECK_SAME_DEVICE
from kornia.utils.helpers import _torch_inverse_cast
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 0e584d4b3..ba7e875ba 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -7,7 +7,7 @@ import torch.nn.functional as F
from kornia.constants import pi
from kornia.core import Tensor, concatenate, pad, stack, tensor, where
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.utils.helpers import _torch_inverse_cast
from kornia.utils.misc import eye_like
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index fb48c1a7c..58417b9f6 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -5,8 +5,8 @@ import torch
import torch.nn.functional as F
from kornia.core import Module, Tensor, concatenate, tensor
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters.sobel import spatial_gradient
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.utils import create_meshgrid
from .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_points
diff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.py
index a2fa3cd15..dcf698bfd 100644
--- a/kornia/geometry/epipolar/_metrics.py
+++ b/kornia/geometry/epipolar/_metrics.py
@@ -2,9 +2,9 @@
from torch import Tensor
+from kornia.core.check import KORNIA_CHECK_IS_TENSOR
from kornia.geometry.conversions import convert_points_to_homogeneous
from kornia.geometry.linalg import point_line_distance
-from kornia.testing import KORNIA_CHECK_IS_TENSOR
def sampson_epipolar_distance(
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 19c6cfe31..ad602dc11 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -5,9 +5,9 @@ from typing import Optional, Tuple
import torch
from kornia.core import Tensor
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import transform_points
-from kornia.testing import KORNIA_CHECK_SHAPE
from kornia.utils.helpers import _torch_svd_cast
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index f8de186ce..cad46d5bc 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -4,7 +4,7 @@ from typing import Optional, Tuple
import torch
from kornia.core import Tensor
-from kornia.testing import KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.utils import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_mask
from kornia.utils.helpers import _torch_svd_cast
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 4ddc1e12c..0c79bcffd 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -3,9 +3,9 @@
from typing import Optional, Tuple, overload
from kornia.core import Module, Parameter, Tensor, concatenate, pad, rand, stack, tensor, where, zeros_like
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPE
from kornia.geometry.liegroup._utils import check_se2_omega_shape, check_se2_r_t_shape, check_v_shape
from kornia.geometry.liegroup.so2 import So2
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPE
class Se2(Module):
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 92c63adc6..784b22bb9 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -3,9 +3,9 @@
from typing import Optional, Tuple
from kornia.core import Module, Parameter, Tensor, concatenate, eye, pad, rand, stack, tensor, where, zeros_like
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPE
from kornia.geometry.liegroup.so3 import So3
from kornia.geometry.linalg import batched_dot_product
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPE
class Se3(Module):
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index d31cb5add..a00539c08 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -3,13 +3,13 @@
from typing import Optional, overload
from kornia.core import Module, Parameter, Tensor, complex, rand, stack, tensor, zeros_like
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
from kornia.geometry.liegroup._utils import (
check_so2_matrix_shape,
check_so2_t_shape,
check_so2_theta_shape,
check_so2_z_shape,
)
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
class So2(Module):
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index a28919a6e..40aaea62b 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -3,9 +3,9 @@
from typing import Optional
from kornia.core import Module, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
+from kornia.core.check import KORNIA_CHECK_TYPE
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.quaternion import Quaternion
-from kornia.testing import KORNIA_CHECK_TYPE
class So3(Module):
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 323309813..a11e82714 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -1,8 +1,8 @@
import torch
from torch import Tensor
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, check_is_tensor
__all__ = [
"compose_transformations",
@@ -171,8 +171,8 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Te
>>> trans_01 = torch.eye(4).view(1, 4, 4) # Bx4x4
>>> points_0 = transform_points(trans_01, points_1) # BxNx3
"""
- check_is_tensor(trans_01)
- check_is_tensor(points_1)
+ KORNIA_CHECK_IS_TENSOR(trans_01)
+ KORNIA_CHECK_IS_TENSOR(points_1)
if not trans_01.shape[0] == points_1.shape[0] and trans_01.shape[0] != 1:
raise ValueError(
"Input batch size must be the same for both tensors or 1." f"Got {trans_01.shape} and {points_1.shape}"
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 7bc729dbd..627b7ec59 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -5,9 +5,9 @@ from typing import Optional, Tuple, Union
import torch
from kornia.core import Module, Parameter, Tensor, normalize, where
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.geometry.linalg import batched_dot_product, squared_norm
from kornia.geometry.plane import Hyperplane
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.utils.helpers import _torch_svd_cast
__all__ = ["ParametrizedLine", "fit_line"]
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 6796fdc81..da76c2884 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -4,10 +4,10 @@
from typing import Optional
from kornia.core import Module, Tensor, stack, where
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
from kornia.core.tensor_wrapper import unwrap, wrap
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.vector import Scalar, Vector3
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
from kornia.utils.helpers import _torch_svd_cast
__all__ = ["Hyperplane", "fit_plane"]
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index eab845ba4..cbb5d623d 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -6,6 +6,7 @@ from math import pi
from typing import Optional, Tuple, Union
from kornia.core import Module, Parameter, Tensor, concatenate, rand, stack, tensor, where
+from kornia.core.check import KORNIA_CHECK_TYPE
from kornia.geometry.conversions import (
QuaternionCoeffOrder,
angle_axis_to_quaternion,
@@ -14,7 +15,6 @@ from kornia.geometry.conversions import (
rotation_matrix_to_quaternion,
)
from kornia.geometry.linalg import batched_dot_product
-from kornia.testing import KORNIA_CHECK_TYPE
class Quaternion(Module):
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 8b371ac83..614c6a6b7 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -5,6 +5,7 @@ from typing import Callable, Optional, Tuple
import torch
from kornia.core import Device, Module, Tensor, zeros
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry import (
find_fundamental,
find_homography_dlt,
@@ -18,7 +19,6 @@ from kornia.geometry.homography import (
oneway_transfer_error,
sample_is_valid_for_homography,
)
-from kornia.testing import KORNIA_CHECK_SHAPE
__all__ = ["RANSAC"]
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 5f36a76c9..fe209b1d2 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -5,6 +5,7 @@ import torch.nn.functional as F
from torch.nn.functional import grid_sample
from kornia.core import Tensor, concatenate, stack, tensor, zeros
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import (
angle_axis_to_rotation_matrix,
angle_to_rotation_matrix,
@@ -16,7 +17,6 @@ from kornia.geometry.conversions import (
normalize_pixel_coordinates,
)
from kornia.geometry.linalg import transform_points
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.utils import create_meshgrid, create_meshgrid3d, eye_like
from kornia.utils.helpers import _torch_inverse_cast, _torch_solve_cast
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index d0e3373b9..3de1c84ac 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -5,8 +5,8 @@ import torch
import torch.nn.functional as F
from kornia.core import Module, Tensor, pad, stack, tensor
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters import filter2d, gaussian_blur2d
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
__all__ = [
"PyrDown",
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index a3f045fc7..0e1b08074 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -1,9 +1,9 @@
from typing import Optional, Tuple, Union, cast
from kornia.core import Tensor, as_tensor, normalize, rand, stack
+from kornia.core.check import KORNIA_CHECK
from kornia.core.tensor_wrapper import TensorWrapper, wrap
from kornia.geometry.linalg import batched_dot_product, batched_squared_norm
-from kornia.testing import KORNIA_CHECK
__all__ = ["Vector3", "Vector2", "Scalar"]
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 294b4cb03..e5beac4a9 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -13,7 +13,7 @@ from kornia.color import rgb_to_grayscale, rgba_to_rgb
from kornia.color.gray import grayscale_to_rgb
from kornia.color.rgb import rgb_to_rgba
from kornia.core import Tensor
-from kornia.testing import KORNIA_CHECK
+from kornia.core.check import KORNIA_CHECK
class ImageLoadType(Enum):
diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.py
index adef54575..76d5d4e74 100644
--- a/kornia/losses/cauchy.py
+++ b/kornia/losses/cauchy.py
@@ -1,7 +1,7 @@
from torch import Tensor
from kornia.core import Module
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
def cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.py
index 07da0eea7..8cc966c22 100644
--- a/kornia/losses/charbonnier.py
+++ b/kornia/losses/charbonnier.py
@@ -1,7 +1,7 @@
from torch import Tensor
from kornia.core import Module
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
def charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index cc6209588..2ea43f397 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -5,7 +5,7 @@ import torch
import torch.nn as nn
from kornia.core import Tensor
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.utils.one_hot import one_hot
# based on:
diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.py
index 800402cd3..6eaba99b3 100644
--- a/kornia/losses/geman_mcclure.py
+++ b/kornia/losses/geman_mcclure.py
@@ -1,7 +1,7 @@
from torch import Tensor
from kornia.core import Module
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
def geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.py
index 52598dd9b..4ddac4440 100644
--- a/kornia/losses/lovasz_hinge.py
+++ b/kornia/losses/lovasz_hinge.py
@@ -2,7 +2,7 @@ import torch
import torch.nn as nn
from torch import Tensor
-from kornia.testing import KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK_SHAPE
# based on:
# https://github.com/bermanmaxim/LovaszSoftmax
diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.py
index 88ef91c07..c58490fa9 100644
--- a/kornia/losses/lovasz_softmax.py
+++ b/kornia/losses/lovasz_softmax.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
from torch import Tensor
-from kornia.testing import KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK_SHAPE
# based on:
# https://github.com/bermanmaxim/LovaszSoftmax
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index 988aa4880..a19dab90a 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -1,5 +1,5 @@
from kornia.core import Module, Tensor
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:
diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.py
index fb330584e..1238f6d0c 100644
--- a/kornia/losses/welsch.py
+++ b/kornia/losses/welsch.py
@@ -1,7 +1,7 @@
from torch import Tensor
from kornia.core import Module
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_DEVICE, KORNIA_CHECK_SAME_SHAPE
def welsch_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:
diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.py
index d49e7f506..cd7e9cfb3 100644
--- a/kornia/metrics/ssim3d.py
+++ b/kornia/metrics/ssim3d.py
@@ -1,9 +1,9 @@
from typing import List
from kornia.core import Module, Tensor, pad
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters import filter3d, get_gaussian_kernel3d
from kornia.filters.filter import _compute_padding
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
def _crop(img: Tensor, cropping_shape: List[int]) -> Tensor:
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 40679571d..1772664a6 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -4,33 +4,15 @@ import math
from abc import ABC, abstractmethod
from copy import deepcopy
from itertools import product
-from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, TypeVar, Union, cast
+from typing import Any, Callable, Dict, Optional, Sequence, Tuple, TypeVar, Union
import torch
from torch.autograd import gradcheck
from torch.testing import assert_close as _assert_close
-from typing_extensions import TypeGuard
from kornia.core import Tensor, eye, 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_IS_LIST_OF_TENSOR",
- "KORNIA_CHECK_SAME_DEVICE",
- "KORNIA_CHECK_SAME_DEVICES",
- "KORNIA_CHECK_IS_COLOR",
- "KORNIA_CHECK_IS_GRAY",
- "KORNIA_CHECK_DM_DESC",
- "KORNIA_CHECK_LAF",
-]
+__all__ = ["tensor_to_gradcheck_var", "create_eye_batch", "xla_is_available", "assert_close"]
def xla_is_available() -> bool:
@@ -296,290 +278,3 @@ def assert_close(
equal_nan=False,
**kwargs,
)
-
-
-# Logger api
-
-# TODO: add somehow type check, or enforce to do it before
-# TODO: get rid of torchscript test because prevents us to have type safe code
-
-
-def KORNIA_CHECK_SHAPE(x: Tensor, 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
- """
- if '*' == shape[0]:
- shape_to_check = shape[1:]
- x_shape_to_check = x.shape[-len(shape) + 1 :]
- elif '*' == shape[-1]:
- shape_to_check = shape[:-1]
- x_shape_to_check = x.shape[: len(shape) - 1]
- else:
- shape_to_check = shape
- x_shape_to_check = x.shape
-
- if len(x_shape_to_check) != len(shape_to_check):
- raise TypeError(f"{x} shape must be [{shape}]. Got {x.shape}")
-
- for i in range(len(x_shape_to_check)):
- # The voodoo below is because torchscript does not like
- # that dim can be both int and str
- dim_: str = shape_to_check[i]
- if not dim_.isnumeric():
- continue
- dim = int(dim_)
- if x_shape_to_check[i] != dim:
- raise TypeError(f"{x} shape must be [{shape}]. Got {x.shape}")
-
-
-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) # type: ignore # TODO: this function will change after kornia/pr#1987
-
-
-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_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]]) -> TypeGuard[List[Tensor]]:
- """Check the input variable is a List of Tensors.
-
- Args:
- x: Any sequence of objects
-
- Return:
- True if the input is a list of Tensors, otherwise return False.
-
- Example:
- >>> x = torch.rand(2, 3, 3)
- >>> KORNIA_CHECK_IS_LIST_OF_TENSOR(x)
- False
- >>> KORNIA_CHECK_IS_LIST_OF_TENSOR([x])
- True
- """
- return isinstance(x, list) and all(isinstance(d, Tensor) for d in x)
-
-
-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_SAME_SHAPE(x: Tensor, y: Tensor) -> None:
- """Check whether two tensor have the same shape.
-
- Args:
- x: first tensor to evaluate.
- y: sencod tensor to evaluate.
- msg: message to show in the exception.
-
- Raises:
- TypeException: if the two tensors have not the same shape.
-
- Example:
- >>> x1 = torch.rand(2, 3, 3)
- >>> x2 = torch.rand(2, 3, 3)
- >>> KORNIA_CHECK_SAME_SHAPE(x1, x2)
- """
- if x.shape != y.shape:
- raise TypeError(f"Not same shape for tensors. Got: {x.shape} and {y.shape}")
-
-
-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):
- """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)`.
-
- 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}
- desc2 {desc2.shape}"""
- raise TypeError(message)
-
-
-def KORNIA_CHECK_LAF(laf: Tensor) -> None:
- """Check whether a Local Affine Frame (laf) has a valid shape.
-
- Args:
- 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"])
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
index 64fd20cf2..a4c97704e 100644
--- a/kornia/utils/draw.py
+++ b/kornia/utils/draw.py
@@ -3,7 +3,7 @@ from typing import List, Optional, Tuple, Union
import torch
from torch import Tensor
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
# TODO: implement width of the line
diff --git a/test/core/test_check.py b/test/core/test_check.py
new file mode 100644
index 000000000..22b01b728
--- /dev/null
+++ b/test/core/test_check.py
@@ -0,0 +1,185 @@
+import pytest
+import torch
+
+from kornia.core.check import (
+ KORNIA_CHECK,
+ KORNIA_CHECK_DM_DESC,
+ KORNIA_CHECK_IS_COLOR,
+ KORNIA_CHECK_IS_COLOR_OR_GRAY,
+ KORNIA_CHECK_IS_GRAY,
+ KORNIA_CHECK_IS_LIST_OF_TENSOR,
+ KORNIA_CHECK_IS_TENSOR,
+ KORNIA_CHECK_LAF,
+ KORNIA_CHECK_SAME_DEVICE,
+ KORNIA_CHECK_SAME_DEVICES,
+ KORNIA_CHECK_SAME_SHAPE,
+ KORNIA_CHECK_SHAPE,
+ KORNIA_CHECK_TYPE,
+)
+
+
+class TestCheck:
+ def test_valid(self):
+ KORNIA_CHECK(True, "This is a test")
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK(False, "This is a test")
+
+
+class TestCheckShape:
+ @pytest.mark.parametrize(
+ "data,shape",
+ [
+ (torch.rand(2, 3), ["*", "H", "W"]),
+ (torch.rand(3, 2, 3), ["3", "H", "W"]),
+ (torch.rand(1, 1, 2, 3), ["1", "1", "H", "W"]),
+ (torch.rand(2, 3, 2, 3), ["2", "3", "H", "W"]),
+ ],
+ )
+ def test_valid(self, data, shape):
+ KORNIA_CHECK_SHAPE(data, shape)
+
+ @pytest.mark.parametrize(
+ "data,shape",
+ [
+ (torch.rand(2, 3), ["1", "H", "W"]),
+ (torch.rand(3, 2, 3), ["H", "W"]),
+ (torch.rand(1, 2, 3), ["3", "H", "W"]),
+ (torch.rand(1, 3, 2, 3), ["2", "C", "H", "W"]),
+ ],
+ )
+ def test_invalid(self, data, shape):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_SHAPE(data, shape)
+
+
+class TestCheckSameShape:
+ def test_valid(self):
+ KORNIA_CHECK_SAME_SHAPE(torch.rand(2, 3), torch.rand(2, 3))
+ KORNIA_CHECK_SAME_SHAPE(torch.rand(1, 2, 3), torch.rand(1, 2, 3))
+ KORNIA_CHECK_SAME_SHAPE(torch.rand(2, 3, 3), torch.rand(2, 3, 3))
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_SAME_SHAPE(torch.rand(2, 3), torch.rand(2, 2, 3))
+ KORNIA_CHECK_SAME_SHAPE(torch.rand(2, 3), torch.rand(1, 2, 3))
+ KORNIA_CHECK_SAME_SHAPE(torch.rand(2, 3), torch.rand(2, 3, 3))
+
+
+class TestCheckType:
+ def test_valid(self):
+ KORNIA_CHECK_TYPE("hello", str)
+ KORNIA_CHECK_TYPE(23, int)
+ KORNIA_CHECK_TYPE(torch.rand(1), torch.Tensor)
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_TYPE("world", int)
+ KORNIA_CHECK_TYPE(23, float)
+
+
+class TestCheckIsTensor:
+ def test_valid(self):
+ KORNIA_CHECK_IS_TENSOR(torch.rand(1))
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_IS_TENSOR([1, 2, 3])
+
+
+class TestCheckIsListOfTensor:
+ def test_valid(self):
+ assert KORNIA_CHECK_IS_LIST_OF_TENSOR([torch.rand(1), torch.rand(1), torch.rand(1)])
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ assert KORNIA_CHECK_IS_LIST_OF_TENSOR([torch.rand(1), [2, 3], torch.rand(1)])
+ assert KORNIA_CHECK_IS_LIST_OF_TENSOR([1, 2, 3])
+
+
+class TestCheckSameDevice:
+ def test_valid(self, device):
+ KORNIA_CHECK_SAME_DEVICE(torch.rand(1, device=device), torch.rand(1, device=device))
+
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU.")
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_SAME_DEVICE(torch.rand(1, device="cpu"), torch.rand(1, device="cuda"))
+
+
+class TestCheckSameDevices:
+ def test_valid(self, device):
+ KORNIA_CHECK_SAME_DEVICES([torch.rand(1, device=device), torch.rand(1, device=device)])
+
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU.")
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_SAME_DEVICES([torch.rand(1, device="cpu"), torch.rand(1, device="cuda")])
+
+
+class TestCheckIsColor:
+ def test_valid(self):
+ KORNIA_CHECK_IS_COLOR(torch.rand(3, 4, 4))
+ KORNIA_CHECK_IS_COLOR(torch.rand(1, 3, 4, 4))
+ KORNIA_CHECK_IS_COLOR(torch.rand(2, 3, 4, 4))
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_IS_COLOR(torch.rand(1, 4, 4))
+ KORNIA_CHECK_IS_COLOR(torch.rand(2, 4, 4))
+ KORNIA_CHECK_IS_COLOR(torch.rand(3, 4, 4, 4))
+ KORNIA_CHECK_IS_COLOR(torch.rand(1, 3, 4, 4, 4))
+
+
+class TestCheckIsGray:
+ def test_valid(self):
+ KORNIA_CHECK_IS_GRAY(torch.rand(1, 4, 4))
+ KORNIA_CHECK_IS_GRAY(torch.rand(2, 1, 4, 4))
+ KORNIA_CHECK_IS_GRAY(torch.rand(3, 1, 4, 4))
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_IS_GRAY(torch.rand(3, 4, 4))
+ KORNIA_CHECK_IS_GRAY(torch.rand(1, 4, 4, 4))
+ KORNIA_CHECK_IS_GRAY(torch.rand(1, 3, 4, 4))
+ KORNIA_CHECK_IS_GRAY(torch.rand(1, 3, 4, 4, 4))
+
+
+class TestCheckIsColorOrGray:
+ def test_valid(self):
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(3, 4, 4))
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(1, 3, 4, 4))
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(2, 3, 4, 4))
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(1, 4, 4))
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(2, 1, 4, 4))
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(3, 1, 4, 4))
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(1, 4, 4, 4))
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(1, 3, 4, 4, 4))
+
+
+class TestCheckDmDesc:
+ def test_valid(self):
+ KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(4, 8))
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(4, 7))
+ KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(3, 8))
+ KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(3, 7))
+ KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(4, 8, 3))
+
+
+class TestCheckLaf:
+ def test_valid(self):
+ KORNIA_CHECK_LAF(torch.rand(4, 2, 2, 3))
+
+ def test_invalid(self):
+ with pytest.raises(Exception):
+ KORNIA_CHECK_LAF(torch.rand(4, 2, 2))
+ KORNIA_CHECK_LAF(torch.rand(4, 2, 3, 2))
+ KORNIA_CHECK_LAF(torch.rand(4, 2, 2, 2))
+ KORNIA_CHECK_LAF(torch.rand(4, 2, 3, 3, 3))