π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-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.pyindex 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 _BasicAugmentationBasefrom kornia.augmentation.utils import _transform_input, _transform_output_shape, _validate_input_dtypefrom kornia.constants import DataKey, DTypefrom kornia.core import Tensor, tensor+from kornia.core.check import KORNIA_UNWRAPfrom kornia.geometry.boxes import Boxes-from kornia.testing import KORNIA_UNWRAPclass MixAugmentationBaseV2(_BasicAugmentationBase):diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.pyindex 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 rgfrom kornia.augmentation._2d.mix.base import MixAugmentationBaseV2from kornia.constants import DataKey, Resamplefrom kornia.core import Tensor, as_tensor, concatenate, pad, zeros+from kornia.core.check import KORNIA_UNWRAPfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform-from kornia.testing import KORNIA_UNWRAPfrom kornia.utils import eye_like__all__ = ["RandomMosaic"]diff --git a/kornia/color/colormap.py b/kornia/color/colormap.pyindex 341ad616c..d6c9f51f2 100644--- a/kornia/color/colormap.py+++ b/kornia/color/colormap.py@@ -5,7 +5,7 @@ import torchfrom torch.nn.functional import interpolatefrom kornia.core import Module, Tensor, tensor-from kornia.testing import KORNIA_CHECK_IS_GRAY+from kornia.core.check import KORNIA_CHECK_IS_GRAYRGBColor = List[float]diff --git a/kornia/color/gray.py b/kornia/color/gray.pyindex 317e21219..578180fb0 100644--- a/kornia/color/gray.py+++ b/kornia/color/gray.py@@ -4,7 +4,7 @@ import torchfrom kornia.color.rgb import bgr_to_rgbfrom kornia.core import Module, Tensor, concatenate-from kornia.testing import KORNIA_CHECK_IS_TENSOR+from kornia.core.check import KORNIA_CHECK_IS_TENSORdef grayscale_to_rgb(image: Tensor) -> Tensor:diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.pyindex 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, Unionimport torchfrom kornia.core import Tensor+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.enhance import normalize_min_maxfrom kornia.filters import filter2d-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE# the default kernels for the diamond squaredefault_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.pyindex 9ad220816..a8d674043 100644--- a/kornia/contrib/edge_detection.py+++ b/kornia/contrib/edge_detection.py@@ -1,8 +1,8 @@from typing import Listfrom kornia.core import Module, Tensor+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.filters.dexined import DexiNed-from kornia.testing import KORNIA_CHECK_SHAPEclass EdgeDetector(Module):diff --git a/kornia/core/check.py b/kornia/core/check.pynew file mode 100644index 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.pyindex 6a2de22a7..01503b1da 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -6,7 +6,7 @@ from torch import Tensorfrom torch.nn import Module, Parameterfrom 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_TENSORfrom kornia.utils.helpers import _torch_histc_castfrom kornia.utils.image import perform_keep_shape_image, perform_keep_shape_videodiff --git a/kornia/enhance/core.py b/kornia/enhance/core.pyindex 037673fdd..31f577bd6 100644--- a/kornia/enhance/core.py+++ b/kornia/enhance/core.py@@ -1,7 +1,7 @@from typing import Unionfrom 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_TENSORdef add_weighted(diff --git a/kornia/enhance/integral.py b/kornia/enhance/integral.pyindex 9d74ccec1..4216ad480 100644--- a/kornia/enhance/integral.py+++ b/kornia/enhance/integral.py@@ -1,7 +1,7 @@from typing import Optional, Tuplefrom kornia.core import Module, Tensor-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEdef integral_tensor(input: Tensor, dim: Optional[Tuple[int, ...]] = None) -> Tensor:diff --git a/kornia/enhance/shift_rgb.py b/kornia/enhance/shift_rgb.pyindex 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_TENSORdef 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.pyindex 4af2f47c4..cd1ecda35 100644--- a/kornia/feature/adalam/adalam.py+++ b/kornia/feature/adalam/adalam.py@@ -7,8 +7,8 @@ from typing import Optional, Tuple, Unionimport torchfrom kornia.core import Tensor+from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom kornia.feature.laf import get_laf_center, get_laf_orientation, get_laf_scale-from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom .core import AdalamConfig, _no_match, adalam_corefrom .utils import dist_matrixdiff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 3f1d8fbd3..87b149feb 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -5,9 +5,9 @@ from typing import Dict, Optionalimport torchimport torch.nn as nn+from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom kornia.filters.kernels import get_gaussian_kernel2dfrom kornia.filters.sobel import SpatialGradient-from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom kornia.utils.helpers import map_location_to_cpufrom .laf import (diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex df0311c62..2df949353 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -4,7 +4,8 @@ import torchimport torch.nn as nnimport 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_safefrom kornia.utils.helpers import map_location_to_cpuurls: Dict[str, str] = {}diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex 3ea67722e..35d3da090 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -5,9 +5,9 @@ import torchfrom kornia.color import rgb_to_grayscalefrom kornia.core import Device, Module, Tensor, concatenate+from kornia.core.check import KORNIA_CHECK_LAFfrom kornia.geometry.subpix import ConvQuadInterp3dfrom kornia.geometry.transform import ScalePyramid-from kornia.testing import KORNIA_CHECK_LAFfrom .affine_shape import LAFAffNetShapeEstimatorfrom .hardnet import HardNetdiff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex 89f6e5467..4bf828273 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -5,10 +5,10 @@ import torchimport torch.nn.functional as Ffrom kornia.core import Tensor, concatenate, stack, tensor, zeros+from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous, rad2degfrom kornia.geometry.linalg import transform_pointsfrom kornia.geometry.transform import pyrdown-from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEdef get_laf_scale(LAF: Tensor) -> Tensor:diff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex 430fc4712..b737e89d1 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -3,8 +3,10 @@ from typing import Dict, Optional, Tupleimport torchimport torch.nn as nn+from kornia.core import Tensor+from kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPEfrom 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_safefrom .adalam import get_adalam_default_config, match_adalamdiff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex 2456feb23..98df0c13a 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -6,9 +6,9 @@ import torch.nn as nnimport torch.nn.functional as Ffrom kornia.constants import pi+from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom kornia.filters import SpatialGradient, get_gaussian_kernel2dfrom kornia.geometry import rad2deg-from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom kornia.utils.helpers import map_location_to_cpufrom .laf import extract_patches_from_pyramid, get_laf_orientation, set_laf_orientationdiff --git a/kornia/feature/responses.py b/kornia/feature/responses.pyindex a474176db..4a3e916ab 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -3,8 +3,8 @@ from typing import Optional, Unionimport torchfrom kornia.core import Module, Tensor, tensor+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.filters import gaussian_blur2d, spatial_gradient-from kornia.testing import KORNIA_CHECK_SHAPEdef _get_kernel_size(sigma: float):diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex 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 Ffrom typing_extensions import TypedDictfrom kornia.core import Device, Module, Tensor, concatenate, eye, tensor, where, zeros+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.geometry.subpix import ConvSoftArgmax3d, NonMaximaSuppression2dfrom kornia.geometry.transform import ScalePyramid, pyrdown, resize-from kornia.testing import KORNIA_CHECK_SHAPEfrom .laf import laf_from_center_scale_ori, laf_is_inside_imagefrom .orientation import PassLAFdiff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex df88383fb..be02d31a5 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -5,9 +5,9 @@ import torchimport torch.nn as nnfrom kornia.core import Module, Tensor, concatenate, eye, normalize+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.filters import get_gaussian_kernel2d, spatial_gradientfrom kornia.geometry.conversions import pi-from kornia.testing import KORNIA_CHECK_SHAPEdef _get_reshape_kernel(kd: int, ky: int, kx: int) -> Tensor:diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.pyindex bb92e241f..d94ab76bc 100644--- a/kornia/feature/sold2/sold2.py+++ b/kornia/feature/sold2/sold2.py@@ -4,8 +4,8 @@ import torchimport torch.nn.functional as Ffrom kornia.core import Module, Tensor, concatenate, pad, stack+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.geometry.conversions import normalize_pixel_coordinates-from kornia.testing import KORNIA_CHECK_SHAPEfrom kornia.utils import map_location_to_cpufrom .backbones import SOLD2Netdiff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.pyindex 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, Tupleimport torchfrom kornia.core import Module, Tensor, concatenate, stack, tensor, where, zeros+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.geometry.bbox import nms-from kornia.testing import KORNIA_CHECK_SHAPEfrom kornia.utils import map_location_to_cpu, torch_meshgridfrom .backbones import SOLD2Netdiff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex 0be734ecc..173f050f8 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -3,7 +3,7 @@ from typing import Dictimport torchimport torch.nn as nn-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.utils.helpers import map_location_to_cpuurls: Dict[str, str] = {}diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.pyindex 42c938ec9..eabce3e0b 100644--- a/kornia/feature/tfeat.py+++ b/kornia/feature/tfeat.py@@ -3,7 +3,7 @@ from typing import Dictimport torchimport torch.nn as nn-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.utils.helpers import map_location_to_cpuurls: Dict[str, str] = {}diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.pyindex 8a0c3ca84..d7cfabcc7 100644--- a/kornia/filters/blur_pool.py+++ b/kornia/filters/blur_pool.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport torch.nn.functional as Ffrom 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_SHAPEfrom .kernels import get_pascal_kernel_2dfrom .median import _compute_zero_padding # TODO: Move to proper placediff --git a/kornia/filters/canny.py b/kornia/filters/canny.pyindex d9756561b..05b810a3c 100644--- a/kornia/filters/canny.py+++ b/kornia/filters/canny.py@@ -7,7 +7,7 @@ import torch.nn.functional as Ffrom kornia.color import rgb_to_grayscalefrom 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_SHAPEfrom .gaussian import gaussian_blur2dfrom .kernels import get_canny_nms_kernel, get_hysteresis_kerneldiff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.pyindex 72d42e2c4..6338e0fd5 100644--- a/kornia/filters/dexined.py+++ b/kornia/filters/dexined.py@@ -9,7 +9,7 @@ import torch.nn as nnimport torch.nn.functional as Ffrom kornia.core import Module, Tensor, concatenate-from kornia.testing import KORNIA_CHECK+from kornia.core.check import KORNIA_CHECKfrom kornia.utils import map_location_to_cpuurl: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex 15c8b44dc..755368999 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport torch.nn.functional as Ffrom 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_SHAPEfrom .kernels import normalize_kernel2ddiff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex 1fe9fafa0..2e52c64b2 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom typing import Anyfrom kornia.core import Module, Tensor, tensor-from kornia.testing import KORNIA_CHECK_IS_TENSOR+from kornia.core.check import KORNIA_CHECK_IS_TENSORfrom kornia.utils import deprecatedfrom .filter import filter2d, filter2d_separablediff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 973aecca2..c09cb68ec 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -7,7 +7,7 @@ from typing import Anyimport torchfrom 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_TYPEfrom 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 ofthe 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 Besselfunction.@@ -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 kerneldtype: 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 kerneldtype: 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 kerneldtype: 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 kerneldtype: 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 kerneldtype: 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 kerneldtype: 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.pyindex 21c9c9ea4..0bdb45378 100644--- a/kornia/filters/kernels_geometry.py+++ b/kornia/filters/kernels_geometry.py@@ -3,8 +3,8 @@ from __future__ import annotationsimport torchfrom kornia.core import Tensor, pad, stack, tensor, zeros+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom kornia.geometry.transform import rotate, rotate3d-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom kornia.utils import _extract_device_dtypefrom .kernels import _check_kernel_size, _unpack_2d_ks, _unpack_3d_ksdiff --git a/kornia/filters/median.py b/kornia/filters/median.pyindex 6782d8c41..5deacd78c 100644--- a/kornia/filters/median.py+++ b/kornia/filters/median.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport torch.nn.functional as Ffrom 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_SHAPEfrom .kernels import _unpack_2d_ks, get_binary_kernel2ddiff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 96dafea0f..1c979403f 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -1,7 +1,7 @@from __future__ import annotationsfrom kornia.core import Module, Tensor-from kornia.testing import KORNIA_CHECK+from kornia.core.check import KORNIA_CHECKfrom .filter import filter2d, filter3dfrom .kernels_geometry import get_motion_kernel2d, get_motion_kernel3ddiff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex 2f1ad69ad..1b9780509 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -4,7 +4,7 @@ import torchimport torch.nn.functional as Ffrom 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_SHAPEfrom .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2ddiff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex 72a60ea07..b065354e4 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -3,9 +3,9 @@ from typing import Iterable, Listimport torchfrom kornia.core import Device, Tensor+from kornia.core.check import KORNIA_CHECK_SAME_DEVICEfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.linalg import inverse_transformation, transform_points-from kornia.testing import KORNIA_CHECK_SAME_DEVICEfrom kornia.utils.helpers import _torch_inverse_castdiff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 0e584d4b3..ba7e875ba 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -7,7 +7,7 @@ import torch.nn.functional as Ffrom kornia.constants import pifrom 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_SHAPEfrom kornia.utils.helpers import _torch_inverse_castfrom kornia.utils.misc import eye_likediff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex fb48c1a7c..58417b9f6 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -5,8 +5,8 @@ import torchimport torch.nn.functional as Ffrom kornia.core import Module, Tensor, concatenate, tensor+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.filters.sobel import spatial_gradient-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.utils import create_meshgridfrom .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_pointsdiff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.pyindex 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_TENSORfrom kornia.geometry.conversions import convert_points_to_homogeneousfrom kornia.geometry.linalg import point_line_distance-from kornia.testing import KORNIA_CHECK_IS_TENSORdef sampson_epipolar_distance(diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex 19c6cfe31..ad602dc11 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -5,9 +5,9 @@ from typing import Optional, Tupleimport torchfrom kornia.core import Tensor+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.linalg import transform_points-from kornia.testing import KORNIA_CHECK_SHAPEfrom kornia.utils.helpers import _torch_svd_castdiff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex f8de186ce..cad46d5bc 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -4,7 +4,7 @@ from typing import Optional, Tupleimport torchfrom kornia.core import Tensor-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.utils import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_maskfrom kornia.utils.helpers import _torch_svd_castdiff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.pyindex 4ddc1e12c..0c79bcffd 100644--- a/kornia/geometry/liegroup/se2.py+++ b/kornia/geometry/liegroup/se2.py@@ -3,9 +3,9 @@from typing import Optional, Tuple, overloadfrom 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_TYPEfrom kornia.geometry.liegroup._utils import check_se2_omega_shape, check_se2_r_t_shape, check_v_shapefrom kornia.geometry.liegroup.so2 import So2-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPEclass Se2(Module):diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.pyindex 92c63adc6..784b22bb9 100644--- a/kornia/geometry/liegroup/se3.py+++ b/kornia/geometry/liegroup/se3.py@@ -3,9 +3,9 @@from typing import Optional, Tuplefrom 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_TYPEfrom kornia.geometry.liegroup.so3 import So3from kornia.geometry.linalg import batched_dot_product-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPEclass Se3(Module):diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.pyindex d31cb5add..a00539c08 100644--- a/kornia/geometry/liegroup/so2.py+++ b/kornia/geometry/liegroup/so2.py@@ -3,13 +3,13 @@from typing import Optional, overloadfrom kornia.core import Module, Parameter, Tensor, complex, rand, stack, tensor, zeros_like+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSORfrom 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_TENSORclass So2(Module):diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.pyindex a28919a6e..40aaea62b 100644--- a/kornia/geometry/liegroup/so3.py+++ b/kornia/geometry/liegroup/so3.py@@ -3,9 +3,9 @@from typing import Optionalfrom kornia.core import Module, Tensor, concatenate, stack, tensor, where, zeros, zeros_like+from kornia.core.check import KORNIA_CHECK_TYPEfrom kornia.geometry.linalg import batched_dot_productfrom kornia.geometry.quaternion import Quaternion-from kornia.testing import KORNIA_CHECK_TYPEclass So3(Module):diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 323309813..a11e82714 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -1,8 +1,8 @@import torchfrom torch import Tensor+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom 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.pyindex 7bc729dbd..627b7ec59 100644--- a/kornia/geometry/line.py+++ b/kornia/geometry/line.py@@ -5,9 +5,9 @@ from typing import Optional, Tuple, Unionimport torchfrom kornia.core import Module, Parameter, Tensor, normalize, where+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.geometry.linalg import batched_dot_product, squared_normfrom kornia.geometry.plane import Hyperplane-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.utils.helpers import _torch_svd_cast__all__ = ["ParametrizedLine", "fit_line"]diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.pyindex 6796fdc81..da76c2884 100644--- a/kornia/geometry/plane.py+++ b/kornia/geometry/plane.py@@ -4,10 +4,10 @@from typing import Optionalfrom kornia.core import Module, Tensor, stack, where+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPEfrom kornia.core.tensor_wrapper import unwrap, wrapfrom kornia.geometry.linalg import batched_dot_productfrom kornia.geometry.vector import Scalar, Vector3-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPEfrom kornia.utils.helpers import _torch_svd_cast__all__ = ["Hyperplane", "fit_plane"]diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex eab845ba4..cbb5d623d 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -6,6 +6,7 @@ from math import pifrom typing import Optional, Tuple, Unionfrom kornia.core import Module, Parameter, Tensor, concatenate, rand, stack, tensor, where+from kornia.core.check import KORNIA_CHECK_TYPEfrom 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_TYPEclass Quaternion(Module):diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 8b371ac83..614c6a6b7 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -5,6 +5,7 @@ from typing import Callable, Optional, Tupleimport torchfrom kornia.core import Device, Module, Tensor, zeros+from kornia.core.check import KORNIA_CHECK_SHAPEfrom 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.pyindex 5f36a76c9..fe209b1d2 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -5,6 +5,7 @@ import torch.nn.functional as Ffrom torch.nn.functional import grid_samplefrom kornia.core import Tensor, concatenate, stack, tensor, zeros+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom 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_SHAPEfrom kornia.utils import create_meshgrid, create_meshgrid3d, eye_likefrom kornia.utils.helpers import _torch_inverse_cast, _torch_solve_castdiff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.pyindex d0e3373b9..3de1c84ac 100644--- a/kornia/geometry/transform/pyramid.py+++ b/kornia/geometry/transform/pyramid.py@@ -5,8 +5,8 @@ import torchimport torch.nn.functional as Ffrom kornia.core import Module, Tensor, pad, stack, tensor+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom 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.pyindex a3f045fc7..0e1b08074 100644--- a/kornia/geometry/vector.py+++ b/kornia/geometry/vector.py@@ -1,9 +1,9 @@from typing import Optional, Tuple, Union, castfrom kornia.core import Tensor, as_tensor, normalize, rand, stack+from kornia.core.check import KORNIA_CHECKfrom kornia.core.tensor_wrapper import TensorWrapper, wrapfrom 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.pyindex 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_rgbfrom kornia.color.gray import grayscale_to_rgbfrom kornia.color.rgb import rgb_to_rgbafrom kornia.core import Tensor-from kornia.testing import KORNIA_CHECK+from kornia.core.check import KORNIA_CHECKclass ImageLoadType(Enum):diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.pyindex adef54575..76d5d4e74 100644--- a/kornia/losses/cauchy.py+++ b/kornia/losses/cauchy.py@@ -1,7 +1,7 @@from torch import Tensorfrom 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_SHAPEdef cauchy_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.pyindex 07da0eea7..8cc966c22 100644--- a/kornia/losses/charbonnier.py+++ b/kornia/losses/charbonnier.py@@ -1,7 +1,7 @@from torch import Tensorfrom 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_SHAPEdef charbonnier_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex cc6209588..2ea43f397 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -5,7 +5,7 @@ import torchimport torch.nn as nnfrom 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_SHAPEfrom kornia.utils.one_hot import one_hot# based on:diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.pyindex 800402cd3..6eaba99b3 100644--- a/kornia/losses/geman_mcclure.py+++ b/kornia/losses/geman_mcclure.py@@ -1,7 +1,7 @@from torch import Tensorfrom 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_SHAPEdef geman_mcclure_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.pyindex 52598dd9b..4ddac4440 100644--- a/kornia/losses/lovasz_hinge.py+++ b/kornia/losses/lovasz_hinge.py@@ -2,7 +2,7 @@ import torchimport torch.nn as nnfrom torch import Tensor-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK_SHAPE# based on:# https://github.com/bermanmaxim/LovaszSoftmaxdiff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.pyindex 88ef91c07..c58490fa9 100644--- a/kornia/losses/lovasz_softmax.py+++ b/kornia/losses/lovasz_softmax.py@@ -4,7 +4,7 @@ import torchimport torch.nn as nnfrom torch import Tensor-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK_SHAPE# based on:# https://github.com/bermanmaxim/LovaszSoftmaxdiff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.pyindex 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_SHAPEdef total_variation(img: Tensor, reduction: str = "sum") -> Tensor:diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.pyindex fb330584e..1238f6d0c 100644--- a/kornia/losses/welsch.py+++ b/kornia/losses/welsch.py@@ -1,7 +1,7 @@from torch import Tensorfrom 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_SHAPEdef welsch_loss(img1: Tensor, img2: Tensor, reduction: str = "none") -> Tensor:diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.pyindex d49e7f506..cd7e9cfb3 100644--- a/kornia/metrics/ssim3d.py+++ b/kornia/metrics/ssim3d.py@@ -1,9 +1,9 @@from typing import Listfrom kornia.core import Module, Tensor, pad+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.filters import filter3d, get_gaussian_kernel3dfrom kornia.filters.filter import _compute_padding-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEdef _crop(img: Tensor, cropping_shape: List[int]) -> Tensor:diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex 40679571d..1772664a6 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -4,33 +4,15 @@ import mathfrom abc import ABC, abstractmethodfrom copy import deepcopyfrom 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, Unionimport torchfrom torch.autograd import gradcheckfrom torch.testing import assert_close as _assert_close-from typing_extensions import TypeGuardfrom 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.pyindex 64fd20cf2..a4c97704e 100644--- a/kornia/utils/draw.py+++ b/kornia/utils/draw.py@@ -3,7 +3,7 @@ from typing import List, Optional, Tuple, Unionimport torchfrom 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 linediff --git a/test/core/test_check.py b/test/core/test_check.pynew file mode 100644index 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))