Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Depreciates `kornia.testing` (#2745)

João Gustavo A. Amorimce434e467faf
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ef3a46c06..23adeab7d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -160,9 +160,13 @@ maintainable.
- Add tests:
- Tests are crucial and we expect you to write unit tests for each of the functionalities that you implement.
It is also a good idea to group the tests for functionalities
+ - At [testing/](./testing/) directory we have a bunch of functions to help you to produce meaningful tests. Feel free,
+ to add any functionality which you that you think is essential and can be used with the test suite. Under this
+ testing directory should go all code which are needed under the tests and aren't tests or pytest configs (fixtures,
+ etc).
```python
- from kornia.testing import BaseTester
+ from testing.base import BaseTester
class TestMyFunction(BaseTester):
# To compare the actual and expected tensors use `self.assert_close(...)`
diff --git a/docs/source/testing.rst b/docs/source/testing.rst
index 68a9ecfb1..f30509e0e 100644
--- a/docs/source/testing.rst
+++ b/docs/source/testing.rst
@@ -1,5 +1,7 @@
kornia.testing
==============
+This module has been deprecated and will be removed on release 0.8.0 (dec 2024).
+
.. automodule:: kornia.testing
:members:
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 384f6474f..9f3ca2a7c 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -9,8 +9,7 @@ from . import augmentation, color, contrib, core, enhance, feature, io, losses,
# NOTE: we are going to expose to top level very few things
from kornia.constants import pi
-from kornia.testing import xla_is_available
-from kornia.utils import eye_like, vec_like, create_meshgrid, image_to_tensor, tensor_to_image
+from kornia.utils import eye_like, vec_like, create_meshgrid, image_to_tensor, tensor_to_image, xla_is_available
# Version variable
__version__ = "0.7.2-dev"
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 8f86bc15f..938fac637 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -5,8 +5,7 @@ import torch.nn.functional as F
from torch import nn
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
+from kornia.utils.helpers import is_mps_tensor_safe, map_location_to_cpu
urls: Dict[str, str] = {}
urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 82fad911a..1df00793c 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -5,7 +5,7 @@ import torch
from kornia.core import Module, Tensor, concatenate
from kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE
from kornia.feature.laf import get_laf_center
-from kornia.testing import is_mps_tensor_safe
+from kornia.utils.helpers import is_mps_tensor_safe
from .adalam import get_adalam_default_config, match_adalam
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 805b73adc..1f7e92eac 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -1,6 +1,7 @@
"""The testing package contains testing-specific utilities."""
import importlib.util
import math
+import warnings
from abc import ABC, abstractmethod
from copy import deepcopy
from itertools import product
@@ -11,10 +12,28 @@ from torch.autograd import gradcheck
from torch.testing import assert_close as _assert_close
from kornia.core import Device, Dtype, Tensor, eye, tensor
+from kornia.utils.helpers import deprecated
+
+warnings.simplefilter("always", DeprecationWarning)
+warnings.warn(
+ (
+ "Since kornia 0.7.2 the `kornia.testing` module is deprecated and will be removed in kornia 0.8.0 (dec 2024)."
+ " Most of these functionalities will be removed from kornia package and will be part of the tests of kornia."
+ " Some functionalities which we think is important to keep will be moved to other kornia module."
+ ),
+ category=DeprecationWarning,
+ stacklevel=2,
+)
+warnings.simplefilter("default", DeprecationWarning)
__all__ = ["tensor_to_gradcheck_var", "create_eye_batch", "xla_is_available", "assert_close"]
+@deprecated(
+ "kornia.utils.xla_is_available",
+ "0.7.2",
+ extra_reason="The `kornia.testing` module is deprecated and will be removed in kornia 0.8.0 (dec 2024).",
+)
def xla_is_available() -> bool:
"""Return whether `torch_xla` is available in the system."""
if importlib.util.find_spec("torch_xla") is not None:
@@ -22,12 +41,21 @@ def xla_is_available() -> bool:
return False
+@deprecated(
+ "kornia.utils.is_mps_tensor_safe",
+ "0.7.2",
+ extra_reason="The `kornia.testing` module is deprecated and will be removed in kornia 0.8.0 (dec 2024).",
+)
def is_mps_tensor_safe(x: Tensor) -> bool:
"""Return whether tensor is on MPS device."""
return "mps" in str(x.device)
-# TODO: Isn't this function duplicated with eye_like?
+@deprecated(
+ "kornia.utils.misc.eye_like",
+ "0.7.2",
+ extra_reason="The `kornia.testing` module is deprecated and will be removed in kornia 0.8.0 (dec 2024).",
+)
def create_eye_batch(batch_size: int, eye_size: int, device: Device = None, dtype: Dtype = None) -> Tensor:
"""Create a batch of identity matrices of shape Bx3x3."""
return eye(eye_size, device=device, dtype=dtype).view(1, eye_size, eye_size).expand(batch_size, -1, -1)
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index 2cce92b03..bfec86fe4 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -8,9 +8,11 @@ from .helpers import (
get_cuda_or_mps_device_if_available,
get_mps_device_if_available,
is_autocast_enabled,
+ is_mps_tensor_safe,
map_location_to_cpu,
safe_inverse_with_mask,
safe_solve_with_mask,
+ xla_is_available,
)
from .image import ImageToTensor, image_list_to_tensor, image_to_tensor, tensor_to_image
from .image_print import image_to_string, print_image
@@ -48,4 +50,6 @@ __all__ = [
"deprecated",
"image_to_string",
"print_image",
+ "xla_is_available",
+ "is_mps_tensor_safe",
]
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 63904a6ea..e3a07122e 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -1,3 +1,4 @@
+import importlib.util
import platform
import sys
import warnings
@@ -12,6 +13,18 @@ from kornia.core import Tensor
from kornia.utils._compat import torch_version_ge
+def xla_is_available() -> bool:
+ """Return whether `torch_xla` is available in the system."""
+ if importlib.util.find_spec("torch_xla") is not None:
+ return True
+ return False
+
+
+def is_mps_tensor_safe(x: Tensor) -> bool:
+ """Return whether tensor is on MPS device."""
+ return "mps" in str(x.device)
+
+
def get_cuda_device_if_available(index: int = 0) -> torch.device:
"""Tries to get cuda device, if fail, returns cpu.
diff --git a/pyproject.toml b/pyproject.toml
index d2f698429..5744d61f0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -145,8 +145,10 @@ requires = [
skip-magic-trailing-comma = false
[tool.ruff.isort]
- known-first-party = ["examples", "kornia", "test"]
+ known-first-party = ["kornia"]
split-on-trailing-comma = true
+ forced-separate = ["testing", "tests"]
+
[tool.ruff.mccabe]
max-complexity = 20
@@ -164,6 +166,7 @@ requires = [
"docs/generate_examples.py" = ["C901"] # Allow too complex function
"kornia/__init__.py" = ["I001"] # Allow unsorted imports
"tests/*" = ["S101", "S311", "BLE", "RUF012", "RUF005"] # allow assert, random, ignore BLE, mutable class attr
+ "testing/*" = ["S101",] # allow assert
[tool.pytest.ini_options]
addopts = "--color=yes"
diff --git a/testing/__init__.py b/testing/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/testing/augmentation/__init__.py b/testing/augmentation/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/testing/augmentation/datasets.py b/testing/augmentation/datasets.py
new file mode 100644
index 000000000..d8459ba66
--- /dev/null
+++ b/testing/augmentation/datasets.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import torch.nn
+from torch.utils.data import Dataset
+
+from kornia.augmentation import (
+ ColorJiggle,
+ ColorJitter,
+ RandomAffine,
+ RandomAffine3D,
+ RandomCrop,
+ RandomCrop3D,
+ RandomCutMixV2,
+ RandomErasing,
+ RandomGaussianBlur,
+ RandomJigsaw,
+ RandomMixUpV2,
+ RandomMosaic,
+ RandomMotionBlur,
+ RandomMotionBlur3D,
+ RandomPerspective,
+ RandomPerspective3D,
+ RandomPlanckianJitter,
+ RandomPosterize,
+ RandomRain,
+ RandomRotation3D,
+ RandomShear,
+ RandomTranslate,
+ Resize,
+)
+
+
+class DummyMPDataset(Dataset):
+ def __init__(self, context: str):
+ super().__init__()
+ # we add all transforms that could potentially fail in
+ # multiprocessing with a spawn context below, that is all the
+ # transforms that define a RNG
+ transforms = [
+ RandomTranslate(),
+ RandomShear(0.1),
+ RandomPosterize(),
+ RandomErasing(),
+ RandomMotionBlur(kernel_size=3, angle=(0, 360), direction=(-1, 1)),
+ RandomGaussianBlur(3, (0.1, 2.0)),
+ RandomPerspective(),
+ ColorJitter(),
+ ColorJiggle(),
+ RandomJigsaw(),
+ RandomAffine(degrees=15),
+ RandomMotionBlur3D(kernel_size=3, angle=(0, 360), direction=(-1, 1)),
+ RandomPerspective3D(),
+ RandomAffine3D(degrees=15),
+ RandomRotation3D(degrees=15),
+ ]
+
+ if context != "fork":
+ # random planckian jitter auto selects a GPU. But it is not possible
+ # to init a CUDA context in a forked process.
+ # So we skip it in this case.
+ transforms.append(RandomPlanckianJitter())
+
+ self._transform = torch.nn.Sequential()
+
+ self._resize = Resize((10, 10))
+ self._mosaic = RandomMosaic((2, 2))
+ self._crop = RandomCrop((5, 5))
+ self._crop3d = RandomCrop3D((5, 5, 5))
+ self._mixup = RandomMixUpV2()
+ self._cutmix = RandomCutMixV2()
+ self._rain = RandomRain(p=1, drop_height=(1, 2), drop_width=(1, 2), number_of_drops=(1, 1))
+
+ def __len__(self):
+ return 10
+
+ def __getitem__(self, _):
+ mosaic = self._mosaic(torch.rand(1, 3, 64, 64))
+ rain = self._rain(torch.rand(1, 1, 5, 5))
+ rain = self._resize(rain)
+ cropped = self._crop(torch.rand(3, 3, 64, 64))
+ cropped3d = self._crop3d(torch.rand(3, 64, 64, 64))
+ mixed = self._mixup(torch.rand(3, 3, 64, 64), torch.rand(3, 3, 64, 64))
+ mixed = self._cutmix(torch.rand(3, 3, 64, 64), mixed)
+
+ return (self._transform(mixed), cropped, cropped3d, mixed, mosaic, rain)
diff --git a/testing/base.py b/testing/base.py
new file mode 100644
index 000000000..74e99e953
--- /dev/null
+++ b/testing/base.py
@@ -0,0 +1,143 @@
+from __future__ import annotations
+
+import math
+from typing import Any, Callable, Optional, Sequence, Union
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_close as _assert_close
+
+from kornia.core import Dtype, Tensor
+
+# {dtype: (rtol, atol)}
+_DTYPE_PRECISIONS = {
+ torch.bfloat16: (7.8e-3, 7.8e-3),
+ torch.float16: (9.7e-4, 9.7e-4),
+ torch.float32: (1e-4, 1e-5), # TODO: Update to ~1.2e-7
+ # TODO: Update to ~2.3e-16 for fp64
+ torch.float64: (1e-5, 1e-5), # TODO: BaseTester used (1.3e-6, 1e-5), but it fails for general cases
+}
+
+
+def _default_tolerances(*inputs: Any) -> tuple[float, float]:
+ rtols, atols = zip(*[_DTYPE_PRECISIONS.get(torch.as_tensor(input_).dtype, (0.0, 0.0)) for input_ in inputs])
+ return max(rtols), max(atols)
+
+
+def assert_close(
+ actual: Tensor, expected: Tensor, *, rtol: Optional[float] = None, atol: Optional[float] = None, **kwargs: Any
+) -> None:
+ if rtol is None and atol is None:
+ # `torch.testing.assert_close` used different default tolerances than `torch.testing.assert_allclose`.
+ # TODO: remove this special handling as soon as https://github.com/kornia/kornia/issues/1134 is resolved
+ # Basically, this whole wrapper function can be removed and `torch.testing.assert_close` can be used
+ # directly.
+ rtol, atol = _default_tolerances(actual, expected)
+
+ return _assert_close(
+ actual,
+ expected,
+ rtol=rtol,
+ atol=atol,
+ # this is the default value for torch>=1.10, but not for torch==1.9
+ # TODO: remove this if kornia relies on torch>=1.10
+ check_stride=False,
+ equal_nan=False,
+ **kwargs,
+ )
+
+
+def tensor_to_gradcheck_var(
+ tensor: Tensor, dtype: Dtype = torch.float64, requires_grad: bool = True
+) -> Union[Tensor, str]:
+ """Convert the input tensor to a valid variable to check the gradient.
+
+ `gradcheck` needs 64-bit floating point and requires gradient.
+ """
+ if not torch.is_tensor(tensor):
+ raise AssertionError(type(tensor))
+ t = tensor.type(dtype)
+
+ if t.is_floating_point():
+ return t.requires_grad_(requires_grad)
+
+ return t
+
+
+class BaseTester:
+ @staticmethod
+ def assert_close(
+ actual: Tensor | float,
+ expected: Tensor | float,
+ rtol: Optional[float] = None,
+ atol: Optional[float] = None,
+ low_tolerance: bool = False,
+ ) -> None:
+ """Asserts that `actual` and `expected` are close.
+
+ Args:
+ actual: Actual input.
+ expected: Expected input.
+ rtol: Relative tolerance.
+ atol: Absolute tolerance.
+ low_tolerance:
+ This parameter allows to reduce tolerance. Half the decimal places.
+ Example, 1e-4 -> 1e-2 or 1e-6 -> 1e-3
+ """
+ if hasattr(actual, "data"):
+ actual = actual.data
+ if hasattr(expected, "data"):
+ expected = expected.data
+
+ if (isinstance(actual, Tensor) and "xla" in actual.device.type) or (
+ isinstance(expected, Tensor) and "xla" in expected.device.type
+ ):
+ rtol, atol = 1e-2, 1e-2
+
+ if (isinstance(actual, Tensor) and isinstance(expected, Tensor)) and rtol is None and atol is None:
+ actual_rtol, actual_atol = _DTYPE_PRECISIONS.get(actual.dtype, (0.0, 0.0))
+ expected_rtol, expected_atol = _DTYPE_PRECISIONS.get(expected.dtype, (0.0, 0.0))
+ rtol, atol = max(actual_rtol, expected_rtol), max(actual_atol, expected_atol)
+
+ # halve the tolerance if `low_tolerance` is true
+ rtol = math.sqrt(rtol) if low_tolerance else rtol
+ atol = math.sqrt(atol) if low_tolerance else atol
+
+ return assert_close(actual, expected, rtol=rtol, atol=atol)
+
+ @staticmethod
+ def gradcheck(
+ func: Callable[..., Union[torch.Tensor, Sequence[torch.Tensor]]],
+ inputs: Union[torch.Tensor, Sequence[Any]],
+ *,
+ raise_exception: bool = True,
+ fast_mode: bool = True,
+ requires_grad: Sequence[bool] = [],
+ dtypes: Sequence[Dtype] = [],
+ **kwargs: Any,
+ ) -> bool:
+ """It will gradcheck the function using the `torch.autograd.gradcheck` method.
+
+ By default this method will pass all tensor to `tensor_to_gradcheck_var` which casts the tensor
+ to be float64 dtype, and requires grad as True. You can overwrite which tensors should have requires grad
+ equals True, by using a Sequence of the same length of the sequence of inputs, within the requires_grad
+ per item. You also, can overwrite with the same mechanics the dtype using the `dtypes`
+ parameter.
+ """
+ requires_grad = requires_grad if len(requires_grad) > 0 else [True] * len(inputs)
+ dtypes = dtypes if len(dtypes) > 0 else [torch.float64] * len(inputs)
+
+ if isinstance(inputs, torch.Tensor):
+ inputs = tensor_to_gradcheck_var(inputs)
+ elif isinstance(inputs, dict):
+ inputs = {
+ k: tensor_to_gradcheck_var(v, d, r) if isinstance(v, torch.Tensor) else v
+ for (k, v), d, r in zip(inputs.items(), dtypes, requires_grad)
+ }
+ else:
+ inputs = [
+ tensor_to_gradcheck_var(i, d, r) if isinstance(i, torch.Tensor) else i
+ for i, r, d in zip(inputs, requires_grad, dtypes)
+ ]
+
+ return gradcheck(func, inputs, raise_exception=raise_exception, fast_mode=fast_mode, **kwargs)
diff --git a/testing/casts.py b/testing/casts.py
new file mode 100644
index 000000000..58800651a
--- /dev/null
+++ b/testing/casts.py
@@ -0,0 +1,14 @@
+from __future__ import annotations
+
+from typing import Any, TypeVar
+
+from kornia.core import Device, Dtype, Tensor
+
+T = TypeVar("T")
+
+
+def dict_to(data: dict[T, Any], device: Device, dtype: Dtype) -> dict[T, Any]:
+ out: dict[T, Any] = {}
+ for key, val in data.items():
+ out[key] = val.to(device, dtype) if isinstance(val, Tensor) else val
+ return out
diff --git a/testing/error.py b/testing/error.py
new file mode 100644
index 000000000..03d300180
--- /dev/null
+++ b/testing/error.py
@@ -0,0 +1,10 @@
+from __future__ import annotations
+
+import torch
+
+from kornia.core import Tensor
+
+
+def compute_patch_abs_error(x: Tensor, y: Tensor, h: int, w: int) -> Tensor:
+ """Compute the absolute error between patches."""
+ return torch.abs(x - y)[..., h // 4 : -h // 4, w // 4 : -w // 4].mean()
diff --git a/testing/geometry/__init__.py b/testing/geometry/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/testing/geometry/create.py b/testing/geometry/create.py
new file mode 100644
index 000000000..3de1d8956
--- /dev/null
+++ b/testing/geometry/create.py
@@ -0,0 +1,83 @@
+from __future__ import annotations
+
+import torch
+
+import kornia.geometry.epipolar as epi
+from kornia.core import Device, Dtype, Tensor, tensor, zeros
+from kornia.utils.misc import eye_like
+
+
+def create_random_homography(inpt: Tensor, eye_size: int, std_val: float = 1e-3) -> Tensor:
+ """Create a batch of random homographies of shape Bx3x3."""
+ std = zeros(inpt.shape[0], eye_size, eye_size, device=inpt.device, dtype=inpt.dtype)
+ eye = eye_like(eye_size, inpt)
+ return eye + std.uniform_(-std_val, std_val)
+
+
+def create_rectified_fundamental_matrix(batch_size: int, dtype: Dtype = None, device: Device = None) -> Tensor:
+ """Create a batch of rectified fundamental matrices of shape Bx3x3."""
+ F_rect = tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype).view(1, 3, 3)
+ F_repeat = F_rect.expand(batch_size, 3, 3)
+ return F_repeat
+
+
+def create_random_fundamental_matrix(
+ batch_size: int, std_val: float = 1e-3, dtype: Dtype = None, device: Device = None
+) -> Tensor:
+ """Create a batch of random fundamental matrices of shape Bx3x3."""
+ F_rect = create_rectified_fundamental_matrix(batch_size, dtype, device)
+ H_left = create_random_homography(F_rect, 3, std_val)
+ H_right = create_random_homography(F_rect, 3, std_val)
+ return H_left.permute(0, 2, 1) @ F_rect @ H_right
+
+
+def generate_two_view_random_scene(
+ device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.float32
+) -> dict[str, torch.Tensor]:
+ num_views: int = 2
+ num_points: int = 30
+
+ scene: dict[str, torch.Tensor] = epi.generate_scene(num_views, num_points)
+
+ # internal parameters (same K)
+ K1 = scene["K"].to(device, dtype)
+ K2 = K1.clone()
+
+ # rotation
+ R1 = scene["R"][0:1].to(device, dtype)
+ R2 = scene["R"][1:2].to(device, dtype)
+
+ # translation
+ t1 = scene["t"][0:1].to(device, dtype)
+ t2 = scene["t"][1:2].to(device, dtype)
+
+ # projection matrix, P = K(R|t)
+ P1 = scene["P"][0:1].to(device, dtype)
+ P2 = scene["P"][1:2].to(device, dtype)
+
+ # fundamental matrix
+ F_mat = epi.fundamental_from_projections(P1[..., :3, :], P2[..., :3, :])
+
+ F_mat = epi.normalize_transformation(F_mat)
+
+ # points 3d
+ X = scene["points3d"].to(device, dtype)
+
+ # projected points
+ x1 = scene["points2d"][0:1].to(device, dtype)
+ x2 = scene["points2d"][1:2].to(device, dtype)
+
+ return {
+ "K1": K1,
+ "K2": K2,
+ "R1": R1,
+ "R2": R2,
+ "t1": t1,
+ "t2": t2,
+ "P1": P1,
+ "P2": P2,
+ "F": F_mat,
+ "X": X,
+ "x1": x1,
+ "x2": x2,
+ }
diff --git a/testing/geometry/linalg.py b/testing/geometry/linalg.py
new file mode 100644
index 000000000..256664239
--- /dev/null
+++ b/testing/geometry/linalg.py
@@ -0,0 +1,74 @@
+import torch
+
+
+def identity_matrix(batch_size, device, dtype):
+ r"""Create a batched homogeneous identity matrix."""
+ return torch.eye(4, device=device, dtype=dtype).repeat(batch_size, 1, 1) # Nx4x4
+
+
+def euler_angles_to_rotation_matrix(x, y, z):
+ r"""Create a rotation matrix from x, y, z angles."""
+ assert x.dim() == 1, x.shape
+ assert x.shape == y.shape == z.shape
+ ones, zeros = torch.ones_like(x), torch.zeros_like(x)
+ # the rotation matrix for the x-axis
+ rx_tmp = [
+ ones,
+ zeros,
+ zeros,
+ zeros,
+ zeros,
+ torch.cos(x),
+ -torch.sin(x),
+ zeros,
+ zeros,
+ torch.sin(x),
+ torch.cos(x),
+ zeros,
+ zeros,
+ zeros,
+ zeros,
+ ones,
+ ]
+ rx = torch.stack(rx_tmp, dim=-1).view(-1, 4, 4)
+ # the rotation matrix for the y-axis
+ ry_tmp = [
+ torch.cos(y),
+ zeros,
+ torch.sin(y),
+ zeros,
+ zeros,
+ ones,
+ zeros,
+ zeros,
+ -torch.sin(y),
+ zeros,
+ torch.cos(y),
+ zeros,
+ zeros,
+ zeros,
+ zeros,
+ ones,
+ ]
+ ry = torch.stack(ry_tmp, dim=-1).view(-1, 4, 4)
+ # the rotation matrix for the z-axis
+ rz_tmp = [
+ torch.cos(z),
+ -torch.sin(z),
+ zeros,
+ zeros,
+ torch.sin(z),
+ torch.cos(z),
+ zeros,
+ zeros,
+ zeros,
+ zeros,
+ ones,
+ zeros,
+ zeros,
+ zeros,
+ zeros,
+ ones,
+ ]
+ rz = torch.stack(rz_tmp, dim=-1).view(-1, 4, 4)
+ return torch.matmul(rz, torch.matmul(ry, rx)) # Bx4x4
diff --git a/testing/overwrite.py b/testing/overwrite.py
new file mode 100644
index 000000000..f06f69bf8
--- /dev/null
+++ b/testing/overwrite.py
@@ -0,0 +1,15 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Any
+
+
+def default_with_one_parameter_changed(*, default: dict[str, Any] = {}, **possible_parameters: Any) -> Any:
+ if not isinstance(default, dict):
+ raise AssertionError(f"default should be a dict not a {type(default)}")
+
+ for parameter_name, possible_values in possible_parameters.items():
+ for v in possible_values:
+ param_set = deepcopy(default)
+ param_set[parameter_name] = v
+ yield param_set
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index d24e76ece..fab512968 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -4,10 +4,8 @@ from unittest.mock import patch
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
from kornia.augmentation import (
AugmentationSequential,
CenterCrop,
@@ -17,16 +15,12 @@ from kornia.augmentation import (
LongestMaxSize,
Normalize,
PadTo,
- RandomAffine,
- RandomAffine3D,
RandomBoxBlur,
RandomBrightness,
RandomChannelShuffle,
RandomClahe,
RandomContrast,
RandomCrop,
- RandomCrop3D,
- RandomCutMixV2,
RandomElasticTransform,
RandomEqualize,
RandomErasing,
@@ -38,14 +32,7 @@ from kornia.augmentation import (
RandomHorizontalFlip,
RandomHue,
RandomInvert,
- RandomJigsaw,
RandomMedianBlur,
- RandomMixUpV2,
- RandomMosaic,
- RandomMotionBlur,
- RandomMotionBlur3D,
- RandomPerspective,
- RandomPerspective3D,
RandomPlanckianJitter,
RandomPlasmaBrightness,
RandomPlasmaContrast,
@@ -55,12 +42,9 @@ from kornia.augmentation import (
RandomResizedCrop,
RandomRGBShift,
RandomRotation,
- RandomRotation3D,
RandomSaturation,
- RandomShear,
RandomSnow,
RandomThinPlateSpline,
- RandomTranslate,
RandomVerticalFlip,
Resize,
SmallestMaxSize,
@@ -68,15 +52,18 @@ from kornia.augmentation import (
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import Resample, pi
from kornia.geometry import transform_points
-from kornia.testing import BaseTester, assert_close, default_with_one_parameter_changed
from kornia.utils import create_meshgrid
from kornia.utils.helpers import _torch_inverse_cast
-# TODO same_on_batch tests?
+from testing.augmentation.datasets import DummyMPDataset
+from testing.base import BaseTester
+from testing.overwrite import default_with_one_parameter_changed
@pytest.mark.usefixtures("device", "dtype")
class CommonTests(BaseTester):
+ # TODO same_on_batch tests?
+
fixture_names = ("device", "dtype")
############################################################################################################
@@ -217,7 +204,7 @@ class CommonTests(BaseTester):
augmentation = self._create_augmentation_from_params(**params, p=0.0)
test_input = torch.rand((2, 3, 4, 5), device=self.device, dtype=self.dtype)
output = augmentation(test_input)
- assert_close(output, test_input)
+ self.assert_close(output, test_input)
def _test_random_p_1_implementation(self, input_tensor, expected_output, params, expected_transformation=None):
augmentation = self._create_augmentation_from_params(**params, p=1.0)
@@ -284,13 +271,7 @@ class CommonTests(BaseTester):
@pytest.mark.slow
def _test_gradcheck_implementation(self, params):
input_tensor = torch.rand((3, 5, 5), device=self.device, dtype=self.dtype) # 3 x 3
- input_tensor = utils.tensor_to_gradcheck_var(input_tensor) # to var
- assert gradcheck(
- self._create_augmentation_from_params(**params, p=1.0),
- (input_tensor,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(self._create_augmentation_from_params(**params, p=1.0), (input_tensor,))
class TestRandomEqualizeAlternative(CommonTests):
@@ -697,7 +678,7 @@ class TestRandomGrayscaleAlternative(CommonTests):
self._create_augmentation_from_params(p=1.0)(torch.rand((1, 4, 4, 5), device=self.device, dtype=self.dtype))
-class TestRandomHorizontalFlip:
+class TestRandomHorizontalFlip(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
@@ -728,12 +709,12 @@ class TestRandomHorizontalFlip:
[[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
) # 1 x 3 x 3
- assert_close(f(input), expected)
- assert_close(f.transform_matrix, expected_transform)
- assert_close(f1(input), input)
- assert_close(f1.transform_matrix, identity)
- assert_close(f.inverse(expected), input)
- assert_close(f1.inverse(expected), expected)
+ self.assert_close(f(input), expected)
+ self.assert_close(f.transform_matrix, expected_transform)
+ self.assert_close(f1(input), input)
+ self.assert_close(f1.transform_matrix, identity)
+ self.assert_close(f.inverse(expected), input)
+ self.assert_close(f1.inverse(expected), expected)
def test_batch_random_hflip(self, device, dtype):
f = RandomHorizontalFlip(p=1.0)
@@ -760,19 +741,19 @@ class TestRandomHorizontalFlip:
expected_transform = expected_transform.repeat(5, 1, 1) # 5 x 3 x 3
identity = identity.repeat(5, 1, 1) # 5 x 3 x 3
- assert_close(f(input), expected)
- assert_close(f.transform_matrix, expected_transform)
- assert_close(f1(input), input)
- assert_close(f1.transform_matrix, identity)
- assert_close(f.inverse(expected), input)
- assert_close(f1.inverse(expected), expected)
+ self.assert_close(f(input), expected)
+ self.assert_close(f.transform_matrix, expected_transform)
+ self.assert_close(f1(input), input)
+ self.assert_close(f1.transform_matrix, identity)
+ self.assert_close(f.inverse(expected), input)
+ self.assert_close(f1.inverse(expected), expected)
def test_same_on_batch(self, device, dtype):
f = RandomHorizontalFlip(p=0.5, same_on_batch=True)
input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
- assert_close(f.inverse(res), input)
+ self.assert_close(res[0], res[1])
+ self.assert_close(f.inverse(res), input)
def test_sequential(self, device, dtype):
f = AugmentationSequential(RandomHorizontalFlip(p=1.0), RandomHorizontalFlip(p=1.0))
@@ -788,9 +769,9 @@ class TestRandomHorizontalFlip:
expected_transform_1 = expected_transform @ expected_transform
out = f(input)
- assert_close(out, input)
- assert_close(f.transform_matrix, expected_transform_1)
- assert_close(f.inverse(out), input)
+ self.assert_close(out, input)
+ self.assert_close(f.transform_matrix, expected_transform_1)
+ self.assert_close(f.inverse(out), input)
def test_random_hflip_coord_check(self, device, dtype):
f = RandomHorizontalFlip(p=1.0)
@@ -824,7 +805,7 @@ class TestRandomHorizontalFlip:
# Tensors must have the same shapes and values
assert output.shape == expected_output.shape
- assert_close(output, expected_output)
+ self.assert_close(output, expected_output)
# Transformed indices must not be out of bound
assert (
torch.torch.logical_and(result_coordinates[0, 0, :] >= 0, result_coordinates[0, 0, :] < input.shape[-1])
@@ -835,16 +816,15 @@ class TestRandomHorizontalFlip:
# Values in the output tensor at the places of transformed indices must
# have the same value as the input tensor has at the corresponding
# positions
- assert_close(
+ self.assert_close(
output[..., result_coordinates[0, 1, :], result_coordinates[0, 0, :]],
input[..., input_coordinates[0, 1, :], input_coordinates[0, 0, :]],
)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand((3, 3), device=device, dtype=dtype) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomHorizontalFlip(p=1.0), (input,), raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, device):
+ input = torch.rand((3, 3), device=device, dtype=torch.float64) # 3 x 3
+ self.gradcheck(RandomHorizontalFlip(p=1.0), (input,))
class TestRandomVerticalFlip(BaseTester):
@@ -916,8 +896,8 @@ class TestRandomVerticalFlip(BaseTester):
f = RandomVerticalFlip(p=0.5, same_on_batch=True)
input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
- assert_close(f.inverse(res), input)
+ self.assert_close(res[0], res[1])
+ self.assert_close(f.inverse(res), input)
def test_sequential(self, device, dtype):
f = AugmentationSequential(RandomVerticalFlip(p=1.0), RandomVerticalFlip(p=1.0))
@@ -967,7 +947,7 @@ class TestRandomVerticalFlip(BaseTester):
# Tensors must have the same shapes and values
assert output.shape == expected_output.shape
- assert_close(output, expected_output)
+ self.assert_close(output, expected_output)
# Transformed indices must not be out of bound
assert (
torch.torch.logical_and(result_coordinates[0, 0, :] >= 0, result_coordinates[0, 0, :] < input.shape[-1])
@@ -978,31 +958,11 @@ class TestRandomVerticalFlip(BaseTester):
# Values in the output tensor at the places of transformed indices must
# have the same value as the input tensor has at the corresponding
# positions
- assert_close(
+ self.assert_close(
output[..., result_coordinates[0, 1, :], result_coordinates[0, 0, :]],
input[..., input_coordinates[0, 1, :], input_coordinates[0, 0, :]],
)
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_gradcheck(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
class TestColorJiggle(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
@@ -1043,7 +1003,7 @@ class TestColorJiggle(BaseTester):
f = ColorJiggle(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1, same_on_batch=True)
input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def _get_expected_brightness(self, device, dtype):
return torch.tensor(
@@ -1304,26 +1264,9 @@ class TestColorJiggle(BaseTester):
self.assert_close(f.transform_matrix, expected_transform, low_tolerance=True)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(ColorJiggle(p=1.0), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ def test_gradcheck(self, device):
+ input = torch.rand((3, 5, 5), device=device, dtype=torch.float64).unsqueeze(0) # 3 x 3
+ self.gradcheck(ColorJiggle(p=1.0), (input,))
class TestColorJitter(BaseTester):
@@ -1371,7 +1314,7 @@ class TestColorJitter(BaseTester):
f = ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1, same_on_batch=True)
input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def _get_expected_brightness(self, device, dtype):
return torch.tensor(
@@ -1632,26 +1575,9 @@ class TestColorJitter(BaseTester):
self.assert_close(f.transform_matrix, expected_transform)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(ColorJitter(p=1.0), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ def test_gradcheck(self, device):
+ input = torch.rand((3, 5, 5), device=device, dtype=torch.float64).unsqueeze(0) # 3 x 3
+ self.gradcheck(ColorJitter(p=1.0), (input,))
class TestRandomBrightness(BaseTester):
@@ -1678,7 +1604,7 @@ class TestRandomBrightness(BaseTester):
f = RandomBrightness(brightness=(0.5, 1.5), same_on_batch=True)
input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def _get_expected_brightness(self, device, dtype):
return torch.tensor(
@@ -1736,26 +1662,9 @@ class TestRandomBrightness(BaseTester):
self.assert_close(f(input), expected, low_tolerance=True)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomBrightness(p=1.0), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ def test_gradcheck(self, device):
+ input = torch.rand((3, 5, 5), device=device, dtype=torch.float64).unsqueeze(0) # 3 x 3
+ self.gradcheck(RandomBrightness(p=1.0), (input,))
class TestRandomContrast(BaseTester):
@@ -1780,7 +1689,7 @@ class TestRandomContrast(BaseTester):
f = RandomContrast(contrast=(0.5, 1.5), same_on_batch=True)
input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def _get_expected_contrast(self, device, dtype):
return torch.tensor(
@@ -1838,26 +1747,9 @@ class TestRandomContrast(BaseTester):
self.assert_close(f(input), expected, low_tolerance=True)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomContrast(p=1.0), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ def test_gradcheck(self, device):
+ input = torch.rand((3, 5, 5), device=device, dtype=torch.float64).unsqueeze(0) # 3 x 3
+ self.gradcheck(RandomContrast(p=1.0), (input,))
class TestRandomHue(BaseTester):
@@ -1882,7 +1774,7 @@ class TestRandomHue(BaseTester):
f = RandomHue(hue=(-0.5, 0.5), same_on_batch=True)
input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def _get_expected_hue(self, device, dtype):
return torch.tensor(
@@ -1948,26 +1840,9 @@ class TestRandomHue(BaseTester):
self.assert_close(f(input), expected, low_tolerance=True)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomHue(p=1.0), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ def test_gradcheck(self, device):
+ input = torch.rand((3, 5, 5), device=device, dtype=torch.float64).unsqueeze(0) # 3 x 3
+ self.gradcheck(RandomHue(p=1.0), (input,))
class TestRandomSaturation(BaseTester):
@@ -1992,7 +1867,7 @@ class TestRandomSaturation(BaseTester):
f = RandomSaturation(saturation=(0.5, 1.5), same_on_batch=True)
input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def _get_expected_saturation(self, device, dtype):
return torch.tensor(
@@ -2058,26 +1933,9 @@ class TestRandomSaturation(BaseTester):
self.assert_close(f(input), expected, low_tolerance=True)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomSaturation(p=1.0), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ def test_gradcheck(self, device):
+ input = torch.rand((3, 5, 5), device=device, dtype=torch.float64).unsqueeze(0) # 3 x 3
+ self.gradcheck(RandomSaturation(p=1.0), (input,))
class TestRectangleRandomErasing(BaseTester):
@@ -2104,10 +1962,10 @@ class TestRectangleRandomErasing(BaseTester):
f = RandomErasing(erase_scale_range, aspect_ratio_range, same_on_batch=True, p=0.5)
input = torch.rand(shape).unsqueeze(dim=0).repeat(2, 1, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
batch_shape = (2, 3, 11, 7)
erase_scale_range = (0.2, 0.4)
@@ -2117,29 +1975,8 @@ class TestRectangleRandomErasing(BaseTester):
rect_params = rand_rec.forward_parameters(batch_shape)
# evaluate function gradient
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(rand_rec, (input, rect_params), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ input = torch.rand(batch_shape, device=device, dtype=torch.float64)
+ self.gradcheck(rand_rec, (input, rect_params))
class TestRandomGamma(BaseTester):
@@ -2157,7 +1994,7 @@ class TestRandomGamma(BaseTester):
f = RandomGamma(gamma=(0.5, 2.0), gain=(0.5, 0.5), same_on_batch=True)
input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def _get_expected_gamma(self, device, dtype):
return torch.tensor(
@@ -2246,26 +2083,9 @@ class TestRandomGamma(BaseTester):
self.assert_close(f(input), expected, low_tolerance=True)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomGamma(p=1.0), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ def test_gradcheck(self, device):
+ input = torch.rand((3, 5, 5), device=device, dtype=torch.float64).unsqueeze(0) # 3 x 3
+ self.gradcheck(RandomGamma(p=1.0), (input,))
class TestRandomGrayscale(BaseTester):
@@ -2290,7 +2110,7 @@ class TestRandomGrayscale(BaseTester):
f = RandomGrayscale(p=0.5, same_on_batch=True)
input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def test_opencv_true(self, device, dtype):
data = torch.tensor(
@@ -2504,27 +2324,10 @@ class TestRandomGrayscale(BaseTester):
self.assert_close(f.transform_matrix, expected_transform)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand((3, 5, 5), device=device, dtype=dtype) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomGrayscale(p=1.0), (input,), raise_exception=True, fast_mode=True)
- assert gradcheck(RandomGrayscale(p=0.0), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ def test_gradcheck(self, device, p):
+ input = torch.rand((3, 5, 5), device=device, dtype=torch.float64) # 3 x 3
+ self.gradcheck(RandomGrayscale(p=p), (input,))
class TestCenterCrop(BaseTester):
@@ -2570,30 +2373,9 @@ class TestCenterCrop(BaseTester):
self.assert_close(out, op2(img, op1._params))
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
- input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(CenterCrop(3), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ def test_gradcheck(self, device):
+ input = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)
+ self.gradcheck(CenterCrop(3), (input,))
class TestRandomRotation(BaseTester):
@@ -2700,7 +2482,7 @@ class TestRandomRotation(BaseTester):
f = RandomRotation(degrees=40, same_on_batch=True)
input = torch.eye(6, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def test_sequential(self, device, dtype):
torch.manual_seed(0) # for random reproductibility
@@ -2739,28 +2521,11 @@ class TestRandomRotation(BaseTester):
self.assert_close(f.transform_matrix, expected_transform, low_tolerance=True)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- input = torch.rand((3, 3), device=device, dtype=dtype) # 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomRotation(degrees=(15.0, 15.0), p=1.0), (input,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ input = torch.rand((3, 3), device=device, dtype=torch.float64) # 3 x 3
+ self.gradcheck(RandomRotation(degrees=(15.0, 15.0), p=1.0), (input,))
class TestRandomCrop(BaseTester):
@@ -2825,7 +2590,7 @@ class TestRandomCrop(BaseTester):
f = RandomCrop(size=(2, 3), padding=1, same_on_batch=True, align_corners=True, p=1.0)
input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def test_padding(self, device, dtype):
torch.manual_seed(42)
@@ -3014,11 +2779,10 @@ class TestRandomCrop(BaseTester):
self.assert_close(out, op2(img, op1._params))
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- inp = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3
- inp = utils.tensor_to_gradcheck_var(inp) # to var
- assert gradcheck(RandomCrop(size=(3, 3), p=1.0), (inp,), raise_exception=True, fast_mode=True)
+ inp = torch.rand((3, 3, 3), device=device, dtype=torch.float64) # 3 x 3
+ self.gradcheck(RandomCrop(size=(3, 3), p=1.0), (inp,))
@pytest.mark.skip("Need to fix Union type")
def test_jit(self, device, dtype):
@@ -3049,18 +2813,6 @@ class TestRandomCrop(BaseTester):
expected = op(img)
self.assert_close(actual, expected)
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
class TestRandomResizedCrop(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
@@ -3208,32 +2960,10 @@ class TestRandomResizedCrop(BaseTester):
self.assert_close(out, op2(img, op1._params))
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- inp = torch.rand((1, 3, 3), device=device, dtype=dtype) # 3 x 3
- inp = utils.tensor_to_gradcheck_var(inp) # to var
- assert gradcheck(
- RandomResizedCrop(size=(3, 3), scale=(1.0, 1.0), ratio=(1.0, 1.0)),
- (inp,),
- raise_exception=True,
- fast_mode=True,
- )
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ inp = torch.rand((1, 3, 3), device=device, dtype=torch.float64) # 3 x 3
+ self.gradcheck(RandomResizedCrop(size=(3, 3), scale=(1.0, 1.0), ratio=(1.0, 1.0)), (inp,))
class TestRandomEqualize(BaseTester):
@@ -3331,15 +3061,14 @@ class TestRandomEqualize(BaseTester):
input = torch.eye(4, device=device, dtype=dtype)
input = input.unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- input = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomEqualize(p=0.5), (input,), raise_exception=True, fast_mode=True)
+ input = torch.rand((3, 3, 3), device=device, dtype=torch.float64) # 3 x 3 x 3
+ self.gradcheck(RandomEqualize(p=0.5), (input,))
@staticmethod
def build_input(channels, height, width, bs=1, row=None, device="cpu", dtype=torch.float32):
@@ -3352,22 +3081,6 @@ class TestRandomEqualize(BaseTester):
return batch.to(device, dtype)
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
class TestRandomGaussianBlur(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
@@ -3398,7 +3111,7 @@ class TestRandomGaussianBlur(BaseTester):
self.assert_close(actual, actual)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(0)
# test parameters
@@ -3407,15 +3120,14 @@ class TestRandomGaussianBlur(BaseTester):
sigma = (1.5, 1.5)
# evaluate function gradient
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomGaussianBlur(kernel_size, sigma, "replicate", p=1.0), (input,), raise_exception=True)
+ input = torch.rand(batch_shape, device=device, dtype=torch.float64)
+ self.gradcheck(RandomGaussianBlur(kernel_size, sigma, "replicate", p=1.0), (input,), fast_mode=False)
@pytest.mark.xfail(
reason="might fail due to the sampling distribution gradcheck errors. "
"See: https://github.com/pytorch/pytorch/issues/78346."
)
- def test_gradcheck_class_non_deterministic(self, device, dtype):
+ def test_gradcheck_class_non_deterministic(self, device):
torch.manual_seed(0)
# test parameters
@@ -3424,9 +3136,8 @@ class TestRandomGaussianBlur(BaseTester):
sigma = (1.5, 2.1)
# evaluate function gradient
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomGaussianBlur(kernel_size, sigma, "replicate", p=1.0), (input,), raise_exception=True)
+ input = torch.rand(batch_shape, device=device, dtype=torch.float64)
+ self.gradcheck(RandomGaussianBlur(kernel_size, sigma, "replicate", p=1.0), (input,), fast_mode=False)
def test_module(self, device, dtype):
func_params = [(3, 3), torch.tensor([1.5, 1.5]).view(1, -1)]
@@ -3455,36 +3166,12 @@ class TestRandomGaussianBlur(BaseTester):
img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
self.assert_close(op(img, *func_params), op_module(img))
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
class TestRandomInvert(BaseTester):
def test_smoke(self, device, dtype):
img = torch.ones(1, 3, 4, 5, device=device, dtype=dtype)
self.assert_close(RandomInvert(p=1.0)(img), torch.zeros_like(img))
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_gradcheck(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
class TestRandomChannelShuffle(BaseTester):
def test_smoke(self, device, dtype):
@@ -3501,26 +3188,6 @@ class TestRandomChannelShuffle(BaseTester):
out = aug(img)
self.assert_close(out, out_expected)
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_gradcheck(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
class TestRandomClahe(BaseTester):
def test_smoke(self, device, dtype):
@@ -3533,24 +3200,8 @@ class TestRandomClahe(BaseTester):
output_data = RandomClahe(p=1.0, grid_size=(2, 2))(input_data)
assert output_data.shape == batch_shape
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_gradcheck(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
-class TestRandomGaussianNoise:
+class TestRandomGaussianNoise(BaseTester):
def test_smoke(self, device, dtype):
torch.manual_seed(0)
img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
@@ -3618,33 +3269,11 @@ class TestNormalize(BaseTester):
self.assert_close(f1.transform_matrix, identity)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- input = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(
- Normalize(mean=torch.tensor([1.0]), std=torch.tensor([1.0]), p=1.0),
- (input,),
- raise_exception=True,
- fast_mode=True,
- )
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ input = torch.rand((3, 3, 3), device=device, dtype=torch.float64) # 3 x 3 x 3
+ self.gradcheck(Normalize(mean=torch.tensor([1.0]), std=torch.tensor([1.0]), p=1.0), (input,))
class TestDenormalize(BaseTester):
@@ -3687,36 +3316,14 @@ class TestDenormalize(BaseTester):
self.assert_close(f1.transform_matrix, identity)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- input = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(
- Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([1.0]), p=1.0),
- (input,),
- raise_exception=True,
- fast_mode=True,
- )
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
+ input = torch.rand((3, 3, 3), device=device, dtype=torch.float64) # 3 x 3 x 3
+ self.gradcheck(Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([1.0]), p=1.0), (input,))
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
-
-class TestRandomFisheye:
+class TestRandomFisheye(BaseTester):
def test_smoke(self, device, dtype):
torch.manual_seed(0)
center_x = torch.tensor([-0.3, 0.3])
@@ -3741,14 +3348,10 @@ class TestRandomFisheye:
center_x = torch.tensor([-0.3, 0.3], device=device, dtype=dtype)
center_y = torch.tensor([-0.3, 0.3], device=device, dtype=dtype)
gamma = torch.tensor([-1.0, 1.0], device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- center_x = utils.tensor_to_gradcheck_var(center_x) # to var
- center_y = utils.tensor_to_gradcheck_var(center_y) # to var
- gamma = utils.tensor_to_gradcheck_var(gamma) # to var
- assert gradcheck(RandomFisheye(center_x, center_y, gamma), (img,), raise_exception=True, fast_mode=True)
+ self.gradcheck(RandomFisheye(center_x, center_y, gamma), (img,))
-class TestRandomElasticTransform:
+class TestRandomElasticTransform(BaseTester):
def test_smoke(self, device, dtype):
img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
aug = RandomElasticTransform(p=1.0)
@@ -3758,7 +3361,7 @@ class TestRandomElasticTransform:
f = RandomElasticTransform(p=1.0, same_on_batch=True)
input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1)
res = f(input)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def test_mask_transform(self, device, dtype):
torch.manual_seed(0)
@@ -3776,7 +3379,7 @@ class TestRandomElasticTransform:
# The transformed values are fine if we use mask input type
labels_transformed = compose(features, labels, data_keys=["input", "mask"])[1]
- assert_close(labels_transformed.unique(), torch.tensor([0, 10], dtype=dtype, device=device))
+ self.assert_close(labels_transformed.unique(), torch.tensor([0, 10], dtype=dtype, device=device))
@pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])
def test_apply(self, batch_prob, device, dtype):
@@ -3790,11 +3393,11 @@ class TestRandomElasticTransform:
to_apply = torch.tensor(batch_prob, device=device)
with patch.object(aug_list[0], "__batch_prob_generator__", return_value=to_apply):
features_transformed, labels_transformed = aug_list(features, labels, data_keys=["input", "mask"])
- assert_close(aug_list._params[0].data["batch_prob"], to_apply)
+ self.assert_close(aug_list._params[0].data["batch_prob"], to_apply)
# Images should remain unchanged if the transformation is not applied
- assert_close(features_transformed[~to_apply], features[~to_apply])
- assert_close(labels_transformed[~to_apply], labels[~to_apply])
+ self.assert_close(features_transformed[~to_apply], features[~to_apply])
+ self.assert_close(labels_transformed[~to_apply], labels[~to_apply])
# At least one value in the images should change if the transformation is applied
if to_apply.any():
@@ -3816,13 +3419,13 @@ class TestRandomBoxBlur:
assert img.shape == aug(img).shape
-class TestPadTo:
+class TestPadTo(BaseTester):
def test_smoke(self, device, dtype):
img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
aug = PadTo(size=(4, 5))
out = aug(img)
assert out.shape == (1, 1, 4, 5)
- assert_close(aug.inverse(out), img)
+ self.assert_close(aug.inverse(out), img)
class TestResize:
@@ -4103,32 +3706,8 @@ class TestPlanckianJitter(BaseTester):
expected = self._get_expected_output_same_on_batch(device, dtype)
self.assert_close(f(input), expected, low_tolerance=True)
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_gradcheck(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
-
-class TestRandomRGBShift:
+class TestRandomRGBShift(BaseTester):
def test_smoke(self, device, dtype):
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
aug = RandomRGBShift(p=1.0).to(device)
@@ -4157,7 +3736,7 @@ class TestRandomRGBShift:
device=device,
dtype=dtype,
)
- utils.assert_close(f(input), expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(f(input), expected, rtol=1e-4, atol=1e-4)
def test_random_rgb_shift_same_batch(self, device, dtype):
torch.manual_seed(0)
@@ -4176,10 +3755,10 @@ class TestRandomRGBShift:
device=device,
dtype=dtype,
)
- utils.assert_close(f(input), expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(f(input), expected, rtol=1e-4, atol=1e-4)
-class TestRandomTranslate:
+class TestRandomTranslate(BaseTester):
torch.manual_seed(0) # for random reproductibility
def test_smoke_no_transform(self, device):
@@ -4192,15 +3771,11 @@ class TestRandomTranslate:
@pytest.mark.slow
def test_gradcheck(self, device):
- input = torch.rand(1, 2, 5, 7).to(device)
- input = utils.tensor_to_gradcheck_var(input) # to var
- # TODO: turned off with p=0
- assert gradcheck(
- kornia.augmentation.RandomTranslate((0.5, 0.5), p=1.0), (input,), raise_exception=True, fast_mode=True
- )
+ input = torch.rand(1, 2, 5, 7, device=device)
+ self.gradcheck(kornia.augmentation.RandomTranslate((0.5, 0.5), p=1.0), (input,))
-class TestRandomAutoContrast:
+class TestRandomAutoContrast(BaseTester):
torch.manual_seed(0) # for random reproductibility
def test_smoke_no_transform(self, device):
@@ -4211,10 +3786,9 @@ class TestRandomAutoContrast:
@pytest.mark.slow
def test_gradcheck(self, device):
- input = torch.rand(1, 2, 5, 7).to(device)
- input = utils.tensor_to_gradcheck_var(input) # to var
+ input = torch.rand(1, 2, 5, device=device, dtype=torch.float64)
# TODO: turned off with p=0
- assert gradcheck(kornia.augmentation.RandomAutoContrast(p=1.0), (input,), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.augmentation.RandomAutoContrast(p=1.0), (input,))
class TestRandomSnow(BaseTester):
@@ -4252,9 +3826,8 @@ class TestRandomSnow(BaseTester):
@pytest.mark.slow
def test_gradcheck(self, device):
- input_data = torch.rand(1, 3, 6, 8, device=device)
- grad_input = utils.tensor_to_gradcheck_var(input_data)
- self.gradcheck(RandomSnow(p=1.0), (grad_input,))
+ input_data = torch.rand(1, 3, 6, 8, device=device, dtype=torch.float64)
+ self.gradcheck(RandomSnow(p=1.0), (input_data,))
def test_exception(self, device, dtype):
exception_test_data = self._get_exception_test_data(device, dtype)
@@ -4265,12 +3838,8 @@ class TestRandomSnow(BaseTester):
assert err_msg in str(errinfo)
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
-class TestRandomMedianBlur:
+class TestRandomMedianBlur(BaseTester):
def test_smoke(self, device, dtype):
image = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
aug = RandomMedianBlur(p=0.8)
@@ -4288,7 +3857,7 @@ class TestRandomMedianBlur:
dtype=dtype,
)
- utils.assert_close(out, expected)
+ self.assert_close(out, expected)
class TestRandomRain(BaseTester):
@@ -4322,10 +3891,6 @@ class TestRandomRain(BaseTester):
output_data = aug(input_data)
assert output_data.shape == input_data.shape
- @pytest.mark.skip(reason="not implemented yet")
- def test_gradcheck(self, device):
- pass
-
def test_exception(self, device, dtype):
exception_test_data = self._get_exception_test_data(device, dtype)
for err_msg, drop_height, drop_width, input_data in exception_test_data:
@@ -4335,65 +3900,6 @@ class TestRandomRain(BaseTester):
assert err_msg in str(errinfo)
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
-
-class DummyMPDataset(torch.utils.data.Dataset):
- def __init__(self, context: str):
- super().__init__()
- # we add all transforms that could potentially fail in
- # multiprocessing with a spawn context below, that is all the
- # transforms that define a RNG
- transforms = [
- RandomTranslate(),
- RandomShear(0.1),
- RandomPosterize(),
- RandomErasing(),
- RandomMotionBlur(kernel_size=3, angle=(0, 360), direction=(-1, 1)),
- RandomGaussianBlur(3, (0.1, 2.0)),
- RandomPerspective(),
- ColorJitter(),
- ColorJiggle(),
- RandomJigsaw(),
- RandomAffine(degrees=15),
- RandomMotionBlur3D(kernel_size=3, angle=(0, 360), direction=(-1, 1)),
- RandomPerspective3D(),
- RandomAffine3D(degrees=15),
- RandomRotation3D(degrees=15),
- ]
-
- if context != "fork":
- # random planckian jitter auto selects a GPU. But it is not possible
- # to init a CUDA context in a forked process.
- # So we skip it in this case.
- transforms.append(RandomPlanckianJitter())
-
- self._transform = torch.nn.Sequential()
-
- self._resize = Resize((10, 10))
- self._mosaic = RandomMosaic((2, 2))
- self._crop = RandomCrop((5, 5))
- self._crop3d = RandomCrop3D((5, 5, 5))
- self._mixup = RandomMixUpV2()
- self._cutmix = RandomCutMixV2()
- self._rain = RandomRain(p=1, drop_height=(1, 2), drop_width=(1, 2), number_of_drops=(1, 1))
-
- def __len__(self):
- return 10
-
- def __getitem__(self, _):
- mosaic = self._mosaic(torch.rand(1, 3, 64, 64))
- rain = self._rain(torch.rand(1, 1, 5, 5))
- rain = self._resize(rain)
- cropped = self._crop(torch.rand(3, 3, 64, 64))
- cropped3d = self._crop3d(torch.rand(3, 64, 64, 64))
- mixed = self._mixup(torch.rand(3, 3, 64, 64), torch.rand(3, 3, 64, 64))
- mixed = self._cutmix(torch.rand(3, 3, 64, 64), mixed)
-
- return (self._transform(mixed), cropped, cropped3d, mixed, mosaic, rain)
-
class TestMultiprocessing:
torch.manual_seed(0) # for random reproductibility
diff --git a/tests/augmentation/test_augmentation_3d.py b/tests/augmentation/test_augmentation_3d.py
index b1b8b55ea..c9dd3b55a 100644
--- a/tests/augmentation/test_augmentation_3d.py
+++ b/tests/augmentation/test_augmentation_3d.py
@@ -1,9 +1,7 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
from kornia.augmentation import (
CenterCrop3D,
RandomAffine3D,
@@ -16,10 +14,11 @@ from kornia.augmentation import (
RandomVerticalFlip3D,
)
from kornia.augmentation.container.augment import AugmentationSequential
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestRandomHorizontalFlip3D:
+
+class TestRandomHorizontalFlip3D(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
@@ -60,10 +59,10 @@ class TestRandomHorizontalFlip3D:
[[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]], device=device
) # 1 x 4 x 4
- assert_close(f(input_tensor), expected)
- assert_close(f.transform_matrix, expected_transform)
- assert_close(f1(input_tensor), input_tensor)
- assert_close(f1.transform_matrix, identity)
+ self.assert_close(f(input_tensor), expected)
+ self.assert_close(f.transform_matrix, expected_transform)
+ self.assert_close(f1(input_tensor), input_tensor)
+ self.assert_close(f1.transform_matrix, identity)
def test_batch_random_hflip(self, device):
f = RandomHorizontalFlip3D(p=1.0)
@@ -89,14 +88,14 @@ class TestRandomHorizontalFlip3D:
expected_transform = expected_transform.repeat(5, 1, 1) # 5 x 4 x 4
identity = identity.repeat(5, 1, 1) # 5 x 4 x 4
- assert_close(f(input_tensor), expected)
- assert_close(f.transform_matrix, expected_transform)
+ self.assert_close(f(input_tensor), expected)
+ self.assert_close(f.transform_matrix, expected_transform)
def test_same_on_batch(self, device):
f = RandomHorizontalFlip3D(p=0.5, same_on_batch=True)
input_tensor = torch.eye(3, device=device).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1, 1)
res = f(input_tensor)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def test_sequential(self, device):
f = AugmentationSequential(RandomHorizontalFlip3D(p=1.0), RandomHorizontalFlip3D(p=1.0))
@@ -112,16 +111,15 @@ class TestRandomHorizontalFlip3D:
expected_transform_1 = expected_transform @ expected_transform
expected_transform_1 = expected_transform_1.to(device)
- assert_close(f(input_tensor), input_tensor)
- assert_close(f.transform_matrix, expected_transform_1)
+ self.assert_close(f(input_tensor), input_tensor)
+ self.assert_close(f.transform_matrix, expected_transform_1)
def test_gradcheck(self, device):
input_tensor = torch.rand((1, 3, 3)).to(device) # 3 x 3
- input_tensor = utils.tensor_to_gradcheck_var(input_tensor) # to var
- assert gradcheck(RandomHorizontalFlip3D(p=1.0), (input_tensor,), raise_exception=True, fast_mode=True)
+ self.gradcheck(RandomHorizontalFlip3D(p=1.0), (input_tensor,))
-class TestRandomVerticalFlip3D:
+class TestRandomVerticalFlip3D(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
@@ -172,10 +170,10 @@ class TestRandomVerticalFlip3D:
dtype=dtype,
) # 1 x 4 x 4
- assert_close(f(input_tensor), expected)
- assert_close(f.transform_matrix, expected_transform)
- assert_close(f1(input_tensor), input_tensor)
- assert_close(f1.transform_matrix, identity)
+ self.assert_close(f(input_tensor), expected)
+ self.assert_close(f.transform_matrix, expected_transform)
+ self.assert_close(f1(input_tensor), input_tensor)
+ self.assert_close(f1.transform_matrix, identity)
def test_batch_random_vflip(self, device):
f = RandomVerticalFlip3D(p=1.0)
@@ -202,16 +200,16 @@ class TestRandomVerticalFlip3D:
expected_transform = expected_transform.repeat(5, 1, 1) # 5 x 4 x 4
identity = identity.repeat(5, 1, 1) # 5 x 4 x 4
- assert_close(f(input_tensor), expected)
- assert_close(f.transform_matrix, expected_transform)
- assert_close(f1(input_tensor), input_tensor)
- assert_close(f1.transform_matrix, identity)
+ self.assert_close(f(input_tensor), expected)
+ self.assert_close(f.transform_matrix, expected_transform)
+ self.assert_close(f1(input_tensor), input_tensor)
+ self.assert_close(f1.transform_matrix, identity)
def test_same_on_batch(self, device):
f = RandomVerticalFlip3D(p=0.5, same_on_batch=True)
input_tensor = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1, 1)
res = f(input_tensor)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def test_sequential(self, device):
f = AugmentationSequential(RandomVerticalFlip3D(p=1.0), RandomVerticalFlip3D(p=1.0))
@@ -226,16 +224,15 @@ class TestRandomVerticalFlip3D:
expected_transform_1 = expected_transform @ expected_transform
- assert_close(f(input_tensor), input_tensor)
- assert_close(f.transform_matrix, expected_transform_1)
+ self.assert_close(f(input_tensor), input_tensor)
+ self.assert_close(f.transform_matrix, expected_transform_1)
def test_gradcheck(self, device):
input_tensor = torch.rand((1, 3, 3)).to(device) # 4 x 4
- input_tensor = utils.tensor_to_gradcheck_var(input_tensor) # to var
- assert gradcheck(RandomVerticalFlip3D(p=1.0), (input_tensor,), raise_exception=True, fast_mode=True)
+ self.gradcheck(RandomVerticalFlip3D(p=1.0), (input_tensor,))
-class TestRandomDepthicalFlip3D:
+class TestRandomDepthicalFlip3D(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
@@ -286,10 +283,10 @@ class TestRandomDepthicalFlip3D:
dtype=dtype,
) # 4 x 4
- assert_close(f(input_tensor), expected)
- assert_close(f.transform_matrix, expected_transform)
- assert_close(f1(input_tensor), input_tensor)
- assert_close(f1.transform_matrix, identity)
+ self.assert_close(f(input_tensor), expected)
+ self.assert_close(f.transform_matrix, expected_transform)
+ self.assert_close(f1(input_tensor), input_tensor)
+ self.assert_close(f1.transform_matrix, identity)
def test_batch_random_dflip(self, device):
f = RandomDepthicalFlip3D(p=1.0)
@@ -327,16 +324,16 @@ class TestRandomDepthicalFlip3D:
expected_transform = expected_transform.repeat(5, 1, 1) # 5 x 4 x 4
identity = identity.repeat(5, 1, 1) # 5 x 4 x 4
- assert_close(f(input_tensor), expected)
- assert_close(f.transform_matrix, expected_transform)
- assert_close(f1(input_tensor), input_tensor)
- assert_close(f1.transform_matrix, identity)
+ self.assert_close(f(input_tensor), expected)
+ self.assert_close(f.transform_matrix, expected_transform)
+ self.assert_close(f1(input_tensor), input_tensor)
+ self.assert_close(f1.transform_matrix, identity)
def test_same_on_batch(self, device):
f = RandomDepthicalFlip3D(p=0.5, same_on_batch=True)
input_tensor = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 2, 1, 1)
res = f(input_tensor)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def test_sequential(self, device):
f = AugmentationSequential(RandomDepthicalFlip3D(p=1.0), RandomDepthicalFlip3D(p=1.0))
@@ -360,16 +357,15 @@ class TestRandomDepthicalFlip3D:
expected_transform_1 = expected_transform @ expected_transform
- assert_close(f(input_tensor), input_tensor)
- assert_close(f.transform_matrix, expected_transform_1)
+ self.assert_close(f(input_tensor), input_tensor)
+ self.assert_close(f.transform_matrix, expected_transform_1)
def test_gradcheck(self, device):
input_tensor = torch.rand((1, 3, 3)).to(device) # 4 x 4
- input_tensor = utils.tensor_to_gradcheck_var(input_tensor) # to var
- assert gradcheck(RandomDepthicalFlip3D(p=1.0), (input_tensor,), raise_exception=True, fast_mode=True)
+ self.gradcheck(RandomDepthicalFlip3D(p=1.0), (input_tensor,))
-class TestRandomRotation3D:
+class TestRandomRotation3D(BaseTester):
torch.manual_seed(0) # for random reproductibility
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
@@ -444,8 +440,8 @@ class TestRandomRotation3D:
)
out = f(input_tensor)
- assert_close(out, expected, rtol=1e-6, atol=1e-4)
- assert_close(f.transform_matrix, expected_transform, rtol=1e-6, atol=1e-4)
+ self.assert_close(out, expected, rtol=1e-6, atol=1e-4)
+ self.assert_close(f.transform_matrix, expected_transform, rtol=1e-6, atol=1e-4)
def test_batch_random_rotation(self, device, dtype):
torch.manual_seed(24) # for random reproductibility
@@ -537,14 +533,14 @@ class TestRandomRotation3D:
input_tensor = input_tensor.repeat(2, 1, 1, 1, 1) # 5 x 4 x 4 x 3
out = f(input_tensor)
- assert_close(out, expected, rtol=1e-6, atol=1e-4)
- assert_close(f.transform_matrix, expected_transform, rtol=1e-6, atol=1e-4)
+ self.assert_close(out, expected, rtol=1e-6, atol=1e-4)
+ self.assert_close(f.transform_matrix, expected_transform, rtol=1e-6, atol=1e-4)
def test_same_on_batch(self, device, dtype):
f = RandomRotation3D(degrees=40, same_on_batch=True)
input_tensor = torch.eye(6, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 6, 1, 1)
res = f(input_tensor)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def test_sequential(self, device, dtype):
torch.manual_seed(24) # for random reproductibility
@@ -603,20 +599,17 @@ class TestRandomRotation3D:
)
out = f(input_tensor)
- assert_close(out, expected, rtol=1e-6, atol=1e-4)
- assert_close(f.transform_matrix, expected_transform, rtol=1e-6, atol=1e-4)
+ self.assert_close(out, expected, rtol=1e-6, atol=1e-4)
+ self.assert_close(f.transform_matrix, expected_transform, rtol=1e-6, atol=1e-4)
def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- input_tensor = torch.rand((3, 3, 3)).to(device) # 3 x 3 x 3
- input_tensor = utils.tensor_to_gradcheck_var(input_tensor) # to var
- assert gradcheck(
- RandomRotation3D(degrees=(15.0, 15.0), p=1.0), (input_tensor,), raise_exception=True, fast_mode=True
- )
+ input_tensor = torch.rand((3, 3, 3), device=device, dtype=torch.float64) # 3 x 3 x 3
+ self.gradcheck(RandomRotation3D(degrees=(15.0, 15.0), p=1.0), (input_tensor,))
-class TestRandomCrop3D:
+class TestRandomCrop3D(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
@@ -691,7 +684,7 @@ class TestRandomCrop3D:
dtype=dtype,
)
- assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
def test_same_on_batch(self, device, dtype):
f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1.0, same_on_batch=True)
@@ -703,7 +696,7 @@ class TestRandomCrop3D:
.repeat(2, 3, 5, 1, 1)
)
res = f(input_tensor)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
@pytest.mark.parametrize("padding", [1, (1, 1, 1), (1, 1, 1, 1, 1, 1)])
def test_padding_batch(self, padding, device, dtype):
@@ -733,7 +726,7 @@ class TestRandomCrop3D:
f = RandomCrop3D(size=(2, 3, 4), fill=10.0, padding=padding, align_corners=True, p=1.0)
out = f(input_tensor)
- assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
def test_pad_if_needed(self, device, dtype):
torch.manual_seed(42)
@@ -753,13 +746,12 @@ class TestRandomCrop3D:
rc = RandomCrop3D(size=(2, 3, 4), pad_if_needed=True, fill=9, align_corners=True, p=1.0)
out = rc(input_tensor)
- assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- input_tensor = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3
- input_tensor = utils.tensor_to_gradcheck_var(input_tensor) # to var
- assert gradcheck(RandomCrop3D(size=(3, 3, 3), p=1.0), (input_tensor,), raise_exception=True, fast_mode=True)
+ input_tensor = torch.rand((3, 3, 3), device=device, dtype=torch.float64) # 3 x 3
+ self.gradcheck(RandomCrop3D(size=(3, 3, 3), p=1.0), (input_tensor,))
@pytest.mark.skip("Need to fix Union type")
def test_jit(self, device, dtype):
@@ -770,7 +762,7 @@ class TestRandomCrop3D:
actual = op_script(img)
expected = kornia.geometry.transform.center_crop3d(img)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
@pytest.mark.skip("Need to fix Union type")
def test_jit_trace(self, device, dtype):
@@ -788,10 +780,10 @@ class TestRandomCrop3D:
# 3. Evaluate
actual = op_trace(img)
expected = op(img)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestCenterCrop3D:
+class TestCenterCrop3D(BaseTester):
def test_no_transform(self, device, dtype):
inp = torch.rand(1, 2, 4, 4, 4, device=device, dtype=dtype)
out = CenterCrop3D(2)(inp)
@@ -809,13 +801,12 @@ class TestCenterCrop3D:
out = CenterCrop3D((3, 4, 5))(inp)
assert out.shape == (1, 2, 3, 4, 5)
- def test_gradcheck(self, device, dtype):
- input_tensor = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
- input_tensor = utils.tensor_to_gradcheck_var(input_tensor) # to var
- assert gradcheck(CenterCrop3D(3), (input_tensor,), raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, device):
+ input_tensor = torch.rand(1, 2, 3, 4, 5, device=device, dtype=torch.float64)
+ self.gradcheck(CenterCrop3D(3), (input_tensor,))
-class TestRandomEqualize3D:
+class TestRandomEqualize3D(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
@@ -841,10 +832,10 @@ class TestRandomEqualize3D:
identity = kornia.eye_like(4, expected)
- assert_close(f(inputs3d), expected, rtol=1e-4, atol=1e-4)
- assert_close(f.transform_matrix, identity, rtol=1e-4, atol=1e-4)
- assert_close(f1(inputs3d), inputs3d, rtol=1e-4, atol=1e-4)
- assert_close(f1.transform_matrix, identity, rtol=1e-4, atol=1e-4)
+ self.assert_close(f(inputs3d), expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(f.transform_matrix, identity, rtol=1e-4, atol=1e-4)
+ self.assert_close(f1(inputs3d), inputs3d, rtol=1e-4, atol=1e-4)
+ self.assert_close(f1.transform_matrix, identity, rtol=1e-4, atol=1e-4)
def test_batch_random_equalize(self, device, dtype):
f = RandomEqualize3D(p=1.0)
@@ -859,24 +850,23 @@ class TestRandomEqualize3D:
identity = kornia.eye_like(4, expected) # 2 x 4 x 4
- assert_close(f(inputs3d), expected, rtol=1e-4, atol=1e-4)
- assert_close(f.transform_matrix, identity, rtol=1e-4, atol=1e-4)
- assert_close(f1(inputs3d), inputs3d, rtol=1e-4, atol=1e-4)
- assert_close(f1.transform_matrix, identity, rtol=1e-4, atol=1e-4)
+ self.assert_close(f(inputs3d), expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(f.transform_matrix, identity, rtol=1e-4, atol=1e-4)
+ self.assert_close(f1(inputs3d), inputs3d, rtol=1e-4, atol=1e-4)
+ self.assert_close(f1.transform_matrix, identity, rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
f = RandomEqualize3D(p=0.5, same_on_batch=True)
input_tensor = torch.eye(4, device=device, dtype=dtype)
input_tensor = input_tensor.unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 2, 1, 1)
res = f(input_tensor)
- assert_close(res[0], res[1])
+ self.assert_close(res[0], res[1])
def test_gradcheck(self, device, dtype):
torch.manual_seed(0) # for random reproductibility
inputs3d = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
- inputs3d = utils.tensor_to_gradcheck_var(inputs3d) # to var
- assert gradcheck(RandomEqualize3D(p=0.5), (inputs3d,), raise_exception=True, fast_mode=True)
+ self.gradcheck(RandomEqualize3D(p=0.5), (inputs3d,))
@staticmethod
def build_input(channels, depth, height, width, bs=1, row=None, device="cpu", dtype=torch.float32):
@@ -891,7 +881,7 @@ class TestRandomEqualize3D:
return batch.to(device, dtype)
-class TestRandomAffine3D:
+class TestRandomAffine3D(BaseTester):
def test_batch_random_affine_3d(self, device, dtype):
# TODO(jian): cuda and fp64
if "cuda" in str(device) and dtype == torch.float64:
@@ -916,5 +906,5 @@ class TestRandomAffine3D:
expected = expected.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3
expected_transform = expected_transform.repeat(5, 1, 1) # 5 x 4 x 4
- assert_close(f(tensor), expected)
- assert_close(f.transform_matrix, expected_transform)
+ self.assert_close(f(tensor), expected)
+ self.assert_close(f.transform_matrix, expected_transform)
diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.py
index 2e76f5721..3bb657336 100644
--- a/tests/augmentation/test_augmentation_mix.py
+++ b/tests/augmentation/test_augmentation_mix.py
@@ -12,10 +12,11 @@ from kornia.augmentation import (
RandomTransplantation,
RandomTransplantation3D,
)
-from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
+from testing.base import BaseTester
-class TestRandomMixUpV2:
+
+class TestRandomMixUpV2(BaseTester):
def test_smoke(self, device, dtype):
f = RandomMixUpV2()
repr = "RandomMixUpV2(lambda_val=None, p=1.0, p_batch=1.0, same_on_batch=False)"
@@ -40,10 +41,10 @@ class TestRandomMixUpV2:
out_image, out_label = f(input, label)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_label[:, 0], label)
- assert_close(out_label[:, 1], torch.tensor([0, 1], device=device, dtype=dtype))
- assert_close(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label[:, 0], label)
+ self.assert_close(out_label[:, 1], torch.tensor([0, 1], device=device, dtype=dtype))
+ self.assert_close(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)
def test_random_mixup_p0(self, device, dtype):
torch.manual_seed(0)
@@ -59,8 +60,8 @@ class TestRandomMixUpV2:
out_image, out_label = f(input, label)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)
def test_random_mixup_lam0(self, device, dtype):
torch.manual_seed(0)
@@ -76,10 +77,10 @@ class TestRandomMixUpV2:
out_image, out_label = f(input, label)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_label[:, 0], label)
- assert_close(out_label[:, 1], torch.tensor([0, 1], device=device, dtype=dtype))
- assert_close(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label[:, 0], label)
+ self.assert_close(out_label[:, 1], torch.tensor([0, 1], device=device, dtype=dtype))
+ self.assert_close(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)
def test_random_mixup_same_on_batch(self, device, dtype):
torch.manual_seed(0)
@@ -99,13 +100,13 @@ class TestRandomMixUpV2:
)
out_image, out_label = f(input, label)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_label[:, 0], label)
- assert_close(out_label[:, 1], torch.tensor([0, 1], device=device, dtype=dtype))
- assert_close(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label[:, 0], label)
+ self.assert_close(out_label[:, 1], torch.tensor([0, 1], device=device, dtype=dtype))
+ self.assert_close(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)
-class TestRandomCutMixV2:
+class TestRandomCutMixV2(BaseTester):
def test_smoke(self):
f = RandomCutMixV2(data_keys=["input", "class"])
repr = "RandomCutMixV2(cut_size=None, beta=None, num_mix=1, p=1.0, p_batch=1.0, same_on_batch=False)"
@@ -131,10 +132,10 @@ class TestRandomCutMixV2:
out_image, out_label = f(input, label)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_label[0, :, 0], label)
- assert_close(out_label[0, :, 1], torch.tensor([0, 1], device=device, dtype=dtype))
- assert_close(out_label[0, :, 2], torch.tensor([0.5, 0.5], device=device, dtype=dtype))
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label[0, :, 0], label)
+ self.assert_close(out_label[0, :, 1], torch.tensor([0, 1], device=device, dtype=dtype))
+ self.assert_close(out_label[0, :, 2], torch.tensor([0.5, 0.5], device=device, dtype=dtype))
def test_random_mixup_p0(self, device, dtype):
torch.manual_seed(76)
@@ -150,8 +151,8 @@ class TestRandomCutMixV2:
out_image, out_label = f(input, label)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_label, exp_label)
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label, exp_label)
def test_random_mixup_beta0(self, device, dtype):
torch.manual_seed(76)
@@ -175,11 +176,11 @@ class TestRandomCutMixV2:
out_image, out_label = f(input, label)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_label[0, :, 0], label)
- assert_close(out_label[0, :, 1], torch.tensor([0, 1], device=device, dtype=dtype))
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label[0, :, 0], label)
+ self.assert_close(out_label[0, :, 1], torch.tensor([0, 1], device=device, dtype=dtype))
# cut area = 4 / 12
- assert_close(out_label[0, :, 2], torch.tensor([0.33333, 0.33333], device=device, dtype=dtype))
+ self.assert_close(out_label[0, :, 2], torch.tensor([0.33333, 0.33333], device=device, dtype=dtype))
def test_random_mixup_num2(self, device, dtype):
torch.manual_seed(76)
@@ -201,12 +202,12 @@ class TestRandomCutMixV2:
out_image, out_label = f(input, label)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_label[:, :, 0], label.view(1, -1).expand(5, 2))
- assert_close(
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label[:, :, 0], label.view(1, -1).expand(5, 2))
+ self.assert_close(
out_label[:, :, 1], torch.tensor([[1, 0], [1, 0], [1, 0], [1, 0], [0, 1]], device=device, dtype=dtype)
)
- assert_close(
+ self.assert_close(
out_label[:, :, 2],
torch.tensor(
[[0.0833, 0.3333], [0.0, 0.1667], [0.5, 0.0833], [0.0833, 0.0], [0.5, 0.3333]],
@@ -237,15 +238,15 @@ class TestRandomCutMixV2:
out_image, out_label = f(input, label)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_label[0, :, 0], label)
- assert_close(out_label[0, :, 1], torch.tensor([0, 1], device=device, dtype=dtype))
- assert_close(
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label[0, :, 0], label)
+ self.assert_close(out_label[0, :, 1], torch.tensor([0, 1], device=device, dtype=dtype))
+ self.assert_close(
out_label[0, :, 2], torch.tensor([0.5000, 0.5000], device=device, dtype=dtype), rtol=1e-4, atol=1e-4
)
-class TestRandomMosaic:
+class TestRandomMosaic(BaseTester):
def test_smoke(self):
f = RandomMosaic(data_keys=["input", "class"])
repr = (
@@ -324,8 +325,8 @@ class TestRandomMosaic:
dtype=dtype,
)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- assert_close(out_box, expected_box, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_box, expected_box, rtol=1e-4, atol=1e-4)
@pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
def test_p(self, p, device, dtype):
@@ -347,7 +348,7 @@ class TestRandomMosaic:
f(input, boxes)
-class TestRandomJigsaw:
+class TestRandomJigsaw(BaseTester):
def test_smoke(self, device, dtype):
f = RandomJigsaw(data_keys=["input"])
repr = "RandomJigsaw(grid=(4, 4), p=0.5, p_batch=1.0, same_on_batch=False, grid=(4, 4))"
@@ -386,7 +387,7 @@ class TestRandomJigsaw:
dtype=dtype,
)
- assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
@pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
@pytest.mark.parametrize("same_on_batch", [True, False])
@@ -566,10 +567,7 @@ class TestRandomTransplantation(BaseTester):
image = torch.rand(1, 3, 2, 2, device=device, dtype=torch.float64)
mask = torch.randint(0, 2, (1, 2, 2), device=device, dtype=torch.float64)
- image = tensor_to_gradcheck_var(image) # to var
- mask = tensor_to_gradcheck_var(mask) # to var
-
- assert self.gradcheck(RandomTransplantation(p=1.0), (image, mask), raise_exception=True, fast_mode=True)
+ self.gradcheck(RandomTransplantation(p=1.0), (image, mask))
def test_exception(self, device, dtype):
torch.manual_seed(22)
diff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.py
index 2635193a8..25411e59b 100644
--- a/tests/augmentation/test_auto_operation.py
+++ b/tests/augmentation/test_auto_operation.py
@@ -11,8 +11,10 @@ from kornia.augmentation.auto.rand_augment.rand_augment import default_policy as
from kornia.augmentation.auto.trivial_augment import TrivialAugment
from kornia.augmentation.container import AugmentationSequential
from kornia.geometry.bbox import bbox_to_mask
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version
+
+from testing.base import BaseTester
+
from tests.augmentation.test_container import reproducibility_test
@@ -73,7 +75,7 @@ class TestOperations:
assert init_prob != op.probability.item()
-class TestAutoAugment:
+class TestAutoAugment(BaseTester):
@pytest.mark.parametrize("policy", ["imagenet", "cifar10", "svhn", [[("shear_x", 0.9, 4), ("invert", 0.2, None)]]])
def test_smoke(self, policy, device, dtype):
aug = AutoAugment(policy)
@@ -86,20 +88,20 @@ class TestAutoAugment:
in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
aug(in_tensor)
trans = aug.get_transformation_matrix(in_tensor, params=aug._params)
- assert_close(trans, aug.transform_matrix)
+ self.assert_close(trans, aug.transform_matrix)
def test_reproduce(self, device, dtype):
aug = AutoAugment()
in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
out_tensor = aug(in_tensor)
out_tensor_2 = aug(in_tensor, params=aug._params)
- assert_close(out_tensor, out_tensor_2)
+ self.assert_close(out_tensor, out_tensor_2)
def test_sequential(augment_method, device, dtype):
_test_sequential(AutoAugment(), device=device, dtype=dtype)
-class TestRandAugment:
+class TestRandAugment(BaseTester):
@pytest.mark.parametrize("policy", [None, [[("translate_y", -0.5, 0.5)]]])
def test_smoke(self, policy):
if policy is None:
@@ -119,20 +121,20 @@ class TestRandAugment:
in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
aug(in_tensor)
trans = aug.get_transformation_matrix(in_tensor, params=aug._params)
- assert_close(trans, aug.transform_matrix)
+ self.assert_close(trans, aug.transform_matrix)
def test_reproduce(self, device, dtype):
aug = RandAugment(n=3, m=15)
in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
out_tensor = aug(in_tensor)
out_tensor_2 = aug(in_tensor, params=aug._params)
- assert_close(out_tensor, out_tensor_2)
+ self.assert_close(out_tensor, out_tensor_2)
def test_sequential(augment_method, device, dtype):
_test_sequential(RandAugment(n=3, m=15), device=device, dtype=dtype)
-class TestTrivialAugment:
+class TestTrivialAugment(BaseTester):
@pytest.mark.parametrize("policy", [None, [[("translate_y", -0.5, 0.5)]]])
def test_smoke(self, policy):
aug = TrivialAugment(policy=policy)
@@ -145,14 +147,14 @@ class TestTrivialAugment:
aug(in_tensor)
aug(in_tensor)
trans = aug.get_transformation_matrix(in_tensor, params=aug._params)
- assert_close(trans, aug.transform_matrix)
+ self.assert_close(trans, aug.transform_matrix)
def test_reproduce(self, device, dtype):
aug = TrivialAugment()
in_tensor = torch.rand(10, 3, 50, 50, device=device, dtype=dtype, requires_grad=True)
out_tensor = aug(in_tensor)
out_tensor_2 = aug(in_tensor, params=aug._params)
- assert_close(out_tensor, out_tensor_2)
+ self.assert_close(out_tensor, out_tensor_2)
def test_sequential(augment_method, device, dtype):
_test_sequential(TrivialAugment(), device=device, dtype=dtype)
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 276fcedba..385db7e49 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -2,19 +2,18 @@ from unittest.mock import patch
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.augmentation._2d.geometric.affine import RandomAffine
from kornia.augmentation._2d.intensity.gaussian_blur import RandomGaussianBlur
from kornia.augmentation._3d.geometric.affine import RandomAffine3D
from kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3D
from kornia.augmentation.base import _BasicAugmentationBase
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestBasicAugmentationBase:
+
+class TestBasicAugmentationBase(BaseTester):
def test_smoke(self):
base = _BasicAugmentationBase(p=0.5, p_batch=1.0, same_on_batch=True)
__repr__ = "_BasicAugmentationBase(p=0.5, p_batch=1.0, same_on_batch=True)"
@@ -27,7 +26,7 @@ class TestBasicAugmentationBase:
transform_tensor.side_effect = lambda x: x.unsqueeze(dim=2)
output = augmentation.transform_tensor(input)
assert output.shape == torch.Size([2, 3, 1, 4, 5])
- assert_close(input, output[:, :, 0, :, :])
+ self.assert_close(input, output[:, :, 0, :, :])
@pytest.mark.parametrize(
"p,p_batch,same_on_batch,num,seed",
@@ -76,10 +75,10 @@ class TestBasicAugmentationBase:
# check_batching.side_effect = lambda input: None
output = augmentation(input)
assert output.shape == expected_output.shape
- assert_close(output, expected_output)
+ self.assert_close(output, expected_output)
-class TestAugmentationBase2D:
+class TestAugmentationBase2D(BaseTester):
def test_forward(self, device, dtype):
torch.manual_seed(42)
input = torch.rand((2, 3, 4, 5), device=device, dtype=dtype)
@@ -124,18 +123,12 @@ class TestAugmentationBase2D:
# output = augmentation((input, input_transform))
# assert output is expected_output
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(42)
- input = torch.rand((1, 1, 3, 3), device=device, dtype=dtype)
- output = torch.rand((1, 1, 3, 3), device=device, dtype=dtype)
- input_transform = torch.rand((1, 3, 3), device=device, dtype=dtype)
- other_transform = torch.rand((1, 3, 3), device=device, dtype=dtype)
-
- input = utils.tensor_to_gradcheck_var(input) # to var
- input_transform = utils.tensor_to_gradcheck_var(input_transform) # to var
- output = utils.tensor_to_gradcheck_var(output) # to var
- other_transform = utils.tensor_to_gradcheck_var(other_transform) # to var
+ input = torch.rand((1, 1, 3, 3), device=device, dtype=torch.float64)
+ output = torch.rand((1, 1, 3, 3), device=device, dtype=torch.float64)
+ input_transform = torch.rand((1, 3, 3), device=device, dtype=torch.float64)
input_param = {"batch_prob": torch.tensor([True]), "x": input_transform, "y": {}}
@@ -143,7 +136,7 @@ class TestAugmentationBase2D:
with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform:
apply_transform.return_value = output
- assert gradcheck(augmentation, ((input, input_param)), raise_exception=True, fast_mode=True)
+ self.gradcheck(augmentation, ((input, input_param)))
class TestGeometricAugmentationBase2D:
diff --git a/tests/augmentation/test_container.py b/tests/augmentation/test_container.py
index 7a97c647c..9c6480786 100644
--- a/tests/augmentation/test_container.py
+++ b/tests/augmentation/test_container.py
@@ -9,7 +9,8 @@ import kornia.augmentation as K
from kornia.augmentation.container.base import ParamItem
from kornia.constants import BorderType
from kornia.geometry.bbox import bbox_to_mask
-from kornia.testing import assert_close
+
+from testing.base import assert_close
def reproducibility_test(input, seq):
diff --git a/tests/augmentation/test_dist_mapper.py b/tests/augmentation/test_dist_mapper.py
index a7b13107b..b255c8e01 100644
--- a/tests/augmentation/test_dist_mapper.py
+++ b/tests/augmentation/test_dist_mapper.py
@@ -3,7 +3,8 @@ from torch import nn
from torch.distributions import Normal
from kornia.augmentation.random_generator import DistributionWithMapper
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestDistMapper:
diff --git a/tests/augmentation/test_motionblur.py b/tests/augmentation/test_motionblur.py
index 004325710..da0ea3156 100644
--- a/tests/augmentation/test_motionblur.py
+++ b/tests/augmentation/test_motionblur.py
@@ -1,14 +1,13 @@
import pytest
import torch
-from torch.autograd import gradcheck
from kornia.augmentation import RandomMotionBlur, RandomMotionBlur3D
from kornia.filters import motion_blur, motion_blur3d
-from kornia.testing import assert_close, tensor_to_gradcheck_var
+from testing.base import BaseTester
-# TODO: add kornia.testing.BaseTester
-class TestRandomMotionBlur:
+
+class TestRandomMotionBlur(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
@@ -32,9 +31,9 @@ class TestRandomMotionBlur:
output = f(input)
if same_on_batch:
- assert_close(output[0], output[1], rtol=1e-4, atol=1e-4)
+ self.assert_close(output[0], output[1], rtol=1e-4, atol=1e-4)
elif p == 0:
- assert_close(output, input, rtol=1e-4, atol=1e-4)
+ self.assert_close(output, input, rtol=1e-4, atol=1e-4)
else:
assert not torch.allclose(output[0], output[1], rtol=1e-4, atol=1e-4)
@@ -55,13 +54,12 @@ class TestRandomMotionBlur:
f.flags["border_type"].name.lower(),
)
- assert_close(output, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(output, expected, rtol=1e-4, atol=1e-4)
@pytest.mark.slow
def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- inp = torch.rand((1, 3, 11, 7)).to(device)
- inp = tensor_to_gradcheck_var(inp) # to var
+ inp = torch.rand((1, 3, 11, 7), device=device, dtype=torch.float64)
# TODO: Gradcheck for param random gen failed. Suspect get_motion_kernel2d issue.
params = {
"batch_prob": torch.tensor([True]),
@@ -71,15 +69,14 @@ class TestRandomMotionBlur:
"border_type": torch.tensor([0]),
"idx": torch.tensor([0]),
}
- assert gradcheck(
+ self.gradcheck(
RandomMotionBlur(kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0),
(inp, params),
- raise_exception=True,
+ fast_mode=False,
)
-# TODO: add kornia.testing.BaseTester
-class TestRandomMotionBlur3D:
+class TestRandomMotionBlur3D(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
@@ -102,9 +99,9 @@ class TestRandomMotionBlur3D:
output = f(input)
if same_on_batch:
- assert_close(output[0], output[1], rtol=1e-4, atol=1e-4)
+ self.assert_close(output[0], output[1], rtol=1e-4, atol=1e-4)
elif p == 0:
- assert_close(output, input, rtol=1e-4, atol=1e-4)
+ self.assert_close(output, input, rtol=1e-4, atol=1e-4)
else:
assert not torch.allclose(output[0], output[1], rtol=1e-4, atol=1e-4)
@@ -125,13 +122,12 @@ class TestRandomMotionBlur3D:
f.flags["border_type"].name.lower(),
)
- assert_close(output, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(output, expected, rtol=1e-4, atol=1e-4)
@pytest.mark.slow
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
- inp = torch.rand((1, 3, 6, 7), device=device, dtype=dtype)
- inp = tensor_to_gradcheck_var(inp) # to var
+ inp = torch.rand((1, 3, 6, 7), device=device, dtype=torch.float64)
params = {
"batch_prob": torch.tensor([True]),
"ksize_factor": torch.tensor([31]),
@@ -140,8 +136,8 @@ class TestRandomMotionBlur3D:
"border_type": torch.tensor([0]),
"idx": torch.tensor([0]),
}
- assert gradcheck(
+ self.gradcheck(
RandomMotionBlur3D(kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0),
(inp, params),
- raise_exception=True,
+ fast_mode=False,
)
diff --git a/tests/augmentation/test_perspective_rand.py b/tests/augmentation/test_perspective_rand.py
index 3a7fde800..afdf307c8 100644
--- a/tests/augmentation/test_perspective_rand.py
+++ b/tests/augmentation/test_perspective_rand.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestRandomPerspective:
+
+class TestRandomPerspective(BaseTester):
torch.manual_seed(0) # for random reproductibility
def test_smoke_no_transform_float(self, device):
@@ -80,8 +79,8 @@ class TestRandomPerspective:
out_perspective = aug(x_data)
assert out_perspective.shape == x_data.shape
assert aug.transform_matrix.shape == (1, 3, 3)
- assert_close(out_perspective, x_data)
- assert_close(aug.transform_matrix, torch.eye(3, device=device, dtype=dtype)[None])
+ self.assert_close(out_perspective, x_data)
+ self.assert_close(aug.transform_matrix, torch.eye(3, device=device, dtype=dtype)[None])
assert aug.inverse(out_perspective).shape == x_data.shape
def test_transform_module_should_return_expected_transform(self, device, dtype):
@@ -123,23 +122,20 @@ class TestRandomPerspective:
assert out_perspective.shape == x_data.shape
assert aug.transform_matrix.shape == (1, 3, 3)
- assert_close(out_perspective, expected_output, atol=1e-4, rtol=1e-4)
- assert_close(aug.transform_matrix, expected_transform, atol=1e-4, rtol=1e-4)
+ self.assert_close(out_perspective, expected_output, atol=1e-4, rtol=1e-4)
+ self.assert_close(aug.transform_matrix, expected_transform, atol=1e-4, rtol=1e-4)
assert aug.inverse(out_perspective).shape == x_data.shape
def test_gradcheck(self, device, dtype):
- input = torch.rand(1, 2, 5, 7, dtype=dtype).to(device)
- input = utils.tensor_to_gradcheck_var(input) # to var
+ input = torch.rand(1, 2, 5, 7, dtype=torch.float64, device=device)
# TODO: turned off with p=0
- assert gradcheck(
+ self.gradcheck(
kornia.augmentation.RandomPerspective(torch.tensor(0.5, device=device, dtype=dtype), p=0.0),
(input,),
- raise_exception=True,
- fast_mode=True,
)
-class TestRandomAffine:
+class TestRandomAffine(BaseTester):
torch.manual_seed(0) # for random reproductibility
def test_smoke_no_transform(self, device):
@@ -192,13 +188,12 @@ class TestRandomAffine:
assert aug.inverse(out).shape == x_data.shape
def test_gradcheck(self, device):
- input = torch.rand(1, 2, 5, 7).to(device)
- input = utils.tensor_to_gradcheck_var(input) # to var
+ input = torch.rand(1, 2, 5, 7, device=device, dtype=torch.float64)
# TODO: turned off with p=0
- assert gradcheck(kornia.augmentation.RandomAffine(10, p=0.0), (input,), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.augmentation.RandomAffine(10, p=0.0), (input,))
-class TestRandomShear:
+class TestRandomShear(BaseTester):
torch.manual_seed(0) # for random reproductibility
def test_smoke_no_transform(self, device):
@@ -210,9 +205,6 @@ class TestRandomShear:
assert aug.inverse(out, aug._params).shape == x_data.shape
def test_gradcheck(self, device):
- input = torch.rand(1, 2, 5, 7).to(device)
- input = utils.tensor_to_gradcheck_var(input) # to var
+ input = torch.rand(1, 2, 5, 7, device=device, dtype=torch.float64)
# TODO: turned off with p=0
- assert gradcheck(
- kornia.augmentation.RandomShear((10.0, 10.0), p=1.0), (input,), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.augmentation.RandomShear((10.0, 10.0), p=1.0), (input,))
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index 451526c1e..2bd281d4b 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -18,9 +18,10 @@ from kornia.augmentation.random_generator import (
ResizedCropGenerator,
center_crop_generator,
)
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version_ge
+from testing.base import assert_close
+
class RandomGeneratorBaseTests:
def test_valid_param_combinations(self, device, dtype):
diff --git a/tests/augmentation/test_random_generator_3d.py b/tests/augmentation/test_random_generator_3d.py
index 013a5e8c0..1ea3eafbb 100644
--- a/tests/augmentation/test_random_generator_3d.py
+++ b/tests/augmentation/test_random_generator_3d.py
@@ -9,7 +9,8 @@ from kornia.augmentation.random_generator import (
RotationGenerator3D,
center_crop_generator3d,
)
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class RandomGeneratorBaseTests:
diff --git a/tests/color/test_colormap.py b/tests/color/test_colormap.py
index 5ec0d1872..28ab66ad4 100644
--- a/tests/color/test_colormap.py
+++ b/tests/color/test_colormap.py
@@ -1,10 +1,10 @@
import pytest
import torch
-from torch.autograd import gradcheck
from kornia.color import AUTUMN, ApplyColorMap, apply_colormap
from kornia.core import tensor
-from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
+
+from testing.base import BaseTester, assert_close
def test_autumn(device, dtype):
@@ -80,15 +80,12 @@ class TestApplyColorMap(BaseTester):
assert actual.shape == expected_shape
@pytest.mark.skip(reason="jacobian mismatch")
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# TODO: implement differentiability
- cm = AUTUMN(device=device, dtype=dtype)
- input_tensor = torch.randint(0, 63, (1, 2, 1), device=device, dtype=dtype)
-
- input_tensor = tensor_to_gradcheck_var(input_tensor)
- cm.colors = tensor_to_gradcheck_var(cm.colors)
+ cm = AUTUMN(device=device, dtype=torch.float64)
+ input_tensor = torch.randint(0, 63, (1, 2, 1), device=device, dtype=torch.float64)
- assert gradcheck(apply_colormap, (input_tensor, cm), raise_exception=True, fast_mode=True)
+ self.gradcheck(apply_colormap, (input_tensor, cm))
def test_dynamo(self, device, dtype, torch_optimizer):
op = apply_colormap
diff --git a/tests/color/test_gray.py b/tests/color/test_gray.py
index 75620ac9f..87f667257 100644
--- a/tests/color/test_gray.py
+++ b/tests/color/test_gray.py
@@ -3,9 +3,10 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester, assert_close
from kornia.utils._compat import torch_version
+from testing.base import BaseTester, assert_close
+
class TestGrayscaleToRgb(BaseTester):
def test_smoke(self, device, dtype):
diff --git a/tests/color/test_hls.py b/tests/color/test_hls.py
index 550eff5f1..5ca89b768 100644
--- a/tests/color/test_hls.py
+++ b/tests/color/test_hls.py
@@ -7,7 +7,8 @@ from packaging import version
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestRgbToHls(BaseTester):
diff --git a/tests/color/test_hsv.py b/tests/color/test_hsv.py
index 58d79e5e1..3af0562ee 100644
--- a/tests/color/test_hsv.py
+++ b/tests/color/test_hsv.py
@@ -5,7 +5,8 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestRgbToHsv(BaseTester):
diff --git a/tests/color/test_lab.py b/tests/color/test_lab.py
index bfda90acf..4292901b7 100644
--- a/tests/color/test_lab.py
+++ b/tests/color/test_lab.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestRgbToLab(BaseTester):
diff --git a/tests/color/test_luv.py b/tests/color/test_luv.py
index e55505222..47e95672c 100644
--- a/tests/color/test_luv.py
+++ b/tests/color/test_luv.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestRgbToLuv(BaseTester):
diff --git a/tests/color/test_raw.py b/tests/color/test_raw.py
index b61e3c504..782cead4d 100644
--- a/tests/color/test_raw.py
+++ b/tests/color/test_raw.py
@@ -6,7 +6,11 @@ from packaging import version
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester, assert_close # test utils
+
+from testing.base import (
+ BaseTester,
+ assert_close, # test utils
+)
class TestRawToRgb(BaseTester):
diff --git a/tests/color/test_rgb.py b/tests/color/test_rgb.py
index 05151b5a3..aa017b57b 100644
--- a/tests/color/test_rgb.py
+++ b/tests/color/test_rgb.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestRgbToBgr(BaseTester):
diff --git a/tests/color/test_sepia.py b/tests/color/test_sepia.py
index 3266e7aed..c411b6194 100644
--- a/tests/color/test_sepia.py
+++ b/tests/color/test_sepia.py
@@ -1,10 +1,9 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestSepia(BaseTester):
@@ -59,14 +58,13 @@ class TestSepia(BaseTester):
assert actual.is_contiguous()
self.assert_close(actual, actual)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
batch_shape = (1, 3, 5, 5)
# evaluate function gradient
- input_tensor = torch.rand(batch_shape, device=device, dtype=dtype)
- input_tensor = utils.tensor_to_gradcheck_var(input_tensor)
- assert gradcheck(kornia.color.sepia, (input_tensor,), raise_exception=True, fast_mode=True)
+ input_tensor = torch.rand(batch_shape, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.color.sepia, (input_tensor,))
def test_jit(self, device, dtype):
op = kornia.color.sepia
diff --git a/tests/color/test_xyz.py b/tests/color/test_xyz.py
index 733d5ad14..f85ce2b78 100644
--- a/tests/color/test_xyz.py
+++ b/tests/color/test_xyz.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestRgbToXyz(BaseTester):
diff --git a/tests/color/test_ycbcr.py b/tests/color/test_ycbcr.py
index c29199829..b60669e08 100644
--- a/tests/color/test_ycbcr.py
+++ b/tests/color/test_ycbcr.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestRgbToYcbcr(BaseTester):
diff --git a/tests/color/test_yuv.py b/tests/color/test_yuv.py
index 04de6af05..2e8b70feb 100644
--- a/tests/color/test_yuv.py
+++ b/tests/color/test_yuv.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestRgbToYuv(BaseTester):
diff --git a/tests/contrib/models/test_rt_detr.py b/tests/contrib/models/test_rt_detr.py
index 1ea683745..f5f3803c9 100644
--- a/tests/contrib/models/test_rt_detr.py
+++ b/tests/contrib/models/test_rt_detr.py
@@ -8,7 +8,8 @@ from kornia.contrib.models.rt_detr.architecture.hybrid_encoder import HybridEnco
from kornia.contrib.models.rt_detr.architecture.resnet_d import ResNetD
from kornia.contrib.models.rt_detr.architecture.rtdetr_head import RTDETRHead
from kornia.contrib.models.rt_detr.model import RTDETR, RTDETRConfig
-from kornia.testing import BaseTester, assert_close
+
+from testing.base import BaseTester, assert_close
@pytest.mark.parametrize(
diff --git a/tests/contrib/models/test_sam.py b/tests/contrib/models/test_sam.py
index adb0e58c4..dd3b8814d 100644
--- a/tests/contrib/models/test_sam.py
+++ b/tests/contrib/models/test_sam.py
@@ -3,7 +3,8 @@ import torch
from kornia.contrib.models.sam import Sam, SamConfig
from kornia.core import pad
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
def _pad_rb(x, size):
diff --git a/tests/contrib/models/test_tiny_vit.py b/tests/contrib/models/test_tiny_vit.py
index 59cb6f650..1be183ff0 100644
--- a/tests/contrib/models/test_tiny_vit.py
+++ b/tests/contrib/models/test_tiny_vit.py
@@ -3,7 +3,8 @@ import torch
from kornia.contrib.models.tiny_vit import TinyViT
from kornia.core import Tensor
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestTinyViT(BaseTester):
diff --git a/tests/contrib/test_contrib.py b/tests/contrib/test_contrib.py
index 12a5bd5af..e7e144136 100644
--- a/tests/contrib/test_contrib.py
+++ b/tests/contrib/test_contrib.py
@@ -3,17 +3,16 @@ from unittest.mock import PropertyMock, patch
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
from kornia.contrib.face_detection import FaceKeypoint
from kornia.contrib.models.rt_detr import RTDETR, DETRPostProcessor, RTDETRConfig
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version_lt
+from testing.base import BaseTester
-class TestDiamondSquare:
+
+class TestDiamondSquare(BaseTester):
def test_smoke(self, device, dtype):
torch.manual_seed(0)
output_size = (1, 1, 3, 4)
@@ -35,11 +34,11 @@ class TestDiamondSquare:
out = kornia.contrib.diamond_square(
output_size, roughness, random_scale, normalize_range=normalize_range, device=device, dtype=dtype
)
- assert_close(out.min(), expected_min)
- assert_close(out.max(), expected_max)
+ self.assert_close(out.min(), expected_min)
+ self.assert_close(out.max(), expected_max)
-class TestVisionTransformer:
+class TestVisionTransformer(BaseTester):
@pytest.mark.parametrize("B", [1, 2])
@pytest.mark.parametrize("H", [1, 3, 8])
@pytest.mark.parametrize("D", [240, 768])
@@ -78,7 +77,7 @@ class TestVisionTransformer:
assert out.shape == (1, 197, 128)
-class TestMobileViT:
+class TestMobileViT(BaseTester):
@pytest.mark.parametrize("B", [1, 2])
@pytest.mark.parametrize("image_size", [(256, 256)])
@pytest.mark.parametrize("mode", ["xxs", "xs", "s"])
@@ -95,7 +94,7 @@ class TestMobileViT:
assert out.shape == (B, channel[mode], 8, 8)
-class TestClassificationHead:
+class TestClassificationHead(BaseTester):
@pytest.mark.parametrize("B, D, N", [(1, 8, 10), (2, 2, 5)])
def test_smoke(self, device, dtype, B, D, N):
feat = torch.rand(B, D, D, device=device, dtype=dtype)
@@ -104,7 +103,7 @@ class TestClassificationHead:
assert logits.shape == (B, N)
-class TestConnectedComponents:
+class TestConnectedComponents(BaseTester):
def test_smoke(self, device, dtype):
img = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
out = kornia.contrib.connected_components(img, num_iterations=10)
@@ -172,19 +171,19 @@ class TestConnectedComponents:
)
out = kornia.contrib.connected_components(img, num_iterations=10)
- assert_close(out, expected)
+ self.assert_close(out, expected)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
B, C, H, W = 2, 1, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.contrib.connected_components, (img,), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.contrib.connected_components, (img,))
def test_jit(self, device, dtype):
B, C, H, W = 2, 1, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.contrib.connected_components
op_jit = torch.jit.script(op)
- assert_close(op(img), op_jit(img))
+ self.assert_close(op(img), op_jit(img))
def test_compute_padding():
@@ -193,7 +192,7 @@ def test_compute_padding():
assert kornia.contrib.compute_padding((8, 7), (4, 4)) == (0, 0, 0, 1)
-class TestExtractTensorPatches:
+class TestExtractTensorPatches(BaseTester):
def test_smoke(self, device):
img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(3)
@@ -204,10 +203,10 @@ class TestExtractTensorPatches:
m = kornia.contrib.ExtractTensorPatches(3)
patches = m(img)
assert patches.shape == (1, 4, 1, 3, 3)
- assert_close(img[0, :, :3, :3], patches[0, 0])
- assert_close(img[0, :, :3, 1:], patches[0, 1])
- assert_close(img[0, :, 1:, :3], patches[0, 2])
- assert_close(img[0, :, 1:, 1:], patches[0, 3])
+ self.assert_close(img[0, :, :3, :3], patches[0, 0])
+ self.assert_close(img[0, :, :3, 1:], patches[0, 1])
+ self.assert_close(img[0, :, 1:, :3], patches[0, 2])
+ self.assert_close(img[0, :, 1:, 1:], patches[0, 3])
def test_b1_ch2_h4w4_ws3(self, device):
img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
@@ -215,50 +214,50 @@ class TestExtractTensorPatches:
m = kornia.contrib.ExtractTensorPatches(3)
patches = m(img)
assert patches.shape == (1, 4, 2, 3, 3)
- assert_close(img[0, :, :3, :3], patches[0, 0])
- assert_close(img[0, :, :3, 1:], patches[0, 1])
- assert_close(img[0, :, 1:, :3], patches[0, 2])
- assert_close(img[0, :, 1:, 1:], patches[0, 3])
+ self.assert_close(img[0, :, :3, :3], patches[0, 0])
+ self.assert_close(img[0, :, :3, 1:], patches[0, 1])
+ self.assert_close(img[0, :, 1:, :3], patches[0, 2])
+ self.assert_close(img[0, :, 1:, 1:], patches[0, 3])
def test_b1_ch1_h4w4_ws2(self, device):
img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(2)
patches = m(img)
assert patches.shape == (1, 9, 1, 2, 2)
- assert_close(img[0, :, 0:2, 1:3], patches[0, 1])
- assert_close(img[0, :, 0:2, 2:4], patches[0, 2])
- assert_close(img[0, :, 1:3, 1:3], patches[0, 4])
- assert_close(img[0, :, 2:4, 1:3], patches[0, 7])
+ self.assert_close(img[0, :, 0:2, 1:3], patches[0, 1])
+ self.assert_close(img[0, :, 0:2, 2:4], patches[0, 2])
+ self.assert_close(img[0, :, 1:3, 1:3], patches[0, 4])
+ self.assert_close(img[0, :, 2:4, 1:3], patches[0, 7])
def test_b1_ch1_h4w4_ws2_stride2(self, device):
img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(2, stride=2)
patches = m(img)
assert patches.shape == (1, 4, 1, 2, 2)
- assert_close(img[0, :, 0:2, 0:2], patches[0, 0])
- assert_close(img[0, :, 0:2, 2:4], patches[0, 1])
- assert_close(img[0, :, 2:4, 0:2], patches[0, 2])
- assert_close(img[0, :, 2:4, 2:4], patches[0, 3])
+ self.assert_close(img[0, :, 0:2, 0:2], patches[0, 0])
+ self.assert_close(img[0, :, 0:2, 2:4], patches[0, 1])
+ self.assert_close(img[0, :, 2:4, 0:2], patches[0, 2])
+ self.assert_close(img[0, :, 2:4, 2:4], patches[0, 3])
def test_b1_ch1_h4w4_ws2_stride21(self, device):
img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(2, stride=(2, 1))
patches = m(img)
assert patches.shape == (1, 6, 1, 2, 2)
- assert_close(img[0, :, 0:2, 1:3], patches[0, 1])
- assert_close(img[0, :, 0:2, 2:4], patches[0, 2])
- assert_close(img[0, :, 2:4, 0:2], patches[0, 3])
- assert_close(img[0, :, 2:4, 2:4], patches[0, 5])
+ self.assert_close(img[0, :, 0:2, 1:3], patches[0, 1])
+ self.assert_close(img[0, :, 0:2, 2:4], patches[0, 2])
+ self.assert_close(img[0, :, 2:4, 0:2], patches[0, 3])
+ self.assert_close(img[0, :, 2:4, 2:4], patches[0, 5])
def test_b1_ch1_h3w3_ws2_stride1_padding1(self, device):
img = torch.arange(9.0).view(1, 1, 3, 3).to(device)
m = kornia.contrib.ExtractTensorPatches(2, stride=1, padding=1)
patches = m(img)
assert patches.shape == (1, 16, 1, 2, 2)
- assert_close(img[0, :, 0:2, 0:2], patches[0, 5])
- assert_close(img[0, :, 0:2, 1:3], patches[0, 6])
- assert_close(img[0, :, 1:3, 0:2], patches[0, 9])
- assert_close(img[0, :, 1:3, 1:3], patches[0, 10])
+ self.assert_close(img[0, :, 0:2, 0:2], patches[0, 5])
+ self.assert_close(img[0, :, 0:2, 1:3], patches[0, 6])
+ self.assert_close(img[0, :, 1:3, 0:2], patches[0, 9])
+ self.assert_close(img[0, :, 1:3, 1:3], patches[0, 10])
def test_b2_ch1_h3w3_ws2_stride1_padding1(self, device):
batch_size = 2
@@ -268,28 +267,28 @@ class TestExtractTensorPatches:
patches = m(img)
assert patches.shape == (batch_size, 16, 1, 2, 2)
for i in range(batch_size):
- assert_close(img[i, :, 0:2, 0:2], patches[i, 5])
- assert_close(img[i, :, 0:2, 1:3], patches[i, 6])
- assert_close(img[i, :, 1:3, 0:2], patches[i, 9])
- assert_close(img[i, :, 1:3, 1:3], patches[i, 10])
+ self.assert_close(img[i, :, 0:2, 0:2], patches[i, 5])
+ self.assert_close(img[i, :, 0:2, 1:3], patches[i, 6])
+ self.assert_close(img[i, :, 1:3, 0:2], patches[i, 9])
+ self.assert_close(img[i, :, 1:3, 1:3], patches[i, 10])
def test_b1_ch1_h3w3_ws23(self, device):
img = torch.arange(9.0).view(1, 1, 3, 3).to(device)
m = kornia.contrib.ExtractTensorPatches((2, 3))
patches = m(img)
assert patches.shape == (1, 2, 1, 2, 3)
- assert_close(img[0, :, 0:2, 0:3], patches[0, 0])
- assert_close(img[0, :, 1:3, 0:3], patches[0, 1])
+ self.assert_close(img[0, :, 0:2, 0:3], patches[0, 0])
+ self.assert_close(img[0, :, 1:3, 0:3], patches[0, 1])
def test_b1_ch1_h3w4_ws23(self, device):
img = torch.arange(12.0).view(1, 1, 3, 4).to(device)
m = kornia.contrib.ExtractTensorPatches((2, 3))
patches = m(img)
assert patches.shape == (1, 4, 1, 2, 3)
- assert_close(img[0, :, 0:2, 0:3], patches[0, 0])
- assert_close(img[0, :, 0:2, 1:4], patches[0, 1])
- assert_close(img[0, :, 1:3, 0:3], patches[0, 2])
- assert_close(img[0, :, 1:3, 1:4], patches[0, 3])
+ self.assert_close(img[0, :, 0:2, 0:3], patches[0, 0])
+ self.assert_close(img[0, :, 0:2, 1:4], patches[0, 1])
+ self.assert_close(img[0, :, 1:3, 0:3], patches[0, 2])
+ self.assert_close(img[0, :, 1:3, 1:4], patches[0, 3])
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
@@ -303,12 +302,11 @@ class TestExtractTensorPatches:
actual = op_script(grid, height, width)
expected = kornia.denormalize_pixel_coordinates(grid, height, width)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
def test_gradcheck(self, device):
- img = torch.rand(2, 3, 4, 4).to(device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.contrib.extract_tensor_patches, (img, 3), raise_exception=True, fast_mode=True)
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.contrib.extract_tensor_patches, (img, 3))
def test_auto_padding_stride(self, device, dtype):
img_shape = (11, 14)
@@ -323,13 +321,13 @@ class TestExtractTensorPatches:
assert patches.shape == (1, 35, 1, *window_size)
-class TestCombineTensorPatches:
+class TestCombineTensorPatches(BaseTester):
def test_smoke(self, device, dtype):
img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
m = kornia.contrib.CombineTensorPatches((4, 4), (2, 2), (2, 2))
patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2))
assert m(patches).shape == (1, 1, 4, 4)
- assert_close(img, m(patches))
+ self.assert_close(img, m(patches))
def test_error(self, device, dtype):
patches = kornia.contrib.extract_tensor_patches(
@@ -345,7 +343,7 @@ class TestCombineTensorPatches:
patches, original_size=(4, 3), window_size=(2, 2), stride=(2, 2), unpadding=(0, 2)
)
assert m.shape == (1, 1, 4, 3)
- assert_close(img, m)
+ self.assert_close(img, m)
def test_pad_triple_error(self, device, dtype):
patches = kornia.contrib.extract_tensor_patches(
@@ -361,7 +359,7 @@ class TestCombineTensorPatches:
patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2), padding=1)
m = kornia.contrib.CombineTensorPatches((4, 6), (2, 2), (2, 2), unpadding=1)
assert m(patches).shape == (1, 1, 4, 6)
- assert_close(img, m(patches))
+ self.assert_close(img, m(patches))
def test_padding1(self, device, dtype):
img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
@@ -369,14 +367,14 @@ class TestCombineTensorPatches:
patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(1, 1), padding=padding)
m = kornia.contrib.CombineTensorPatches((4, 4), (2, 2), stride=(1, 1), unpadding=padding)
assert m(patches).shape == (1, 1, 4, 4)
- assert_close(img, m(patches))
+ self.assert_close(img, m(patches))
def test_padding2(self, device, dtype):
img = torch.arange(64, device=device, dtype=dtype).view(1, 1, 8, 8)
patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2), padding=1)
m = kornia.contrib.CombineTensorPatches((8, 8), (2, 2), stride=(2, 2), unpadding=1)
assert m(patches).shape == (1, 1, 8, 8)
- assert_close(img, m(patches))
+ self.assert_close(img, m(patches))
def test_compute_padding(self, device, dtype):
img_shape = (8, 13)
@@ -389,7 +387,7 @@ class TestCombineTensorPatches:
)
m = kornia.contrib.CombineTensorPatches(img_shape, window_size, stride=window_size, unpadding=padding)
assert m(patches).shape == (1, 1, *img_shape)
- assert_close(img, m(patches))
+ self.assert_close(img, m(patches))
def test_stride_greater_than_window_size(self, device, dtype):
patches = kornia.contrib.extract_tensor_patches(
@@ -411,7 +409,7 @@ class TestCombineTensorPatches:
m = kornia.contrib.CombineTensorPatches(img_shape, window_size, stride=window_size, unpadding=padding)
assert m(patches).shape == (1, 1, *img_shape)
- assert_close(img, m(patches))
+ self.assert_close(img, m(patches))
def test_impl_autopadding(self, device, dtype):
img_shape = (11, 16)
@@ -424,19 +422,16 @@ class TestCombineTensorPatches:
patches, img_shape, window_size=window_size, stride=window_size, allow_auto_unpadding=True
)
assert recomb.shape == img.shape
- assert_close(img, recomb)
+ self.assert_close(img, recomb)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
patches = kornia.contrib.extract_tensor_patches(
- torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2)
- )
- img = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(
- kornia.contrib.combine_tensor_patches, (img, (4, 4), (2, 2), (2, 2)), raise_exception=True, fast_mode=True
+ torch.arange(16.0, device=device, dtype=torch.float64).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2)
)
+ self.gradcheck(kornia.contrib.combine_tensor_patches, (patches, (4, 4), (2, 2), (2, 2)))
-class TestLambdaModule:
+class TestLambdaModule(BaseTester):
def add_2_layer(self, tensor):
return tensor + 2
@@ -469,14 +464,14 @@ class TestLambdaModule:
out = lambda_module(img)
assert isinstance(out, torch.Tensor)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
B, C, H, W = 1, 3, 4, 5
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
func = kornia.color.bgr_to_grayscale
- assert gradcheck(kornia.contrib.Lambda(func), (img,), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.contrib.Lambda(func), (img,))
-class TestImageStitcher:
+class TestImageStitcher(BaseTester):
@pytest.mark.parametrize("estimator", ["ransac", "vanilla"])
def test_smoke(self, estimator, device, dtype):
B, C, H, W = 1, 3, 6, 6
@@ -600,7 +595,7 @@ class TestImageStitcher:
stitcher(sample1, sample2)
-class TestConvDistanceTransform:
+class TestConvDistanceTransform(BaseTester):
@pytest.mark.parametrize("kernel_size", [3, 5, 7])
def test_smoke(self, kernel_size, device, dtype):
sample1 = torch.rand(1, 3, 100, 100, device=device, dtype=dtype)
@@ -621,8 +616,7 @@ class TestConvDistanceTransform:
output1 = distance_transformer(sample1)
output2 = kornia.contrib.distance_transform(sample1)
- tol_val: float = utils._get_precision(device, dtype)
- assert_close(output1, output2, rtol=tol_val, atol=tol_val)
+ self.assert_close(output1, output2)
def test_exception(self, device, dtype):
B, C, H, W = 1, 1, 224, 224
@@ -666,12 +660,12 @@ class TestConvDistanceTransform:
dtype=dtype,
)
output1 = kornia.contrib.distance_transform(sample1, kernel_size, h)
- assert_close(expected_output1, output1)
+ self.assert_close(expected_output1, output1)
def test_gradcheck(self, device):
B, C, H, W = 1, 1, 32, 32
sample1 = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.contrib.distance_transform, (sample1), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.contrib.distance_transform, (sample1))
def test_loss_grad(self, device, dtype):
B, C, H, W = 1, 1, 32, 32
@@ -684,14 +678,14 @@ class TestConvDistanceTransform:
loss.backward()
-class TestHistMatch:
+class TestHistMatch(BaseTester):
def test_interp(self, device, dtype):
xp = torch.tensor([1, 2, 3], device=device, dtype=dtype)
fp = torch.tensor([4, 2, 0], device=device, dtype=dtype)
x = torch.tensor([4, 5, 6], device=device, dtype=dtype)
x_hat_expected = torch.tensor([-2.0, -4.0, -6.0], device=device, dtype=dtype)
x_hat = kornia.contrib.interp(x, xp, fp)
- assert_close(x_hat_expected, x_hat)
+ self.assert_close(x_hat_expected, x_hat)
def test_histmatch(self, device, dtype):
torch.manual_seed(44)
@@ -712,17 +706,17 @@ class TestHistMatch:
dtype=dtype,
)
assert exp.shape == out.shape
- assert_close(out, exp, rtol=1e-4, atol=1e-4)
+ self.assert_close(out, exp, rtol=1e-4, atol=1e-4)
@pytest.mark.skip(reason="not differentiable now.")
def test_grad(self, device):
B, C, H, W = 1, 3, 32, 32
src = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
dst = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.contrib.histogram_matching, (src, dst), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.contrib.histogram_matching, (src, dst))
-class TestFaceDetection:
+class TestFaceDetection(BaseTester):
@pytest.mark.slow
def test_smoke(self, device, dtype):
assert kornia.contrib.FaceDetector().to(device, dtype) is not None
@@ -778,7 +772,7 @@ class TestFaceDetection:
_ = kornia.contrib.FaceDetectorResult(data)
-class TestEdgeDetector:
+class TestEdgeDetector(BaseTester):
@pytest.mark.slow
def test_smoke(self, device, dtype):
img = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)
@@ -793,7 +787,7 @@ class TestEdgeDetector:
assert op_jit is not None
-class TestObjectDetector:
+class TestObjectDetector(BaseTester):
def test_smoke(self, device, dtype):
batch_size = 3
confidence = 0.3
diff --git a/tests/contrib/test_prompter.py b/tests/contrib/test_prompter.py
index cf164b065..b35ae440e 100644
--- a/tests/contrib/test_prompter.py
+++ b/tests/contrib/test_prompter.py
@@ -3,7 +3,8 @@ import torch
from kornia.contrib.models.sam import SamConfig
from kornia.contrib.visual_prompter import VisualPrompter
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestVisualPrompter(BaseTester):
diff --git a/tests/core/test_tensor_wrapper.py b/tests/core/test_tensor_wrapper.py
index 8b51dbea8..e83af785c 100644
--- a/tests/core/test_tensor_wrapper.py
+++ b/tests/core/test_tensor_wrapper.py
@@ -3,7 +3,8 @@ import torch
from kornia.core import Tensor
from kornia.core.tensor_wrapper import TensorWrapper, unwrap, wrap
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestTensorWrapper(BaseTester):
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index ec1c1b7ef..3e0000ed7 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -1,11 +1,11 @@
import pytest
import torch
from torch import Tensor
-from torch.autograd import gradcheck
import kornia
from kornia.constants import pi
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class TestInvert(BaseTester):
@@ -34,7 +34,7 @@ class TestInvert(BaseTester):
B, C, H, W = 1, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
max_val = torch.tensor(1.0, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.enhance.invert, (img, max_val), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.enhance.invert, (img, max_val))
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -51,10 +51,6 @@ class TestInvert(BaseTester):
op_mod = kornia.enhance.Invert()
self.assert_close(op(img), op_mod(img))
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
class TestAdjustSaturation(BaseTester):
@pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])
@@ -121,35 +117,15 @@ class TestAdjustSaturation(BaseTester):
f = kornia.enhance.AdjustSaturationWithGraySubtraction(torch.ones(2))
self.assert_close(f(data), expected)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.enhance.adjust_saturation, (img, 2.0), raise_exception=True, fast_mode=True)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.adjust_saturation, (img, 2.0))
- def test_gradcheck_with_gray_subtraction(self, device, dtype):
+ def test_gradcheck_with_gray_subtraction(self, device):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.enhance.adjust_saturation_with_gray_subtraction, (img, 2.0), raise_exception=True, fast_mode=True
- )
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.adjust_saturation_with_gray_subtraction, (img, 2.0))
class TestAdjustHue(BaseTester):
@@ -201,27 +177,10 @@ class TestAdjustHue(BaseTester):
result = f(data)
self.assert_close(result, result.flip(0))
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.enhance.adjust_hue, (img, 2.0), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.adjust_hue, (img, 2.0))
class TestAdjustGamma(BaseTester):
@@ -310,27 +269,10 @@ class TestAdjustGamma(BaseTester):
f = kornia.enhance.AdjustGamma(p1, gain=p2)
self.assert_close(f(data), expected)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
- img = tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.enhance.adjust_gamma, (img, 1.0, 2.0), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
+ img = torch.ones(batch_size, channels, height, width, device=device, dtype=torch.float)
+ self.gradcheck(kornia.enhance.adjust_gamma, (img, 1.0, 2.0))
class TestAdjustContrast(BaseTester):
@@ -604,35 +546,15 @@ class TestAdjustContrast(BaseTester):
self.assert_close(f(data), expected, low_tolerance=True)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.enhance.adjust_contrast, (img, 2.0), raise_exception=True, fast_mode=True)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.adjust_contrast, (img, 2.0))
- def test_gradcheck_with_mean_subtraction(self, device, dtype):
+ def test_gradcheck_with_mean_subtraction(self, device):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.enhance.adjust_contrast_with_mean_subtraction, (img, 2.0), raise_exception=True, fast_mode=True
- )
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.adjust_contrast_with_mean_subtraction, (img, 2.0))
class TestAdjustBrightness(BaseTester):
@@ -702,39 +624,15 @@ class TestAdjustBrightness(BaseTester):
f = kornia.enhance.AdjustBrightnessAccumulative(factor)
self.assert_close(f(data), expected)
- def test_gradcheck_additive(self, device, dtype):
+ def test_gradcheck_additive(self, device):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.enhance.adjust_brightness, (img, 1.0), raise_exception=True, fast_mode=True)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.adjust_brightness, (img, 1.0))
- def test_gradcheck_accumulative(self, device, dtype):
+ def test_gradcheck_accumulative(self, device):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.enhance.adjust_brightness_accumulative, (img, 2.0), raise_exception=True, fast_mode=True
- )
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_gradcheck(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_jit(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.adjust_brightness_accumulative, (img, 2.0))
class TestAdjustSigmoid(BaseTester):
@@ -782,27 +680,10 @@ class TestAdjustSigmoid(BaseTester):
self.assert_close(op(img), op_optimized(img))
@pytest.mark.grad()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
bs, channels, height, width = 1, 2, 3, 3
- inputs = torch.ones(bs, channels, height, width, device=device, dtype=dtype)
- inputs = tensor_to_gradcheck_var(inputs)
- assert gradcheck(kornia.enhance.adjust_sigmoid, inputs, raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
+ inputs = torch.ones(bs, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.adjust_sigmoid, inputs)
class TestAdjustLog(BaseTester):
@@ -852,27 +733,10 @@ class TestAdjustLog(BaseTester):
self.assert_close(op(img), op_optimized(img))
@pytest.mark.grad()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
bs, channels, height, width = 1, 2, 3, 3
- inputs = torch.ones(bs, channels, height, width, device=device, dtype=dtype)
- inputs = tensor_to_gradcheck_var(inputs)
- assert gradcheck(kornia.enhance.adjust_log, (inputs, 0.1), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
+ inputs = torch.ones(bs, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.adjust_log, (inputs, 0.1))
class TestEqualize(BaseTester):
@@ -967,11 +831,10 @@ class TestEqualize(BaseTester):
self.assert_close(f(inputs), expected, low_tolerance=True)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
bs, channels, height, width = 1, 2, 3, 3
- inputs = torch.ones(bs, channels, height, width, device=device, dtype=dtype)
- inputs = tensor_to_gradcheck_var(inputs)
- assert gradcheck(kornia.enhance.equalize, (inputs,), raise_exception=True)
+ inputs = torch.ones(bs, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.equalize, (inputs,), fast_mode=False)
@pytest.mark.skip(reason="args and kwargs in decorator")
def test_jit(self, device, dtype):
@@ -994,22 +857,6 @@ class TestEqualize(BaseTester):
return batch
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
-
class TestEqualize3D(BaseTester):
@pytest.mark.parametrize("shape", [(3, 6, 10, 10), (2, 3, 6, 10, 10), (3, 2, 3, 6, 10, 10)])
@@ -1061,11 +908,10 @@ class TestEqualize3D(BaseTester):
self.assert_close(f(inputs3d), expected, low_tolerance=True)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
bs, channels, depth, height, width = 1, 2, 3, 4, 5
- inputs3d = torch.ones(bs, channels, depth, height, width, device=device, dtype=dtype)
- inputs3d = tensor_to_gradcheck_var(inputs3d)
- assert gradcheck(kornia.enhance.equalize3d, (inputs3d,), raise_exception=True)
+ inputs3d = torch.ones(bs, channels, depth, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.equalize3d, (inputs3d,), fast_mode=False)
@pytest.mark.skip(reason="args and kwargs in decorator")
def test_jit(self, device, dtype):
@@ -1089,22 +935,6 @@ class TestEqualize3D(BaseTester):
return batch
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
-
class TestSharpness(BaseTester):
f = kornia.enhance.sharpness
@@ -1185,11 +1015,10 @@ class TestSharpness(BaseTester):
self.assert_close(TestSharpness.f(inputs, torch.tensor([0.8, 1.3])), expected_08_13, low_tolerance=True)
@pytest.mark.grad()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
bs, channels, height, width = 2, 3, 4, 5
- inputs = torch.rand(bs, channels, height, width, device=device, dtype=dtype)
- inputs = tensor_to_gradcheck_var(inputs)
- assert gradcheck(TestSharpness.f, (inputs, 0.8), raise_exception=True, fast_mode=True)
+ inputs = torch.rand(bs, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(TestSharpness.f, (inputs, 0.8))
@pytest.mark.skip(reason="union type input")
@pytest.mark.jit()
@@ -1201,14 +1030,6 @@ class TestSharpness(BaseTester):
actual = op_script(img, 0.8)
self.assert_close(actual, expected)
- # TODO: update with module when exists
- @pytest.mark.skip(reason="Not having it yet.")
- def test_module(self, device, dtype):
- img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
- ops = TestSharpness.f
- mod = TestSharpness.f
- self.assert_close(ops(img), mod(img))
-
@pytest.mark.skipif(kornia.xla_is_available(), reason="issues with xla device")
class TestSolarize(BaseTester):
@@ -1275,11 +1096,10 @@ class TestSolarize(BaseTester):
self.assert_close(TestSolarize.f(inputs, 0.5), expected, rtol=1e-2, atol=1e-2)
@pytest.mark.grad()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
bs, channels, height, width = 2, 3, 4, 5
- inputs = torch.rand(bs, channels, height, width, device=device, dtype=dtype)
- inputs = tensor_to_gradcheck_var(inputs)
- assert gradcheck(TestSolarize.f, (inputs, 0.8), raise_exception=True, fast_mode=True)
+ inputs = torch.rand(bs, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(TestSolarize.f, (inputs, 0.8))
# TODO: implement me
@pytest.mark.skip(reason="union type input")
@@ -1292,14 +1112,6 @@ class TestSolarize(BaseTester):
actual = op_script(img, 0.8)
self.assert_close(actual, expected)
- # TODO: update with module when exists
- @pytest.mark.skip(reason="Not having it yet.")
- def test_module(self, device, dtype):
- img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
- ops = TestSolarize.f
- mod = TestSolarize.f
- self.assert_close(ops(img), mod(img))
-
class TestPosterize(BaseTester):
f = kornia.enhance.posterize
@@ -1356,11 +1168,10 @@ class TestPosterize(BaseTester):
@pytest.mark.skip(reason="IndexError: tuple index out of range")
@pytest.mark.grad()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
bs, channels, height, width = 2, 3, 4, 5
- inputs = torch.rand(bs, channels, height, width, device=device, dtype=dtype)
- inputs = tensor_to_gradcheck_var(inputs)
- assert gradcheck(TestPosterize.f, (inputs, 0), raise_exception=True, fast_mode=True)
+ inputs = torch.rand(bs, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(TestPosterize.f, (inputs, 0))
# TODO: implement me
@pytest.mark.skip(reason="union type input")
@@ -1372,11 +1183,3 @@ class TestPosterize(BaseTester):
expected = op(img, 8)
actual = op_script(img, 8)
self.assert_close(actual, expected)
-
- # TODO: update with module when exists
- @pytest.mark.skip(reason="Not having it yet.")
- def test_module(self, device, dtype):
- img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
- ops = TestPosterize.f
- mod = TestPosterize.f
- self.assert_close(ops(img), mod(img))
diff --git a/tests/enhance/test_core.py b/tests/enhance/test_core.py
index 436021bdc..15701efe7 100644
--- a/tests/enhance/test_core.py
+++ b/tests/enhance/test_core.py
@@ -2,19 +2,18 @@ import random
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
from kornia.core import Tensor
-from kornia.testing import assert_close
+
+from testing.base import BaseTester
def random_shape(dim, min_elem=1, max_elem=10):
return tuple(random.randint(min_elem, max_elem) for _ in range(dim))
-class TestAddWeighted:
+class TestAddWeighted(BaseTester):
fcn = kornia.enhance.add_weighted
def get_input(self, device, dtype, size, max_elem=10):
@@ -29,7 +28,7 @@ class TestAddWeighted:
@pytest.mark.parametrize("size", [2, 3, 4, 5])
def test_smoke(self, device, dtype, size):
src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3)
- assert_close(TestAddWeighted.fcn(src1, alpha, src2, beta, gamma), src1 * alpha + src2 * beta + gamma)
+ self.assert_close(TestAddWeighted.fcn(src1, alpha, src2, beta, gamma), src1 * alpha + src2 * beta + gamma)
@pytest.mark.parametrize("size1, size2", [((2, 5, 5), (4, 5, 5)), ((2, 5, 5), (2, 3, 5, 5))])
def test_shape_mismatch(self, device, dtype, size1, size2):
@@ -51,7 +50,7 @@ class TestAddWeighted:
beta = beta.to(src2)
if isinstance(gamma, Tensor):
gamma = gamma.to(src1)
- assert_close(TestAddWeighted.fcn(src1, alpha, src2, beta, gamma), src1 * alpha + src2 * beta + gamma)
+ self.assert_close(TestAddWeighted.fcn(src1, alpha, src2, beta, gamma), src1 * alpha + src2 * beta + gamma)
def test_dynamo(self, device, dtype, torch_optimizer):
src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3)
@@ -60,16 +59,14 @@ class TestAddWeighted:
op = TestAddWeighted.fcn
op_optimized = torch_optimizer(op)
- assert_close(op(*inputs), op_optimized(*inputs), atol=1e-4, rtol=1e-4)
+ self.assert_close(op(*inputs), op_optimized(*inputs), atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("size", [2, 3])
- def test_gradcheck(self, size, device, dtype):
- src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3, max_elem=5) # to shave time on gradcheck
- src1 = utils.tensor_to_gradcheck_var(src1) # to var
- src2 = utils.tensor_to_gradcheck_var(src2) # to var
- assert gradcheck(
- kornia.enhance.AddWeighted(alpha, beta, gamma), (src1, src2), raise_exception=True, fast_mode=True
- )
+ def test_gradcheck(self, size, device):
+ src1, src2, alpha, beta, gamma = self.get_input(
+ device, torch.float64, size=3, max_elem=5
+ ) # to shave time on gradcheck
+ self.gradcheck(kornia.enhance.AddWeighted(alpha, beta, gamma), (src1, src2))
def test_module(self, device, dtype):
src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3)
@@ -78,4 +75,4 @@ class TestAddWeighted:
op = TestAddWeighted.fcn
op_module = kornia.enhance.AddWeighted(alpha, beta, gamma)
- assert_close(op(*inputs), op_module(src1, src2))
+ self.assert_close(op(*inputs), op_module(src1, src2))
diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.py
index a24f972e5..69d7996b5 100644
--- a/tests/enhance/test_equalization.py
+++ b/tests/enhance/test_equalization.py
@@ -2,11 +2,11 @@ from typing import Tuple
import pytest
import torch
-from torch.autograd import gradcheck
from kornia import enhance
from kornia.geometry import rotate
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class TestEqualization(BaseTester):
@@ -70,17 +70,16 @@ class TestEqualization(BaseTester):
with pytest.raises(TypeError):
enhance.equalize_clahe([1, 2, 3])
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
torch.random.manual_seed(4)
bs, channels, height, width = 1, 1, 11, 11
- inputs = torch.rand(bs, channels, height, width, device=device, dtype=dtype)
- inputs = tensor_to_gradcheck_var(inputs)
+ inputs = torch.rand(bs, channels, height, width, device=device, dtype=torch.float64)
def grad_rot(inpt, a, b, c):
rot = rotate(inpt, torch.tensor(30.0, dtype=inpt.dtype, device=device))
return enhance.equalize_clahe(rot, a, b, c)
- assert gradcheck(grad_rot, (inputs, 40.0, (2, 2), True), nondet_tol=1e-4, raise_exception=True, fast_mode=True)
+ self.gradcheck(grad_rot, (inputs, 40.0, (2, 2), True), nondet_tol=1e-4)
@pytest.mark.skip(reason="args and kwargs in decorator")
def test_jit(self, device, dtype):
diff --git a/tests/enhance/test_histogram.py b/tests/enhance/test_histogram.py
index 1821dbc56..bef3073fd 100644
--- a/tests/enhance/test_histogram.py
+++ b/tests/enhance/test_histogram.py
@@ -1,14 +1,13 @@
import pytest
import torch
from packaging import version
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestImageHistogram2d:
+
+class TestImageHistogram2d(BaseTester):
fcn = kornia.enhance.image_histogram2d
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
@@ -33,17 +32,10 @@ class TestImageHistogram2d:
assert pdf.shape == (8, 3, 256)
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
- def test_gradcheck(self, device, dtype, kernel):
- sample = torch.ones(32, 32, device=device, dtype=dtype)
- sample = utils.tensor_to_gradcheck_var(sample) # to var
- centers = torch.linspace(0, 255, 8, device=device, dtype=dtype)
- centers = utils.tensor_to_gradcheck_var(centers)
- assert gradcheck(
- TestImageHistogram2d.fcn,
- (sample, 0.0, 255.0, 256, None, centers, True, kernel),
- raise_exception=True,
- fast_mode=True,
- )
+ def test_gradcheck(self, device, kernel):
+ sample = torch.ones(32, 32, device=device, dtype=torch.float64)
+ centers = torch.linspace(0, 255, 8, device=device, dtype=torch.float64)
+ self.gradcheck(TestImageHistogram2d.fcn, (sample, 0.0, 255.0, 256, None, centers, True, kernel))
@pytest.mark.skipif(
version.parse(torch.__version__) < version.parse("1.9"), reason="Tuple cannot be jitted with PyTorch < v1.9"
@@ -58,8 +50,8 @@ class TestImageHistogram2d:
op_script = torch.jit.script(op)
out, out_script = op(*samples), op_script(*samples)
- assert_close(out[0], out_script[0])
- assert_close(out[1], out_script[1])
+ self.assert_close(out[0], out_script[0])
+ self.assert_close(out[1], out_script[1])
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
@pytest.mark.parametrize("size", [(1, 1), (3, 1, 1), (8, 3, 1, 1)])
@@ -73,7 +65,7 @@ class TestImageHistogram2d:
bandwidth = None
hist, _ = TestImageHistogram2d.fcn(sample_x, 0.0, 255.0, 10, bandwidth=bandwidth, centers=sample, kernel=kernel)
ans = 10 * torch.ones_like(hist)
- assert_close(ans, hist)
+ self.assert_close(ans, hist)
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
@pytest.mark.parametrize("size", [(1, 1), (3, 1, 1), (8, 3, 1, 1)])
@@ -89,10 +81,10 @@ class TestImageHistogram2d:
sample_x, 0.0, 255.0, 10, bandwidth=bandwidth, centers=sample, kernel=kernel, return_pdf=True
)
ans = 0.1 * torch.ones_like(hist)
- assert_close(ans, pdf)
+ self.assert_close(ans, pdf)
-class TestHistogram2d:
+class TestHistogram2d(BaseTester):
fcn = kornia.enhance.histogram2d
def test_shape(self, device, dtype):
@@ -111,16 +103,12 @@ class TestHistogram2d:
pdf = TestHistogram2d.fcn(inp1, inp2, bins, bandwidth)
assert pdf.shape == (8, 128, 128)
- def test_gradcheck(self, device, dtype):
- inp1 = torch.ones(1, 8, device=device, dtype=dtype)
- inp2 = torch.ones(1, 8, device=device, dtype=dtype)
- inp1 = utils.tensor_to_gradcheck_var(inp1) # to var
- inp2 = utils.tensor_to_gradcheck_var(inp2) # to var
- bins = torch.linspace(0, 255, 8, device=device, dtype=dtype)
- bins = utils.tensor_to_gradcheck_var(bins)
- bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
- bandwidth = utils.tensor_to_gradcheck_var(bandwidth)
- assert gradcheck(TestHistogram2d.fcn, (inp1, inp2, bins, bandwidth), raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, device):
+ inp1 = torch.ones(1, 8, device=device, dtype=torch.float64)
+ inp2 = torch.ones(1, 8, device=device, dtype=torch.float64)
+ bins = torch.linspace(0, 255, 8, device=device, dtype=torch.float64)
+ bandwidth = torch.tensor(0.9, device=device, dtype=torch.float64)
+ self.gradcheck(TestHistogram2d.fcn, (inp1, inp2, bins, bandwidth))
def test_jit(self, device, dtype):
sample1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
@@ -132,7 +120,7 @@ class TestHistogram2d:
op = TestHistogram2d.fcn
op_script = torch.jit.script(op)
- assert_close(op(*samples), op_script(*samples))
+ self.assert_close(op(*samples), op_script(*samples))
def test_uniform_dist(self, device, dtype):
sample1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
@@ -142,10 +130,10 @@ class TestHistogram2d:
pdf = TestHistogram2d.fcn(sample1, sample2, bins, bandwidth)
ans = 0.1 * kornia.eye_like(10, pdf)
- assert_close(ans, pdf)
+ self.assert_close(ans, pdf)
-class TestHistogram:
+class TestHistogram(BaseTester):
fcn = kornia.enhance.histogram
def test_shape(self, device, dtype):
@@ -162,14 +150,11 @@ class TestHistogram:
pdf = TestHistogram.fcn(inp, bins, bandwidth)
assert pdf.shape == (8, 128)
- def test_gradcheck(self, device, dtype):
- inp = torch.ones(1, 8, device=device, dtype=dtype)
- inp = utils.tensor_to_gradcheck_var(inp) # to var
- bins = torch.linspace(0, 255, 8, device=device, dtype=dtype)
- bins = utils.tensor_to_gradcheck_var(bins)
- bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
- bandwidth = utils.tensor_to_gradcheck_var(bandwidth)
- assert gradcheck(TestHistogram.fcn, (inp, bins, bandwidth), raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, device):
+ inp = torch.ones(1, 8, device=device, dtype=torch.float64)
+ bins = torch.linspace(0, 255, 8, device=device, dtype=torch.float64)
+ bandwidth = torch.tensor(0.9, device=device, dtype=torch.float64)
+ self.gradcheck(TestHistogram.fcn, (inp, bins, bandwidth))
def test_jit(self, device, dtype):
input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
@@ -180,7 +165,7 @@ class TestHistogram:
op = TestHistogram.fcn
op_script = torch.jit.script(op)
- assert_close(op(*inputs), op_script(*inputs))
+ self.assert_close(op(*inputs), op_script(*inputs))
def test_uniform_dist(self, device, dtype):
input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
@@ -189,4 +174,4 @@ class TestHistogram:
pdf = TestHistogram.fcn(input1, input2, bandwidth)
ans = 0.1 * torch.ones(1, 10, device=device, dtype=dtype)
- assert_close(ans, pdf)
+ self.assert_close(ans, pdf)
diff --git a/tests/enhance/test_integral.py b/tests/enhance/test_integral.py
index 0c2c5d921..fe5c5b1cb 100644
--- a/tests/enhance/test_integral.py
+++ b/tests/enhance/test_integral.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.enhance.integral import IntegralImage, IntegralTensor, integral_image, integral_tensor
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestIntegralTensor(BaseTester):
diff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.py
index 64b4ea266..51dc469f8 100644
--- a/tests/enhance/test_normalize.py
+++ b/tests/enhance/test_normalize.py
@@ -1,10 +1,9 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestNormalize(BaseTester):
@@ -92,17 +91,13 @@ class TestNormalize(BaseTester):
self.assert_close(op(*inputs), op_script(*inputs))
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# prepare input data
- data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
- mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
- std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
-
- data = utils.tensor_to_gradcheck_var(data) # to var
- mean = utils.tensor_to_gradcheck_var(mean) # to var
- std = utils.tensor_to_gradcheck_var(std) # to var
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=torch.float64)
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=torch.float64).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=torch.float64).repeat(2, 1)
- assert gradcheck(kornia.enhance.Normalize(mean, std), (data,), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.enhance.Normalize(mean, std), (data,))
def test_single_value(self, device, dtype):
# prepare input data
@@ -226,18 +221,14 @@ class TestDenormalize(BaseTester):
self.assert_close(op(*inputs), op_script(*inputs))
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# prepare input data
- data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=torch.float64)
data += 2
- mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype)
- std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype)
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=torch.float64)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=torch.float64)
- data = utils.tensor_to_gradcheck_var(data) # to var
- mean = utils.tensor_to_gradcheck_var(mean) # to var
- std = utils.tensor_to_gradcheck_var(std) # to var
-
- assert gradcheck(kornia.enhance.Denormalize(mean, std), (data,), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.enhance.Denormalize(mean, std), (data,))
def test_single_value(self, device, dtype):
# prepare input data
@@ -317,10 +308,6 @@ class TestNormalizeMinMax(BaseTester):
self.assert_close(op(x), op_jit(x))
@pytest.mark.grad()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
x = torch.ones(1, 1, 1, 1, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.enhance.normalize_min_max, (x,), raise_exception=True, fast_mode=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ self.gradcheck(kornia.enhance.normalize_min_max, (x,))
diff --git a/tests/enhance/test_shift_rgb.py b/tests/enhance/test_shift_rgb.py
index bc8e22bb0..8751970dd 100644
--- a/tests/enhance/test_shift_rgb.py
+++ b/tests/enhance/test_shift_rgb.py
@@ -1,19 +1,19 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
+from testing.base import BaseTester
-class TestRGBShift:
+
+class TestRGBShift(BaseTester):
def test_rgb_shift_no_shift(self, device, dtype):
r_shift, g_shift, b_shift = torch.Tensor([0]), torch.Tensor([0]), torch.Tensor([0])
image = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)
expected = image
shifted = kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)
- utils.assert_close(shifted, expected)
+ self.assert_close(shifted, expected)
def test_rgb_shift_all_zeros(self, device, dtype):
r_shift, g_shift, b_shift = torch.Tensor([-0.1]), torch.Tensor([-0.1]), torch.Tensor([-0.1])
@@ -21,7 +21,7 @@ class TestRGBShift:
expected = image
shifted = kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)
- utils.assert_close(shifted, expected)
+ self.assert_close(shifted, expected)
def test_rgb_shift_all_ones(self, device, dtype):
r_shift, g_shift, b_shift = torch.Tensor([1]), torch.Tensor([1]), torch.Tensor([1])
@@ -29,7 +29,7 @@ class TestRGBShift:
expected = torch.ones(2, 3, 5, 5, device=device, dtype=dtype)
shifted = kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)
- utils.assert_close(shifted, expected)
+ self.assert_close(shifted, expected)
def test_rgb_shift_invalid_parameter_shape(self, device, dtype):
r_shift, g_shift, b_shift = torch.Tensor([0.5]), torch.Tensor([0.5]), torch.Tensor([0.5])
@@ -37,13 +37,10 @@ class TestRGBShift:
with pytest.raises(TypeError):
kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)
- def test_rgb_shift_gradcheck(self, device, dtype):
+ def test_rgb_shift_gradcheck(self, device):
r_shift, g_shift, b_shift = torch.Tensor([0.4]), torch.Tensor([0.5]), torch.Tensor([0.2])
- image = torch.randn(2, 3, 5, 5, device=device, dtype=dtype)
- image = utils.tensor_to_gradcheck_var(image) # to var
- assert gradcheck(
- kornia.enhance.shift_rgb, (image, r_shift, g_shift, b_shift), raise_exception=True, fast_mode=True
- )
+ image = torch.randn(2, 3, 5, 5, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.shift_rgb, (image, r_shift, g_shift, b_shift))
def test_rgb_shift(self, device, dtype):
r_shift, g_shift, b_shift = torch.Tensor([0.1]), torch.Tensor([0.3]), torch.Tensor([-0.3])
@@ -59,4 +56,4 @@ class TestRGBShift:
dtype=dtype,
)
- utils.assert_close(shifted, expected)
+ self.assert_close(shifted, expected)
diff --git a/tests/enhance/test_zca.py b/tests/enhance/test_zca.py
index 65e140fb3..10cd2bb34 100644
--- a/tests/enhance/test_zca.py
+++ b/tests/enhance/test_zca.py
@@ -1,10 +1,9 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestZCA(BaseTester):
@@ -69,11 +68,9 @@ class TestZCA(BaseTester):
self.assert_close(data, data_hat, low_tolerance=True)
- def test_grad_zca_individual_transforms(self, device, dtype):
+ def test_grad_zca_individual_transforms(self, device):
"""Check if the gradients of the transforms are correct w.r.t to the input data."""
- data = torch.tensor([[2, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=dtype)
-
- data = utils.tensor_to_gradcheck_var(data)
+ data = torch.tensor([[2, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=torch.float64)
def zca_T(x):
return kornia.enhance.zca_mean(x)[0]
@@ -84,30 +81,27 @@ class TestZCA(BaseTester):
def zca_T_inv(x):
return kornia.enhance.zca_mean(x, return_inverse=True)[2]
- assert gradcheck(zca_T, (data,), raise_exception=True)
- assert gradcheck(zca_mu, (data,), raise_exception=True)
- assert gradcheck(zca_T_inv, (data,), raise_exception=True)
+ self.gradcheck(zca_T, (data,))
+ self.gradcheck(zca_mu, (data,))
+ self.gradcheck(zca_T_inv, (data,))
- def test_grad_zca_with_fit(self, device, dtype):
- data = torch.tensor([[2, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=dtype)
-
- data = utils.tensor_to_gradcheck_var(data)
+ def test_grad_zca_with_fit(self, device):
+ data = torch.tensor([[2, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=torch.float64)
def zca_fit(x):
zca = kornia.enhance.ZCAWhitening(detach_transforms=False)
return zca(x, include_fit=True)
- assert gradcheck(zca_fit, (data,), raise_exception=True)
+ self.gradcheck(zca_fit, (data,))
- def test_grad_detach_zca(self, device, dtype):
- data = torch.tensor([[1, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=dtype)
+ def test_grad_detach_zca(self, device):
+ data = torch.tensor([[1, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=torch.float64)
- data = utils.tensor_to_gradcheck_var(data)
zca = kornia.enhance.ZCAWhitening()
zca.fit(data)
- assert gradcheck(zca, (data,), raise_exception=True)
+ self.gradcheck(zca, (data,))
def test_not_fitted(self, device, dtype):
with pytest.raises(RuntimeError):
@@ -144,23 +138,3 @@ class TestZCA(BaseTester):
actual = kornia.enhance.zca_whiten(data, unbiased=unbiased)
self.assert_close(actual, expected, low_tolerance=True)
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_cardinality(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_gradcheck(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_smoke(self, device, dtype):
- pass
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.py
index cfffd980d..f4efd6618 100644
--- a/tests/feature/test_affine_shape_estimator.py
+++ b/tests/feature/test_affine_shape_estimator.py
@@ -1,13 +1,12 @@
+import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature.affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, PatchAffineShapeEstimator
-from kornia.testing import assert_close
+from testing.base import BaseTester
-# TODO: add kornia.testing.BaseTester
-class TestPatchAffineShapeEstimator:
+
+class TestPatchAffineShapeEstimator(BaseTester):
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
ori = PatchAffineShapeEstimator(32).to(device)
@@ -30,18 +29,16 @@ class TestPatchAffineShapeEstimator:
inp[:, :, 5:-5, 1:-1] = 1
abc = aff(inp)
expected = torch.tensor([[[0.4146, 0.0000, 1.0000]]], device=device)
- assert_close(abc, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(abc, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 13, 13
ori = PatchAffineShapeEstimator(width).to(device)
- patches = torch.rand(batch_size, channels, height, width, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(ori, (patches,), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(ori, (patches,), nondet_tol=1e-4)
-# TODO: add kornia.testing.BaseTester
-class TestLAFAffineShapeEstimator:
+class TestLAFAffineShapeEstimator(BaseTester):
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
laf = torch.rand(1, 1, 2, 3, device=device)
@@ -67,7 +64,7 @@ class TestLAFAffineShapeEstimator:
laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
expected = torch.tensor([[[[35.078, 0.0, 16.0], [0.0, 11.403, 16.0]]]], device=device, dtype=dtype)
- assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
def test_toy_preserve(self, device, dtype):
aff = LAFAffineShapeEstimator(32, preserve_orientation=True).to(device, dtype)
@@ -76,7 +73,7 @@ class TestLAFAffineShapeEstimator:
laf = torch.tensor([[[[0.0, 20.0, 16.0], [-20.0, 0.0, 16.0]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
expected = torch.tensor([[[[0.0, 35.078, 16.0], [-11.403, 0, 16.0]]]], device=device, dtype=dtype)
- assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
def test_toy_not_preserve(self, device):
aff = LAFAffineShapeEstimator(32, preserve_orientation=False).to(device)
@@ -85,27 +82,22 @@ class TestLAFAffineShapeEstimator:
laf = torch.tensor([[[[0.0, 20.0, 16.0], [-20.0, 0.0, 16.0]]]], device=device)
new_laf = aff(laf, inp)
expected = torch.tensor([[[[35.078, 0, 16.0], [0, 11.403, 16.0]]]], device=device)
- assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 40, 40
- patches = torch.rand(batch_size, channels, height, width, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
- laf = torch.tensor([[[[5.0, 0.0, 26.0], [0.0, 5.0, 26.0]]]], device=device)
- laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ laf = torch.tensor([[[[5.0, 0.0, 26.0], [0.0, 5.0, 26.0]]]], device=device, dtype=torch.float64)
+ self.gradcheck(
LAFAffineShapeEstimator(11).to(device),
(laf, patches),
- raise_exception=True,
rtol=1e-3,
atol=1e-3,
nondet_tol=1e-4,
- fast_mode=True,
)
-# TODO: add kornia.testing.BaseTester
-class TestLAFAffNetShapeEstimator:
+class TestLAFAffNetShapeEstimator(BaseTester):
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
laf = torch.rand(1, 1, 2, 3, device=device)
@@ -138,20 +130,18 @@ class TestLAFAffNetShapeEstimator:
laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
expected = torch.tensor([[[[33.2073, 0.0, 16.0], [-1.3766, 12.0456, 16.0]]]], device=device, dtype=dtype)
- assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+ @pytest.mark.slow
def test_gradcheck(self, device):
+ torch.manual_seed(0)
batch_size, channels, height, width = 1, 1, 35, 35
- patches = torch.rand(batch_size, channels, height, width, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device)
- laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(
+ self.gradcheck(
LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype),
(laf, patches),
- raise_exception=True,
rtol=1e-3,
atol=1e-3,
nondet_tol=1e-4,
- fast_mode=True,
)
diff --git a/tests/feature/test_defmo.py b/tests/feature/test_defmo.py
index aa4cd653e..bbc5b243c 100644
--- a/tests/feature/test_defmo.py
+++ b/tests/feature/test_defmo.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature import DeFMO
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestDeFMO:
+
+class TestDeFMO(BaseTester):
@pytest.mark.slow
def test_shape(self, device, dtype):
inp = torch.ones(1, 6, 128, 160, device=device, dtype=dtype)
@@ -26,11 +25,10 @@ class TestDeFMO:
@pytest.mark.slow
@pytest.mark.grad
- def test_gradcheck(self, device, dtype):
- patches = torch.rand(2, 6, 64, 64, device=device, dtype=dtype)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ def test_gradcheck(self, device):
+ patches = torch.rand(2, 6, 64, 64, device=device, dtype=torch.float64)
defmo = DeFMO().to(patches.device, patches.dtype)
- assert gradcheck(defmo, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8, raise_exception=True, fast_mode=True)
+ self.gradcheck(defmo, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)
@pytest.mark.slow
@pytest.mark.jit
@@ -40,4 +38,4 @@ class TestDeFMO:
model = DeFMO(True).to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(DeFMO(True).to(patches.device, patches.dtype).eval())
with torch.no_grad():
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
diff --git a/tests/feature/test_disk.py b/tests/feature/test_disk.py
index b877227ee..bc1275b85 100644
--- a/tests/feature/test_disk.py
+++ b/tests/feature/test_disk.py
@@ -3,12 +3,13 @@ import sys
import pytest
import torch
-import kornia.testing as utils # test utils
from kornia.feature.disk import DISK, DISKFeatures
-from kornia.testing import assert_close
+from testing.base import BaseTester
+from testing.casts import dict_to
-class TestDisk:
+
+class TestDisk(BaseTester):
def test_smoke(self, dtype, device):
disk = DISK().to(device, dtype)
inp = torch.ones(1, 3, 64, 64, device=device, dtype=dtype)
@@ -41,12 +42,12 @@ class TestDisk:
@pytest.mark.parametrize("data", ["disk_outdoor"], indirect=True)
def test_pretrained_outdoor(self, device, dtype, data):
disk = DISK.from_pretrained(checkpoint="depth", device=device).to(dtype)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
num_feat = 256
with torch.no_grad():
out = disk(data_dev["img1"], num_feat)
- assert_close(out[0].keypoints, data_dev["disk1"][0].keypoints.to(dtype))
- assert_close(out[0].descriptors, data_dev["disk1"][0].descriptors.to(dtype))
+ self.assert_close(out[0].keypoints, data_dev["disk1"][0].keypoints.to(dtype))
+ self.assert_close(out[0].descriptors, data_dev["disk1"][0].descriptors.to(dtype))
def test_heatmap_and_dense_descriptors(self, dtype, device):
disk = DISK().to(device, dtype)
diff --git a/tests/feature/test_hardnet.py b/tests/feature/test_hardnet.py
index e43296da9..9c80b4d74 100644
--- a/tests/feature/test_hardnet.py
+++ b/tests/feature/test_hardnet.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature import HardNet, HardNet8
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestHardNet:
+
+class TestHardNet(BaseTester):
@pytest.mark.slow
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
@@ -24,12 +23,9 @@ class TestHardNet:
assert out.shape == (16, 128)
def test_gradcheck(self, device):
- patches = torch.rand(2, 1, 32, 32, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)
hardnet = HardNet().to(patches.device, patches.dtype)
- assert gradcheck(
- hardnet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8, raise_exception=True, fast_mode=True
- )
+ self.gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -37,10 +33,10 @@ class TestHardNet:
patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
model = HardNet().to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(HardNet().to(patches.device, patches.dtype).eval())
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
-class TestHardNet8:
+class TestHardNet8(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
hardnet = HardNet8().to(device)
@@ -56,10 +52,9 @@ class TestHardNet8:
@pytest.mark.skip("jacobian not well computed")
def test_gradcheck(self, device):
- patches = torch.rand(2, 1, 32, 32, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)
hardnet = HardNet8().to(patches.device, patches.dtype)
- assert gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4, raise_exception=True, fast_mode=True)
+ self.gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -67,4 +62,4 @@ class TestHardNet8:
patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
model = HardNet8().to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(HardNet8().to(patches.device, patches.dtype).eval())
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
diff --git a/tests/feature/test_hynet.py b/tests/feature/test_hynet.py
index d16b0cc2a..b56fd2103 100644
--- a/tests/feature/test_hynet.py
+++ b/tests/feature/test_hynet.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature import HyNet
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestHyNet:
+
+class TestHyNet(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
hynet = HyNet().to(device)
@@ -21,10 +20,9 @@ class TestHyNet:
assert out.shape == (16, 128)
def test_gradcheck(self, device):
- patches = torch.rand(2, 1, 32, 32, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)
hynet = HyNet().to(patches.device, patches.dtype)
- assert gradcheck(hynet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8, raise_exception=True, fast_mode=True)
+ self.gradcheck(hynet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -32,4 +30,4 @@ class TestHyNet:
patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
model = HyNet().to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(model)
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.py
index 35dae6911..8f66f0df9 100644
--- a/tests/feature/test_integrated.py
+++ b/tests/feature/test_integrated.py
@@ -3,10 +3,8 @@ import sys
import pytest
import torch
from torch import nn
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
from kornia.feature import (
DescriptorMatcher,
GFTTAffNetHardNet,
@@ -24,12 +22,13 @@ from kornia.feature import (
)
from kornia.feature.integrated import LocalFeatureMatcher
from kornia.geometry import RANSAC, resize, transform_points
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version_le
+from testing.base import BaseTester
+from testing.casts import dict_to
-# TODO: add kornia.testing.BaseTester
-class TestGetLAFDescriptors:
+
+class TestGetLAFDescriptors(BaseTester):
def test_same(self, device, dtype):
B, C, H, W = 1, 3, 64, 64
PS = 16
@@ -48,10 +47,11 @@ class TestGetLAFDescriptors:
# Descriptor accepts standard tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
# So we need to reshape a bit :)
descs_reference = sift(patches.view(B1 * N1, CH1, H1, W1)).view(B1, N1, -1)
- assert_close(descs_test_from_rgb, descs_reference)
- assert_close(descs_test_from_gray, descs_reference)
+ self.assert_close(descs_test_from_rgb, descs_reference)
+ self.assert_close(descs_test_from_gray, descs_reference)
- def test_gradcheck(self, device, dtype=torch.float64):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
B, C, H, W = 1, 1, 32, 32
PS = 16
img = torch.rand(B, C, H, W, device=device)
@@ -59,27 +59,22 @@ class TestGetLAFDescriptors:
scales = torch.tensor([(H + W) / 5.0, (H + W) / 6.0], device=device, dtype=dtype).view(1, 2, 1, 1)
ori = torch.tensor([0.0, 30.0], device=device, dtype=dtype).view(1, 2, 1)
lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
- img = utils.tensor_to_gradcheck_var(img) # to var
- lafs = utils.tensor_to_gradcheck_var(lafs) # to var
class _MeanPatch(nn.Module):
def forward(self, inputs):
return inputs.mean(dim=(2, 3))
desc = _MeanPatch()
- assert gradcheck(
+ self.gradcheck(
get_laf_descriptors,
(img, lafs, desc, PS, True),
eps=1e-3,
atol=1e-3,
- raise_exception=True,
nondet_tol=1e-3,
- fast_mode=True,
)
-# TODO: add kornia.testing.BaseTester
-class TestLAFDescriptor:
+class TestLAFDescriptor(BaseTester):
def test_same(self, device, dtype):
B, C, H, W = 1, 3, 64, 64
PS = 16
@@ -97,7 +92,7 @@ class TestLAFDescriptor:
# Descriptor accepts standard tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
# So we need to reshape a bit :)
descs_reference = sift(patches.view(B1 * N1, CH1, H1, W1)).view(B1, N1, -1)
- assert_close(descs_test, descs_reference)
+ self.assert_close(descs_test, descs_reference)
def test_empty(self, device):
B, C, H, W = 1, 1, 32, 32
@@ -117,21 +112,16 @@ class TestLAFDescriptor:
scales = torch.tensor([(H + W) / 5.0, (H + W) / 6.0], device=device).view(1, 2, 1, 1)
ori = torch.tensor([0.0, 30.0], device=device).view(1, 2, 1)
lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
- img = utils.tensor_to_gradcheck_var(img) # to var
- lafs = utils.tensor_to_gradcheck_var(lafs) # to var
class _MeanPatch(nn.Module):
def forward(self, inputs):
return inputs.mean(dim=(2, 3))
lafdesc = LAFDescriptor(_MeanPatch(), PS)
- assert gradcheck(
- lafdesc, (img, lafs), eps=1e-3, atol=1e-3, raise_exception=True, nondet_tol=1e-3, fast_mode=True
- )
+ self.gradcheck(lafdesc, (img, lafs), eps=1e-3, atol=1e-3, nondet_tol=1e-3)
-# TODO: add kornia.testing.BaseTester
-class TestLocalFeature:
+class TestLocalFeature(BaseTester):
def test_smoke(self, device, dtype):
det = ScaleSpaceDetector(10)
desc = SIFTDescriptor(32)
@@ -147,14 +137,14 @@ class TestLocalFeature:
local_feature = LocalFeature(det, LAFDescriptor(desc, PS)).to(device, dtype)
lafs, responses, descs = local_feature(img)
lafs1, responses1 = det(img)
- assert_close(lafs, lafs1)
- assert_close(responses, responses1)
+ self.assert_close(lafs, lafs1)
+ self.assert_close(responses, responses1)
patches = extract_patches_from_pyramid(img, lafs1, PS)
B1, N1, CH1, H1, W1 = patches.size()
# Descriptor accepts standard tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
# So we need to reshape a bit :)
descs1 = desc(patches.view(B1 * N1, CH1, H1, W1)).view(B1, N1, -1)
- assert_close(descs, descs1)
+ self.assert_close(descs, descs1)
def test_scale(self, device, dtype):
B, C, H, W = 1, 1, 64, 64
@@ -166,21 +156,19 @@ class TestLocalFeature:
local_feature2 = LocalFeature(det, LAFDescriptor(desc, PS), 2.0).to(device, dtype)
lafs, responses, descs = local_feature(img)
lafs2, responses2, descs2 = local_feature2(img)
- assert_close(get_laf_center(lafs), get_laf_center(lafs2))
- assert_close(get_laf_orientation(lafs), get_laf_orientation(lafs2))
- assert_close(2.0 * get_laf_scale(lafs), get_laf_scale(lafs2))
+ self.assert_close(get_laf_center(lafs), get_laf_center(lafs2))
+ self.assert_close(get_laf_orientation(lafs), get_laf_orientation(lafs2))
+ self.assert_close(2.0 * get_laf_scale(lafs), get_laf_scale(lafs2))
def test_gradcheck(self, device):
B, C, H, W = 1, 1, 32, 32
PS = 16
- img = torch.rand(B, C, H, W, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(B, C, H, W, device=device, dtype=torch.float64)
local_feature = LocalFeature(ScaleSpaceDetector(2), LAFDescriptor(SIFTDescriptor(PS), PS)).to(device, img.dtype)
- assert gradcheck(local_feature, img, eps=1e-4, atol=1e-4, nondet_tol=1e-8, raise_exception=True, fast_mode=True)
+ self.gradcheck(local_feature, img, eps=1e-4, atol=1e-4, nondet_tol=1e-8)
-# TODO: add kornia.testing.BaseTester
-class TestSIFTFeature:
+class TestSIFTFeature(BaseTester):
# The real test is in TestLocalFeatureMatcher
def test_smoke(self, device, dtype):
sift = SIFTFeature()
@@ -189,14 +177,12 @@ class TestSIFTFeature:
@pytest.mark.skip("jacobian not well computed")
def test_gradcheck(self, device):
B, C, H, W = 1, 1, 32, 32
- img = torch.rand(B, C, H, W, device=device)
- local_feature = SIFTFeature(2, True).to(device).to(device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(local_feature, img, eps=1e-4, atol=1e-4, raise_exception=True)
+ img = torch.rand(B, C, H, W, device=device, dtype=torch.float64)
+ local_feature = SIFTFeature(2, True).to(device)
+ self.gradcheck(local_feature, img, eps=1e-4, atol=1e-4, fast_mode=False)
-# TODO: add kornia.testing.BaseTester
-class TestKeyNetHardNetFeature:
+class TestKeyNetHardNetFeature(BaseTester):
# The real test is in TestLocalFeatureMatcher
def test_smoke(self, device, dtype):
sift = KeyNetHardNet(2).to(device, dtype)
@@ -208,14 +194,12 @@ class TestKeyNetHardNetFeature:
@pytest.mark.skip("jacobian not well computed")
def test_gradcheck(self, device):
B, C, H, W = 1, 1, 32, 32
- img = torch.rand(B, C, H, W, device=device)
+ img = torch.rand(B, C, H, W, device=device, dtype=torch.float64)
local_feature = KeyNetHardNet(2, True).to(device).to(device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(local_feature, img, eps=1e-4, atol=1e-4, raise_exception=True)
+ self.gradcheck(local_feature, img, eps=1e-4, atol=1e-4, fast_mode=False)
-# TODO: add kornia.testing.BaseTester
-class TestGFTTAffNetHardNet:
+class TestGFTTAffNetHardNet(BaseTester):
# The real test is in TestLocalFeatureMatcher
def test_smoke(self, device, dtype):
feat = GFTTAffNetHardNet().to(device, dtype)
@@ -224,14 +208,12 @@ class TestGFTTAffNetHardNet:
@pytest.mark.skip("jacobian not well computed")
def test_gradcheck(self, device):
B, C, H, W = 1, 1, 32, 32
- img = torch.rand(B, C, H, W, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(B, C, H, W, device=device, dtype=torch.float64)
local_feature = GFTTAffNetHardNet(2, True).to(device, img.dtype)
- assert gradcheck(local_feature, img, eps=1e-4, atol=1e-4, raise_exception=True)
+ self.gradcheck(local_feature, img, eps=1e-4, atol=1e-4, fast_mode=False)
-# TODO: add kornia.testing.BaseTester
-class TestLocalFeatureMatcher:
+class TestLocalFeatureMatcher(BaseTester):
def test_smoke(self, device):
matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher("snn", 0.8)).to(device)
assert matcher is not None
@@ -240,7 +222,7 @@ class TestLocalFeatureMatcher:
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_nomatch(self, device, dtype, data):
matcher = LocalFeatureMatcher(GFTTAffNetHardNet(100), DescriptorMatcher("snn", 0.8)).to(device, dtype)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
with torch.no_grad():
out = matcher({"image0": data_dev["image0"], "image1": 0 * data_dev["image0"]})
assert len(out["keypoints0"]) == 0
@@ -248,15 +230,13 @@ class TestLocalFeatureMatcher:
@pytest.mark.skip("Takes too long time (but works)")
def test_gradcheck(self, device):
matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher("nn", 1.0)).to(device)
- patches = torch.rand(1, 1, 32, 32, device=device)
+ patches = torch.rand(1, 1, 32, 32, device=device, dtype=torch.float64)
patches05 = resize(patches, (48, 48))
- patches = utils.tensor_to_gradcheck_var(patches) # to var
- patches05 = utils.tensor_to_gradcheck_var(patches05) # to var
def proxy_forward(x, y):
return matcher({"image0": x, "image1": y})["keypoints0"]
- assert gradcheck(proxy_forward, (patches, patches05), eps=1e-4, atol=1e-4, raise_exception=True, fast_mode=True)
+ self.gradcheck(proxy_forward, (patches, patches05), eps=1e-4, atol=1e-4)
@pytest.mark.slow
@pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")
@@ -266,7 +246,7 @@ class TestLocalFeatureMatcher:
# This is not unit test, but that is quite good integration test
matcher = LocalFeatureMatcher(SIFTFeature(1000), DescriptorMatcher("snn", 0.8)).to(device, dtype)
ransac = RANSAC("homography", 1.0, 1024, 5).to(device, dtype)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
pts_src = data_dev["pts0"]
pts_dst = data_dev["pts1"]
with torch.no_grad():
@@ -274,7 +254,7 @@ class TestLocalFeatureMatcher:
homography, inliers = ransac(out["keypoints0"], out["keypoints1"])
assert inliers.sum().item() > 50 # we have enough inliers
# Reprojection error of 5px is OK
- assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
+ self.assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
@pytest.mark.slow
@pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")
@@ -285,7 +265,7 @@ class TestLocalFeatureMatcher:
feat = SIFTFeature(1000).to(device, dtype)
matcher = LocalFeatureMatcher(feat, DescriptorMatcher("snn", 0.8)).to(device)
ransac = RANSAC("homography", 1.0, 1024, 5).to(device, dtype)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
pts_src = data_dev["pts0"]
pts_dst = data_dev["pts1"]
@@ -302,7 +282,7 @@ class TestLocalFeatureMatcher:
homography, inliers = ransac(out["keypoints0"], out["keypoints1"])
assert inliers.sum().item() > 50 # we have enough inliers
# Reprojection error of 5px is OK
- assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
+ self.assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
@pytest.mark.slow
@pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")
@@ -312,7 +292,7 @@ class TestLocalFeatureMatcher:
# This is not unit test, but that is quite good integration test
matcher = LocalFeatureMatcher(GFTTAffNetHardNet(1000), DescriptorMatcher("snn", 0.8)).to(device, dtype)
ransac = RANSAC("homography", 1.0, 1024, 5).to(device, dtype)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
pts_src = data_dev["pts0"]
pts_dst = data_dev["pts1"]
with torch.no_grad():
@@ -321,7 +301,7 @@ class TestLocalFeatureMatcher:
homography, inliers = ransac(out["keypoints0"], out["keypoints1"])
assert inliers.sum().item() > 50 # we have enough inliers
# Reprojection error of 5px is OK
- assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
+ self.assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
@pytest.mark.slow
@pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")
@@ -332,7 +312,7 @@ class TestLocalFeatureMatcher:
# This is not unit test, but that is quite good integration test
matcher = LocalFeatureMatcher(KeyNetHardNet(500), DescriptorMatcher("snn", 0.9)).to(device, dtype)
ransac = RANSAC("homography", 1.0, 1024, 5).to(device, dtype)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
pts_src = data_dev["pts0"]
pts_dst = data_dev["pts1"]
with torch.no_grad():
@@ -340,7 +320,7 @@ class TestLocalFeatureMatcher:
homography, inliers = ransac(out["keypoints0"], out["keypoints1"])
assert inliers.sum().item() > 50 # we have enough inliers
# Reprojection error of 5px is OK
- assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
+ self.assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
@pytest.mark.skip("ScaleSpaceDetector now is not jittable")
def test_jit(self, device, dtype):
@@ -354,4 +334,4 @@ class TestLocalFeatureMatcher:
out = model(inputs)
out_jit = model_jit(inputs)
for k, v in out.items():
- assert_close(v, out_jit[k])
+ self.assert_close(v, out_jit[k])
diff --git a/tests/feature/test_keynet.py b/tests/feature/test_keynet.py
index 9d43ab389..afbd49a5c 100644
--- a/tests/feature/test_keynet.py
+++ b/tests/feature/test_keynet.py
@@ -1,11 +1,11 @@
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature import KeyNet
+from testing.base import BaseTester
-class TestKeyNet:
+
+class TestKeyNet(BaseTester):
def test_shape(self, device, dtype):
inp = torch.rand(1, 1, 16, 16, device=device, dtype=dtype)
keynet = KeyNet().to(device, dtype)
@@ -19,7 +19,6 @@ class TestKeyNet:
assert out.shape == inp.shape
def test_gradcheck(self, device):
- patches = torch.rand(2, 1, 16, 16, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(2, 1, 16, 16, device=device, dtype=torch.float64)
keynet = KeyNet().to(patches.device, patches.dtype)
- assert gradcheck(keynet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8, raise_exception=True, fast_mode=True)
+ self.gradcheck(keynet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index 4761595e1..c164fb717 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -1,14 +1,14 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
import kornia.geometry.transform.imgwarp
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
+from testing.geometry.create import create_random_homography
-class TestAngleToRotationMatrix:
+
+class TestAngleToRotationMatrix(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4).to(device)
rotmat = kornia.geometry.transform.imgwarp.angle_to_rotation_matrix(inp)
@@ -18,15 +18,12 @@ class TestAngleToRotationMatrix:
ang_deg = torch.tensor([0, 90.0], device=device)
expected = torch.tensor([[[1.0, 0.0], [0.0, 1.0]], [[0, 1.0], [-1.0, 0]]], device=device)
rotmat = kornia.geometry.transform.imgwarp.angle_to_rotation_matrix(ang_deg)
- assert_close(rotmat, expected)
+ self.assert_close(rotmat, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.geometry.transform.imgwarp.angle_to_rotation_matrix, (img,), raise_exception=True, fast_mode=True
- )
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.imgwarp.angle_to_rotation_matrix, (img,))
@pytest.mark.jit()
@pytest.mark.skip("Problems with kornia.pi")
@@ -35,10 +32,10 @@ class TestAngleToRotationMatrix:
patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
model = kornia.geometry.transform.imgwarp.angle_to_rotation_matrix
model_jit = torch.jit.script(kornia.geometry.transform.imgwarp.angle_to_rotation_matrix)
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
-class TestGetLAFScale:
+class TestGetLAFScale(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
rotmat = kornia.feature.get_laf_scale(inp)
@@ -49,13 +46,12 @@ class TestGetLAFScale:
inp = inp.view(1, 1, 2, 3)
expected = torch.tensor([[[[2]]]], device=device).float()
rotmat = kornia.feature.get_laf_scale(inp)
- assert_close(rotmat, expected)
+ self.assert_close(rotmat, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 2, 3
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.get_laf_scale, (img,), raise_exception=True, fast_mode=True)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.get_laf_scale, (img,))
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -63,10 +59,10 @@ class TestGetLAFScale:
img = torch.rand(batch_size, channels, height, width, device=device)
model = kornia.feature.get_laf_scale
model_jit = torch.jit.script(kornia.feature.get_laf_scale)
- assert_close(model(img), model_jit(img))
+ self.assert_close(model(img), model_jit(img))
-class TestGetLAFCenter:
+class TestGetLAFCenter(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
xy = kornia.feature.get_laf_center(inp)
@@ -77,13 +73,12 @@ class TestGetLAFCenter:
inp = inp.view(1, 1, 2, 3)
expected = torch.tensor([[[2, 3]]], device=device).float()
xy = kornia.feature.get_laf_center(inp)
- assert_close(xy, expected)
+ self.assert_close(xy, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 2, 3
- img = torch.rand(batch_size, channels, height, width)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.get_laf_center, (img,), raise_exception=True, fast_mode=True)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.get_laf_center, (img,))
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -91,10 +86,10 @@ class TestGetLAFCenter:
img = torch.rand(batch_size, channels, height, width, device=device)
model = kornia.feature.get_laf_center
model_jit = torch.jit.script(kornia.feature.get_laf_center)
- assert_close(model(img), model_jit(img))
+ self.assert_close(model(img), model_jit(img))
-class TestGetLAFOri:
+class TestGetLAFOri(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
ori = kornia.feature.get_laf_orientation(inp)
@@ -105,13 +100,12 @@ class TestGetLAFOri:
inp = inp.view(1, 1, 2, 3)
expected = torch.tensor([[[45.0]]], device=device).float()
angle = kornia.feature.get_laf_orientation(inp)
- assert_close(angle, expected)
+ self.assert_close(angle, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 2, 3
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.get_laf_orientation, (img,), raise_exception=True, fast_mode=True)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.get_laf_orientation, (img,))
@pytest.mark.jit()
@pytest.mark.skip("Union")
@@ -120,10 +114,10 @@ class TestGetLAFOri:
img = torch.rand(batch_size, channels, height, width, device=device)
model = kornia.feature.get_laf_orientation
model_jit = torch.jit.script(kornia.feature.get_laf_orientation)
- assert_close(model(img), model_jit(img))
+ self.assert_close(model(img), model_jit(img))
-class TestScaleLAF:
+class TestScaleLAF(BaseTester):
def test_shape_float(self, device):
inp = torch.ones(7, 3, 2, 3, device=device).float()
scale = 23.0
@@ -140,15 +134,13 @@ class TestScaleLAF:
scale = torch.tensor([[[[2.0]]]], device=device).float()
out = kornia.feature.scale_laf(inp, scale)
expected = torch.tensor([[[[10.0, 2, 0.8], [2, 2, -4.0]]]], device=device).float()
- assert_close(out, expected)
+ self.assert_close(out, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 2, 3
- laf = torch.rand(batch_size, channels, height, width, device=device)
- scale = torch.rand(batch_size, device=device)
- scale = utils.tensor_to_gradcheck_var(scale) # to var
- laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(kornia.feature.scale_laf, (laf, scale), raise_exception=True, atol=1e-4, fast_mode=True)
+ laf = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ scale = torch.rand(batch_size, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.scale_laf, (laf, scale), atol=1e-4)
@pytest.mark.jit()
@pytest.mark.skip("Union")
@@ -158,10 +150,10 @@ class TestScaleLAF:
scale = torch.rand(batch_size, device=device)
model = kornia.feature.scale_laf
model_jit = torch.jit.script(kornia.feature.scale_laf)
- assert_close(model(laf, scale), model_jit(laf, scale))
+ self.assert_close(model(laf, scale), model_jit(laf, scale))
-class TestSetLAFOri:
+class TestSetLAFOri(BaseTester):
def test_shape_tensor(self, device):
inp = torch.ones(7, 3, 2, 3, device=device).float()
ori = torch.ones(7, 3, 1, 1, device=device).float()
@@ -173,17 +165,13 @@ class TestSetLAFOri:
ori = torch.zeros(1, 1, 1, 1, device=device).float()
out = kornia.feature.set_laf_orientation(inp, ori)
expected = torch.tensor([[[[5.0, 0.0, 0.8], [0.0, 5.0, -4.0]]]], device=device).float()
- assert_close(out, expected)
+ self.assert_close(out, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 2, 3
- laf = torch.rand(batch_size, channels, height, width, device=device)
- ori = torch.rand(batch_size, channels, 1, 1, device=device)
- ori = utils.tensor_to_gradcheck_var(ori) # to var
- laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(
- kornia.feature.set_laf_orientation, (laf, ori), raise_exception=True, atol=1e-4, fast_mode=True
- )
+ laf = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ ori = torch.rand(batch_size, channels, 1, 1, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.set_laf_orientation, (laf, ori), atol=1e-4)
@pytest.mark.jit()
@pytest.mark.skip("Union")
@@ -193,10 +181,10 @@ class TestSetLAFOri:
ori = torch.rand(batch_size, channels, 1, 1, device=device)
model = kornia.feature.set_laf_orientation
model_jit = torch.jit.script(kornia.feature.set_laf_orientation)
- assert_close(model(laf, ori), model_jit(laf, ori))
+ self.assert_close(model(laf, ori), model_jit(laf, ori))
-class TestMakeUpright:
+class TestMakeUpright(BaseTester):
def test_shape(self, device):
inp = torch.ones(5, 3, 2, 3, device=device)
rotmat = kornia.feature.make_upright(inp)
@@ -207,26 +195,25 @@ class TestMakeUpright:
inp = inp.view(1, 1, 2, 3)
expected = torch.tensor([[[[1, 0, 0], [0, 1, 0]]]], device=device).float()
laf = kornia.feature.make_upright(inp)
- assert_close(laf, expected)
+ self.assert_close(laf, expected)
def test_do_nothing_with_scalea(self, device):
inp = torch.tensor([[2, 0, 0], [0, 2, 0]], device=device).float()
inp = inp.view(1, 1, 2, 3)
expected = torch.tensor([[[[2, 0, 0], [0, 2, 0]]]], device=device).float()
laf = kornia.feature.make_upright(inp)
- assert_close(laf, expected)
+ self.assert_close(laf, expected)
def test_check_zeros(self, device):
inp = torch.rand(4, 5, 2, 3, device=device)
laf = kornia.feature.make_upright(inp)
must_be_zeros = laf[:, :, 0, 1]
- assert_close(must_be_zeros, torch.zeros_like(must_be_zeros))
+ self.assert_close(must_be_zeros, torch.zeros_like(must_be_zeros))
def test_gradcheck(self, device):
batch_size, channels, height, width = 14, 2, 2, 3
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.make_upright, (img,), raise_exception=True, fast_mode=True)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.make_upright, (img,))
@pytest.mark.jit()
@pytest.mark.skip("Union")
@@ -235,10 +222,10 @@ class TestMakeUpright:
img = torch.rand(batch_size, channels, height, width, device=device)
model = kornia.feature.make_upright
model_jit = torch.jit.script(kornia.feature.make_upright)
- assert_close(model(img), model_jit(img))
+ self.assert_close(model(img), model_jit(img))
-class TestELL2LAF:
+class TestELL2LAF(BaseTester):
def test_shape(self, device):
inp = torch.ones(5, 3, 5, device=device)
inp[:, :, 3] = 0
@@ -251,16 +238,15 @@ class TestELL2LAF:
expected = torch.tensor([[10, 0, 10.0], [0, 10, -20]], device=device).float()
expected = expected.view(1, 1, 2, 3)
laf = kornia.feature.ellipse_to_laf(inp)
- assert_close(laf, expected)
+ self.assert_close(laf, expected)
def test_gradcheck(self, device):
batch_size, channels, height = 1, 2, 5
- img = torch.rand(batch_size, channels, height, device=device).abs()
+ img = torch.rand(batch_size, channels, height, device=device, dtype=torch.float64).abs()
img[:, :, 2] = img[:, :, 3].abs() + 0.3
img[:, :, 4] += 1.0
# assure it is positive definite
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.ellipse_to_laf, (img,), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.feature.ellipse_to_laf, (img,))
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -270,10 +256,10 @@ class TestELL2LAF:
img[:, :, 4] += 1.0
model = kornia.feature.ellipse_to_laf
model_jit = torch.jit.script(kornia.feature.ellipse_to_laf)
- assert_close(model(img), model_jit(img))
+ self.assert_close(model(img), model_jit(img))
-class TestNormalizeLAF:
+class TestNormalizeLAF(BaseTester):
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3)
img = torch.rand(5, 3, 10, 10)
@@ -286,16 +272,14 @@ class TestNormalizeLAF:
img = torch.rand(1, 3, h, w)
expected = torch.tensor([[[[0.25, 0, 0.125], [0, 0.25, 0.25]]]]).float()
lafn = kornia.feature.normalize_laf(laf, img)
- assert_close(lafn, expected)
+ self.assert_close(lafn, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 2, 3
- laf = torch.rand(batch_size, channels, height, width)
- img = torch.rand(batch_size, 3, 10, 32)
- img = utils.tensor_to_gradcheck_var(img) # to var
- laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(kornia.feature.normalize_laf, (laf, img), raise_exception=True, fast_mode=True)
+ laf = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ img = torch.rand(batch_size, 3, 10, 32, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.normalize_laf, (laf, img))
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -305,10 +289,10 @@ class TestNormalizeLAF:
img = torch.rand(batch_size, 3, 10, 32)
model = kornia.feature.normalize_laf
model_jit = torch.jit.script(kornia.feature.normalize_laf)
- assert_close(model(laf, img), model_jit(laf, img))
+ self.assert_close(model(laf, img), model_jit(laf, img))
-class TestLAF2pts:
+class TestLAF2pts(BaseTester):
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3, device=device)
n_pts = 13
@@ -320,13 +304,12 @@ class TestLAF2pts:
n_pts = 6
expected = torch.tensor([[[[1, 1], [1, 2], [2, 1], [1, 0], [0, 1], [1, 2]]]], device=device).float()
pts = kornia.feature.laf_to_boundary_points(laf, n_pts)
- assert_close(pts, expected)
+ self.assert_close(pts, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 3, 2, 2, 3
- laf = torch.rand(batch_size, channels, height, width, device=device)
- laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(kornia.feature.laf_to_boundary_points, (laf), raise_exception=True, fast_mode=True)
+ laf = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.laf_to_boundary_points, (laf))
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -334,10 +317,10 @@ class TestLAF2pts:
laf = torch.rand(batch_size, channels, height, width, device=device)
model = kornia.feature.laf_to_boundary_points
model_jit = torch.jit.script(kornia.feature.laf_to_boundary_points)
- assert_close(model(laf), model_jit(laf))
+ self.assert_close(model(laf), model_jit(laf))
-class TestDenormalizeLAF:
+class TestDenormalizeLAF(BaseTester):
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3, device=device)
img = torch.rand(5, 3, 10, 10, device=device)
@@ -350,16 +333,14 @@ class TestDenormalizeLAF:
img = torch.rand(1, 3, h, w, device=device)
lafn = torch.tensor([[0.25, 0, 0.125], [0, 0.25, 0.25]], device=device).float()
laf = kornia.feature.denormalize_laf(lafn.view(1, 1, 2, 3), img)
- assert_close(laf, expected)
+ self.assert_close(laf, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 2, 3
- laf = torch.rand(batch_size, channels, height, width, device=device)
- img = torch.rand(batch_size, 3, 10, 32, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(kornia.feature.denormalize_laf, (laf, img), raise_exception=True, fast_mode=True)
+ laf = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ img = torch.rand(batch_size, 3, 10, 32, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.denormalize_laf, (laf, img))
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -369,10 +350,10 @@ class TestDenormalizeLAF:
img = torch.rand(batch_size, 3, 10, 32)
model = kornia.feature.denormalize_laf
model_jit = torch.jit.script(kornia.feature.denormalize_laf)
- assert_close(model(laf, img), model_jit(laf, img))
+ self.assert_close(model(laf, img), model_jit(laf, img))
-class TestGenPatchGrid:
+class TestGenPatchGrid(BaseTester):
def test_shape(self, device):
laf = torch.rand(5, 3, 2, 3, device=device)
img = torch.rand(5, 3, 10, 10, device=device)
@@ -383,17 +364,15 @@ class TestGenPatchGrid:
assert grid.shape == (15, 3, 3, 2)
def test_gradcheck(self, device):
- laf = torch.rand(5, 3, 2, 3, device=device)
- img = torch.rand(5, 3, 10, 10, device=device)
+ laf = torch.rand(5, 3, 2, 3, device=device, dtype=torch.float64)
+ img = torch.rand(5, 3, 10, 10, device=device, dtype=torch.float64)
PS = 3
from kornia.feature.laf import generate_patch_grid_from_normalized_LAF
- img = utils.tensor_to_gradcheck_var(img) # to var
- laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(generate_patch_grid_from_normalized_LAF, (img, laf, PS), raise_exception=True, fast_mode=True)
+ self.gradcheck(generate_patch_grid_from_normalized_LAF, (img, laf, PS))
-class TestExtractPatchesSimple:
+class TestExtractPatchesSimple(BaseTester):
def test_shape(self, device):
laf = torch.rand(5, 4, 2, 3, device=device)
img = torch.rand(5, 3, 100, 30, device=device)
@@ -416,26 +395,24 @@ class TestExtractPatchesSimple:
laf = torch.tensor([[2.0, 0, 2.0], [0, 2.0, 2.0]]).reshape(1, 1, 2, 3).to(device, dtype)
patch = kornia.feature.extract_patches_simple(img, laf, 5, 1.0)
- assert_close(img, patch[0])
+ self.assert_close(img, patch[0])
def test_same_even(self, device, dtype):
img = torch.arange(4)[None].repeat(4, 1)[None, None].to(device, dtype)
laf = torch.tensor([[1.5, 0, 1.5], [0, 1.5, 1.5]]).reshape(1, 1, 2, 3).to(device, dtype)
patch = kornia.feature.extract_patches_simple(img, laf, 4, 1.0)
- assert_close(img, patch[0])
+ self.assert_close(img, patch[0])
def test_gradcheck(self, device):
- nlaf = torch.tensor([[0.1, 0.001, 0.5], [0, 0.1, 0.5]], device=device).float()
+ nlaf = torch.tensor([[0.1, 0.001, 0.5], [0, 0.1, 0.5]], device=device, dtype=torch.float64)
nlaf = nlaf.view(1, 1, 2, 3)
- img = torch.rand(1, 3, 20, 30, device=device)
+ img = torch.rand(1, 3, 20, 30, device=device, dtype=torch.float64)
PS = 11
- img = utils.tensor_to_gradcheck_var(img) # to var
- nlaf = utils.tensor_to_gradcheck_var(nlaf) # to var
- assert gradcheck(kornia.feature.extract_patches_simple, (img, nlaf, PS, False), raise_exception=True)
+ self.gradcheck(kornia.feature.extract_patches_simple, (img, nlaf, PS, False), fast_mode=False)
-class TestExtractPatchesPyr:
+class TestExtractPatchesPyr(BaseTester):
def test_shape(self, device):
laf = torch.rand(5, 4, 2, 3, device=device)
img = torch.rand(5, 3, 100, 30, device=device)
@@ -458,32 +435,28 @@ class TestExtractPatchesPyr:
laf = torch.tensor([[2.0, 0, 2.0], [0, 2.0, 2.0]]).reshape(1, 1, 2, 3).to(device, dtype)
patch = kornia.feature.extract_patches_from_pyramid(img, laf, 5, 1.0)
- assert_close(img, patch[0])
+ self.assert_close(img, patch[0])
def test_same_even(self, device, dtype):
img = torch.arange(4)[None].repeat(4, 1)[None, None].to(device, dtype)
laf = torch.tensor([[1.5, 0, 1.5], [0, 1.5, 1.5]]).reshape(1, 1, 2, 3).to(device, dtype)
patch = kornia.feature.extract_patches_from_pyramid(img, laf, 4, 1.0)
- assert_close(img, patch[0])
+ self.assert_close(img, patch[0])
def test_gradcheck(self, device):
- nlaf = torch.tensor([[0.1, 0.001, 0.5], [0, 0.1, 0.5]], device=device).float()
+ nlaf = torch.tensor([[0.1, 0.001, 0.5], [0, 0.1, 0.5]], device=device, dtype=torch.float64)
nlaf = nlaf.view(1, 1, 2, 3)
- img = torch.rand(1, 3, 20, 30, device=device)
+ img = torch.rand(1, 3, 20, 30, device=device, dtype=torch.float64)
PS = 11
- img = utils.tensor_to_gradcheck_var(img) # to var
- nlaf = utils.tensor_to_gradcheck_var(nlaf) # to var
- assert gradcheck(
+ self.gradcheck(
kornia.feature.extract_patches_from_pyramid,
(img, nlaf, PS, False),
nondet_tol=1e-8,
- raise_exception=True,
- fast_mode=True,
)
-class TestLAFIsTouchingBoundary:
+class TestLAFIsTouchingBoundary(BaseTester):
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3, device=device)
img = torch.rand(5, 3, 10, 10, device=device)
@@ -503,10 +476,10 @@ class TestLAFIsTouchingBoundary:
laf = torch.tensor([[[[10, 0, 3], [0, 10, 3]], [[1, 0, 5], [0, 1, 2]]]], device=device).float()
model = kornia.feature.laf_is_inside_image
model_jit = torch.jit.script(kornia.feature.laf_is_inside_image)
- assert_close(model(laf, img), model_jit(laf, img))
+ self.assert_close(model(laf, img), model_jit(laf, img))
-class TestGetCreateLAF:
+class TestGetCreateLAF(BaseTester):
def test_shape(self, device):
xy = torch.ones(1, 3, 2, device=device)
ori = torch.ones(1, 3, 1, device=device)
@@ -520,13 +493,13 @@ class TestGetCreateLAF:
scale = 5 * torch.ones(1, 1, 1, 1, device=device)
expected = torch.tensor([[[[5, 0, 1], [0, 5, 1]]]], device=device).float()
laf = kornia.feature.laf_from_center_scale_ori(xy, scale, ori)
- assert_close(laf, expected)
+ self.assert_close(laf, expected)
def test_laf_def(self, device):
xy = torch.ones(1, 1, 2, device=device)
expected = torch.tensor([[[[1, 0, 1], [0, 1, 1]]]], device=device).float()
laf = kornia.feature.laf_from_center_scale_ori(xy)
- assert_close(laf, expected)
+ self.assert_close(laf, expected)
def test_cross_consistency(self, device):
batch_size, channels = 3, 2
@@ -535,20 +508,18 @@ class TestGetCreateLAF:
scale = torch.abs(torch.rand(batch_size, channels, 1, 1, device=device))
laf = kornia.feature.laf_from_center_scale_ori(xy, scale, ori)
scale2 = kornia.feature.get_laf_scale(laf)
- assert_close(scale, scale2)
+ self.assert_close(scale, scale2)
xy2 = kornia.feature.get_laf_center(laf)
- assert_close(xy2, xy)
+ self.assert_close(xy2, xy)
ori2 = kornia.feature.get_laf_orientation(laf)
- assert_close(ori2, ori)
+ self.assert_close(ori2, ori)
def test_gradcheck(self, device):
batch_size, channels = 3, 2
- xy = utils.tensor_to_gradcheck_var(torch.rand(batch_size, channels, 2, device=device))
- ori = utils.tensor_to_gradcheck_var(torch.rand(batch_size, channels, 1, device=device))
- scale = utils.tensor_to_gradcheck_var(torch.abs(torch.rand(batch_size, channels, 1, 1, device=device)))
- assert gradcheck(
- kornia.feature.laf_from_center_scale_ori, (xy, scale, ori), raise_exception=True, fast_mode=True
- )
+ xy = torch.rand(batch_size, channels, 2, device=device, dtype=torch.float64)
+ ori = torch.rand(batch_size, channels, 1, device=device, dtype=torch.float64)
+ scale = torch.abs(torch.rand(batch_size, channels, 1, 1, device=device, dtype=torch.float64))
+ self.gradcheck(kornia.feature.laf_from_center_scale_ori, (xy, scale, ori))
@pytest.mark.skip("Depends on angle-to-rotation-matric")
@pytest.mark.jit()
@@ -559,10 +530,10 @@ class TestGetCreateLAF:
scale = torch.abs(torch.rand(batch_size, channels, 1, 1, device=device))
model = kornia.feature.laf_from_center_scale_ori
model_jit = torch.jit.script(kornia.feature.laf_from_center_scale_ori)
- assert_close(model(xy, scale, ori), model_jit(xy, scale, ori))
+ self.assert_close(model(xy, scale, ori), model_jit(xy, scale, ori))
-class TestGetLAF3pts:
+class TestGetLAF3pts(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
out = kornia.feature.laf_to_three_points(inp)
@@ -577,13 +548,12 @@ class TestGetLAF3pts:
inp = torch.tensor([[1, 0, 2], [0, 1, 3]], device=device).float().view(1, 1, 2, 3)
expected = torch.tensor([[3, 2, 2], [3, 4, 3]], device=device).float().view(1, 1, 2, 3)
threepts = kornia.feature.laf_to_three_points(inp)
- assert_close(threepts, expected)
+ self.assert_close(threepts, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 3, 2, 2, 3
- inp = torch.rand(batch_size, channels, height, width, device=device)
- inp = utils.tensor_to_gradcheck_var(inp) # to var
- assert gradcheck(kornia.feature.laf_to_three_points, (inp,), raise_exception=True, fast_mode=True)
+ inp = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.laf_to_three_points, (inp,))
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -591,10 +561,10 @@ class TestGetLAF3pts:
inp = torch.rand(batch_size, channels, height, width, device=device)
model = kornia.feature.laf_to_three_points
model_jit = torch.jit.script(kornia.feature.laf_to_three_points)
- assert_close(model(inp), model_jit(inp))
+ self.assert_close(model(inp), model_jit(inp))
-class TestGetLAFFrom3pts:
+class TestGetLAFFrom3pts(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
out = kornia.feature.laf_from_three_points(inp)
@@ -609,20 +579,19 @@ class TestGetLAFFrom3pts:
expected = torch.tensor([[1, 0, 2], [0, 1, 3]], device=device).float().view(1, 1, 2, 3)
inp = torch.tensor([[3, 2, 2], [3, 4, 3]], device=device).float().view(1, 1, 2, 3)
threepts = kornia.feature.laf_from_three_points(inp)
- assert_close(threepts, expected)
+ self.assert_close(threepts, expected)
def test_cross_consistency(self, device):
batch_size, channels, height, width = 3, 2, 2, 3
inp = torch.rand(batch_size, channels, height, width, device=device)
inp_2 = kornia.feature.laf_from_three_points(inp)
inp_2 = kornia.feature.laf_to_three_points(inp_2)
- assert_close(inp_2, inp)
+ self.assert_close(inp_2, inp)
def test_gradcheck(self, device):
batch_size, channels, height, width = 3, 2, 2, 3
- inp = torch.rand(batch_size, channels, height, width, device=device)
- inp = utils.tensor_to_gradcheck_var(inp) # to var
- assert gradcheck(kornia.feature.laf_from_three_points, (inp,), raise_exception=True, fast_mode=True)
+ inp = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.laf_from_three_points, (inp,))
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -630,10 +599,10 @@ class TestGetLAFFrom3pts:
inp = torch.rand(batch_size, channels, height, width, device=device)
model = kornia.feature.laf_from_three_points
model_jit = torch.jit.script(kornia.feature.laf_from_three_points)
- assert_close(model(inp), model_jit(inp))
+ self.assert_close(model(inp), model_jit(inp))
-class TestTransformLAFs:
+class TestTransformLAFs(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 5])
@pytest.mark.parametrize("num_points", [2, 3, 5])
def test_transform_points(self, batch_size, num_points, device, dtype):
@@ -641,8 +610,7 @@ class TestTransformLAFs:
eye_size = 3
lafs_src = torch.rand(batch_size, num_points, 2, 3, device=device, dtype=dtype)
- dst_homo_src = utils.create_random_homography(batch_size, eye_size).to(device=device, dtype=dtype)
-
+ dst_homo_src = create_random_homography(lafs_src, eye_size)
# transform the points from dst to ref
lafs_dst = kornia.feature.perspective_transform_lafs(dst_homo_src, lafs_src)
@@ -651,17 +619,13 @@ class TestTransformLAFs:
lafs_dst_to_src = kornia.feature.perspective_transform_lafs(src_homo_dst, lafs_dst)
# projected should be equal as initial
- assert_close(lafs_src, lafs_dst_to_src)
+ self.assert_close(lafs_src, lafs_dst_to_src)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# generate input data
batch_size, num_points = 2, 3
eye_size = 3
- points_src = torch.rand(batch_size, num_points, 2, 3, device=device, dtype=dtype)
- dst_homo_src = utils.create_random_homography(batch_size, eye_size).to(device=device, dtype=dtype)
+ points_src = torch.rand(batch_size, num_points, 2, 3, device=device, dtype=torch.float64)
+ dst_homo_src = create_random_homography(points_src, eye_size)
# evaluate function gradient
- points_src = utils.tensor_to_gradcheck_var(points_src) # to var
- dst_homo_src = utils.tensor_to_gradcheck_var(dst_homo_src) # to var
- assert gradcheck(
- kornia.feature.perspective_transform_lafs, (dst_homo_src, points_src), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.feature.perspective_transform_lafs, (dst_homo_src, points_src))
diff --git a/tests/feature/test_local_features_orientation.py b/tests/feature/test_local_features_orientation.py
index b61542f44..b8cd8b246 100644
--- a/tests/feature/test_local_features_orientation.py
+++ b/tests/feature/test_local_features_orientation.py
@@ -1,14 +1,13 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature.orientation import LAFOrienter, OriNet, PassLAF, PatchDominantGradientOrientation
from kornia.geometry.conversions import rad2deg
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestPassLAF:
+
+class TestPassLAF(BaseTester):
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
laf = torch.rand(1, 1, 2, 3, device=device)
@@ -32,17 +31,16 @@ class TestPassLAF:
laf = torch.rand(1, 1, 2, 3, device=device)
ori = PassLAF().to(device)
out = ori(laf, inp)
- assert_close(out, laf)
+ self.assert_close(out, laf)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 21, 21
- patches = torch.rand(batch_size, channels, height, width, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
- laf = torch.rand(batch_size, 4, 2, 3)
- assert gradcheck(PassLAF().to(device), (patches, laf), raise_exception=True, fast_mode=True)
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ laf = torch.rand(batch_size, 4, 2, 3, device=device, dtype=torch.float64)
+ self.gradcheck(PassLAF().to(device), (patches, laf))
-class TestPatchDominantGradientOrientation:
+class TestPatchDominantGradientOrientation(BaseTester):
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
ori = PatchDominantGradientOrientation(32).to(device)
@@ -65,14 +63,13 @@ class TestPatchDominantGradientOrientation:
inp[:, :, :10, :] = 1
ang = ori(inp)
expected = torch.tensor([90.0], device=device)
- assert_close(rad2deg(ang), expected)
+ self.assert_close(rad2deg(ang), expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 13, 13
ori = PatchDominantGradientOrientation(width).to(device)
- patches = torch.rand(batch_size, channels, height, width, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(ori, (patches,), raise_exception=True, fast_mode=True)
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(ori, (patches,))
@pytest.mark.jit()
@pytest.mark.skip(" Compiled functions can't take variable number")
@@ -81,10 +78,10 @@ class TestPatchDominantGradientOrientation:
patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
model = PatchDominantGradientOrientation(13).to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(PatchDominantGradientOrientation(13).to(patches.device, patches.dtype).eval())
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
-class TestOriNet:
+class TestOriNet(BaseTester):
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
ori = OriNet().to(device=device, dtype=inp.dtype).eval()
@@ -113,15 +110,14 @@ class TestOriNet:
ori = OriNet(True).to(device=device, dtype=inp.dtype).eval()
ang = ori(inp)
expected = torch.tensor([70.58], device=device)
- assert_close(rad2deg(ang), expected, atol=1e-2, rtol=1e-3)
+ self.assert_close(rad2deg(ang), expected, atol=1e-2, rtol=1e-3)
@pytest.mark.skip("jacobian not well computed")
def test_gradcheck(self, device):
batch_size, channels, height, width = 2, 1, 32, 32
- patches = torch.rand(batch_size, channels, height, width, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
ori = OriNet().to(device=device, dtype=patches.dtype)
- assert gradcheck(ori, (patches,), raise_exception=True)
+ self.gradcheck(ori, (patches,), fast_mode=False)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -129,10 +125,10 @@ class TestOriNet:
patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
tfeat = OriNet(True).to(patches.device, patches.dtype).eval()
tfeat_jit = torch.jit.script(OriNet(True).to(patches.device, patches.dtype).eval())
- assert_close(tfeat_jit(patches), tfeat(patches))
+ self.assert_close(tfeat_jit(patches), tfeat(patches))
-class TestLAFOrienter:
+class TestLAFOrienter(BaseTester):
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
laf = torch.rand(1, 1, 2, 3, device=device)
@@ -158,16 +154,12 @@ class TestLAFOrienter:
laf = torch.tensor([[[[5.0, 0.0, 8.0], [0.0, 5.0, 8.0]]]], device=device)
new_laf = ori(laf, inp)
expected = torch.tensor([[[[-5.0, 0.0, 8.0], [0.0, -5.0, 8.0]]]], device=device)
- assert_close(new_laf, expected)
+ self.assert_close(new_laf, expected)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 21, 21
- patches = torch.rand(batch_size, channels, height, width, device=device).float()
- patches = utils.tensor_to_gradcheck_var(patches) # to var
- laf = torch.ones(batch_size, 2, 2, 3, device=device).float()
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ laf = torch.ones(batch_size, 2, 2, 3, device=device, dtype=torch.float64)
laf[:, :, 0, 1] = 0
laf[:, :, 1, 0] = 0
- laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(
- LAFOrienter(8).to(device), (laf, patches), raise_exception=True, rtol=1e-3, atol=1e-3, fast_mode=True
- )
+ self.gradcheck(LAFOrienter(8).to(device), (laf, patches), rtol=1e-3, atol=1e-3)
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index 0187fb587..23baf59a5 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -2,16 +2,16 @@ import sys
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature import LoFTR
from kornia.geometry import resize
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version_ge
+from testing.base import BaseTester
+from testing.casts import dict_to
-class TestLoFTR:
+
+class TestLoFTR(BaseTester):
@pytest.mark.slow
def test_pretrained_outdoor_smoke(self, device, dtype):
loftr = LoFTR("outdoor").to(device, dtype)
@@ -28,11 +28,11 @@ class TestLoFTR:
@pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)
def test_pretrained_indoor(self, device, dtype, data):
loftr = LoFTR("indoor").to(device, dtype)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
with torch.no_grad():
out = loftr(data_dev)
- assert_close(out["keypoints0"], data_dev["loftr_indoor_tentatives0"])
- assert_close(out["keypoints1"], data_dev["loftr_indoor_tentatives1"])
+ self.assert_close(out["keypoints0"], data_dev["loftr_indoor_tentatives0"])
+ self.assert_close(out["keypoints1"], data_dev["loftr_indoor_tentatives1"])
@pytest.mark.slow
@pytest.mark.skipif(torch_version_ge(1, 10), reason="RuntimeError: CUDA out of memory with pytorch>=1.10")
@@ -40,11 +40,11 @@ class TestLoFTR:
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_pretrained_outdoor(self, device, dtype, data):
loftr = LoFTR("outdoor").to(device, dtype)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
with torch.no_grad():
out = loftr(data_dev)
- assert_close(out["keypoints0"], data_dev["loftr_outdoor_tentatives0"])
- assert_close(out["keypoints1"], data_dev["loftr_outdoor_tentatives1"])
+ self.assert_close(out["keypoints0"], data_dev["loftr_outdoor_tentatives0"])
+ self.assert_close(out["keypoints1"], data_dev["loftr_outdoor_tentatives1"])
@pytest.mark.slow
def test_mask(self, device):
@@ -58,16 +58,14 @@ class TestLoFTR:
@pytest.mark.slow
def test_gradcheck(self, device):
- patches = torch.rand(1, 1, 32, 32, device=device)
+ patches = torch.rand(1, 1, 32, 32, device=device, dtype=torch.float64)
patches05 = resize(patches, (48, 48))
- patches = utils.tensor_to_gradcheck_var(patches) # to var
- patches05 = utils.tensor_to_gradcheck_var(patches05) # to var
loftr = LoFTR().to(patches.device, patches.dtype)
def proxy_forward(x, y):
return loftr.forward({"image0": x, "image1": y})["keypoints0"]
- assert gradcheck(proxy_forward, (patches, patches05), eps=1e-4, atol=1e-4, raise_exception=True, fast_mode=True)
+ self.gradcheck(proxy_forward, (patches, patches05), eps=1e-4, atol=1e-4)
@pytest.mark.skip("does not like transformer.py:L99, zip iteration")
def test_jit(self, device, dtype):
@@ -80,4 +78,4 @@ class TestLoFTR:
out = model(sample)
out_jit = model_jit(sample)
for k, v in out.items():
- assert_close(v, out_jit[k])
+ self.assert_close(v, out_jit[k])
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index b3b10285c..3fd6d9bba 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -1,8 +1,6 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature.integrated import LightGlueMatcher
from kornia.feature.laf import laf_from_center_scale_ori
from kornia.feature.matching import (
@@ -15,10 +13,12 @@ from kornia.feature.matching import (
match_smnn,
match_snn,
)
-from kornia.testing import assert_close
+from testing.base import BaseTester
+from testing.casts import dict_to
-class TestMatchNN:
+
+class TestMatchNN(BaseTester):
@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(1, 4, 4), (2, 5, 128), (6, 2, 32)])
def test_shape(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)
@@ -35,22 +35,20 @@ class TestMatchNN:
dists, idxs = match_nn(desc1, desc2)
expected_dists = torch.tensor([0, 0, 0.5, 0, 0], device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
- assert_close(dists, expected_dists)
- assert_close(idxs, expected_idx)
+ self.assert_close(dists, expected_dists)
+ self.assert_close(idxs, expected_idx)
dists1, idxs1 = match_nn(desc1, desc2)
- assert_close(dists1, expected_dists)
- assert_close(idxs1, expected_idx)
+ self.assert_close(dists1, expected_dists)
+ self.assert_close(idxs1, expected_idx)
def test_gradcheck(self, device):
- desc1 = torch.rand(5, 8, device=device)
- desc2 = torch.rand(7, 8, device=device)
- desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
- desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
- assert gradcheck(match_mnn, (desc1, desc2), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ desc1 = torch.rand(5, 8, device=device, dtype=torch.float64)
+ desc2 = torch.rand(7, 8, device=device, dtype=torch.float64)
+ self.gradcheck(match_mnn, (desc1, desc2), nondet_tol=1e-4)
-class TestMatchMNN:
+class TestMatchMNN(BaseTester):
@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(1, 4, 4), (2, 5, 128), (6, 2, 32)])
def test_shape(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)
@@ -69,22 +67,20 @@ class TestMatchMNN:
dists, idxs = match_mnn(desc1, desc2)
expected_dists = torch.tensor([0, 0, 0.5, 0, 0], device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
- assert_close(dists, expected_dists)
- assert_close(idxs, expected_idx)
+ self.assert_close(dists, expected_dists)
+ self.assert_close(idxs, expected_idx)
matcher = DescriptorMatcher("mnn").to(device)
dists1, idxs1 = matcher(desc1, desc2)
- assert_close(dists1, expected_dists)
- assert_close(idxs1, expected_idx)
+ self.assert_close(dists1, expected_dists)
+ self.assert_close(idxs1, expected_idx)
def test_gradcheck(self, device):
- desc1 = torch.rand(5, 8, device=device)
- desc2 = torch.rand(7, 8, device=device)
- desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
- desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
- assert gradcheck(match_mnn, (desc1, desc2), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ desc1 = torch.rand(5, 8, device=device, dtype=torch.float64)
+ desc2 = torch.rand(7, 8, device=device, dtype=torch.float64)
+ self.gradcheck(match_mnn, (desc1, desc2), nondet_tol=1e-4)
-class TestMatchSNN:
+class TestMatchSNN(BaseTester):
@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)])
def test_shape(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)
@@ -111,12 +107,12 @@ class TestMatchSNN:
dists, idxs = match_snn(desc1, desc2, 0.8)
expected_dists = torch.tensor([0, 0, 0.35355339059327373, 0, 0], device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
- assert_close(dists, expected_dists)
- assert_close(idxs, expected_idx)
+ self.assert_close(dists, expected_dists)
+ self.assert_close(idxs, expected_idx)
matcher = DescriptorMatcher("snn", 0.8).to(device)
dists1, idxs1 = matcher(desc1, desc2)
- assert_close(dists1, expected_dists)
- assert_close(idxs1, expected_idx)
+ self.assert_close(dists1, expected_dists)
+ self.assert_close(idxs1, expected_idx)
def test_matching2(self, device):
desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
@@ -125,22 +121,20 @@ class TestMatchSNN:
dists, idxs = match_snn(desc1, desc2, 0.1)
expected_dists = torch.tensor([0.0, 0, 0, 0], device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
- assert_close(dists, expected_dists)
- assert_close(idxs, expected_idx)
+ self.assert_close(dists, expected_dists)
+ self.assert_close(idxs, expected_idx)
matcher = DescriptorMatcher("snn", 0.1).to(device)
dists1, idxs1 = matcher(desc1, desc2)
- assert_close(dists1, expected_dists)
- assert_close(idxs1, expected_idx)
+ self.assert_close(dists1, expected_dists)
+ self.assert_close(idxs1, expected_idx)
def test_gradcheck(self, device):
- desc1 = torch.rand(5, 8, device=device)
- desc2 = torch.rand(7, 8, device=device)
- desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
- desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
- assert gradcheck(match_snn, (desc1, desc2, 0.8), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ desc1 = torch.rand(5, 8, device=device, dtype=torch.float64)
+ desc2 = torch.rand(7, 8, device=device, dtype=torch.float64)
+ self.gradcheck(match_snn, (desc1, desc2, 0.8), nondet_tol=1e-4)
-class TestMatchSMNN:
+class TestMatchSMNN(BaseTester):
@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)])
def test_shape(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)
@@ -160,12 +154,12 @@ class TestMatchSMNN:
dists, idxs = match_smnn(desc1, desc2, 0.8)
expected_dists = torch.tensor([0, 0, 0.5423, 0, 0], device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
- assert_close(dists, expected_dists)
- assert_close(idxs, expected_idx)
+ self.assert_close(dists, expected_dists)
+ self.assert_close(idxs, expected_idx)
matcher = DescriptorMatcher("smnn", 0.8).to(device)
dists1, idxs1 = matcher(desc1, desc2)
- assert_close(dists1, expected_dists)
- assert_close(idxs1, expected_idx)
+ self.assert_close(dists1, expected_dists)
+ self.assert_close(idxs1, expected_idx)
def test_nomatch(self, device):
desc1 = torch.tensor([[0, 0.0]], device=device)
@@ -182,12 +176,12 @@ class TestMatchSMNN:
dists, idxs = match_smnn(desc1, desc2, 0.1)
expected_dists = torch.tensor([0.0, 0, 0, 0], device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
- assert_close(dists, expected_dists)
- assert_close(idxs, expected_idx)
+ self.assert_close(dists, expected_dists)
+ self.assert_close(idxs, expected_idx)
matcher = DescriptorMatcher("smnn", 0.1).to(device)
dists1, idxs1 = matcher(desc1, desc2)
- assert_close(dists1, expected_dists)
- assert_close(idxs1, expected_idx)
+ self.assert_close(dists1, expected_dists)
+ self.assert_close(idxs1, expected_idx)
@pytest.mark.parametrize(
"match_type, d1, d2",
@@ -215,13 +209,11 @@ class TestMatchSMNN:
assert idxs is not None
def test_gradcheck(self, device):
- desc1 = torch.rand(5, 8, device=device)
- desc2 = torch.rand(7, 8, device=device)
- desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
- desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
+ desc1 = torch.rand(5, 8, device=device, dtype=torch.float64)
+ desc2 = torch.rand(7, 8, device=device, dtype=torch.float64)
matcher = DescriptorMatcher("smnn", 0.8).to(device)
- assert gradcheck(match_smnn, (desc1, desc2, 0.8), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
- assert gradcheck(matcher, (desc1, desc2), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ self.gradcheck(match_smnn, (desc1, desc2, 0.8), nondet_tol=1e-4)
+ self.gradcheck(matcher, (desc1, desc2), nondet_tol=1e-4)
@pytest.mark.jit()
@pytest.mark.parametrize("match_type", ["nn", "snn", "mnn", "smnn"])
@@ -230,11 +222,11 @@ class TestMatchSMNN:
desc2 = torch.rand(7, 8, device=device, dtype=dtype)
matcher = DescriptorMatcher(match_type, 0.8).to(device)
matcher_jit = torch.jit.script(DescriptorMatcher(match_type, 0.8).to(device))
- assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2)[0])
- assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2)[1])
+ self.assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2)[0])
+ self.assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2)[1])
-class TestMatchFGINN:
+class TestMatchFGINN(BaseTester):
@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)])
def test_shape_one_way(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)
@@ -271,12 +263,12 @@ class TestMatchFGINN:
dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.8, 0.01)
expected_dists = torch.tensor([0, 0, 0.3536, 0, 0], dtype=dtype, device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
- assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)
- assert_close(idxs, expected_idx)
+ self.assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)
+ self.assert_close(idxs, expected_idx)
matcher = GeometryAwareDescriptorMatcher("fginn", {"spatial_th": 0.01}).to(device)
dists1, idxs1 = matcher(desc1, desc2, lafs1, lafs2)
- assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)
- assert_close(idxs1, expected_idx)
+ self.assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)
+ self.assert_close(idxs1, expected_idx)
def test_matching_mutual(self, device, dtype):
desc1 = torch.tensor([[0, 0.1], [1, 1.001], [2, 2], [3, 3.0], [5, 5.0], [0.0, 0]], dtype=dtype, device=device)
@@ -287,12 +279,12 @@ class TestMatchFGINN:
dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.8, 2.0, mutual=True)
expected_dists = torch.tensor([0, 0.1768, 0, 0, 0], dtype=dtype, device=device).view(-1, 1)
expected_idx = torch.tensor([[1, 3], [2, 2], [3, 1], [4, 0], [5, 4]], device=device)
- assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)
- assert_close(idxs, expected_idx)
+ self.assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)
+ self.assert_close(idxs, expected_idx)
matcher = GeometryAwareDescriptorMatcher("fginn", {"spatial_th": 2.0, "mutual": True}).to(device)
dists1, idxs1 = matcher(desc1, desc2, lafs1, lafs2)
- assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)
- assert_close(idxs1, expected_idx)
+ self.assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)
+ self.assert_close(idxs1, expected_idx)
def test_nomatch(self, device, dtype):
desc1 = torch.tensor([[0, 0.0]], dtype=dtype, device=device)
@@ -313,27 +305,21 @@ class TestMatchFGINN:
dists, idxs = match_fginn(desc1, desc2, lafs1, lafs2, 0.8, 2.0)
expected_dists = torch.tensor([0, 0, 0.1768, 0, 0], dtype=dtype, device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
- assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)
- assert_close(idxs, expected_idx)
+ self.assert_close(dists, expected_dists, rtol=0.001, atol=1e-3)
+ self.assert_close(idxs, expected_idx)
matcher = GeometryAwareDescriptorMatcher("fginn", {"spatial_th": 2.0}).to(device)
dists1, idxs1 = matcher(desc1, desc2, lafs1, lafs2)
- assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)
- assert_close(idxs1, expected_idx)
+ self.assert_close(dists1, expected_dists, rtol=0.001, atol=1e-3)
+ self.assert_close(idxs1, expected_idx)
def test_gradcheck(self, device):
- desc1 = torch.rand(5, 8, device=device)
- desc2 = torch.rand(7, 8, device=device)
- center1 = torch.rand(1, 5, 2, device=device)
- center2 = torch.rand(1, 7, 2, device=device)
+ desc1 = torch.rand(5, 8, device=device, dtype=torch.float64)
+ desc2 = torch.rand(7, 8, device=device, dtype=torch.float64)
+ center1 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)
+ center2 = torch.rand(1, 7, 2, device=device, dtype=torch.float64)
lafs1 = laf_from_center_scale_ori(center1)
lafs2 = laf_from_center_scale_ori(center2)
- desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
- desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
- lafs1 = utils.tensor_to_gradcheck_var(lafs1) # to var
- lafs2 = utils.tensor_to_gradcheck_var(lafs2) # to var
- assert gradcheck(
- match_fginn, (desc1, desc2, lafs1, lafs2, 0.8, 0.05), raise_exception=True, nondet_tol=1e-4, fast_mode=True
- )
+ self.gradcheck(match_fginn, (desc1, desc2, lafs1, lafs2, 0.8, 0.05), nondet_tol=1e-4)
@pytest.mark.jit()
@pytest.mark.skip("keyword-arg expansion is not supported")
@@ -346,17 +332,17 @@ class TestMatchFGINN:
lafs2 = laf_from_center_scale_ori(center2)
matcher = GeometryAwareDescriptorMatcher("fginn", 0.8).to(device)
matcher_jit = torch.jit.script(GeometryAwareDescriptorMatcher("fginn", 0.8).to(device))
- assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2, lafs1, lafs2)[0])
- assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2, lafs1, lafs2)[1])
+ self.assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2, lafs1, lafs2)[0])
+ self.assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2, lafs1, lafs2)[1])
-class TestAdalam:
+class TestAdalam(BaseTester):
@pytest.mark.slow
@pytest.mark.parametrize("data", ["adalam_idxs"], indirect=True)
def test_real(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
with torch.no_grad():
dists, idxs = match_adalam(data_dev["descs1"], data_dev["descs2"], data_dev["lafs1"], data_dev["lafs2"])
assert idxs.shape[1] == 2
@@ -365,14 +351,14 @@ class TestAdalam:
assert dists.shape[0] <= data_dev["descs1"].shape[0]
assert dists.shape[0] <= data_dev["descs2"].shape[0]
expected_idxs = data_dev["expected_idxs"].long()
- assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
+ self.assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
@pytest.mark.slow
@pytest.mark.parametrize("data", ["adalam_idxs"], indirect=True)
def test_single_nocrash(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
with torch.no_grad():
dists, idxs = match_adalam(
data_dev["descs1"], data_dev["descs2"][:1], data_dev["lafs1"], data_dev["lafs2"][:, :1]
@@ -386,7 +372,7 @@ class TestAdalam:
def test_small_user_conf(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
adalam_config = {"device": device}
with torch.no_grad():
dists, idxs = match_adalam(
@@ -402,7 +388,7 @@ class TestAdalam:
def test_empty_nocrash(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
with torch.no_grad():
dists, idxs = match_adalam(
data_dev["descs1"],
@@ -422,7 +408,7 @@ class TestAdalam:
def test_small(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
with torch.no_grad():
dists, idxs = match_adalam(
data_dev["descs1"][:4], data_dev["descs2"][:4], data_dev["lafs1"][:, :4], data_dev["lafs2"][:, :4]
@@ -433,7 +419,7 @@ class TestAdalam:
def test_seeds_fail(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
with torch.no_grad():
dists, idxs = match_adalam(
data_dev["descs1"][:100],
@@ -447,7 +433,7 @@ class TestAdalam:
def test_module(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
matcher = GeometryAwareDescriptorMatcher("adalam", {"device": device}).to(device, dtype)
with torch.no_grad():
dists, idxs = matcher(data_dev["descs1"], data_dev["descs2"], data_dev["lafs1"], data_dev["lafs2"])
@@ -457,16 +443,16 @@ class TestAdalam:
assert dists.shape[0] <= data_dev["descs1"].shape[0]
assert dists.shape[0] <= data_dev["descs2"].shape[0]
expected_idxs = data_dev["expected_idxs"].long()
- assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
+ self.assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
-class TestLightGlueDISK:
+class TestLightGlueDISK(BaseTester):
@pytest.mark.slow
@pytest.mark.parametrize("data", ["lightglue_idxs"], indirect=True)
def test_real(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
config = {"depth_confidence": -1, "width_confidence": -1}
lg = LightGlueMatcher("disk", config).to(device=device, dtype=dtype).eval()
with torch.no_grad():
@@ -477,14 +463,14 @@ class TestLightGlueDISK:
assert dists.shape[0] <= data_dev["descs1"].shape[0]
assert dists.shape[0] <= data_dev["descs2"].shape[0]
expected_idxs = data_dev["lightglue_disk_idxs"].long()
- assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
+ self.assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
@pytest.mark.slow
@pytest.mark.parametrize("data", ["lightglue_idxs"], indirect=True)
def test_single_nocrash(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
lg = LightGlueMatcher("disk").to(device, dtype).eval()
with torch.no_grad():
dists, idxs = lg(data_dev["descs1"], data_dev["descs2"][:1], data_dev["lafs1"], data_dev["lafs2"][:, :1])
@@ -495,7 +481,7 @@ class TestLightGlueDISK:
def test_empty_nocrash(self, device, dtype, data):
torch.random.manual_seed(0)
# This is not unit test, but that is quite good integration test
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
lg = LightGlueMatcher("disk").to(device, dtype).eval()
with torch.no_grad():
dists, idxs = lg(
diff --git a/tests/feature/test_mkd.py b/tests/feature/test_mkd.py
index df4d05af1..7ca7f93b9 100644
--- a/tests/feature/test_mkd.py
+++ b/tests/feature/test_mkd.py
@@ -2,9 +2,7 @@ from math import pi
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature.mkd import (
COEFFS,
EmbedGradients,
@@ -18,7 +16,8 @@ from kornia.feature.mkd import (
get_kron_order,
spatial_kernel_embedding,
)
-from kornia.testing import assert_close
+
+from testing.base import BaseTester
@pytest.mark.parametrize("ps", [5, 13, 25])
@@ -36,7 +35,7 @@ def test_get_kron_order(d1, d2):
assert out.shape == (d1 * d2, 2)
-class TestMKDGradients:
+class TestMKDGradients(BaseTester):
@pytest.mark.parametrize("ps", [5, 13, 25])
def test_shape(self, ps, device):
inp = torch.ones(1, 1, ps, ps).to(device)
@@ -64,23 +63,22 @@ class TestMKDGradients:
expected_mags = expected_mags_1.unsqueeze(0).repeat(6, 1)
expected_oris_1 = torch.Tensor([-pi, -pi, 0, 0, -pi, -pi]).to(device)
expected_oris = expected_oris_1.unsqueeze(0).repeat(6, 1)
- assert_close(out[0, 0, :, :], expected_mags, atol=1e-3, rtol=1e-3)
- assert_close(out[0, 1, :, :], expected_oris, atol=1e-3, rtol=1e-3)
+ self.assert_close(out[0, 0, :, :], expected_mags, atol=1e-3, rtol=1e-3)
+ self.assert_close(out[0, 1, :, :], expected_oris, atol=1e-3, rtol=1e-3)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 13, 13
- patches = torch.rand(batch_size, channels, height, width).to(device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
def grad_describe(patches):
mkd_grads = MKDGradients()
mkd_grads.to(device)
return mkd_grads(patches)
- assert gradcheck(grad_describe, (patches), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ self.gradcheck(grad_describe, (patches), nondet_tol=1e-4)
-class TestVonMisesKernel:
+class TestVonMisesKernel(BaseTester):
@pytest.mark.parametrize("ps", [5, 13, 25])
def test_shape(self, ps, device):
inp = torch.ones(1, 1, ps, ps).to(device)
@@ -112,27 +110,26 @@ class TestVonMisesKernel:
vm = VonMisesKernel(patch_size=6, coeffs=[0.38214156, 0.48090413]).to(device)
out = vm(patch)
expected = torch.ones_like(out[0, 0, :, :]).to(device)
- assert_close(out[0, 0, :, :], expected * 0.6182, atol=1e-3, rtol=1e-3)
+ self.assert_close(out[0, 0, :, :], expected * 0.6182, atol=1e-3, rtol=1e-3)
expected = torch.Tensor([0.3747, 0.3747, 0.3747, 0.6935, 0.6935, 0.6935]).to(device)
expected = expected.unsqueeze(0).repeat(6, 1)
- assert_close(out[0, 1, :, :], expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(out[0, 1, :, :], expected, atol=1e-3, rtol=1e-3)
expected = torch.Tensor([0.5835, 0.5835, 0.5835, 0.0000, 0.0000, 0.0000]).to(device)
expected = expected.unsqueeze(0).repeat(6, 1)
- assert_close(out[0, 2, :, :], expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(out[0, 2, :, :], expected, atol=1e-3, rtol=1e-3)
def test_gradcheck(self, device):
batch_size, channels, ps = 1, 1, 13
- patches = torch.rand(batch_size, channels, ps, ps).to(device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(batch_size, channels, ps, ps, device=device, dtype=torch.float64)
def vm_describe(patches, ps=13):
vmkernel = VonMisesKernel(patch_size=ps, coeffs=[0.38214156, 0.48090413]).double()
vmkernel.to(device)
return vmkernel(patches.double())
- assert gradcheck(vm_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ self.gradcheck(vm_describe, (patches, ps), nondet_tol=1e-4)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -142,10 +139,10 @@ class TestVonMisesKernel:
model_jit = torch.jit.script(
VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval()
)
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
-class TestEmbedGradients:
+class TestEmbedGradients(BaseTester):
@pytest.mark.parametrize("ps,relative", [(5, True), (13, True), (25, True), (5, False), (13, False), (25, False)])
def test_shape(self, ps, relative, device):
inp = torch.ones(1, 2, ps, ps).to(device)
@@ -170,22 +167,21 @@ class TestEmbedGradients:
emb_grads = EmbedGradients(patch_size=6, relative=True).to(device)
out = emb_grads(grads)
expected = torch.ones_like(out[0, 0, :, :3]).to(device)
- assert_close(out[0, 0, :, :3], expected * 0.3787, atol=1e-3, rtol=1e-3)
- assert_close(out[0, 0, :, 3:], expected * 0, atol=1e-3, rtol=1e-3)
+ self.assert_close(out[0, 0, :, :3], expected * 0.3787, atol=1e-3, rtol=1e-3)
+ self.assert_close(out[0, 0, :, 3:], expected * 0, atol=1e-3, rtol=1e-3)
# TODO: review this test implementation
# @pytest.mark.xfail(reason="RuntimeError: Jacobian mismatch for output 0 with respect to input 0,")
def test_gradcheck(self, device):
batch_size, channels, ps = 1, 2, 13
- patches = torch.rand(batch_size, channels, ps, ps).to(device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(batch_size, channels, ps, ps, device=device, dtype=torch.float64)
def emb_grads_describe(patches, ps=13):
emb_grads = EmbedGradients(patch_size=ps, relative=True).double()
emb_grads.to(device)
return emb_grads(patches.double())
- assert gradcheck(emb_grads_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ self.gradcheck(emb_grads_describe, (patches, ps), nondet_tol=1e-4)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -195,7 +191,7 @@ class TestEmbedGradients:
model_jit = torch.jit.script(
EmbedGradients(patch_size=W, relative=True).to(patches.device, patches.dtype).eval()
)
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
@pytest.mark.parametrize("kernel_type,d,ps", [("cart", 9, 9), ("polar", 25, 9), ("cart", 9, 16), ("polar", 25, 16)])
@@ -205,7 +201,7 @@ def test_spatial_kernel_embedding(kernel_type, ps, d):
assert spatial_kernel.shape == (d, ps, ps)
-class TestExplicitSpacialEncoding:
+class TestExplicitSpacialEncoding(BaseTester):
@pytest.mark.parametrize(
"kernel_type,ps,in_dims", [("cart", 9, 3), ("polar", 9, 3), ("cart", 13, 7), ("polar", 13, 7)]
)
@@ -238,28 +234,25 @@ class TestExplicitSpacialEncoding:
out = cart_ese(inp)
out_part = out[:, :9]
expected = torch.zeros_like(out_part).to(device)
- assert_close(out_part, expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(out_part, expected, atol=1e-3, rtol=1e-3)
polar_ese = ExplicitSpacialEncoding(kernel_type="polar", fmap_size=6, in_dims=2).to(device)
out = polar_ese(inp)
out_part = out[:, :25]
expected = torch.zeros_like(out_part).to(device)
- assert_close(out_part, expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(out_part, expected, atol=1e-3, rtol=1e-3)
@pytest.mark.parametrize("kernel_type", ["cart", "polar"])
def test_gradcheck(self, kernel_type, device):
batch_size, channels, ps = 1, 2, 13
- patches = torch.rand(batch_size, channels, ps, ps).to(device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(batch_size, channels, ps, ps, device=device, dtype=torch.float64)
def explicit_spatial_describe(patches, ps=13):
ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=ps, in_dims=2)
ese.to(device)
return ese(patches)
- assert gradcheck(
- explicit_spatial_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4, fast_mode=True
- )
+ self.gradcheck(explicit_spatial_describe, (patches, ps), nondet_tol=1e-4)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -271,10 +264,10 @@ class TestExplicitSpacialEncoding:
model_jit = torch.jit.script(
ExplicitSpacialEncoding(kernel_type="cart", fmap_size=W, in_dims=2).to(patches.device, patches.dtype).eval()
)
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
-class TestWhitening:
+class TestWhitening(BaseTester):
@pytest.mark.parametrize(
"kernel_type,xform,output_dims",
[
@@ -309,19 +302,18 @@ class TestWhitening:
inp = torch.ones(1, 175).to(device).float()
out = wh(inp)
expected = torch.ones_like(inp).to(device) * 0.0756
- assert_close(out, expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(out, expected, atol=1e-3, rtol=1e-3)
def test_gradcheck(self, device):
batch_size, in_dims = 1, 175
- patches = torch.rand(batch_size, in_dims).to(device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(batch_size, in_dims, device=device, dtype=torch.float64)
def whitening_describe(patches, in_dims=175):
wh = Whitening(xform="lw", whitening_model=None, in_dims=in_dims).double()
wh.to(device)
return wh(patches.double())
- assert gradcheck(whitening_describe, (patches, in_dims), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ self.gradcheck(whitening_describe, (patches, in_dims), nondet_tol=1e-4)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -331,10 +323,10 @@ class TestWhitening:
model_jit = torch.jit.script(
Whitening(xform="lw", whitening_model=None, in_dims=in_dims).to(patches.device, patches.dtype).eval()
)
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
-class TestMKDDescriptor:
+class TestMKDDescriptor(BaseTester):
dims = {"cart": 63, "polar": 175, "concat": 238}
@pytest.mark.parametrize(
@@ -382,20 +374,19 @@ class TestMKDDescriptor:
out = mkd(inp)
out_part = out[0, -28:]
expected = torch.zeros_like(out_part).to(device)
- assert_close(out_part, expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(out_part, expected, atol=1e-3, rtol=1e-3)
@pytest.mark.parametrize("whitening", [None, "lw", "pca"])
def test_gradcheck(self, whitening, device):
batch_size, channels, ps = 1, 1, 19
- patches = torch.rand(batch_size, channels, ps, ps).to(device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(batch_size, channels, ps, ps, device=device, dtype=torch.float64)
def mkd_describe(patches, patch_size=19):
mkd = MKDDescriptor(patch_size=patch_size, kernel_type="concat", whitening=whitening).double()
mkd.to(device)
return mkd(patches.double())
- assert gradcheck(mkd_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ self.gradcheck(mkd_describe, (patches, ps), nondet_tol=1e-4)
@pytest.mark.skip("neither dict, nor nn.ModuleDict works")
@pytest.mark.jit()
@@ -408,10 +399,10 @@ class TestMKDDescriptor:
model_jit = torch.jit.script(
MKDDescriptor(patch_size=ps, kernel_type=kt, whitening=wt).to(patches.device, patches.dtype).eval()
)
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
-class TestSimpleKD:
+class TestSimpleKD(BaseTester):
dims = {"cart": 63, "polar": 175}
@pytest.mark.parametrize("ps,kernel_type", [(9, "cart"), (9, "polar"), (32, "cart"), (32, "polar")])
@@ -434,12 +425,11 @@ class TestSimpleKD:
def test_gradcheck(self, device):
batch_size, channels, ps = 1, 1, 19
- patches = torch.rand(batch_size, channels, ps, ps).to(device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(batch_size, channels, ps, ps, device=device, dtype=torch.float64)
def skd_describe(patches, patch_size=19):
skd = SimpleKD(patch_size=ps, kernel_type="polar", whitening="lw").double()
skd.to(device)
return skd(patches.double())
- assert gradcheck(skd_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ self.gradcheck(skd_describe, (patches, ps), nondet_tol=1e-4)
diff --git a/tests/feature/test_responces_local_features.py b/tests/feature/test_responces_local_features.py
index 1f5166fbd..f610224d4 100644
--- a/tests/feature/test_responces_local_features.py
+++ b/tests/feature/test_responces_local_features.py
@@ -1,12 +1,11 @@
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestCornerHarris:
+
+class TestCornerHarris(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
harris = kornia.feature.CornerHarris(k=0.04).to(device)
@@ -55,7 +54,7 @@ class TestCornerHarris:
).float()
harris = kornia.feature.CornerHarris(k=0.04).to(device)
scores = harris(inp)
- assert_close(scores, expected, atol=1e-4, rtol=1e-3)
+ self.assert_close(scores, expected, atol=1e-4, rtol=1e-3)
def test_corners_batch(self, device, dtype):
inp = torch.tensor(
@@ -110,19 +109,16 @@ class TestCornerHarris:
/ 10.0
)
scores = kornia.feature.harris_response(inp, k=0.04)
- assert_close(scores, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(scores, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
k = 0.04
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.feature.harris_response, (img, k), raise_exception=True, nondet_tol=1e-4, fast_mode=True
- )
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.harris_response, (img, k), nondet_tol=1e-4)
-class TestCornerGFTT:
+class TestCornerGFTT(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
shi_tomasi = kornia.feature.CornerGFTT().to(device)
@@ -171,7 +167,7 @@ class TestCornerGFTT:
).float()
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
- assert_close(scores, expected, atol=1e-4, rtol=1e-3)
+ self.assert_close(scores, expected, atol=1e-4, rtol=1e-3)
def test_corners_batch(self, device, dtype):
inp = torch.tensor(
@@ -224,16 +220,15 @@ class TestCornerGFTT:
).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
- assert_close(scores, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(scores, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.gftt_response, (img), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.gftt_response, (img), nondet_tol=1e-4)
-class TestBlobHessian:
+class TestBlobHessian(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
shi_tomasi = kornia.feature.BlobHessian().to(device)
@@ -295,16 +290,15 @@ class TestBlobHessian:
).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.BlobHessian().to(device)
scores = shi_tomasi(inp)
- assert_close(scores, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(scores, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.hessian_response, (img), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.hessian_response, (img), nondet_tol=1e-4)
-class TestBlobDoGSingle:
+class TestBlobDoGSingle(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 9, 9, device=device)
shi_tomasi = kornia.feature.BlobDoGSingle().to(device)
@@ -368,12 +362,9 @@ class TestBlobDoGSingle:
).expand(2, 2, 7, 7)
det = kornia.feature.BlobDoGSingle(1.0, 1.6).to(device)
scores = det(inp)
- assert_close(scores, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(scores, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 9, 11
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.feature.dog_response_single, (img), raise_exception=True, nondet_tol=1e-4, fast_mode=True
- )
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.dog_response_single, (img), nondet_tol=1e-4)
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 7cbbf6555..c8dd2b9d8 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -1,13 +1,12 @@
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
from kornia.feature.scale_space_detector import ScaleSpaceDetector
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestScaleSpaceDetector:
+
+class TestScaleSpaceDetector(BaseTester):
def test_shape(self, device, dtype):
inp = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
n_feats = 10
@@ -32,8 +31,8 @@ class TestScaleSpaceDetector:
lafs, resps = det(inp)
expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device, dtype=dtype)
expected_resp = torch.tensor([[0.0857]], device=device, dtype=dtype)
- assert_close(lafs, expected_laf, rtol=0.001, atol=1e-03)
- assert_close(resps, expected_resp, rtol=0.001, atol=1e-03)
+ self.assert_close(lafs, expected_laf, rtol=0.001, atol=1e-03)
+ self.assert_close(resps, expected_resp, rtol=0.001, atol=1e-03)
def test_toy_mask(self, device, dtype):
inp = torch.zeros(1, 1, 33, 33, device=device, dtype=dtype)
@@ -47,13 +46,10 @@ class TestScaleSpaceDetector:
lafs, resps = det(inp, mask)
expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device, dtype=dtype)
expected_resp = torch.tensor([[0.0857]], device=device, dtype=dtype)
- assert_close(lafs, expected_laf, rtol=0.001, atol=1e-03)
- assert_close(resps, expected_resp, rtol=0.001, atol=1e-03)
+ self.assert_close(lafs, expected_laf, rtol=0.001, atol=1e-03)
+ self.assert_close(resps, expected_resp, rtol=0.001, atol=1e-03)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 7, 7
- patches = torch.rand(batch_size, channels, height, width, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(
- ScaleSpaceDetector(2).to(device), patches, raise_exception=True, nondet_tol=1e-4, fast_mode=True
- )
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(ScaleSpaceDetector(2).to(device), patches, nondet_tol=1e-4)
diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.py
index f9de13c99..740a5b907 100644
--- a/tests/feature/test_siftdesc.py
+++ b/tests/feature/test_siftdesc.py
@@ -1,15 +1,14 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature.siftdesc import (
DenseSIFTDescriptor,
SIFTDescriptor,
get_sift_bin_ksize_stride_pad,
get_sift_pooling_kernel,
)
-from kornia.testing import assert_close
+
+from testing.base import BaseTester
@pytest.mark.parametrize("ksize", [5, 13, 25])
@@ -24,8 +23,7 @@ def test_get_sift_bin_ksize_stride_pad(ps, n_bins, ksize, stride, pad):
assert out == (ksize, stride, pad)
-# TODO: add kornia.testing.BaseTester
-class TestSIFTDescriptor:
+class TestSIFTDescriptor(BaseTester):
def test_shape(self, device, dtype):
inp = torch.ones(1, 1, 32, 32, device=device, dtype=dtype)
sift = SIFTDescriptor(32).to(device, dtype)
@@ -50,15 +48,14 @@ class TestSIFTDescriptor:
sift = SIFTDescriptor(6, num_ang_bins=4, num_spatial_bins=1, clipval=0.2, rootsift=False).to(device, dtype)
out = sift(patch)
expected = torch.tensor([[0, 0, 1.0, 0]], device=device, dtype=dtype)
- assert_close(out, expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(out, expected, atol=1e-3, rtol=1e-3)
def test_gradcheck(self, device):
dtype = torch.float64
batch_size, channels, height, width = 1, 1, 15, 15
patches = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
sift = SIFTDescriptor(15).to(device, dtype)
- assert gradcheck(sift, (patches,), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ self.gradcheck(sift, (patches,), nondet_tol=1e-4)
@pytest.mark.skip("Compiled functions can't take variable number")
def test_jit(self, device, dtype):
@@ -66,11 +63,10 @@ class TestSIFTDescriptor:
patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
model = SIFTDescriptor(41).to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(SIFTDescriptor(41).to(patches.device, patches.dtype).eval())
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
-# TODO: add kornia.testing.BaseTester
-class TestDenseSIFTDescriptor:
+class TestDenseSIFTDescriptor(BaseTester):
def test_shape_default(self, device, dtype):
bs, h, w = 1, 20, 15
inp = torch.rand(1, 1, h, w, device=device, dtype=dtype)
@@ -96,8 +92,7 @@ class TestDenseSIFTDescriptor:
sift = DenseSIFTDescriptor()
sift.__repr__()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 16, 16
- patches = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(DenseSIFTDescriptor(4, 2, 2), (patches), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(DenseSIFTDescriptor(4, 2, 2), (patches), nondet_tol=1e-4)
diff --git a/tests/feature/test_sold2.py b/tests/feature/test_sold2.py
index 08193810d..dc6fa4820 100644
--- a/tests/feature/test_sold2.py
+++ b/tests/feature/test_sold2.py
@@ -1,14 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils
from kornia.feature.sold2 import SOLD2, SOLD2_detector
-from kornia.testing import assert_close
+from testing.base import BaseTester
-# TODO: add kornia.testing.BaseTester
-class TestSOLD2_detector:
+
+class TestSOLD2_detector(BaseTester):
@pytest.mark.slow
@pytest.mark.parametrize("batch_size", [1, 2])
def test_shape(self, device, batch_size, dtype):
@@ -20,14 +18,13 @@ class TestSOLD2_detector:
@pytest.mark.skip("Takes ages to run")
def test_gradcheck(self, device):
- img = torch.rand(2, 1, 128, 128, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(2, 1, 128, 128, device=device, dtype=torch.float64)
sold2 = SOLD2_detector(pretrained=False).to(img.device, img.dtype)
def proxy_forward(x):
return sold2.forward(x)["junction_heatmap"]
- assert gradcheck(proxy_forward, (img,), eps=1e-4, atol=1e-4, raise_exception=True, fast_mode=True)
+ self.gradcheck(proxy_forward, (img,), eps=1e-4, atol=1e-4)
@pytest.mark.skip("Does not like recursive definition of Hourglass in backbones.py l.134.")
def test_jit(self, device, dtype):
@@ -35,11 +32,10 @@ class TestSOLD2_detector:
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
model = SOLD2_detector().to(img.device, img.dtype).eval()
model_jit = torch.jit.script(model)
- assert_close(model(img), model_jit(img))
+ self.assert_close(model(img), model_jit(img))
-# TODO: add kornia.testing.BaseTester
-class TestSOLD2:
+class TestSOLD2(BaseTester):
@pytest.mark.slow
@pytest.mark.parametrize("batch_size", [1, 2])
def test_shape(self, device, batch_size, dtype):
@@ -50,14 +46,13 @@ class TestSOLD2:
@pytest.mark.skip("Takes ages to run")
def test_gradcheck(self, device):
- img = torch.rand(2, 1, 256, 256, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(2, 1, 256, 256, device=device, dtype=torch.float64)
sold2 = SOLD2(pretrained=False).to(img.device, img.dtype)
def proxy_forward(x):
return sold2.forward(x)["dense_desc"]
- assert gradcheck(proxy_forward, (img,), eps=1e-4, atol=1e-4, raise_exception=True)
+ self.gradcheck(proxy_forward, (img,), eps=1e-4, atol=1e-4)
@pytest.mark.skip("Does not like recursive definition of Hourglass in backbones.py l.134.")
def test_jit(self, device, dtype):
@@ -65,4 +60,4 @@ class TestSOLD2:
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
model = SOLD2().to(img.device, img.dtype).eval()
model_jit = torch.jit.script(model)
- assert_close(model(img), model_jit(img))
+ self.assert_close(model(img), model_jit(img))
diff --git a/tests/feature/test_sosnet.py b/tests/feature/test_sosnet.py
index ffd1af224..f721c3e63 100644
--- a/tests/feature/test_sosnet.py
+++ b/tests/feature/test_sosnet.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature import SOSNet
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestSOSNet:
+
+class TestSOSNet(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
sosnet = SOSNet(pretrained=False).to(device)
@@ -23,10 +22,9 @@ class TestSOSNet:
@pytest.mark.skip("jacobian not well computed")
def test_gradcheck(self, device):
- patches = torch.rand(2, 1, 32, 32, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)
sosnet = SOSNet(pretrained=False).to(patches.device, patches.dtype)
- assert gradcheck(sosnet, (patches,), eps=1e-4, atol=1e-4, raise_exception=True, fast_mode=True)
+ self.gradcheck(sosnet, (patches,), eps=1e-4, atol=1e-4)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -34,4 +32,4 @@ class TestSOSNet:
patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
model = SOSNet().to(patches.device, patches.dtype).eval()
model_jit = torch.jit.script(SOSNet().to(patches.device, patches.dtype).eval())
- assert_close(model(patches), model_jit(patches))
+ self.assert_close(model(patches), model_jit(patches))
diff --git a/tests/feature/test_tfeat.py b/tests/feature/test_tfeat.py
index 2b149d4e0..0f16c6acb 100644
--- a/tests/feature/test_tfeat.py
+++ b/tests/feature/test_tfeat.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.feature import TFeat
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestTFeat:
+
+class TestTFeat(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
tfeat = TFeat().to(device)
@@ -31,10 +30,9 @@ class TestTFeat:
@pytest.mark.skip("jacobian not well computed")
def test_gradcheck(self, device):
- patches = torch.rand(2, 1, 32, 32, device=device)
- patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)
tfeat = TFeat().to(patches.device, patches.dtype)
- assert gradcheck(tfeat, (patches,), eps=1e-2, atol=1e-2, raise_exception=True, fast_mode=True)
+ self.gradcheck(tfeat, (patches,), eps=1e-2, atol=1e-2)
@pytest.mark.slow
@pytest.mark.jit()
@@ -43,4 +41,4 @@ class TestTFeat:
patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
tfeat = TFeat(True).to(patches.device, patches.dtype).eval()
tfeat_jit = torch.jit.script(TFeat(True).to(patches.device, patches.dtype).eval())
- assert_close(tfeat_jit(patches), tfeat(patches))
+ self.assert_close(tfeat_jit(patches), tfeat(patches))
diff --git a/tests/filters/test_bilateral.py b/tests/filters/test_bilateral.py
index 9f789b950..47989a5d0 100644
--- a/tests/filters/test_bilateral.py
+++ b/tests/filters/test_bilateral.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.filters import BilateralBlur, JointBilateralBlur, bilateral_blur, joint_bilateral_blur
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class TestBilateralBlur(BaseTester):
@@ -52,12 +53,9 @@ class TestBilateralBlur(BaseTester):
assert actual.is_contiguous()
def test_gradcheck(self, device):
- img = torch.rand(1, 2, 5, 4, device=device)
- sigma_color = torch.rand(1, device=device)
- sigma_space = torch.rand(1, 2, device=device)
- img = tensor_to_gradcheck_var(img) # to var
- sigma_color = tensor_to_gradcheck_var(sigma_color)
- sigma_space = tensor_to_gradcheck_var(sigma_space)
+ img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
+ sigma_color = torch.rand(1, device=device, dtype=torch.float64)
+ sigma_space = torch.rand(1, 2, device=device, dtype=torch.float64)
self.gradcheck(bilateral_blur, (img, 3, 1, (1, 1)))
self.gradcheck(bilateral_blur, (img, 3, sigma_color, (1, 1)))
@@ -219,10 +217,8 @@ class TestJointBilateralBlur(BaseTester):
assert actual.is_contiguous()
def test_gradcheck(self, device):
- img = torch.rand(1, 2, 5, 4, device=device)
- guide = torch.rand(1, 2, 5, 4, device=device)
- img = tensor_to_gradcheck_var(img) # to var
- guide = tensor_to_gradcheck_var(guide)
+ img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
+ guide = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
self.gradcheck(joint_bilateral_blur, (img, guide, 3, 1, (1, 1)))
def test_module(self, device, dtype):
diff --git a/tests/filters/test_blur.py b/tests/filters/test_blur.py
index ed1a33071..755a30851 100644
--- a/tests/filters/test_blur.py
+++ b/tests/filters/test_blur.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.filters import BoxBlur, box_blur
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class TestBoxBlur(BaseTester):
@@ -109,10 +110,9 @@ class TestBoxBlur(BaseTester):
assert actual.is_contiguous()
@pytest.mark.parametrize("kernel_size", [(3, 3), 5, (5, 7)])
- def test_gradcheck(self, kernel_size, device, dtype):
+ def test_gradcheck(self, kernel_size, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
fast_mode = "cpu" in str(device) # Disable fast mode for GPU
self.gradcheck(box_blur, (img, kernel_size), fast_mode=fast_mode)
diff --git a/tests/filters/test_blur_pool.py b/tests/filters/test_blur_pool.py
index baf7f258c..6eb6cd5d7 100644
--- a/tests/filters/test_blur_pool.py
+++ b/tests/filters/test_blur_pool.py
@@ -9,7 +9,8 @@ from kornia.filters import (
edge_aware_blur_pool2d,
max_blur_pool2d,
)
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class TestMaxBlurPool(BaseTester):
@@ -45,8 +46,7 @@ class TestMaxBlurPool(BaseTester):
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(max_blur_pool2d, (img, 3))
@pytest.mark.parametrize("kernel_size", [(3, 3), 5])
@@ -104,8 +104,7 @@ class TestBlurPool(BaseTester):
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(blur_pool2d, (img, 3))
@pytest.mark.parametrize("kernel_size", [3, (5, 5)])
@@ -177,8 +176,7 @@ class TestEdgeAwareBlurPool(BaseTester):
self.assert_close(actual, expected)
def test_gradcheck(self, device):
- img = torch.rand((1, 2, 5, 4), device=device)
- img = tensor_to_gradcheck_var(img) # to var
+ img = torch.rand((1, 2, 5, 4), device=device, dtype=torch.float64)
self.gradcheck(edge_aware_blur_pool2d, (img, 3))
def test_smooth(self, device, dtype):
diff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.py
index f8ff4eee9..dbd694dac 100644
--- a/tests/filters/test_canny.py
+++ b/tests/filters/test_canny.py
@@ -2,9 +2,10 @@ import pytest
import torch
from kornia.filters import Canny, canny
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
from kornia.utils._compat import torch_version
+from testing.base import BaseTester
+
class TestCanny(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2])
@@ -282,8 +283,7 @@ class TestCanny(BaseTester):
if "cuda" in str(device):
pytest.skip("RuntimeError: Backward is not reentrant, i.e., running backward,")
batch_size, channels, height, width = 1, 1, 3, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = tensor_to_gradcheck_var(img)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(canny, img)
def test_module(self, device, dtype):
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index 5cdf29776..260cc1a82 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -2,9 +2,10 @@ import pytest
import torch
from kornia.filters import DexiNed, filter2d, filter2d_separable, filter3d
-from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
from kornia.utils._compat import torch_version_le
+from testing.base import BaseTester
+
class TestFilter2D(BaseTester):
@pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
@@ -69,9 +70,9 @@ class TestFilter2D(BaseTester):
dtype=dtype,
)
out_corr = filter2d(inp, kernel, behaviour="corr")
- assert_close(out_corr, corr_expected)
+ self.assert_close(out_corr, corr_expected)
out_conv = filter2d(inp, kernel, behaviour="conv")
- assert_close(out_conv, conv_expected)
+ self.assert_close(out_conv, conv_expected)
def test_exception(self):
k = torch.ones(1, 1, 1)
@@ -345,12 +346,10 @@ class TestFilter2D(BaseTester):
self.assert_close(out, out_sep)
def test_gradcheck(self, device):
- kernel = torch.rand(1, 3, 3, device=device)
- sample = torch.ones(1, 1, 7, 8, device=device)
+ kernel = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ sample = torch.ones(1, 1, 7, 8, device=device, dtype=torch.float64)
# evaluate function gradient
- sample = tensor_to_gradcheck_var(sample) # to var
- kernel = tensor_to_gradcheck_var(kernel) # to var
self.gradcheck(filter2d, (sample, kernel), nondet_tol=1e-8)
@pytest.mark.skip(reason="filter2d do not have a module")
@@ -705,12 +704,10 @@ class TestFilter3D(BaseTester):
assert actual.is_contiguous()
def test_gradcheck(self, device):
- kernel = torch.rand(1, 3, 3, 3, device=device)
- sample = torch.ones(1, 1, 6, 7, 8, device=device)
+ kernel = torch.rand(1, 3, 3, 3, device=device, dtype=torch.float64)
+ sample = torch.ones(1, 1, 6, 7, 8, device=device, dtype=torch.float64)
# evaluate function gradient
- sample = tensor_to_gradcheck_var(sample) # to var
- kernel = tensor_to_gradcheck_var(kernel) # to var
self.gradcheck(filter3d, (sample, kernel), nondet_tol=1e-8)
@pytest.mark.skip(reason="filter3d do not have a module")
@@ -730,7 +727,7 @@ class TestFilter3D(BaseTester):
self.assert_close(actual, expected)
-class TestDexiNed:
+class TestDexiNed(BaseTester):
def test_smoke(self, device, dtype):
img = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)
net = DexiNed(pretrained=False).to(device, dtype)
@@ -756,7 +753,7 @@ class TestDexiNed:
)
out = model(img)[-1]
- assert_close(out, expect, atol=3e-4, rtol=3e-4)
+ self.assert_close(out, expect, atol=3e-4, rtol=3e-4)
@pytest.mark.skip(reason="DexiNed do not compile with dynamo.")
def test_dynamo(self, device, dtype, torch_optimizer):
@@ -768,4 +765,4 @@ class TestDexiNed:
expected = op(inpt)
actual = op_optimized(inpt)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index 19dec5f0e..a8d2608bc 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -10,7 +10,8 @@ from kornia.filters import (
get_gaussian_kernel2d,
get_gaussian_kernel3d,
)
-from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
+
+from testing.base import BaseTester, assert_close
@pytest.mark.parametrize("window_size", [5, 11])
@@ -217,8 +218,7 @@ class TestGaussianBlur2d(BaseTester):
sigma = (1.5, 2.1)
# evaluate function gradient
- sample = torch.rand(batch_shape, device=device)
- sample = tensor_to_gradcheck_var(sample) # to var
+ sample = torch.rand(batch_shape, device=device, dtype=torch.float64)
self.gradcheck(gaussian_blur2d, (sample, kernel_size, sigma, "replicate"))
@pytest.mark.parametrize("kernel_size", [3, (5, 5), (5, 7)])
diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.py
index 00ace1714..b95be79bf 100644
--- a/tests/filters/test_guided.py
+++ b/tests/filters/test_guided.py
@@ -2,9 +2,10 @@ import pytest
import torch
from kornia.filters import GuidedBlur, guided_blur
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
from kornia.utils._compat import torch_version
+from testing.base import BaseTester
+
class TestGuidedBlur(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2])
@@ -67,14 +68,11 @@ class TestGuidedBlur(BaseTester):
assert actual.is_contiguous()
def test_gradcheck(self, device):
- guide = torch.rand(1, 2, 5, 4, device=device)
- img = torch.rand(1, 2, 5, 4, device=device)
- guide = tensor_to_gradcheck_var(guide) # to var
- img = tensor_to_gradcheck_var(img)
+ guide = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
+ img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
self.gradcheck(guided_blur, (guide, img, 3, 0.1))
- eps = torch.rand(1, device=device)
- eps = tensor_to_gradcheck_var(eps)
+ eps = torch.rand(1, device=device, dtype=torch.float64)
self.gradcheck(guided_blur, (guide, img, 3, eps))
@pytest.mark.parametrize("shape", [(1, 1, 8, 16), (2, 3, 12, 8)])
diff --git a/tests/filters/test_hanning.py b/tests/filters/test_hanning.py
index 79a0eed16..2ace0cbf5 100644
--- a/tests/filters/test_hanning.py
+++ b/tests/filters/test_hanning.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.filters import get_hanning_kernel1d, get_hanning_kernel2d
-from kornia.testing import assert_close
+
+from testing.base import assert_close
@pytest.mark.parametrize("window_size", [5, 11])
diff --git a/tests/filters/test_laplacian.py b/tests/filters/test_laplacian.py
index 8829a2115..c72645f3b 100644
--- a/tests/filters/test_laplacian.py
+++ b/tests/filters/test_laplacian.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.filters import Laplacian, get_laplacian_kernel1d, get_laplacian_kernel2d, laplacian
-from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
+
+from testing.base import BaseTester, assert_close
@pytest.mark.parametrize("window_size", [5, 11])
@@ -83,8 +84,7 @@ class TestLaplacian(BaseTester):
kernel_size = 3
# evaluate function gradient
- sample = torch.rand(batch_shape, device=device)
- sample = tensor_to_gradcheck_var(sample)
+ sample = torch.rand(batch_shape, device=device, dtype=torch.float64)
self.gradcheck(laplacian, (sample, kernel_size))
def test_module(self, device, dtype):
diff --git a/tests/filters/test_median.py b/tests/filters/test_median.py
index c4e0cdd68..e1c3648c9 100644
--- a/tests/filters/test_median.py
+++ b/tests/filters/test_median.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.filters import MedianBlur, median_blur
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class TestMedianBlur(BaseTester):
@@ -83,8 +84,7 @@ class TestMedianBlur(BaseTester):
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(median_blur, (img, (5, 3)))
def test_module(self, device, dtype):
diff --git a/tests/filters/test_motion.py b/tests/filters/test_motion.py
index c6623b242..351021678 100644
--- a/tests/filters/test_motion.py
+++ b/tests/filters/test_motion.py
@@ -9,7 +9,8 @@ from kornia.filters import (
motion_blur,
motion_blur3d,
)
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class TestMotionBlur(BaseTester):
@@ -80,8 +81,7 @@ class TestMotionBlur(BaseTester):
angle = 34.0
direction = -0.2
- sample = torch.rand(batch_shape, device=device)
- sample = tensor_to_gradcheck_var(sample)
+ sample = torch.rand(batch_shape, device=device, dtype=torch.float64)
self.gradcheck(motion_blur, (sample, ksize, angle, direction, "replicate"), nondet_tol=1e-8)
def test_module(self, device, dtype):
@@ -171,8 +171,7 @@ class TestMotionBlur3D(BaseTester):
angle = (0.0, 360.0, 150.0)
direction = -0.2
- sample = torch.rand(batch_shape, device=device)
- sample = tensor_to_gradcheck_var(sample)
+ sample = torch.rand(batch_shape, device=device, dtype=torch.float64)
self.gradcheck(motion_blur3d, (sample, ksize, angle, direction, "replicate"), nondet_tol=1e-8)
def test_module(self, device, dtype):
diff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.py
index 8e81771a2..70da63cce 100644
--- a/tests/filters/test_sobel.py
+++ b/tests/filters/test_sobel.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.filters import Sobel, SpatialGradient, SpatialGradient3d, sobel, spatial_gradient, spatial_gradient3d
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class TestSpatialGradient(BaseTester):
@@ -227,8 +228,7 @@ class TestSpatialGradient(BaseTester):
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 3, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(spatial_gradient, (img,))
def test_module(self, device, dtype):
@@ -394,8 +394,7 @@ class TestSpatialGradient3d(BaseTester):
self.assert_close(edges, expected)
def test_gradcheck(self, device):
- img = torch.rand(1, 1, 1, 3, 4, device=device)
- img = tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(1, 1, 1, 3, 4, device=device, dtype=torch.float64)
fast_mode = "cpu" in str(device) # disable fast mode on gpu
self.gradcheck(spatial_gradient3d, (img,), fast_mode=fast_mode)
@@ -491,8 +490,7 @@ class TestSobel(BaseTester):
@pytest.mark.parametrize("normalized", [True, False])
def test_gradcheck(self, normalized, device):
batch_size, channels, height, width = 1, 1, 3, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(sobel, (img, normalized))
def test_module(self, device, dtype):
diff --git a/tests/filters/test_unsharp_mask.py b/tests/filters/test_unsharp_mask.py
index 46a03cf53..ea2cd4c23 100644
--- a/tests/filters/test_unsharp_mask.py
+++ b/tests/filters/test_unsharp_mask.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.filters import UnsharpMask, unsharp_mask
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class Testunsharp(BaseTester):
@@ -48,8 +49,7 @@ class Testunsharp(BaseTester):
sigma = (1.5, 2.1)
# evaluate function gradient
- inpt = torch.rand(shape, device=device)
- inpt = tensor_to_gradcheck_var(inpt) # to var
+ inpt = torch.rand(shape, device=device, dtype=torch.float64)
self.gradcheck(unsharp_mask, (inpt, kernel_size, sigma, "replicate"))
def test_module(self, device, dtype):
diff --git a/tests/geometry/calibration/test_distort.py b/tests/geometry/calibration/test_distort.py
index 7dd51055c..93a338f60 100644
--- a/tests/geometry/calibration/test_distort.py
+++ b/tests/geometry/calibration/test_distort.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
from kornia.geometry.calibration.distort import distort_points
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestDistortPoints:
diff --git a/tests/geometry/calibration/test_pnp.py b/tests/geometry/calibration/test_pnp.py
index f3638381f..d677bb022 100644
--- a/tests/geometry/calibration/test_pnp.py
+++ b/tests/geometry/calibration/test_pnp.py
@@ -1,13 +1,13 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
from kornia.geometry.calibration.pnp import _mean_isotropic_scale_normalize
-from kornia.testing import assert_close, tensor_to_gradcheck_var
+from testing.base import BaseTester
-class TestSolvePnpDlt:
+
+class TestSolvePnpDlt(BaseTester):
@staticmethod
def _get_samples(shape, low, high, device, dtype):
"""Return a tensor having the given shape and whose values are in the range [low, high)"""
@@ -97,23 +97,17 @@ class TestSolvePnpDlt:
assert pred_world_to_cam.shape == (batch_size, 3, 4)
@pytest.mark.parametrize("num_points", (6,))
- def test_gradcheck(self, num_points, device, dtype):
- intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, dtype)
+ def test_gradcheck(self, num_points, device):
+ intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, torch.float64)
- world_points = tensor_to_gradcheck_var(world_points)
- img_points = tensor_to_gradcheck_var(img_points)
- intrinsics = tensor_to_gradcheck_var(intrinsics)
-
- assert gradcheck(
- kornia.geometry.solve_pnp_dlt, (world_points, img_points, intrinsics), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.solve_pnp_dlt, (world_points, img_points, intrinsics))
@pytest.mark.parametrize("num_points", (6, 20))
def test_pred_world_to_cam(self, num_points, device, dtype):
intrinsics, gt_world_to_cam, world_points, img_points = self._get_test_data(num_points, device, dtype)
pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)
- assert_close(pred_world_to_cam, gt_world_to_cam, atol=1e-4, rtol=1e-4)
+ self.assert_close(pred_world_to_cam, gt_world_to_cam, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("num_points", (6, 20))
def test_project(self, num_points, device, dtype):
@@ -127,10 +121,10 @@ class TestSolvePnpDlt:
repeated_intrinsics = intrinsics.unsqueeze(1).repeat(1, num_points, 1, 1)
pred_img_points = self._project_to_image(world_points, pred_world_to_cam_4x4, repeated_intrinsics)
- assert_close(pred_img_points, img_points, atol=1e-3, rtol=1e-3)
+ self.assert_close(pred_img_points, img_points, atol=1e-3, rtol=1e-3)
-class TestNormalization:
+class TestNormalization(BaseTester):
@pytest.mark.parametrize("dimension", (2, 3, 5))
def test_smoke(self, dimension, device, dtype):
batch_size = 10
@@ -142,10 +136,9 @@ class TestNormalization:
assert transform.shape == (batch_size, dimension + 1, dimension + 1)
@pytest.mark.parametrize("dimension", (2, 3, 5))
- def test_gradcheck(self, dimension, device, dtype):
+ def test_gradcheck(self, dimension, device):
batch_size = 3
num_points = 5
- points = torch.rand((batch_size, num_points, dimension), device=device, dtype=dtype)
- points = tensor_to_gradcheck_var(points)
+ points = torch.rand((batch_size, num_points, dimension), device=device, dtype=torch.float64)
- assert gradcheck(_mean_isotropic_scale_normalize, (points,), raise_exception=True, fast_mode=True)
+ self.gradcheck(_mean_isotropic_scale_normalize, (points,))
diff --git a/tests/geometry/calibration/test_undistort.py b/tests/geometry/calibration/test_undistort.py
index 42ffa0c1a..fb8d9af65 100644
--- a/tests/geometry/calibration/test_undistort.py
+++ b/tests/geometry/calibration/test_undistort.py
@@ -2,10 +2,11 @@ import pytest
import torch
from kornia.geometry.calibration.undistort import undistort_image, undistort_points
-from kornia.testing import assert_close, gradcheck
+from testing.base import BaseTester
-class TestUndistortPoints:
+
+class TestUndistortPoints(BaseTester):
def test_smoke(self, device, dtype):
points = torch.rand(1, 2, device=device, dtype=dtype)
K = torch.rand(3, 3, device=device, dtype=dtype)
@@ -67,7 +68,7 @@ class TestUndistortPoints:
[[1030.5992, 790.65533], [1027.3059, 718.10020], [1024.0700, 645.90600]], device=device, dtype=dtype
)
ptsu = undistort_points(pts, K, dist)
- assert_close(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
new_K = K * 2
new_K[2, 2] = 1
@@ -81,7 +82,7 @@ class TestUndistortPoints:
)
print(ptsu_expected)
ptsu = undistort_points(pts, K, dist, new_K)
- assert_close(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
def test_opencv_all_coeff(self, device, dtype):
# Test using 14 distortion coefficients
@@ -124,7 +125,7 @@ class TestUndistortPoints:
[[1030.8245, 786.3807], [1027.5505, 715.0732], [1024.2753, 644.0319]], device=device, dtype=dtype
)
ptsu = undistort_points(pts, K, dist)
- assert_close(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
new_K = K * 2
new_K[2, 2] = 1
@@ -138,7 +139,7 @@ class TestUndistortPoints:
)
print(ptsu_expected)
ptsu = undistort_points(pts, K, dist, new_K)
- assert_close(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
def test_opencv_stereo(self, device, dtype):
# Udistort stereo points with data given in two batches using 14 distortion coefficients
@@ -222,8 +223,8 @@ class TestUndistortPoints:
)
ptsu = undistort_points(pts, K, dist)
- assert_close(ptsu[0], ptsu_expected1, rtol=1e-4, atol=1e-4)
- assert_close(ptsu[1], ptsu_expected2, rtol=1e-4, atol=1e-4)
+ self.assert_close(ptsu[0], ptsu_expected1, rtol=1e-4, atol=1e-4)
+ self.assert_close(ptsu[1], ptsu_expected2, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device):
points = torch.rand(1, 8, 2, device=device, dtype=torch.float64, requires_grad=True)
@@ -231,7 +232,7 @@ class TestUndistortPoints:
new_K = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
distCoeff = torch.rand(1, 4, device=device, dtype=torch.float64)
- gradcheck(undistort_points, (points, K, distCoeff, new_K))
+ self.gradcheck(undistort_points, (points, K, distCoeff, new_K), requires_grad=(True, False, False, False))
def test_dynamo(self, device, dtype, torch_optimizer):
points = torch.rand(1, 1, 2, device=device, dtype=dtype)
@@ -242,10 +243,10 @@ class TestUndistortPoints:
op = undistort_points
op_optimized = torch_optimizer(op)
- assert_close(op(*inputs), op_optimized(*inputs))
+ self.assert_close(op(*inputs), op_optimized(*inputs))
-class TestUndistortImage:
+class TestUndistortImage(BaseTester):
def test_shape(self, device, dtype):
im = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
K = torch.rand(3, 3, device=device, dtype=dtype)
@@ -269,7 +270,7 @@ class TestUndistortImage:
imu = undistort_image(im, K, distCoeff)
assert imu.shape == (3, 2, 3, 5, 5)
- assert_close(imu[0], imu[1])
+ self.assert_close(imu[0], imu[1])
def test_exception(self, device, dtype):
with pytest.raises(ValueError):
@@ -333,14 +334,14 @@ class TestUndistortImage:
)
imu = undistort_image(im / 255.0, K, dist)
- assert_close(imu, imu_expected / 255.0, rtol=1e-2, atol=1e-2)
+ self.assert_close(imu, imu_expected / 255.0, rtol=1e-2, atol=1e-2)
def test_gradcheck(self, device):
im = torch.rand(1, 1, 15, 15, device=device, dtype=torch.float64, requires_grad=True)
K = torch.rand(3, 3, device=device, dtype=torch.float64)
distCoeff = torch.rand(4, device=device, dtype=torch.float64)
- gradcheck(undistort_image, (im, K, distCoeff))
+ self.gradcheck(undistort_image, (im, K, distCoeff), requires_grad=(True, False, False))
@pytest.mark.xfail(reason="Some times this seems to random fail")
def test_dynamo(self, device, dtype, torch_optimizer):
@@ -352,4 +353,4 @@ class TestUndistortImage:
op = undistort_image
op_optimized = torch_optimizer(op)
- assert_close(op(*inputs), op_optimized(*inputs))
+ self.assert_close(op(*inputs), op_optimized(*inputs))
diff --git a/tests/geometry/camera/test_distortion.py b/tests/geometry/camera/test_distortion.py
index bb6c23b67..a63915010 100644
--- a/tests/geometry/camera/test_distortion.py
+++ b/tests/geometry/camera/test_distortion.py
@@ -11,7 +11,8 @@ from kornia.geometry.camera.distortion_kannala_brandt import (
dx_distort_points_kannala_brandt,
undistort_points_kannala_brandt,
)
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+from testing.base import BaseTester
class TestDistortionAffine(BaseTester):
@@ -82,16 +83,12 @@ class TestDistortionAffine(BaseTester):
def _test_gradcheck_distort(self, device):
points = torch.tensor([1.0, 2.0], device=device, dtype=torch.float64)
- points = tensor_to_gradcheck_var(points)
params = torch.tensor([600.0, 600.0, 319.5, 239.5], device=device, dtype=torch.float64)
- params = tensor_to_gradcheck_var(params)
self.gradcheck(distort_points_affine, (points, params))
def _test_gradcheck_undistort(self, device):
points = torch.tensor([601.0, 602.0], device=device, dtype=torch.float64)
- points = tensor_to_gradcheck_var(points)
params = torch.tensor([600.0, 600.0, 319.5, 239.5], device=device, dtype=torch.float64)
- params = tensor_to_gradcheck_var(params)
self.gradcheck(undistort_points_affine, (points, params))
def test_gradcheck(self, device) -> None:
@@ -198,24 +195,20 @@ class TestDistortionKannalaBrandt(BaseTester):
def _test_gradcheck_distort(self, device):
points = torch.tensor([1.0, 2.0], device=device, dtype=torch.float64)
- points = tensor_to_gradcheck_var(points)
params = torch.tensor(
[600.0, 600.0, 319.5, 239.5, 0.1, 0.2, 0.3, 0.4],
device=device,
dtype=torch.float64,
)
- params = tensor_to_gradcheck_var(params)
self.gradcheck(distort_points_kannala_brandt, (points, params))
def _test_gradcheck_undistort(self, device):
points = torch.tensor([919.5000, 1439.5000], device=device, dtype=torch.float64)
- points = tensor_to_gradcheck_var(points)
params = torch.tensor(
[600.0, 600.0, 319.5, 239.5, 0.1, 0.2, 0.3, 0.4],
device=device,
dtype=torch.float64,
)
- params = tensor_to_gradcheck_var(params)
self.gradcheck(undistort_points_kannala_brandt, (points, params))
def test_gradcheck(self, device) -> None:
diff --git a/tests/geometry/camera/test_perspective.py b/tests/geometry/camera/test_perspective.py
index 9db12a51d..b363b3590 100644
--- a/tests/geometry/camera/test_perspective.py
+++ b/tests/geometry/camera/test_perspective.py
@@ -1,11 +1,11 @@
import torch
-from torch.autograd import gradcheck
import kornia
-from kornia.testing import assert_close, tensor_to_gradcheck_var
+from testing.base import BaseTester
-class TestProjectPoints:
+
+class TestProjectPoints(BaseTester):
def test_smoke(self, device, dtype):
point_3d = torch.zeros(1, 3, device=device, dtype=dtype)
camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
@@ -32,29 +32,25 @@ class TestProjectPoints:
)
point_2d = kornia.geometry.camera.project_points(point_3d, camera_matrix)
point_3d_hat = kornia.geometry.camera.unproject_points(point_2d, depth, camera_matrix)
- assert_close(point_3d, point_3d_hat, atol=1e-4, rtol=1e-4)
+ self.assert_close(point_3d, point_3d_hat, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# TODO: point [0, 0, 0] crashes
- points_3d = torch.ones(1, 3, device=device, dtype=dtype)
- camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
+ points_3d = torch.ones(1, 3, device=device)
+ camera_matrix = torch.eye(3, device=device).expand(1, -1, -1)
# evaluate function gradient
- points_3d = tensor_to_gradcheck_var(points_3d)
- camera_matrix = tensor_to_gradcheck_var(camera_matrix)
- assert gradcheck(
- kornia.geometry.camera.project_points, (points_3d, camera_matrix), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.camera.project_points, (points_3d, camera_matrix))
def test_jit(self, device, dtype):
points_3d = torch.zeros(1, 3, device=device, dtype=dtype)
camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
op = kornia.geometry.camera.project_points
op_jit = torch.jit.script(op)
- assert_close(op(points_3d, camera_matrix), op_jit(points_3d, camera_matrix))
+ self.assert_close(op(points_3d, camera_matrix), op_jit(points_3d, camera_matrix))
-class TestUnprojectPoints:
+class TestUnprojectPoints(BaseTester):
def test_smoke(self, device, dtype):
points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
depth = torch.ones(1, 1, device=device, dtype=dtype)
@@ -82,7 +78,7 @@ class TestUnprojectPoints:
camera_matrix = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
expected = torch.tensor([[0.0, 0.0, 2.0]], device=device, dtype=dtype)
actual = kornia.geometry.camera.unproject_points(point_2d, depth, camera_matrix)
- assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
def test_unproject_center_normalize(self, device, dtype):
point_2d = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)
@@ -90,7 +86,7 @@ class TestUnprojectPoints:
camera_matrix = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
expected = torch.tensor([[0.0, 0.0, 2.0]], device=device, dtype=dtype)
actual = kornia.geometry.camera.unproject_points(point_2d, depth, camera_matrix, True)
- assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
def test_unproject_and_project(self, device, dtype):
point_2d = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)
@@ -98,23 +94,15 @@ class TestUnprojectPoints:
camera_matrix = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
point_3d = kornia.geometry.camera.unproject_points(point_2d, depth, camera_matrix)
point_2d_hat = kornia.geometry.camera.project_points(point_3d, camera_matrix)
- assert_close(point_2d, point_2d_hat, atol=1e-4, rtol=1e-4)
+ self.assert_close(point_2d, point_2d_hat, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
- points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
- depth = torch.ones(1, 1, device=device, dtype=dtype)
- camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
+ def test_gradcheck(self, device):
+ points_2d = torch.zeros(1, 2, device=device, dtype=torch.float64)
+ depth = torch.ones(1, 1, device=device, dtype=torch.float64)
+ camera_matrix = torch.eye(3, device=device, dtype=torch.float64).expand(1, -1, -1)
# evaluate function gradient
- points_2d = tensor_to_gradcheck_var(points_2d)
- depth = tensor_to_gradcheck_var(depth)
- camera_matrix = tensor_to_gradcheck_var(camera_matrix)
- assert gradcheck(
- kornia.geometry.camera.unproject_points,
- (points_2d, depth, camera_matrix),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.camera.unproject_points, (points_2d, depth, camera_matrix))
def test_jit(self, device, dtype):
points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
@@ -123,4 +111,4 @@ class TestUnprojectPoints:
args = (points_2d, depth, camera_matrix)
op = kornia.geometry.camera.unproject_points
op_jit = torch.jit.script(op)
- assert_close(op(*args), op_jit(*args))
+ self.assert_close(op(*args), op_jit(*args))
diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.py
index 54b111ce8..44f678e44 100644
--- a/tests/geometry/camera/test_pinhole.py
+++ b/tests/geometry/camera/test_pinhole.py
@@ -2,13 +2,13 @@ import math
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-from kornia.testing import assert_close, tensor_to_gradcheck_var
+from testing.base import BaseTester
-class TestCam2Pixel:
+
+class TestCam2Pixel(BaseTester):
def _create_intrinsics(self, batch_size, fx, fy, cx, cy, device, dtype):
temp = torch.eye(4, device=device, dtype=dtype)
temp[0, 0], temp[0, 2] = fx, cx
@@ -81,10 +81,11 @@ class TestCam2Pixel:
depth=depth, intrinsics_inv=intrinsics_inv, pixel_coords=pixel_coords_concat
)
- assert_close(cam_coords_output, cam_coords_input, atol=1e-4, rtol=1e-4)
+ self.assert_close(cam_coords_output, cam_coords_input, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", (1,))
- def test_gradcheck(self, batch_size, device, dtype):
+ def test_gradcheck(self, batch_size, device):
+ dtype = torch.float64
H, W = 10, 20
fx, fy = W, H
cx, cy = W / 2, H / 2
@@ -107,20 +108,10 @@ class TestCam2Pixel:
torch.manual_seed(seed)
cam_coords_src = self._get_samples((batch_size, H, W, 3), low, high, device, dtype)
- cam_coords_src = tensor_to_gradcheck_var(cam_coords_src)
- proj_mat = tensor_to_gradcheck_var(proj_mat)
-
- assert gradcheck(
- kornia.geometry.camera.cam2pixel,
- (cam_coords_src, proj_mat, eps),
- raise_exception=True,
- atol=atol,
- rtol=rtol,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.camera.cam2pixel, (cam_coords_src, proj_mat, eps), atol=atol, rtol=rtol)
-class TestPixel2Cam:
+class TestPixel2Cam(BaseTester):
def _create_intrinsics(self, batch_size, fx, fy, cx, cy, device, dtype):
temp = torch.eye(4, device=device, dtype=dtype)
temp[0, 0], temp[0, 2] = fx, cx
@@ -195,11 +186,12 @@ class TestPixel2Cam:
)
pixel_coords_concat = torch.cat([pixel_coords_output, last_ch], axis=-1)
- assert_close(pixel_coords_concat, pixel_coords_input, atol=1e-4, rtol=1e-4)
+ self.assert_close(pixel_coords_concat, pixel_coords_input, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", (1,))
@pytest.mark.slow
- def test_gradcheck(self, batch_size, device, dtype):
+ def test_gradcheck(self, batch_size, device):
+ dtype = torch.float64
H, W = 10, 20
fx, fy = W, H
cx, cy = W / 2, H / 2
@@ -219,16 +211,10 @@ class TestPixel2Cam:
batch_size, fx, fy, cx, cy, device=device, dtype=dtype
).contiguous()
- depth = tensor_to_gradcheck_var(depth)
- intrinsics_inv = tensor_to_gradcheck_var(intrinsics_inv)
- pixel_coords_input = tensor_to_gradcheck_var(pixel_coords_input)
-
- assert gradcheck(
- kornia.geometry.camera.pixel2cam, (depth, intrinsics_inv, pixel_coords_input), raise_exception=True
- )
+ self.gradcheck(kornia.geometry.camera.pixel2cam, (depth, intrinsics_inv, pixel_coords_input), fast_mode=False)
-class TestPinholeCamera:
+class TestPinholeCamera(BaseTester):
def _create_intrinsics(self, batch_size, fx, fy, cx, cy, device, dtype):
intrinsics = torch.eye(4, device=device, dtype=dtype)
intrinsics[..., 0, 0] = fx
@@ -389,20 +375,20 @@ class TestPinholeCamera:
pinhole = kornia.geometry.camera.PinholeCamera(intrinsics, extrinsics, height, width)
pinhole_scale = pinhole.scale(scale_factor)
- assert_close(
+ self.assert_close(
pinhole_scale.intrinsics[..., 0, 0], pinhole.intrinsics[..., 0, 0] * scale_val, atol=1e-4, rtol=1e-4
) # fx
- assert_close(
+ self.assert_close(
pinhole_scale.intrinsics[..., 1, 1], pinhole.intrinsics[..., 1, 1] * scale_val, atol=1e-4, rtol=1e-4
) # fy
- assert_close(
+ self.assert_close(
pinhole_scale.intrinsics[..., 0, 2], pinhole.intrinsics[..., 0, 2] * scale_val, atol=1e-4, rtol=1e-4
) # cx
- assert_close(
+ self.assert_close(
pinhole_scale.intrinsics[..., 1, 2], pinhole.intrinsics[..., 1, 2] * scale_val, atol=1e-4, rtol=1e-4
) # cy
- assert_close(pinhole_scale.height, pinhole.height * scale_val, atol=1e-4, rtol=1e-4)
- assert_close(pinhole_scale.width, pinhole.width * scale_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(pinhole_scale.height, pinhole.height * scale_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(pinhole_scale.width, pinhole.width * scale_val, atol=1e-4, rtol=1e-4)
def test_pinhole_camera_scale_inplace(self, device, dtype):
batch_size = 2
@@ -421,20 +407,20 @@ class TestPinholeCamera:
pinhole_scale = pinhole.clone()
pinhole_scale.scale_(scale_factor)
- assert_close(
+ self.assert_close(
pinhole_scale.intrinsics[..., 0, 0], pinhole.intrinsics[..., 0, 0] * scale_val, atol=1e-4, rtol=1e-4
) # fx
- assert_close(
+ self.assert_close(
pinhole_scale.intrinsics[..., 1, 1], pinhole.intrinsics[..., 1, 1] * scale_val, atol=1e-4, rtol=1e-4
) # fy
- assert_close(
+ self.assert_close(
pinhole_scale.intrinsics[..., 0, 2], pinhole.intrinsics[..., 0, 2] * scale_val, atol=1e-4, rtol=1e-4
) # cx
- assert_close(
+ self.assert_close(
pinhole_scale.intrinsics[..., 1, 2], pinhole.intrinsics[..., 1, 2] * scale_val, atol=1e-4, rtol=1e-4
) # cy
- assert_close(pinhole_scale.height, pinhole.height * scale_val, atol=1e-4, rtol=1e-4)
- assert_close(pinhole_scale.width, pinhole.width * scale_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(pinhole_scale.height, pinhole.height * scale_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(pinhole_scale.width, pinhole.width * scale_val, atol=1e-4, rtol=1e-4)
def test_pinhole_camera_project_and_unproject(self, device, dtype):
batch_size = 5
@@ -460,7 +446,7 @@ class TestPinholeCamera:
point_2d = pinhole.project(point_3d)
point_3d_hat = pinhole.unproject(point_2d, depth)
- assert_close(point_3d, point_3d_hat, atol=1e-4, rtol=1e-4)
+ self.assert_close(point_3d, point_3d_hat, atol=1e-4, rtol=1e-4)
def test_pinhole_camera_device(self, device, dtype):
batch_size = 5
diff --git a/tests/geometry/camera/test_projections.py b/tests/geometry/camera/test_projections.py
index ddbc26851..0736af524 100644
--- a/tests/geometry/camera/test_projections.py
+++ b/tests/geometry/camera/test_projections.py
@@ -6,12 +6,9 @@ from kornia.geometry.camera.projection_orthographic import (
project_points_orthographic,
unproject_points_orthographic,
)
-from kornia.geometry.camera.projection_z1 import (
- dx_project_points_z1,
- project_points_z1,
- unproject_points_z1,
-)
-from kornia.testing import BaseTester, tensor_to_gradcheck_var
+from kornia.geometry.camera.projection_z1 import dx_project_points_z1, project_points_z1, unproject_points_z1
+
+from testing.base import BaseTester
class TestProjectionZ1(BaseTester):
@@ -106,14 +103,11 @@ class TestProjectionZ1(BaseTester):
def _test_gradcheck_unproject(self, device):
points = torch.tensor([1.0, 2.0], device=device, dtype=torch.float64)
- points = tensor_to_gradcheck_var(points)
extension = torch.tensor([2.0], device=device, dtype=torch.float64)
- extension = tensor_to_gradcheck_var(extension)
self.gradcheck(unproject_points_z1, (points, extension))
def _test_gradcheck_project(self, device):
points = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=torch.float64)
- points = tensor_to_gradcheck_var(points)
self.gradcheck(project_points_z1, (points,))
def test_gradcheck(self, device) -> None:
@@ -201,14 +195,11 @@ class TestProjectionOrthographic(BaseTester):
def _test_gradcheck_project(self, device):
points = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=torch.float64)
- points = tensor_to_gradcheck_var(points)
self.gradcheck(project_points_orthographic, (points,))
def _test_gradcheck_unproject(self, device):
points = torch.tensor([1.0, 2.0], device=device, dtype=torch.float64)
- points = tensor_to_gradcheck_var(points)
extension = torch.tensor([2.0], device=device, dtype=torch.float64)
- extension = tensor_to_gradcheck_var(extension)
self.gradcheck(unproject_points_orthographic, (points, extension))
def test_gradcheck(self, device) -> None:
diff --git a/tests/geometry/camera/test_stereo.py b/tests/geometry/camera/test_stereo.py
index 0fdb29e63..805781e2c 100644
--- a/tests/geometry/camera/test_stereo.py
+++ b/tests/geometry/camera/test_stereo.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.geometry.camera import StereoCamera
-from kornia.testing import assert_close
+
+from testing.base import assert_close
@pytest.fixture(params=[1, 2, 4])
diff --git a/tests/geometry/epipolar/test_common.py b/tests/geometry/epipolar/test_common.py
deleted file mode 100644
index d19c29dd5..000000000
--- a/tests/geometry/epipolar/test_common.py
+++ /dev/null
@@ -1,57 +0,0 @@
-from typing import Dict
-
-import torch
-
-import kornia.geometry.epipolar as epi
-
-
-def generate_two_view_random_scene(
- device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.float32
-) -> Dict[str, torch.Tensor]:
- num_views: int = 2
- num_points: int = 30
-
- scene: Dict[str, torch.Tensor] = epi.generate_scene(num_views, num_points)
-
- # internal parameters (same K)
- K1 = scene["K"].to(device, dtype)
- K2 = K1.clone()
-
- # rotation
- R1 = scene["R"][0:1].to(device, dtype)
- R2 = scene["R"][1:2].to(device, dtype)
-
- # translation
- t1 = scene["t"][0:1].to(device, dtype)
- t2 = scene["t"][1:2].to(device, dtype)
-
- # projection matrix, P = K(R|t)
- P1 = scene["P"][0:1].to(device, dtype)
- P2 = scene["P"][1:2].to(device, dtype)
-
- # fundamental matrix
- F_mat = epi.fundamental_from_projections(P1[..., :3, :], P2[..., :3, :])
-
- F_mat = epi.normalize_transformation(F_mat)
-
- # points 3d
- X = scene["points3d"].to(device, dtype)
-
- # projected points
- x1 = scene["points2d"][0:1].to(device, dtype)
- x2 = scene["points2d"][1:2].to(device, dtype)
-
- return {
- "K1": K1,
- "K2": K2,
- "R1": R1,
- "R2": R2,
- "t1": t1,
- "t2": t2,
- "P1": P1,
- "P2": P2,
- "F": F_mat,
- "X": X,
- "x1": x1,
- "x2": x2,
- }
diff --git a/tests/geometry/epipolar/test_epipolar_metrics.py b/tests/geometry/epipolar/test_epipolar_metrics.py
index 8338c2ec1..a6f190efd 100644
--- a/tests/geometry/epipolar/test_epipolar_metrics.py
+++ b/tests/geometry/epipolar/test_epipolar_metrics.py
@@ -1,30 +1,32 @@
import torch
-from torch.autograd import gradcheck
import kornia.geometry.epipolar as epi
-import kornia.testing as utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
+from testing.geometry.create import create_random_fundamental_matrix
-class TestSymmetricalEpipolarDistance:
+
+class TestSymmetricalEpipolarDistance(BaseTester):
def test_smoke(self, device, dtype):
pts1 = torch.rand(1, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(1, 4, 3, device=device, dtype=dtype)
- Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)
assert epi.symmetrical_epipolar_distance(pts1, pts2, Fm).shape == (1, 4)
def test_batch(self, device, dtype):
batch_size = 5
pts1 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)
- Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)
assert epi.symmetrical_epipolar_distance(pts1, pts2, Fm).shape == (5, 4)
def test_frames(self, device, dtype):
batch_size, num_frames, num_points = 5, 3, 4
- pts1 = torch.rand(batch_size, num_frames, num_points, 3)
- pts2 = torch.rand(batch_size, num_frames, num_points, 3)
- Fm = torch.stack([utils.create_random_fundamental_matrix(1).type_as(pts1) for _ in range(num_frames)], dim=1)
+ pts1 = torch.rand(batch_size, num_frames, num_points, 3, device=device, dtype=dtype)
+ pts2 = torch.rand(batch_size, num_frames, num_points, 3, device=device, dtype=dtype)
+ Fm = torch.stack(
+ [create_random_fundamental_matrix(1, dtype=dtype, device=device) for _ in range(num_frames)], dim=1
+ )
dist_frame_by_frame = torch.stack(
[
epi.symmetrical_epipolar_distance(pts1[:, t, ...], pts2[:, t, ...], Fm[:, t, ...])
@@ -33,87 +35,93 @@ class TestSymmetricalEpipolarDistance:
dim=1,
)
dist_all_frames = epi.symmetrical_epipolar_distance(pts1, pts2, Fm)
- assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)
+ self.assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)
def test_gradcheck(self, device):
# generate input data
batch_size, num_points, num_dims = 2, 3, 2
points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
- Fm = utils.create_random_fundamental_matrix(batch_size).type_as(points2)
- assert gradcheck(
- epi.symmetrical_epipolar_distance, (points1, points2, Fm), raise_exception=True, fast_mode=True
- )
+ Fm = create_random_fundamental_matrix(batch_size, dtype=torch.float64, device=device)
+
+ self.gradcheck(epi.symmetrical_epipolar_distance, (points1, points2, Fm), requires_grad=(True, False, False))
def test_shift(self, device, dtype):
pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
pts2 = torch.tensor([[2, 0.0], [2, 1], [2, 2.0]], device=device, dtype=dtype)[None]
Fm = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], dtype=dtype, device=device)[None]
expected = torch.tensor([0.0, 2.0, 8.0], device=device, dtype=dtype)[None]
- assert_close(epi.symmetrical_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(epi.symmetrical_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)
-class TestSampsonEpipolarDistance:
+class TestSampsonEpipolarDistance(BaseTester):
def test_smoke(self, device, dtype):
pts1 = torch.rand(1, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(1, 4, 3, device=device, dtype=dtype)
- Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)
+
assert epi.sampson_epipolar_distance(pts1, pts2, Fm).shape == (1, 4)
def test_batch(self, device, dtype):
batch_size = 5
pts1 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)
- Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)
assert epi.sampson_epipolar_distance(pts1, pts2, Fm).shape == (5, 4)
def test_frames(self, device, dtype):
batch_size, num_frames, num_points = 5, 3, 4
- pts1 = torch.rand(batch_size, num_frames, num_points, 3)
- pts2 = torch.rand(batch_size, num_frames, num_points, 3)
- Fm = torch.stack([utils.create_random_fundamental_matrix(1).type_as(pts1) for _ in range(num_frames)], dim=1)
+ pts1 = torch.rand(batch_size, num_frames, num_points, 3, device=device, dtype=dtype)
+ pts2 = torch.rand(batch_size, num_frames, num_points, 3, device=device, dtype=dtype)
+ Fm = torch.stack(
+ [create_random_fundamental_matrix(1, dtype=dtype, device=device) for _ in range(num_frames)], dim=1
+ )
dist_frame_by_frame = torch.stack(
[epi.sampson_epipolar_distance(pts1[:, t, ...], pts2[:, t, ...], Fm[:, t, ...]) for t in range(num_frames)],
dim=1,
)
dist_all_frames = epi.sampson_epipolar_distance(pts1, pts2, Fm)
- assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)
+ self.assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)
def test_shift(self, device, dtype):
pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
pts2 = torch.tensor([[2, 0.0], [2, 1], [2, 2.0]], device=device, dtype=dtype)[None]
Fm = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], dtype=dtype, device=device)[None]
expected = torch.tensor([0.0, 0.5, 2.0], device=device, dtype=dtype)[None]
- assert_close(epi.sampson_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(epi.sampson_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
# generate input data
batch_size, num_points, num_dims = 2, 3, 2
points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
- Fm = utils.create_random_fundamental_matrix(batch_size).type_as(points2)
- assert gradcheck(epi.sampson_epipolar_distance, (points1, points2, Fm), raise_exception=True, fast_mode=True)
+ Fm = create_random_fundamental_matrix(batch_size, dtype=torch.float64, device=device)
+ self.gradcheck(epi.sampson_epipolar_distance, (points1, points2, Fm), requires_grad=(True, False, False))
-class TestLeftToRightEpipolarDistance:
+
+class TestLeftToRightEpipolarDistance(BaseTester):
def test_smoke(self, device, dtype):
pts1 = torch.rand(1, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(1, 4, 3, device=device, dtype=dtype)
- Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)
+
assert epi.left_to_right_epipolar_distance(pts1, pts2, Fm).shape == (1, 4)
def test_batch(self, device, dtype):
batch_size = 5
pts1 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)
- Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)
assert epi.left_to_right_epipolar_distance(pts1, pts2, Fm).shape == (5, 4)
def test_frames(self, device, dtype):
batch_size, num_frames, num_points = 5, 3, 4
- pts1 = torch.rand(batch_size, num_frames, num_points, 3)
- pts2 = torch.rand(batch_size, num_frames, num_points, 3)
- Fm = torch.stack([utils.create_random_fundamental_matrix(1).type_as(pts1) for _ in range(num_frames)], dim=1)
+ pts1 = torch.rand(batch_size, num_frames, num_points, 3, device=device, dtype=dtype)
+ pts2 = torch.rand(batch_size, num_frames, num_points, 3, device=device, dtype=dtype)
+ Fm = torch.stack(
+ [create_random_fundamental_matrix(1, dtype=dtype, device=device) for _ in range(num_frames)], dim=1
+ )
dist_frame_by_frame = torch.stack(
[
epi.left_to_right_epipolar_distance(pts1[:, t, ...], pts2[:, t, ...], Fm[:, t, ...])
@@ -122,45 +130,47 @@ class TestLeftToRightEpipolarDistance:
dim=1,
)
dist_all_frames = epi.left_to_right_epipolar_distance(pts1, pts2, Fm)
- assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)
+ self.assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)
def test_shift(self, device, dtype):
pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
pts2 = torch.tensor([[2, 0.0], [2, 1], [2, 2.0]], device=device, dtype=dtype)[None]
Fm = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], dtype=dtype, device=device)[None]
expected = torch.tensor([0.0, 1.0, 2.0], device=device, dtype=dtype)[None]
- assert_close(epi.left_to_right_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(epi.left_to_right_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
# generate input data
batch_size, num_points, num_dims = 2, 3, 2
points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
- Fm = utils.create_random_fundamental_matrix(batch_size).type_as(points2)
- assert gradcheck(
- epi.left_to_right_epipolar_distance, (points1, points2, Fm), raise_exception=True, fast_mode=True
- )
+ Fm = create_random_fundamental_matrix(batch_size, dtype=torch.float64, device=device)
+ self.gradcheck(epi.left_to_right_epipolar_distance, (points1, points2, Fm), requires_grad=(True, False, False))
-class TestRightToLeftEpipolarDistance:
+
+class TestRightToLeftEpipolarDistance(BaseTester):
def test_smoke(self, device, dtype):
pts1 = torch.rand(1, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(1, 4, 3, device=device, dtype=dtype)
- Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)
+
assert epi.right_to_left_epipolar_distance(pts1, pts2, Fm).shape == (1, 4)
def test_batch(self, device, dtype):
batch_size = 5
pts1 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(batch_size, 4, 3, device=device, dtype=dtype)
- Fm = utils.create_random_fundamental_matrix(1).type_as(pts1)
+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)
assert epi.right_to_left_epipolar_distance(pts1, pts2, Fm).shape == (5, 4)
def test_frames(self, device, dtype):
batch_size, num_frames, num_points = 5, 3, 4
- pts1 = torch.rand(batch_size, num_frames, num_points, 3)
- pts2 = torch.rand(batch_size, num_frames, num_points, 3)
- Fm = torch.stack([utils.create_random_fundamental_matrix(1).type_as(pts1) for _ in range(num_frames)], dim=1)
+ pts1 = torch.rand(batch_size, num_frames, num_points, 3, device=device, dtype=dtype)
+ pts2 = torch.rand(batch_size, num_frames, num_points, 3, device=device, dtype=dtype)
+ Fm = torch.stack(
+ [create_random_fundamental_matrix(1, dtype=dtype, device=device) for _ in range(num_frames)], dim=1
+ )
dist_frame_by_frame = torch.stack(
[
epi.right_to_left_epipolar_distance(pts1[:, t, ...], pts2[:, t, ...], Fm[:, t, ...])
@@ -169,21 +179,20 @@ class TestRightToLeftEpipolarDistance:
dim=1,
)
dist_all_frames = epi.right_to_left_epipolar_distance(pts1, pts2, Fm)
- assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)
+ self.assert_close(dist_frame_by_frame, dist_all_frames, atol=1e-6, rtol=1e-6)
def test_shift(self, device, dtype):
pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
pts2 = torch.tensor([[2, 0.0], [2, 1], [2, 2.0]], device=device, dtype=dtype)[None]
Fm = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], dtype=dtype, device=device)[None]
expected = torch.tensor([0.0, 1.0, 2.0], device=device, dtype=dtype)[None]
- assert_close(epi.right_to_left_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(epi.right_to_left_epipolar_distance(pts1, pts2, Fm), expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
# generate input data
batch_size, num_points, num_dims = 2, 3, 2
points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
- Fm = utils.create_random_fundamental_matrix(batch_size).type_as(points2)
- assert gradcheck(
- epi.right_to_left_epipolar_distance, (points1, points2, Fm), raise_exception=True, fast_mode=True
- )
+ Fm = create_random_fundamental_matrix(batch_size, dtype=torch.float64, device=device)
+
+ self.gradcheck(epi.right_to_left_epipolar_distance, (points1, points2, Fm), requires_grad=(True, False, False))
diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.py
index a090c6c33..6382c4b91 100644
--- a/tests/geometry/epipolar/test_essential.py
+++ b/tests/geometry/epipolar/test_essential.py
@@ -1,14 +1,14 @@
import pytest
-import test_common as utils
import torch
-from torch.autograd import gradcheck
import kornia
import kornia.geometry.epipolar as epi
-from kornia.testing import assert_close
+from testing.base import BaseTester
+from testing.geometry.create import generate_two_view_random_scene
-class TestFindEssential:
+
+class TestFindEssential(BaseTester):
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 5, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 5, 2, device=device, dtype=dtype)
@@ -50,7 +50,7 @@ class TestFindEssential:
if torch.all(E != 0):
distance = epi.symmetrical_epipolar_distance(calibrated_x1, calibrated_x2, E)
mean_error = distance.mean()
- assert_close(mean_error, torch.tensor(0.0, device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(mean_error, torch.tensor(0.0, device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
def test_synthetic_sampson(self, device, dtype):
calibrated_x1 = torch.tensor(
@@ -67,10 +67,12 @@ class TestFindEssential:
weights = torch.ones_like(calibrated_x2)[..., 0]
E_est = epi.essential.find_essential(calibrated_x1, calibrated_x2, weights)
error = epi.sampson_epipolar_distance(calibrated_x1, calibrated_x2, E_est)
- assert_close(error, torch.zeros((calibrated_x1.shape[:2]), device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(
+ error, torch.zeros((calibrated_x1.shape[:2]), device=device, dtype=dtype), atol=1e-4, rtol=1e-4
+ )
-class TestEssentialFromFundamental:
+class TestEssentialFromFundamental(BaseTester):
def test_smoke(self, device, dtype):
F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -94,7 +96,7 @@ class TestEssentialFromFundamental:
K2 = torch.rand(1, 3, 3, device=device, dtype=dtype)
E_mat = epi.essential_from_fundamental(F_mat, K1, K2)
F_hat = epi.fundamental_from_essential(E_mat, K1, K2)
- assert_close(F_mat, F_hat, atol=1e-4, rtol=1e-4)
+ self.assert_close(F_mat, F_hat, atol=1e-4, rtol=1e-4)
def test_shape_large(self, device, dtype):
F_mat = torch.rand(1, 2, 3, 3, device=device, dtype=dtype)
@@ -104,7 +106,7 @@ class TestEssentialFromFundamental:
assert E_mat.shape == (1, 2, 3, 3)
def test_from_fundamental(self, device, dtype):
- scene = utils.generate_two_view_random_scene(device, dtype)
+ scene = generate_two_view_random_scene(device, dtype)
F_mat = scene["F"]
@@ -116,16 +118,16 @@ class TestEssentialFromFundamental:
F_mat_norm = epi.normalize_transformation(F_mat)
F_hat_norm = epi.normalize_transformation(F_hat)
- assert_close(F_mat_norm, F_hat_norm)
+ self.assert_close(F_mat_norm, F_hat_norm)
def test_gradcheck(self, device):
F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
K1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
K2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
- assert gradcheck(epi.essential_from_fundamental, (F_mat, K1, K2), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.essential_from_fundamental, (F_mat, K1, K2), requires_grad=(True, False, False))
-class TestRelativeCameraMotion:
+class TestRelativeCameraMotion(BaseTester):
def test_smoke(self, device, dtype):
R1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
t1 = torch.rand(1, 3, 1, device=device, dtype=dtype)
@@ -158,8 +160,8 @@ class TestRelativeCameraMotion:
t_expected = -t1
R, t = epi.relative_camera_motion(R1, t1, R2, t2)
- assert_close(R_expected, R)
- assert_close(t_expected, t)
+ self.assert_close(R_expected, R)
+ self.assert_close(t_expected, t)
def test_rotate_z(self, device, dtype):
R1 = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
@@ -173,18 +175,18 @@ class TestRelativeCameraMotion:
t_expected = t1
R, t = epi.relative_camera_motion(R1, t1, R2, t2)
- assert_close(R_expected, R)
- assert_close(t_expected, t)
+ self.assert_close(R_expected, R)
+ self.assert_close(t_expected, t)
def test_gradcheck(self, device):
R1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
R2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
t1 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
t2 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
- assert gradcheck(epi.relative_camera_motion, (R1, t1, R2, t2), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.relative_camera_motion, (R1, t1, R2, t2), requires_grad=(True, False, False, False))
-class TestEssentalFromRt:
+class TestEssentalFromRt(BaseTester):
def test_smoke(self, device, dtype):
R1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
t1 = torch.rand(1, 3, 1, device=device, dtype=dtype)
@@ -205,7 +207,7 @@ class TestEssentalFromRt:
@pytest.mark.xfail(reason="TODO: fix #685")
def test_from_fundamental_Rt(self, device, dtype):
- scene = utils.generate_two_view_random_scene(device, dtype)
+ scene = generate_two_view_random_scene(device, dtype)
E_from_Rt = epi.essential_from_Rt(scene["R1"], scene["t1"], scene["R2"], scene["t2"])
@@ -214,17 +216,17 @@ class TestEssentalFromRt:
E_from_Rt_norm = epi.normalize_transformation(E_from_Rt)
E_from_F_norm = epi.normalize_transformation(E_from_F)
# TODO: occasionally failed with error > 0.04
- assert_close(E_from_Rt_norm, E_from_F_norm, rtol=1e-3, atol=1e-3)
+ self.assert_close(E_from_Rt_norm, E_from_F_norm, rtol=1e-3, atol=1e-3)
def test_gradcheck(self, device):
R1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
R2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
t1 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
t2 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
- assert gradcheck(epi.essential_from_Rt, (R1, t1, R2, t2), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.essential_from_Rt, (R1, t1, R2, t2), requires_grad=(True, False, False, False))
-class TestDecomposeEssentialMatrix:
+class TestDecomposeEssentialMatrix(BaseTester):
def test_smoke(self, device, dtype):
E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
R1, R2, t = epi.decompose_essential_matrix(E_mat)
@@ -252,12 +254,12 @@ class TestDecomposeEssentialMatrix:
def eval_vec(input):
return epi.decompose_essential_matrix(input)[2]
- assert gradcheck(eval_rot1, (E_mat,), raise_exception=True, fast_mode=True)
- assert gradcheck(eval_rot2, (E_mat,), raise_exception=True, fast_mode=True)
- assert gradcheck(eval_vec, (E_mat,), raise_exception=True, fast_mode=True)
+ self.gradcheck(eval_rot1, (E_mat,))
+ self.gradcheck(eval_rot2, (E_mat,))
+ self.gradcheck(eval_vec, (E_mat,))
-class TestMotionFromEssential:
+class TestMotionFromEssential(BaseTester):
def test_smoke(self, device, dtype):
E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
Rs, Ts = epi.motion_from_essential(E_mat)
@@ -272,7 +274,7 @@ class TestMotionFromEssential:
assert Ts.shape == batch_shape[:-2] + (4, 3, 1)
def test_two_view(self, device, dtype):
- scene = utils.generate_two_view_random_scene(device, dtype)
+ scene = generate_two_view_random_scene(device, dtype)
R1, t1 = scene["R1"], scene["t1"]
R2, t2 = scene["R2"], scene["t2"]
@@ -299,11 +301,11 @@ class TestMotionFromEssential:
def eval_vec(input):
return epi.motion_from_essential(input)[1]
- assert gradcheck(eval_rot, (E_mat,), raise_exception=True, fast_mode=True)
- assert gradcheck(eval_vec, (E_mat,), raise_exception=True, fast_mode=True)
+ self.gradcheck(eval_rot, (E_mat,))
+ self.gradcheck(eval_vec, (E_mat,))
-class TestMotionFromEssentialChooseSolution:
+class TestMotionFromEssentialChooseSolution(BaseTester):
def test_smoke(self, device, dtype):
E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -341,9 +343,9 @@ class TestMotionFromEssentialChooseSolution:
mask[:, 1:-1] = True
Rm, tm, Xm = epi.motion_from_essential_choose_solution(E_mat, K1, K2, x1, x2, mask=mask)
- assert_close(R, Rm)
- assert_close(t, tm)
- assert_close(X, Xm[:, 1:-1, :])
+ self.assert_close(R, Rm)
+ self.assert_close(t, tm)
+ self.assert_close(X, Xm[:, 1:-1, :])
@pytest.mark.parametrize("num_points", [10, 15, 20])
def test_unbatched(self, num_points, device, dtype):
@@ -363,12 +365,12 @@ class TestMotionFromEssentialChooseSolution:
mask[1:-1] = True
Rm, tm, Xm = epi.motion_from_essential_choose_solution(E_mat, K1, K2, x1, x2, mask=mask)
- assert_close(R, Rm)
- assert_close(t, tm)
- assert_close(X, Xm[1:-1, :])
+ self.assert_close(R, Rm)
+ self.assert_close(t, tm)
+ self.assert_close(X, Xm[1:-1, :])
def test_two_view(self, device, dtype):
- scene = utils.generate_two_view_random_scene(device, dtype)
+ scene = generate_two_view_random_scene(device, dtype)
E_mat = epi.essential_from_Rt(scene["R1"], scene["t1"], scene["R2"], scene["t2"])
@@ -379,8 +381,8 @@ class TestMotionFromEssentialChooseSolution:
E_mat, scene["K1"], scene["K2"], scene["x1"], scene["x2"]
)
- assert_close(t, t_hat)
- assert_close(R, R_hat, rtol=1e-4, atol=1e-4)
+ self.assert_close(t, t_hat)
+ self.assert_close(R, R_hat, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device):
E_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
@@ -389,6 +391,8 @@ class TestMotionFromEssentialChooseSolution:
x1 = torch.rand(1, 2, 2, device=device, dtype=torch.float64)
x2 = torch.rand(1, 2, 2, device=device, dtype=torch.float64)
- assert gradcheck(
- epi.motion_from_essential_choose_solution, (E_mat, K1, K2, x1, x2), raise_exception=True, fast_mode=True
+ self.gradcheck(
+ epi.motion_from_essential_choose_solution,
+ (E_mat, K1, K2, x1, x2),
+ requires_grad=(True, False, False, False, False),
)
diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.py
index dbe58824c..7d0d797dc 100644
--- a/tests/geometry/epipolar/test_fundamental.py
+++ b/tests/geometry/epipolar/test_fundamental.py
@@ -1,16 +1,15 @@
from typing import Dict
import pytest
-import test_common as utils
import torch
-from torch.autograd import gradcheck
import kornia.geometry.epipolar as epi
-import kornia.testing as utils2
-from kornia.testing import assert_close
+from testing.base import BaseTester
+from testing.geometry.create import create_random_fundamental_matrix, generate_two_view_random_scene
-class TestNormalizePoints:
+
+class TestNormalizePoints(BaseTester):
def test_smoke(self, device, dtype):
points = torch.rand(1, 1, 2, device=device, dtype=dtype)
output = epi.normalize_points(points)
@@ -32,15 +31,15 @@ class TestNormalizePoints:
points_norm, _ = epi.normalize_points(points)
points_std, points_mean = torch.std_mean(points_norm, dim=1)
- assert_close(points_mean, torch.zeros_like(points_mean))
+ self.assert_close(points_mean, torch.zeros_like(points_mean))
assert (points_std < 2.0).all()
def test_gradcheck(self, device):
points = torch.rand(2, 3, 2, device=device, requires_grad=True, dtype=torch.float64)
- assert gradcheck(epi.normalize_points, (points,), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.normalize_points, (points,))
-class TestNormalizeTransformation:
+class TestNormalizeTransformation(BaseTester):
def test_smoke(self, device, dtype):
trans = torch.rand(2, 2, device=device, dtype=dtype)
trans_norm = epi.normalize_transformation(trans)
@@ -59,7 +58,7 @@ class TestNormalizeTransformation:
trans_expected = torch.tensor([[[0.0, 0.0, 2.0], [0.0, 4.0, 0.0], [1.0, 0.0, 1.0]]], device=device, dtype=dtype)
trans_norm = epi.normalize_transformation(trans)
- assert_close(trans_norm, trans_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(trans_norm, trans_expected, atol=1e-4, rtol=1e-4)
def test_check_corner_case(self, device, dtype):
trans = torch.tensor([[[0.0, 0.0, 1.0], [0.0, 2.0, 0.0], [0.5, 0.0, 0.0]]], device=device, dtype=dtype)
@@ -67,14 +66,14 @@ class TestNormalizeTransformation:
trans_expected = trans.clone()
trans_norm = epi.normalize_transformation(trans)
- assert_close(trans_norm, trans_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(trans_norm, trans_expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
trans = torch.rand(2, 3, 3, device=device, requires_grad=True, dtype=torch.float64)
- assert gradcheck(epi.normalize_transformation, (trans,), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.normalize_transformation, (trans,))
-class TestFindFundamental:
+class TestFindFundamental(BaseTester):
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 8, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 8, 2, device=device, dtype=dtype)
@@ -169,7 +168,7 @@ class TestFindFundamental:
)
F_mat = epi.find_fundamental(points1, points2, weights)
- assert_close(F_mat, Fm_expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(F_mat, Fm_expected, rtol=1e-4, atol=1e-4)
def test_7point_opencv(self, device, dtype):
points1 = torch.tensor(
@@ -235,10 +234,10 @@ class TestFindFundamental:
dtype=dtype,
)
F_mat = epi.find_fundamental(points1, points2, method="7POINT")
- assert_close(F_mat, Fm_expected, rtol=1e-3, atol=1e-3)
+ self.assert_close(F_mat, Fm_expected, rtol=1e-3, atol=1e-3)
def test_synthetic_sampson_7point(self, device, dtype):
- scene: Dict[str, torch.Tensor] = utils.generate_two_view_random_scene(device, dtype)
+ scene: Dict[str, torch.Tensor] = generate_two_view_random_scene(device, dtype)
x1 = scene["x1"][:, :7, :]
x2 = scene["x2"][:, :7, :]
F_est = epi.find_fundamental(x1, x2, None, "7POINT")
@@ -246,10 +245,10 @@ class TestFindFundamental:
F = F_est[0][i].unsqueeze(0)
if torch.all(F != 0):
error = epi.sampson_epipolar_distance(x1, x2, F)
- assert_close(error, torch.zeros((F.shape[0], 7), device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(error, torch.zeros((F.shape[0], 7), device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
def test_epipolar_constraint_7point(self, device, dtype):
- scene: Dict[str, torch.Tensor] = utils.generate_two_view_random_scene(device, dtype)
+ scene: Dict[str, torch.Tensor] = generate_two_view_random_scene(device, dtype)
x1 = scene["x1"][:, :7, :]
x2 = scene["x2"][:, :7, :]
F_est = epi.find_fundamental(x1, x2, None, "7POINT")
@@ -258,10 +257,10 @@ class TestFindFundamental:
if torch.all(F != 0):
distance = epi.symmetrical_epipolar_distance(x1, x2, F)
mean_error = distance.mean()
- assert_close(mean_error, torch.tensor(0.0, device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(mean_error, torch.tensor(0.0, device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
def test_synthetic_sampson(self, device, dtype):
- scene: Dict[str, torch.Tensor] = utils.generate_two_view_random_scene(device, dtype)
+ scene: Dict[str, torch.Tensor] = generate_two_view_random_scene(device, dtype)
x1 = scene["x1"]
x2 = scene["x2"]
@@ -270,16 +269,16 @@ class TestFindFundamental:
F_est = epi.find_fundamental(x1, x2, weights)
error = epi.sampson_epipolar_distance(x1, x2, F_est)
- assert_close(error, torch.zeros((x1.shape[:2]), device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(error, torch.zeros((x1.shape[:2]), device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
points1 = torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(1, 10, 2, device=device, dtype=torch.float64)
weights = torch.ones(1, 10, device=device, dtype=torch.float64)
- assert gradcheck(epi.find_fundamental, (points1, points2, weights), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.find_fundamental, (points1, points2, weights))
-class TestComputeCorrespondEpilines:
+class TestComputeCorrespondEpilines(BaseTester):
def test_smoke(self, device, dtype):
point = torch.rand(1, 1, 2, device=device, dtype=dtype)
F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -308,7 +307,7 @@ class TestComputeCorrespondEpilines:
lines_T_hops[:, i, ...] = epi.compute_correspond_epilines(point[:, i, ...], F_mat[:, i, ...])
lines_one_hop = epi.compute_correspond_epilines(point, F_mat)
- assert_close(lines_T_hops, lines_one_hop, atol=2e-7, rtol=2e-7)
+ self.assert_close(lines_T_hops, lines_one_hop, atol=2e-7, rtol=2e-7)
def test_opencv(self, device, dtype):
point = torch.rand(1, 2, 2, device=device, dtype=dtype)
@@ -331,15 +330,15 @@ class TestComputeCorrespondEpilines:
)
lines_est = epi.compute_correspond_epilines(point, F_mat)
- assert_close(lines_est, lines_expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(lines_est, lines_expected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device):
point = torch.rand(1, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
- assert gradcheck(epi.compute_correspond_epilines, (point, F_mat), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.compute_correspond_epilines, (point, F_mat), requires_grad=(True, False))
-class TestFundamentlFromEssential:
+class TestFundamentlFromEssential(BaseTester):
def test_smoke(self, device, dtype):
E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -364,7 +363,7 @@ class TestFundamentlFromEssential:
assert F_mat.shape == (1, 2, 3, 3)
def test_from_to_essential(self, device, dtype):
- scene = utils.generate_two_view_random_scene(device, dtype)
+ scene = generate_two_view_random_scene(device, dtype)
F_mat = scene["F"]
E_mat = epi.essential_from_fundamental(F_mat, scene["K1"], scene["K2"])
@@ -372,16 +371,16 @@ class TestFundamentlFromEssential:
F_mat_norm = epi.normalize_transformation(F_mat)
F_hat_norm = epi.normalize_transformation(F_hat)
- assert_close(F_mat_norm, F_hat_norm, atol=1e-4, rtol=1e-4)
+ self.assert_close(F_mat_norm, F_hat_norm, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
E_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
K1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
K2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
- assert gradcheck(epi.fundamental_from_essential, (E_mat, K1, K2), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.fundamental_from_essential, (E_mat, K1, K2), requires_grad=(True, False, False))
-class TestFundamentalFromProjections:
+class TestFundamentalFromProjections(BaseTester):
def test_smoke(self, device, dtype):
P1 = torch.rand(1, 3, 4, device=device, dtype=dtype)
P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
@@ -417,12 +416,12 @@ class TestFundamentalFromProjections:
F_mat_norm = epi.normalize_transformation(F_mat)
F_hat_norm = epi.normalize_transformation(F_hat)
- assert_close(F_mat_norm, F_hat_norm, atol=1e-4, rtol=1e-4)
+ self.assert_close(F_mat_norm, F_hat_norm, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
P1 = torch.rand(1, 3, 4, device=device, dtype=torch.float64, requires_grad=True)
P2 = torch.rand(1, 3, 4, device=device, dtype=torch.float64)
- assert gradcheck(epi.fundamental_from_projections, (P1, P2), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.fundamental_from_projections, (P1, P2), requires_grad=(True, False))
def test_batch_support_check(self, device, dtype):
P1_batch = torch.tensor(
@@ -482,10 +481,10 @@ class TestFundamentalFromProjections:
F_batch = epi.fundamental_from_projections(P1_batch, P2_batch)
F = epi.fundamental_from_projections(P1, P2)
- assert_close(F_batch[0], F[0])
+ self.assert_close(F_batch[0], F[0])
-class TestPerpendicular:
+class TestPerpendicular(BaseTester):
def test_shape(self, device, dtype):
lines = torch.rand(2, 4, 3, device=device, dtype=dtype)
points = torch.rand(2, 4, 2, device=device, dtype=dtype)
@@ -498,19 +497,19 @@ class TestPerpendicular:
lines = torch.tensor([[[1.0, -1.0, 0.0], [0.0, 1.0, 1.0]]], device=device, dtype=dtype)
perp = epi.get_perpendicular(lines, points)
expected = torch.tensor([[[1.0, 1.0, -1.0], [-1.0, 0.0, 0.0]]], device=device, dtype=dtype)
- assert_close(perp, expected)
+ self.assert_close(perp, expected)
def test_gradcheck(self, device):
pt = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
line = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
- assert gradcheck(epi.get_perpendicular, (pt, line), raise_exception=True, fast_mode=True)
+ self.gradcheck(epi.get_perpendicular, (pt, line), requires_grad=(True, False))
-class TestGetClosestPointOnEpipolarLine:
+class TestGetClosestPointOnEpipolarLine(BaseTester):
def test_shape(self, device, dtype):
pts1 = torch.rand(2, 4, 2, device=device, dtype=dtype)
pts2 = torch.rand(2, 4, 2, device=device, dtype=dtype)
- Fm = utils2.create_random_fundamental_matrix(1).type_as(pts1)
+ Fm = create_random_fundamental_matrix(1, device=device, dtype=dtype)
perp = epi.get_closest_point_on_epipolar_line(pts1, pts2, Fm)
assert perp.shape == (2, 4, 2)
@@ -520,10 +519,10 @@ class TestGetClosestPointOnEpipolarLine:
Fm = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], dtype=dtype, device=device)[None]
cp = epi.get_closest_point_on_epipolar_line(pts1, pts2, Fm)
expected = torch.tensor([[[2.0, 0.0], [2.0, 0.0], [2.0, 0.0]]], device=device, dtype=dtype)
- assert_close(cp, expected)
+ self.assert_close(cp, expected)
def test_gradcheck(self, device):
pts1 = torch.rand(2, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
pts2 = torch.rand(2, 4, 2, device=device, dtype=torch.float64)
- Fm = utils2.create_random_fundamental_matrix(1).type_as(pts1)
- assert gradcheck(epi.get_closest_point_on_epipolar_line, (pts1, pts2, Fm), raise_exception=True, fast_mode=True)
+ Fm = create_random_fundamental_matrix(1, dtype=torch.float64, device=device)
+ self.gradcheck(epi.get_closest_point_on_epipolar_line, (pts1, pts2, Fm), requires_grad=(True, False, False))
diff --git a/tests/geometry/epipolar/test_numeric.py b/tests/geometry/epipolar/test_numeric.py
index 7acb3978a..b96ce1b21 100644
--- a/tests/geometry/epipolar/test_numeric.py
+++ b/tests/geometry/epipolar/test_numeric.py
@@ -4,7 +4,8 @@ from torch.autograd import gradcheck
import kornia
import kornia.geometry.epipolar as epi
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestSkewSymmetric:
diff --git a/tests/geometry/epipolar/test_projection.py b/tests/geometry/epipolar/test_projection.py
index d52e52d4d..38ae1f832 100644
--- a/tests/geometry/epipolar/test_projection.py
+++ b/tests/geometry/epipolar/test_projection.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
import kornia.geometry.epipolar as epi
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestIntrinsicsLike:
diff --git a/tests/geometry/epipolar/test_triangulation.py b/tests/geometry/epipolar/test_triangulation.py
index 914a86300..0a568eee2 100644
--- a/tests/geometry/epipolar/test_triangulation.py
+++ b/tests/geometry/epipolar/test_triangulation.py
@@ -6,7 +6,8 @@ from torch.autograd import gradcheck
import kornia
import kornia.geometry.epipolar as epi
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestTriangulation:
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index 5d55ee870..6f8712d43 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -3,7 +3,8 @@ import torch
from kornia.geometry.liegroup import Se2, So2
from kornia.geometry.vector import Vector2
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestSe2(BaseTester):
diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.py
index a599024cb..2784c4dba 100644
--- a/tests/geometry/liegroup/test_se3.py
+++ b/tests/geometry/liegroup/test_se3.py
@@ -5,7 +5,8 @@ from kornia.geometry.conversions import euler_from_quaternion, rotation_matrix_t
from kornia.geometry.liegroup import Se3, So3
from kornia.geometry.quaternion import Quaternion
from kornia.geometry.vector import Vector3
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestSe3(BaseTester):
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index cc87515be..bf7b8814a 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -3,7 +3,8 @@ import torch
from kornia.geometry.liegroup import So2
from kornia.geometry.vector import Vector2
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestSo2(BaseTester):
diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.py
index 297d01373..c10bf4944 100644
--- a/tests/geometry/liegroup/test_so3.py
+++ b/tests/geometry/liegroup/test_so3.py
@@ -5,7 +5,8 @@ from kornia.geometry.conversions import euler_from_quaternion
from kornia.geometry.liegroup import So3
from kornia.geometry.quaternion import Quaternion
from kornia.geometry.vector import Vector3
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestSo3(BaseTester):
diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.py
index 8130f0a6e..b5ef67943 100644
--- a/tests/geometry/solvers/test_polynomial_solver.py
+++ b/tests/geometry/solvers/test_polynomial_solver.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
import kornia.geometry.solvers as solver
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestQuadraticSolver:
diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.py
index daecbeb3c..f2bdce3c2 100644
--- a/tests/geometry/subpix/test_dsnt.py
+++ b/tests/geometry/subpix/test_dsnt.py
@@ -2,7 +2,8 @@ import pytest
import torch
import kornia
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestRenderGaussian2d:
diff --git a/tests/geometry/subpix/test_nms.py b/tests/geometry/subpix/test_nms.py
index 28a2fd1fb..0527cfc07 100644
--- a/tests/geometry/subpix/test_nms.py
+++ b/tests/geometry/subpix/test_nms.py
@@ -1,12 +1,11 @@
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestNMS2d:
+
+class TestNMS2d(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
nms = kornia.geometry.subpix.NonMaximaSuppression2d((3, 3)).to(device)
@@ -47,18 +46,15 @@ class TestNMS2d:
).float()
nms = kornia.geometry.subpix.NonMaximaSuppression2d((3, 3)).to(device)
scores = nms(inp)
- assert_close(scores, expected, atol=1e-4, rtol=1e-3)
+ self.assert_close(scores, expected, atol=1e-4, rtol=1e-3)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.geometry.subpix.nms2d, (img, (3, 3)), raise_exception=True, nondet_tol=1e-4, fast_mode=True
- )
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.subpix.nms2d, (img, (3, 3)), nondet_tol=1e-4)
-class TestNMS3d:
+class TestNMS3d(BaseTester):
def test_shape(self, device):
inp = torch.ones(1, 1, 3, 4, 4, device=device)
nms = kornia.geometry.subpix.NonMaximaSuppression3d((3, 3, 3)).to(device)
@@ -131,12 +127,9 @@ class TestNMS3d:
).to(device)
nms = kornia.geometry.subpix.NonMaximaSuppression3d((3, 3, 3)).to(device)
scores = nms(inp)
- assert_close(scores, expected, atol=1e-4, rtol=1e-3)
+ self.assert_close(scores, expected, atol=1e-4, rtol=1e-3)
def test_gradcheck(self, device):
batch_size, channels, depth, height, width = 1, 1, 4, 5, 4
- img = torch.rand(batch_size, channels, depth, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.geometry.subpix.nms3d, (img, (3, 3, 3)), raise_exception=True, nondet_tol=1e-4, fast_mode=True
- )
+ img = torch.rand(batch_size, channels, depth, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.subpix.nms3d, (img, (3, 3, 3)), nondet_tol=1e-4)
diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.py
index 415a443f4..8be792ae2 100644
--- a/tests/geometry/subpix/test_spatial_softargmax.py
+++ b/tests/geometry/subpix/test_spatial_softargmax.py
@@ -1,14 +1,13 @@
import torch
-from torch.autograd import gradcheck
from torch.nn.functional import mse_loss
import kornia
-import kornia.testing as utils # test utils
from kornia.geometry.subpix.spatial_soft_argmax import _get_center_kernel2d, _get_center_kernel3d
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestCenterKernel2d:
+
+class TestCenterKernel2d(BaseTester):
def test_smoke(self, device, dtype):
kernel = _get_center_kernel2d(3, 4, device=device).to(dtype=dtype)
assert kernel.shape == (2, 2, 3, 4)
@@ -29,17 +28,17 @@ class TestCenterKernel2d:
device=device,
dtype=dtype,
)
- assert_close(kernel, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(kernel, expected, atol=1e-4, rtol=1e-4)
def test_even(self, device, dtype):
kernel = _get_center_kernel2d(2, 2, device=device).to(dtype=dtype)
expected = torch.ones(2, 2, 2, 2, device=device, dtype=dtype) * 0.25
expected[0, 1] = 0
expected[1, 0] = 0
- assert_close(kernel, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(kernel, expected, atol=1e-4, rtol=1e-4)
-class TestCenterKernel3d:
+class TestCenterKernel3d(BaseTester):
def test_smoke(self, device, dtype):
kernel = _get_center_kernel3d(6, 3, 4, device=device).to(dtype=dtype)
assert kernel.shape == (3, 3, 6, 3, 4)
@@ -50,7 +49,7 @@ class TestCenterKernel3d:
expected[0, 0, 1, 2, 3] = 1.0
expected[1, 1, 1, 2, 3] = 1.0
expected[2, 2, 1, 2, 3] = 1.0
- assert_close(kernel, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(kernel, expected, atol=1e-4, rtol=1e-4)
def test_even(self, device, dtype):
kernel = _get_center_kernel3d(2, 4, 3, device=device).to(dtype=dtype)
@@ -58,10 +57,10 @@ class TestCenterKernel3d:
expected[0, 0, :, 1:3, 1] = 0.25
expected[1, 1, :, 1:3, 1] = 0.25
expected[2, 2, :, 1:3, 1] = 0.25
- assert_close(kernel, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(kernel, expected, atol=1e-4, rtol=1e-4)
-class TestSpatialSoftArgmax2d:
+class TestSpatialSoftArgmax2d(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)
m = kornia.geometry.subpix.SpatialSoftArgmax2d()
@@ -77,32 +76,32 @@ class TestSpatialSoftArgmax2d:
sample[..., 0, 0] = 1e16
coord = kornia.geometry.subpix.spatial_soft_argmax2d(sample, normalized_coordinates=True)
- assert_close(coord[..., 0].item(), -1.0, atol=1e-4, rtol=1e-4)
- assert_close(coord[..., 1].item(), -1.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[..., 0].item(), -1.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[..., 1].item(), -1.0, atol=1e-4, rtol=1e-4)
def test_top_left(self, device, dtype):
sample = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)
sample[..., 0, 0] = 1e16
coord = kornia.geometry.subpix.spatial_soft_argmax2d(sample, normalized_coordinates=False)
- assert_close(coord[..., 0].item(), 0.0, atol=1e-4, rtol=1e-4)
- assert_close(coord[..., 1].item(), 0.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[..., 0].item(), 0.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[..., 1].item(), 0.0, atol=1e-4, rtol=1e-4)
def test_bottom_right_normalized(self, device, dtype):
sample = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)
sample[..., -1, -1] = 1e16
coord = kornia.geometry.subpix.spatial_soft_argmax2d(sample, normalized_coordinates=True)
- assert_close(coord[..., 0].item(), 1.0, atol=1e-4, rtol=1e-4)
- assert_close(coord[..., 1].item(), 1.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[..., 0].item(), 1.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[..., 1].item(), 1.0, atol=1e-4, rtol=1e-4)
def test_bottom_right(self, device, dtype):
sample = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)
sample[..., -1, -1] = 1e16
coord = kornia.geometry.subpix.spatial_soft_argmax2d(sample, normalized_coordinates=False)
- assert_close(coord[..., 0].item(), 2.0, atol=1e-4, rtol=1e-4)
- assert_close(coord[..., 1].item(), 1.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[..., 0].item(), 2.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[..., 1].item(), 1.0, atol=1e-4, rtol=1e-4)
def test_batch2_n2(self, device, dtype):
sample = torch.zeros(2, 2, 2, 3, device=device, dtype=dtype)
@@ -112,19 +111,18 @@ class TestSpatialSoftArgmax2d:
sample[1, 1, -1, -1] = 1e16 # bottom-right
coord = kornia.geometry.subpix.spatial_soft_argmax2d(sample)
- assert_close(coord[0, 0, 0].item(), -1.0, atol=1e-4, rtol=1e-4) # top-left
- assert_close(coord[0, 0, 1].item(), -1.0, atol=1e-4, rtol=1e-4)
- assert_close(coord[0, 1, 0].item(), 1.0, atol=1e-4, rtol=1e-4) # top-right
- assert_close(coord[0, 1, 1].item(), -1.0, atol=1e-4, rtol=1e-4)
- assert_close(coord[1, 0, 0].item(), -1.0, atol=1e-4, rtol=1e-4) # bottom-left
- assert_close(coord[1, 0, 1].item(), 1.0, atol=1e-4, rtol=1e-4)
- assert_close(coord[1, 1, 0].item(), 1.0, atol=1e-4, rtol=1e-4) # bottom-right
- assert_close(coord[1, 1, 1].item(), 1.0, atol=1e-4, rtol=1e-4)
-
- def test_gradcheck(self, device, dtype):
- sample = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
- sample = utils.tensor_to_gradcheck_var(sample) # to var
- assert gradcheck(kornia.geometry.subpix.spatial_soft_argmax2d, (sample), raise_exception=True, fast_mode=True)
+ self.assert_close(coord[0, 0, 0].item(), -1.0, atol=1e-4, rtol=1e-4) # top-left
+ self.assert_close(coord[0, 0, 1].item(), -1.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[0, 1, 0].item(), 1.0, atol=1e-4, rtol=1e-4) # top-right
+ self.assert_close(coord[0, 1, 1].item(), -1.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[1, 0, 0].item(), -1.0, atol=1e-4, rtol=1e-4) # bottom-left
+ self.assert_close(coord[1, 0, 1].item(), 1.0, atol=1e-4, rtol=1e-4)
+ self.assert_close(coord[1, 1, 0].item(), 1.0, atol=1e-4, rtol=1e-4) # bottom-right
+ self.assert_close(coord[1, 1, 1].item(), 1.0, atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self, device):
+ sample = torch.rand(2, 3, 3, 2, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.subpix.spatial_soft_argmax2d, (sample))
def test_end_to_end(self, device, dtype):
sample = torch.full((1, 2, 7, 7), 1.0, requires_grad=True, device=device, dtype=dtype)
@@ -132,22 +130,24 @@ class TestSpatialSoftArgmax2d:
std = torch.tensor([1.0, 1.0], device=device, dtype=dtype)
hm = kornia.geometry.subpix.spatial_softmax2d(sample)
- assert_close(hm.sum(-1).sum(-1), torch.tensor([[1.0, 1.0]], device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(
+ hm.sum(-1).sum(-1), torch.tensor([[1.0, 1.0]], device=device, dtype=dtype), atol=1e-4, rtol=1e-4
+ )
pred = kornia.geometry.subpix.spatial_expectation2d(hm)
- assert_close(
+ self.assert_close(
pred, torch.as_tensor([[[0.0, 0.0], [0.0, 0.0]]], device=device, dtype=dtype), atol=1e-4, rtol=1e-4
)
loss1 = mse_loss(pred, target, size_average=None, reduce=None, reduction="none").mean(-1, keepdim=False)
expected_loss1 = torch.as_tensor([[0.0, 1.0]], device=device, dtype=dtype)
- assert_close(loss1, expected_loss1, atol=1e-4, rtol=1e-4)
+ self.assert_close(loss1, expected_loss1, atol=1e-4, rtol=1e-4)
target_hm = kornia.geometry.subpix.render_gaussian2d(target, std, sample.shape[-2:]).contiguous()
loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, reduction="none")
expected_loss2 = torch.as_tensor([[0.0087, 0.0818]], device=device, dtype=dtype)
- assert_close(loss2, expected_loss2, rtol=0, atol=1e-3)
+ self.assert_close(loss2, expected_loss2, rtol=0, atol=1e-3)
loss = (loss1 + loss2).mean()
loss.backward()
@@ -157,10 +157,10 @@ class TestSpatialSoftArgmax2d:
op = kornia.geometry.subpix.spatial_soft_argmax2d
op_optimized = torch_optimizer(op)
- assert_close(op(inpt), op_optimized(inpt))
+ self.assert_close(op(inpt), op_optimized(inpt))
-class TestConvSoftArgmax2d:
+class TestConvSoftArgmax2d(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.zeros(1, 1, 3, 3, device=device, dtype=dtype)
m = kornia.geometry.subpix.ConvSoftArgmax2d((3, 3))
@@ -185,12 +185,9 @@ class TestConvSoftArgmax2d:
assert coords.shape == (2, 5, 2, 3, 3)
assert val.shape == (2, 5, 3, 3)
- def test_gradcheck(self, device, dtype):
- sample = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)
- sample = utils.tensor_to_gradcheck_var(sample) # to var
- assert gradcheck(
- kornia.geometry.subpix.conv_soft_argmax2d, (sample), nondet_tol=1e-8, raise_exception=True, fast_mode=True
- )
+ def test_gradcheck(self, device):
+ sample = torch.rand(2, 3, 5, 5, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.subpix.conv_soft_argmax2d, (sample), nondet_tol=1e-8)
def test_cold_diag(self, device, dtype):
sample = torch.tensor(
@@ -216,8 +213,8 @@ class TestConvSoftArgmax2d:
[[[[[1.0, 3.0], [1.0, 3.0]], [[1.0, 1.0], [3.0, 3.0]]]]], device=device, dtype=dtype
)
coords, val = softargmax(sample)
- assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
- assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+ self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_hot_diag(self, device, dtype):
sample = torch.tensor(
@@ -243,8 +240,8 @@ class TestConvSoftArgmax2d:
[[[[[1.0, 3.0], [1.0, 3.0]], [[1.0, 1.0], [3.0, 3.0]]]]], device=device, dtype=dtype
)
coords, val = softargmax(sample)
- assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
- assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+ self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_cold_diag_norm(self, device, dtype):
sample = torch.tensor(
@@ -270,8 +267,8 @@ class TestConvSoftArgmax2d:
[[[[[-0.5, 0.5], [-0.5, 0.5]], [[-0.5, -0.5], [0.5, 0.5]]]]], device=device, dtype=dtype
)
coords, val = softargmax(sample)
- assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
- assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+ self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_hot_diag_norm(self, device, dtype):
sample = torch.tensor(
@@ -297,11 +294,11 @@ class TestConvSoftArgmax2d:
[[[[[-0.5, 0.5], [-0.5, 0.5]], [[-0.5, -0.5], [0.5, 0.5]]]]], device=device, dtype=dtype
)
coords, val = softargmax(sample)
- assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
- assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+ self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
-class TestConvSoftArgmax3d:
+class TestConvSoftArgmax3d(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.zeros(1, 1, 3, 3, 3, device=device, dtype=dtype)
m = kornia.geometry.subpix.ConvSoftArgmax3d((3, 3, 3), output_value=False)
@@ -314,12 +311,9 @@ class TestConvSoftArgmax3d:
assert coords.shape == (1, 1, 3, 3, 3, 3)
assert val.shape == (1, 1, 3, 3, 3)
- def test_gradcheck(self, device, dtype):
- sample = torch.rand(1, 2, 3, 5, 5, device=device, dtype=dtype)
- sample = utils.tensor_to_gradcheck_var(sample) # to var
- assert gradcheck(
- kornia.geometry.subpix.conv_soft_argmax3d, (sample), nondet_tol=1e-8, raise_exception=True, fast_mode=True
- )
+ def test_gradcheck(self, device):
+ sample = torch.rand(1, 2, 3, 5, 5, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.subpix.conv_soft_argmax3d, (sample), nondet_tol=1e-8)
def test_cold_diag(self, device, dtype):
sample = torch.tensor(
@@ -349,8 +343,8 @@ class TestConvSoftArgmax3d:
dtype=dtype,
)
coords, val = softargmax(sample)
- assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
- assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+ self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_hot_diag(self, device, dtype):
sample = torch.tensor(
@@ -380,8 +374,8 @@ class TestConvSoftArgmax3d:
dtype=dtype,
)
coords, val = softargmax(sample)
- assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
- assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+ self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_cold_diag_norm(self, device, dtype):
sample = torch.tensor(
@@ -411,8 +405,8 @@ class TestConvSoftArgmax3d:
dtype=dtype,
)
coords, val = softargmax(sample)
- assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
- assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+ self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_hot_diag_norm(self, device, dtype):
sample = torch.tensor(
@@ -442,11 +436,11 @@ class TestConvSoftArgmax3d:
dtype=dtype,
)
coords, val = softargmax(sample)
- assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
- assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+ self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
-class TestConvQuadInterp3d:
+class TestConvQuadInterp3d(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.randn(2, 3, 3, 4, 4, device=device, dtype=dtype)
nms = kornia.geometry.ConvQuadInterp3d(1)
@@ -454,18 +448,10 @@ class TestConvQuadInterp3d:
assert coord.shape == (2, 3, 3, 3, 4, 4)
assert val.shape == (2, 3, 3, 4, 4)
- def test_gradcheck(self, device, dtype):
- sample = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)
+ def test_gradcheck(self, device):
+ sample = torch.rand(1, 1, 3, 5, 5, device=device, dtype=torch.float64)
sample[0, 0, 1, 2, 2] += 20.0
- sample = utils.tensor_to_gradcheck_var(sample) # to var
- assert gradcheck(
- kornia.geometry.ConvQuadInterp3d(strict_maxima_bonus=0),
- (sample),
- raise_exception=True,
- atol=1e-3,
- rtol=1e-3,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.ConvQuadInterp3d(strict_maxima_bonus=0), (sample), atol=1e-3, rtol=1e-3)
def test_diag(self, device, dtype):
sample = torch.tensor(
@@ -610,5 +596,5 @@ class TestConvQuadInterp3d:
dtype=dtype,
)
coords, val = softargmax(sample)
- assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
- assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+ self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
+ self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index 5975fcbfb..5f40dc780 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -9,10 +9,11 @@ from kornia.geometry.bbox import (
validate_bbox,
validate_bbox3d,
)
-from kornia.testing import assert_close, gradcheck, tensor_to_gradcheck_var
+from testing.base import BaseTester
-class TestBbox2D:
+
+class TestBbox2D(BaseTester):
def test_smoke(self, device, dtype):
# Sample two points of the rectangle
points = torch.rand(1, 4, device=device, dtype=dtype)
@@ -44,9 +45,8 @@ class TestBbox2D:
assert (h.unique().item(), w.unique().item()) == (2, 3)
def test_gradcheck(self, device):
- boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device)
- boxes = tensor_to_gradcheck_var(boxes)
- gradcheck(infer_bbox_shape, (boxes,))
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=torch.float64)
+ self.gradcheck(infer_bbox_shape, (boxes,))
def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
@@ -58,10 +58,10 @@ class TestBbox2D:
expected = op(boxes)
actual = op_optimized(boxes)
# Compare
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestTransformBoxes2D:
+class TestTransformBoxes2D(BaseTester):
def test_transform_boxes(self, device, dtype):
boxes = torch.tensor([[139.2640, 103.0150, 397.3120, 410.5225]], device=device, dtype=dtype)
@@ -70,7 +70,7 @@ class TestTransformBoxes2D:
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
out = transform_bbox(trans_mat, boxes, restore_coordinates=True)
- assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
def test_transform_multiple_boxes(self, device, dtype):
boxes = torch.tensor(
@@ -115,7 +115,7 @@ class TestTransformBoxes2D:
)
out = transform_bbox(trans_mat, boxes, restore_coordinates=True)
- assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
def test_transform_boxes_wh(self, device, dtype):
boxes = torch.tensor(
@@ -143,7 +143,7 @@ class TestTransformBoxes2D:
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
out = transform_bbox(trans_mat, boxes, mode="xywh", restore_coordinates=True)
- assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
boxes = torch.tensor(
@@ -154,14 +154,14 @@ class TestTransformBoxes2D:
[119.8080, 144.2067, 137.2160, 265.9225],
],
device=device,
+ dtype=torch.float64,
)
- trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device)
-
- trans_mat = tensor_to_gradcheck_var(trans_mat)
- boxes = tensor_to_gradcheck_var(boxes)
+ trans_mat = torch.tensor(
+ [[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=torch.float64
+ )
- gradcheck(transform_bbox, (trans_mat, boxes, "xyxy", True))
+ self.gradcheck(transform_bbox, (trans_mat, boxes, "xyxy", True))
def test_dynamo(self, device, dtype, torch_optimizer):
boxes = torch.tensor([[139.2640, 103.0150, 258.0480, 307.5075]], device=device, dtype=dtype)
@@ -169,10 +169,10 @@ class TestTransformBoxes2D:
args = (boxes, trans_mat)
op = kornia.geometry.transform_points
op_optimized = torch_optimizer(op)
- assert_close(op(*args), op_optimized(*args))
+ self.assert_close(op(*args), op_optimized(*args))
-class TestBbox3D:
+class TestBbox3D(BaseTester):
def test_smoke(self, device, dtype):
# Sample two points of the 3d rect
points = torch.rand(1, 6, device=device, dtype=dtype)
@@ -214,9 +214,9 @@ class TestBbox3D:
) # 2x8x3
d, h, w = infer_bbox_shape3d(boxes)
- assert_close(d, torch.tensor([31.0, 61.0], device=device, dtype=dtype))
- assert_close(h, torch.tensor([21.0, 51.0], device=device, dtype=dtype))
- assert_close(w, torch.tensor([11.0, 41.0], device=device, dtype=dtype))
+ self.assert_close(d, torch.tensor([31.0, 61.0], device=device, dtype=dtype))
+ self.assert_close(h, torch.tensor([21.0, 51.0], device=device, dtype=dtype))
+ self.assert_close(w, torch.tensor([11.0, 41.0], device=device, dtype=dtype))
def test_gradcheck(self, device):
boxes = torch.tensor(
@@ -233,9 +233,9 @@ class TestBbox3D:
]
],
device=device,
+ dtype=torch.float64,
)
- boxes = tensor_to_gradcheck_var(boxes)
- gradcheck(infer_bbox_shape3d, (boxes,))
+ self.gradcheck(infer_bbox_shape3d, (boxes,))
def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
@@ -250,10 +250,10 @@ class TestBbox3D:
actual = op_script(boxes)
expected = op(boxes)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestNMS:
+class TestNMS(BaseTester):
def test_smoke(self, device, dtype):
boxes = torch.tensor(
[
@@ -268,4 +268,4 @@ class TestNMS:
scores = torch.tensor([0.9, 0.8, 0.7, 0.9], device=device, dtype=dtype)
expected = torch.tensor([0, 3, 1], device=device, dtype=torch.long)
actual = nms(boxes, scores, iou_threshold=0.8)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 04236da11..3f4f8c706 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -4,10 +4,11 @@ import pytest
import torch
from kornia.geometry.boxes import Boxes, Boxes3D
-from kornia.testing import assert_close, gradcheck, tensor_to_gradcheck_var
+from testing.base import BaseTester
-class TestBoxes2D:
+
+class TestBoxes2D(BaseTester):
def test_smoke(self, device, dtype):
def _create_tensor_box():
# Sample two points of the rectangle
@@ -54,8 +55,8 @@ class TestBoxes2D:
assert w.ndim == 1
assert len(h) == 2
assert len(w) == 2
- assert_close(h, torch.as_tensor([2.0, 3.0], device=device, dtype=dtype))
- assert_close(w, torch.as_tensor([3.0, 4.0], device=device, dtype=dtype))
+ self.assert_close(h, torch.as_tensor([2.0, 3.0], device=device, dtype=dtype))
+ self.assert_close(w, torch.as_tensor([3.0, 4.0], device=device, dtype=dtype))
# Box batch
h, w = boxes_batch.get_boxes_shape()
@@ -63,8 +64,8 @@ class TestBoxes2D:
assert w.ndim == 2
assert h.shape == (1, 2)
assert w.shape == (1, 2)
- assert_close(h, torch.as_tensor([[2.0, 3.0]], device=device, dtype=dtype))
- assert_close(w, torch.as_tensor([[3.0, 4.0]], device=device, dtype=dtype))
+ self.assert_close(h, torch.as_tensor([[2.0, 3.0]], device=device, dtype=dtype))
+ self.assert_close(w, torch.as_tensor([[3.0, 4.0]], device=device, dtype=dtype))
def test_get_boxes_shape_batch(self, device, dtype):
t_box1 = torch.tensor([[[1.0, 1.0], [3.0, 2.0], [3.0, 1.0], [1.0, 2.0]]], device=device, dtype=dtype)
@@ -76,8 +77,8 @@ class TestBoxes2D:
assert w.ndim == 2
assert h.shape == (2, 1)
assert w.shape == (2, 1)
- assert_close(h, torch.as_tensor([[2], [3]], device=device, dtype=dtype))
- assert_close(w, torch.as_tensor([[3], [4]], device=device, dtype=dtype))
+ self.assert_close(h, torch.as_tensor([[2], [3]], device=device, dtype=dtype))
+ self.assert_close(w, torch.as_tensor([[3], [4]], device=device, dtype=dtype))
@pytest.mark.parametrize("shape", [(1, 4), (1, 1, 4)])
def test_from_tensor(self, shape, device, dtype):
@@ -98,19 +99,19 @@ class TestBoxes2D:
boxes_vertices_plus = Boxes.from_tensor(box_vertices_plus, mode="vertices_plus").data
assert boxes_xyxy.shape == expected_box.shape
- assert_close(boxes_xyxy, expected_box)
+ self.assert_close(boxes_xyxy, expected_box)
assert boxes_xyxy_plus.shape == expected_box.shape
- assert_close(boxes_xyxy_plus, expected_box)
+ self.assert_close(boxes_xyxy_plus, expected_box)
assert boxes_xywh.shape == expected_box.shape
- assert_close(boxes_xywh, expected_box)
+ self.assert_close(boxes_xywh, expected_box)
assert box_vertices.shape == expected_box.shape
- assert_close(box_vertices, expected_box)
+ self.assert_close(box_vertices, expected_box)
assert boxes_vertices_plus.shape == expected_box.shape
- assert_close(boxes_vertices_plus, expected_box)
+ self.assert_close(boxes_vertices_plus, expected_box)
@pytest.mark.parametrize("shape", [(1, 4), (1, 1, 4)])
def test_from_invalid_tensor(self, shape, device, dtype):
@@ -151,19 +152,19 @@ class TestBoxes2D:
boxes_vertices_plus = box.to_tensor(mode="vertices_plus")
assert boxes_xyxy.shape == expected_box_xyxy.shape
- assert_close(boxes_xyxy, expected_box_xyxy)
+ self.assert_close(boxes_xyxy, expected_box_xyxy)
assert boxes_xyxy_plus.shape == expected_box_xyxy_plus.shape
- assert_close(boxes_xyxy_plus, expected_box_xyxy_plus)
+ self.assert_close(boxes_xyxy_plus, expected_box_xyxy_plus)
assert boxes_xywh.shape == expected_box_xywh.shape
- assert_close(boxes_xywh, expected_box_xywh)
+ self.assert_close(boxes_xywh, expected_box_xywh)
assert boxes_vertices.shape == expected_vertices.shape
- assert_close(boxes_vertices, expected_vertices)
+ self.assert_close(boxes_vertices, expected_vertices)
assert boxes_vertices_plus.shape == expected_vertices_plus.shape
- assert_close(boxes_vertices_plus, expected_vertices_plus)
+ self.assert_close(boxes_vertices_plus, expected_vertices_plus)
@pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])
def test_boxes_list_to_tensor_list(self, mode, device, dtype):
@@ -236,16 +237,16 @@ class TestBoxes2D:
batched_masks = batched_boxes.to_mask(height, width)
assert mask1.shape == expected_mask1.shape
- assert_close(mask1, expected_mask1)
+ self.assert_close(mask1, expected_mask1)
assert mask2.shape == expected_mask2.shape
- assert_close(mask2, expected_mask2)
+ self.assert_close(mask2, expected_mask2)
assert two_masks.shape == expected_two_masks.shape
- assert_close(two_masks, expected_two_masks)
+ self.assert_close(two_masks, expected_two_masks)
assert batched_masks.shape == expected_batched_masks.shape
- assert_close(batched_masks, expected_batched_masks)
+ self.assert_close(batched_masks, expected_batched_masks)
def test_to(self, device, dtype):
boxes = Boxes.from_tensor(torch.as_tensor([[1, 2, 3, 4]], device="cpu", dtype=torch.float32))
@@ -262,24 +263,23 @@ class TestBoxes2D:
result = getattr(boxes, method)(**kwargs)
return result.data if isinstance(result, Boxes) else result
- t_boxes1 = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device)
+ t_boxes1 = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=torch.float64)
- t_boxes1 = tensor_to_gradcheck_var(t_boxes1)
- t_boxes2 = tensor_to_gradcheck_var(t_boxes1.detach().clone())
- t_boxes3 = tensor_to_gradcheck_var(t_boxes1.detach().clone())
- t_boxes4 = tensor_to_gradcheck_var(t_boxes1.detach().clone())
- t_boxes_xyxy = tensor_to_gradcheck_var(torch.tensor([[1.0, 3.0, 5.0, 6.0]]))
- t_boxes_xyxy1 = tensor_to_gradcheck_var(t_boxes_xyxy.detach().clone())
+ t_boxes2 = t_boxes1.detach().clone()
+ t_boxes3 = t_boxes1.detach().clone()
+ t_boxes4 = t_boxes1.detach().clone()
+ t_boxes_xyxy = torch.tensor([[1.0, 3.0, 5.0, 6.0]])
+ t_boxes_xyxy1 = t_boxes_xyxy.detach().clone()
- gradcheck(partial(apply_boxes_method, method="to_tensor"), (t_boxes2,))
- gradcheck(partial(apply_boxes_method, method="to_tensor", mode="xyxy_plus"), (t_boxes3,))
- gradcheck(partial(apply_boxes_method, method="to_tensor", mode="vertices_plus"), (t_boxes4,))
- gradcheck(partial(apply_boxes_method, method="get_boxes_shape"), (t_boxes1,))
- gradcheck(lambda x: Boxes.from_tensor(x, mode="xyxy_plus").data, (t_boxes_xyxy,))
- gradcheck(lambda x: Boxes.from_tensor(x, mode="xywh").data, (t_boxes_xyxy1,))
+ self.gradcheck(partial(apply_boxes_method, method="to_tensor"), (t_boxes2,))
+ self.gradcheck(partial(apply_boxes_method, method="to_tensor", mode="xyxy_plus"), (t_boxes3,))
+ self.gradcheck(partial(apply_boxes_method, method="to_tensor", mode="vertices_plus"), (t_boxes4,))
+ self.gradcheck(partial(apply_boxes_method, method="get_boxes_shape"), (t_boxes1,))
+ self.gradcheck(lambda x: Boxes.from_tensor(x, mode="xyxy_plus").data, (t_boxes_xyxy,))
+ self.gradcheck(lambda x: Boxes.from_tensor(x, mode="xywh").data, (t_boxes_xyxy1,))
-class TestTransformBoxes2D:
+class TestTransformBoxes2D(BaseTester):
def test_transform_boxes(self, device, dtype):
# Define boxes in XYXY format for simplicity.
boxes_xyxy = torch.tensor([[139.2640, 103.0150, 398.3120, 411.5225]], device=device, dtype=dtype)
@@ -291,7 +291,7 @@ class TestTransformBoxes2D:
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
transformed_boxes = boxes.transform_boxes(trans_mat)
- assert_close(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
+ self.assert_close(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
# inplace check
assert transformed_boxes is not boxes
@@ -306,7 +306,7 @@ class TestTransformBoxes2D:
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
transformed_boxes = boxes.transform_boxes_(trans_mat)
- assert_close(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
+ self.assert_close(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
# inplace check
assert transformed_boxes is boxes
@@ -355,7 +355,7 @@ class TestTransformBoxes2D:
expected_boxes = Boxes.from_tensor(expected_boxes_xyxy, validate_boxes=False)
out = boxes.transform_boxes(trans_mat)
- assert_close(out.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
+ self.assert_close(out.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
# Define boxes in XYXY format for simplicity.
@@ -367,23 +367,23 @@ class TestTransformBoxes2D:
[119.8080, 144.2067, 137.2160, 265.9225],
],
device=device,
+ dtype=torch.float64,
)
boxes = Boxes.from_tensor(boxes_xyxy)
- trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device)
-
- trans_mat = tensor_to_gradcheck_var(trans_mat)
- t_boxes = tensor_to_gradcheck_var(boxes.data)
+ trans_mat = torch.tensor(
+ [[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=torch.float64
+ )
def _wrapper_transform_boxes(quadrilaterals, M):
boxes = Boxes(quadrilaterals)
boxes = boxes.transform_boxes(M)
return boxes.data
- gradcheck(_wrapper_transform_boxes, (t_boxes, trans_mat))
+ self.gradcheck(_wrapper_transform_boxes, (boxes.data, trans_mat))
-class TestBbox3D:
+class TestBbox3D(BaseTester):
def test_smoke(self, device, dtype):
def _create_tensor_box():
# Sample two points of the 3d rect
@@ -454,9 +454,9 @@ class TestBbox3D:
assert len(d) == 2
assert len(h) == 2
assert len(w) == 2
- assert_close(d, torch.as_tensor([31.0, 61.0], device=device, dtype=dtype))
- assert_close(h, torch.as_tensor([21.0, 51.0], device=device, dtype=dtype))
- assert_close(w, torch.as_tensor([11.0, 41.0], device=device, dtype=dtype))
+ self.assert_close(d, torch.as_tensor([31.0, 61.0], device=device, dtype=dtype))
+ self.assert_close(h, torch.as_tensor([21.0, 51.0], device=device, dtype=dtype))
+ self.assert_close(w, torch.as_tensor([11.0, 41.0], device=device, dtype=dtype))
# Box batch
d, h, w = boxes_batch.get_boxes_shape()
@@ -464,9 +464,9 @@ class TestBbox3D:
assert w.ndim == 2
assert h.shape == (1, 2)
assert w.shape == (1, 2)
- assert_close(d, torch.as_tensor([[31.0, 61.0]], device=device, dtype=dtype))
- assert_close(h, torch.as_tensor([[21.0, 51.0]], device=device, dtype=dtype))
- assert_close(w, torch.as_tensor([[11.0, 41.0]], device=device, dtype=dtype))
+ self.assert_close(d, torch.as_tensor([[31.0, 61.0]], device=device, dtype=dtype))
+ self.assert_close(h, torch.as_tensor([[21.0, 51.0]], device=device, dtype=dtype))
+ self.assert_close(w, torch.as_tensor([[11.0, 41.0]], device=device, dtype=dtype))
def test_get_boxes_shape_batch(self, device, dtype):
t_box1 = torch.tensor(
@@ -488,9 +488,9 @@ class TestBbox3D:
assert d.shape == (2, 1)
assert h.shape == (2, 1)
assert w.shape == (2, 1)
- assert_close(d, torch.as_tensor([[31.0], [61.0]], device=device, dtype=dtype))
- assert_close(h, torch.as_tensor([[21.0], [51.0]], device=device, dtype=dtype))
- assert_close(w, torch.as_tensor([[11.0], [41.0]], device=device, dtype=dtype))
+ self.assert_close(d, torch.as_tensor([[31.0], [61.0]], device=device, dtype=dtype))
+ self.assert_close(h, torch.as_tensor([[21.0], [51.0]], device=device, dtype=dtype))
+ self.assert_close(w, torch.as_tensor([[11.0], [41.0]], device=device, dtype=dtype))
@pytest.mark.parametrize("shape", [(1, 6), (1, 1, 6)])
def test_from_tensor(self, shape, device, dtype):
@@ -509,13 +509,13 @@ class TestBbox3D:
kornia_xyzwhd = Boxes3D.from_tensor(box_xyzwhd, mode="xyzwhd").data
assert kornia_xyzxyz.shape == expected_box.shape
- assert_close(kornia_xyzxyz, expected_box)
+ self.assert_close(kornia_xyzxyz, expected_box)
assert kornia_xyzxyz_plus.shape == expected_box.shape
- assert_close(kornia_xyzxyz_plus, expected_box)
+ self.assert_close(kornia_xyzxyz_plus, expected_box)
assert kornia_xyzwhd.shape == expected_box.shape
- assert_close(kornia_xyzwhd, expected_box)
+ self.assert_close(kornia_xyzwhd, expected_box)
@pytest.mark.parametrize("shape", [(1, 6), (1, 1, 6)])
def test_from_invalid_tensor(self, shape, device, dtype):
@@ -566,19 +566,19 @@ class TestBbox3D:
kornia_vertices_plus = box.to_tensor(mode="vertices_plus")
assert kornia_xyzxyz.shape == expected_box_xyzxyz.shape
- assert_close(kornia_xyzxyz, expected_box_xyzxyz)
+ self.assert_close(kornia_xyzxyz, expected_box_xyzxyz)
assert kornia_xyzxyz_plus.shape == expected_box_xyzxyz_plus.shape
- assert_close(kornia_xyzxyz_plus, expected_box_xyzxyz_plus)
+ self.assert_close(kornia_xyzxyz_plus, expected_box_xyzxyz_plus)
assert kornia_xyzwhd.shape == expected_box_xyzwhd.shape
- assert_close(kornia_xyzwhd, expected_box_xyzwhd)
+ self.assert_close(kornia_xyzwhd, expected_box_xyzwhd)
assert kornia_vertices.shape == expected_vertices.shape
- assert_close(kornia_vertices, expected_vertices)
+ self.assert_close(kornia_vertices, expected_vertices)
assert kornia_vertices_plus.shape == expected_vertices_plus.shape
- assert_close(kornia_vertices_plus, expected_vertices_plus)
+ self.assert_close(kornia_vertices_plus, expected_vertices_plus)
def test_bbox_to_mask(self, device, dtype):
t_box1 = torch.tensor(
@@ -700,16 +700,16 @@ class TestBbox3D:
batched_masks = batched_boxes.to_mask(depth, height, width)
assert mask1.shape == expected_mask1.shape
- assert_close(mask1, expected_mask1)
+ self.assert_close(mask1, expected_mask1)
assert mask2.shape == expected_mask2.shape
- assert_close(mask2, expected_mask2)
+ self.assert_close(mask2, expected_mask2)
assert two_masks.shape == expected_two_masks.shape
- assert_close(two_masks, expected_two_masks)
+ self.assert_close(two_masks, expected_two_masks)
assert batched_masks.shape == expected_batched_masks.shape
- assert_close(batched_masks, expected_batched_masks)
+ self.assert_close(batched_masks, expected_batched_masks)
def test_to(self, device, dtype):
boxes = Boxes3D.from_tensor(torch.as_tensor([[1, 2, 3, 4, 5, 6]], device="cpu", dtype=torch.float32))
@@ -727,29 +727,29 @@ class TestBbox3D:
# result = getattr(boxes, method)(**kwargs)
# return result.data if isinstance(result, Boxes3D) else result
- t_boxes1 = torch.tensor(
- [
- [
- [0.0, 1.0, 2.0],
- [10, 1, 2],
- [10, 21, 2],
- [0, 21, 2],
- [0, 1, 32],
- [10, 1, 32],
- [10, 21, 32],
- [0, 21, 32],
- ]
- ],
- device=device,
- )
+ # t_boxes1 = torch.tensor(
+ # [
+ # [
+ # [0.0, 1.0, 2.0],
+ # [10, 1, 2],
+ # [10, 21, 2],
+ # [0, 21, 2],
+ # [0, 1, 32],
+ # [10, 1, 32],
+ # [10, 21, 32],
+ # [0, 21, 32],
+ # ]
+ # ],
+ # device=device,
+ # dtype=torch.float64,
+ # )
- t_boxes1 = tensor_to_gradcheck_var(t_boxes1)
# Uncomment when enabling gradient checks
# t_boxes2 = tensor_to_gradcheck_var(t_boxes1.detach().clone())
# t_boxes3 = tensor_to_gradcheck_var(t_boxes1.detach().clone())
# t_boxes4 = tensor_to_gradcheck_var(t_boxes1.detach().clone())
- t_boxes_xyzxyz = tensor_to_gradcheck_var(torch.tensor([[1.0, 3.0, 8.0, 5.0, 6.0, 12.0]]))
- t_boxes_xyzxyz1 = tensor_to_gradcheck_var(t_boxes_xyzxyz.detach().clone())
+ t_boxes_xyzxyz = torch.tensor([[1.0, 3.0, 8.0, 5.0, 6.0, 12.0]], device=device, dtype=torch.float64)
+ t_boxes_xyzxyz1 = t_boxes_xyzxyz.detach().clone()
# Gradient checks for Boxes3D.to_tensor (and Boxes3D.get_boxes_shape) are disable since the is a bug
# in their gradient. See https://github.com/kornia/kornia/issues/1396.
@@ -761,11 +761,11 @@ class TestBbox3D:
# partial(apply_boxes_method, method='to_tensor', mode='vertices_plus'), (t_boxes4,), raise_exception=True
# )
# assert gradcheck(partial(apply_boxes_method, method='get_boxes_shape'), (t_boxes1,), raise_exception=True)
- gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzxyz_plus").data, (t_boxes_xyzxyz,))
- gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzwhd").data, (t_boxes_xyzxyz1,))
+ self.gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzxyz_plus").data, (t_boxes_xyzxyz,))
+ self.gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzwhd").data, (t_boxes_xyzxyz1,))
-class TestTransformBoxes3D:
+class TestTransformBoxes3D(BaseTester):
def test_transform_boxes(self, device, dtype):
# Define boxes in XYZXYZ format for simplicity.
boxes_xyzxyz = torch.tensor(
@@ -785,7 +785,7 @@ class TestTransformBoxes3D:
)
transformed_boxes = boxes.transform_boxes(trans_mat)
- assert_close(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
+ self.assert_close(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
# inplace check
assert transformed_boxes is not boxes
@@ -808,7 +808,7 @@ class TestTransformBoxes3D:
)
transformed_boxes = boxes.transform_boxes_(trans_mat)
- assert_close(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
+ self.assert_close(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
# inplace check
assert transformed_boxes is boxes
@@ -857,7 +857,7 @@ class TestTransformBoxes3D:
expected_boxes = Boxes3D.from_tensor(expected_boxes_xyzxyz, validate_boxes=False)
out = boxes.transform_boxes(trans_mat)
- assert_close(out.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
+ self.assert_close(out.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
# Define boxes in XYZXYZ format for simplicity.
@@ -869,19 +869,19 @@ class TestTransformBoxes3D:
[119.8080, 144.2067, 234.21, 257.0240, 410.1292, 386.14],
],
device=device,
+ dtype=torch.float64,
)
boxes = Boxes3D.from_tensor(boxes_xyzxyz)
trans_mat = torch.tensor(
- [[[-1.0, 0.0, 0.0, 512.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 2.0, 1.0], [0.0, 0.0, 0.0, 1.0]]], device=device
+ [[[-1.0, 0.0, 0.0, 512.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 2.0, 1.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=torch.float64,
)
- trans_mat = tensor_to_gradcheck_var(trans_mat)
- t_boxes = tensor_to_gradcheck_var(boxes.data)
-
def _wrapper_transform_boxes(hexahedrons, M):
boxes = Boxes3D(hexahedrons)
boxes = boxes.transform_boxes(M)
return boxes.data
- gradcheck(_wrapper_transform_boxes, (t_boxes, trans_mat))
+ self.gradcheck(_wrapper_transform_boxes, (boxes.data, trans_mat))
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 66587c3d6..f19ec67db 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -3,7 +3,6 @@ from functools import partial
import numpy as np
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
from kornia.geometry.conversions import (
@@ -20,7 +19,9 @@ from kornia.geometry.conversions import (
worldtocam_to_camtoworld_Rt,
)
from kornia.geometry.quaternion import Quaternion
-from kornia.testing import BaseTester, assert_close, create_eye_batch, tensor_to_gradcheck_var
+from kornia.utils.misc import eye_like
+
+from testing.base import BaseTester, assert_close
@pytest.fixture()
@@ -39,11 +40,10 @@ def rtol(device, dtype):
return 1.0e-4
-# based on:
-# https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/rotation_test.cc#L271
-
+class TestAngleAxisToQuaternion(BaseTester):
+ # based on:
+ # https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/rotation_test.cc#L271
-class TestAngleAxisToQuaternion:
def test_smoke(self, device, dtype):
axis_angle = torch.zeros(3, dtype=dtype, device=device)
quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
@@ -59,64 +59,59 @@ class TestAngleAxisToQuaternion:
axis_angle = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
- assert_close(quaternion, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion, expected, atol=atol, rtol=rtol)
def test_small_angle_x(self, device, dtype, atol, rtol):
theta = 1.0e-2
axis_angle = torch.tensor((theta, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((np.cos(theta / 2.0), np.sin(theta / 2.0), 0.0, 0.0), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
- assert_close(quaternion, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion, expected, atol=atol, rtol=rtol)
def test_small_angle_y(self, device, dtype, atol, rtol):
theta = 1.0e-2
axis_angle = torch.tensor((0.0, theta, 0.0), device=device, dtype=dtype)
expected = torch.tensor((np.cos(theta / 2.0), 0.0, np.sin(theta / 2.0), 0.0), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
- assert_close(quaternion, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion, expected, atol=atol, rtol=rtol)
def test_small_angle_z(self, device, dtype, atol, rtol):
theta = 1.0e-2
axis_angle = torch.tensor((0.0, 0.0, theta), device=device, dtype=dtype)
expected = torch.tensor((np.cos(theta / 2.0), 0.0, 0.0, np.sin(theta / 2.0)), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
- assert_close(quaternion, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion, expected, atol=atol, rtol=rtol)
def test_x_rotation(self, device, dtype, atol, rtol):
half_sqrt2 = 0.5 * np.sqrt(2.0)
axis_angle = torch.tensor((kornia.pi / 2.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((half_sqrt2, half_sqrt2, 0.0, 0.0), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
- assert_close(quaternion, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion, expected, atol=atol, rtol=rtol)
def test_y_rotation(self, device, dtype, atol, rtol):
half_sqrt2 = 0.5 * np.sqrt(2.0)
axis_angle = torch.tensor((0.0, kornia.pi / 2.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((half_sqrt2, 0.0, half_sqrt2, 0.0), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
- assert_close(quaternion, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion, expected, atol=atol, rtol=rtol)
def test_z_rotation(self, device, dtype, atol, rtol):
half_sqrt2 = 0.5 * np.sqrt(2.0)
axis_angle = torch.tensor((0.0, 0.0, kornia.pi / 2.0), device=device, dtype=dtype)
expected = torch.tensor((half_sqrt2, 0.0, 0.0, half_sqrt2), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
- assert_close(quaternion, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion, expected, atol=atol, rtol=rtol)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
eps = torch.finfo(dtype).eps
axis_angle = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype) + eps
- axis_angle = tensor_to_gradcheck_var(axis_angle)
# evaluate function gradient
- assert gradcheck(
- partial(kornia.geometry.conversions.axis_angle_to_quaternion),
- (axis_angle,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(partial(kornia.geometry.conversions.axis_angle_to_quaternion), (axis_angle,))
-class TestQuaternionToAngleAxis:
+class TestQuaternionToAngleAxis(BaseTester):
def test_smoke(self, device, dtype):
quaternion = torch.zeros(4, device=device, dtype=dtype)
axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
@@ -132,61 +127,56 @@ class TestQuaternionToAngleAxis:
quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
- assert_close(axis_angle, expected, atol=atol, rtol=rtol)
+ self.assert_close(axis_angle, expected, atol=atol, rtol=rtol)
def test_x_rotation(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((kornia.pi, 0.0, 0.0), device=device, dtype=dtype)
axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
- assert_close(axis_angle, expected, atol=atol, rtol=rtol)
+ self.assert_close(axis_angle, expected, atol=atol, rtol=rtol)
def test_y_rotation(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((0.0, kornia.pi, 0.0), device=device, dtype=dtype)
axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
- assert_close(axis_angle, expected, atol=atol, rtol=rtol)
+ self.assert_close(axis_angle, expected, atol=atol, rtol=rtol)
def test_z_rotation(self, device, dtype, atol, rtol):
quaternion = torch.tensor((np.sqrt(3.0) / 2.0, 0.0, 0.0, 0.5), device=device, dtype=dtype)
expected = torch.tensor((0.0, 0.0, kornia.pi / 3.0), device=device, dtype=dtype)
axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
- assert_close(axis_angle, expected, atol=atol, rtol=rtol)
+ self.assert_close(axis_angle, expected, atol=atol, rtol=rtol)
def test_small_angle_x(self, device, dtype, atol, rtol):
theta = 1.0e-2
quaternion = torch.tensor((np.cos(theta / 2.0), np.sin(theta / 2.0), 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((theta, 0.0, 0.0), device=device, dtype=dtype)
axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
- assert_close(axis_angle, expected, atol=atol, rtol=rtol)
+ self.assert_close(axis_angle, expected, atol=atol, rtol=rtol)
def test_small_angle_y(self, device, dtype, atol, rtol):
theta = 1.0e-2
quaternion = torch.tensor((np.cos(theta / 2), 0.0, np.sin(theta / 2), 0.0), device=device, dtype=dtype)
expected = torch.tensor((0.0, theta, 0.0), device=device, dtype=dtype)
axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
- assert_close(axis_angle, expected, atol=atol, rtol=rtol)
+ self.assert_close(axis_angle, expected, atol=atol, rtol=rtol)
def test_small_angle_z(self, device, dtype, atol, rtol):
theta = 1.0e-2
quaternion = torch.tensor((np.cos(theta / 2), 0.0, 0.0, np.sin(theta / 2)), device=device, dtype=dtype)
expected = torch.tensor((0.0, 0.0, theta), device=device, dtype=dtype)
axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
- assert_close(axis_angle, expected, atol=atol, rtol=rtol)
+ self.assert_close(axis_angle, expected, atol=atol, rtol=rtol)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
eps = torch.finfo(dtype).eps
quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype) + eps
- quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(
- partial(kornia.geometry.conversions.quaternion_to_axis_angle),
- (quaternion,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(partial(kornia.geometry.conversions.quaternion_to_axis_angle), (quaternion,))
-class TestRotationMatrixToQuaternion:
+class TestRotationMatrixToQuaternion(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch(self, batch_size, device, dtype):
matrix = torch.zeros(batch_size, 3, 3, device=device, dtype=dtype)
@@ -197,21 +187,21 @@ class TestRotationMatrixToQuaternion:
matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
expected = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(matrix)
- assert_close(quaternion, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion, expected, atol=atol, rtol=rtol)
def test_rot_x_45(self, device, dtype, atol, rtol):
matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.0)), device=device, dtype=dtype)
pi_half2 = torch.cos(kornia.pi / 4.0).to(device=device, dtype=dtype)
expected = torch.tensor((pi_half2, pi_half2, 0.0, 0.0), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(matrix)
- assert_close(quaternion, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion, expected, atol=atol, rtol=rtol)
def test_back_and_forth(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.0)), device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(matrix, eps=eps)
matrix_hat = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
- assert_close(matrix, matrix_hat, atol=atol, rtol=rtol)
+ self.assert_close(matrix, matrix_hat, atol=atol, rtol=rtol)
def test_corner_case(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
@@ -229,19 +219,14 @@ class TestRotationMatrixToQuaternion:
)
quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(matrix, eps=eps)
torch.set_printoptions(precision=10)
- assert_close(quaternion_true, quaternion, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_true, quaternion, atol=atol, rtol=rtol)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
eps = torch.finfo(dtype).eps
matrix = torch.eye(3, device=device, dtype=dtype)
- matrix = tensor_to_gradcheck_var(matrix)
# evaluate function gradient
- assert gradcheck(
- partial(kornia.geometry.conversions.rotation_matrix_to_quaternion, eps=eps),
- (matrix,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(partial(kornia.geometry.conversions.rotation_matrix_to_quaternion, eps=eps), (matrix,))
def test_dynamo(self, device, dtype, torch_optimizer):
quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
@@ -251,10 +236,10 @@ class TestRotationMatrixToQuaternion:
actual = op_optimized(quaternion)
expected = op(quaternion)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestQuaternionToRotationMatrix:
+class TestQuaternionToRotationMatrix(BaseTester):
@pytest.mark.parametrize("batch_dims", ((), (1,), (3,), (8,), (1, 1), (5, 6)))
def test_smoke_batch(self, batch_dims, device, dtype):
quaternion = torch.zeros(*batch_dims, 4, device=device, dtype=dtype)
@@ -265,36 +250,30 @@ class TestQuaternionToRotationMatrix:
quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
- assert_close(matrix, expected, atol=atol, rtol=rtol)
+ self.assert_close(matrix, expected, atol=atol, rtol=rtol)
def test_x_rotation(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor(((1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
- assert_close(matrix, expected, atol=atol, rtol=rtol)
+ self.assert_close(matrix, expected, atol=atol, rtol=rtol)
def test_y_rotation(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor(((-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
- assert_close(matrix, expected, atol=atol, rtol=rtol)
+ self.assert_close(matrix, expected, atol=atol, rtol=rtol)
def test_z_rotation(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
expected = torch.tensor(((-1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
- assert_close(matrix, expected, atol=atol, rtol=rtol)
+ self.assert_close(matrix, expected, atol=atol, rtol=rtol)
- def test_gradcheck(self, device, dtype):
- quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
- quaternion = tensor_to_gradcheck_var(quaternion)
+ def test_gradcheck(self, device):
+ quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=torch.float64)
# evaluate function gradient
- assert gradcheck(
- partial(kornia.geometry.conversions.quaternion_to_rotation_matrix),
- (quaternion,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(partial(kornia.geometry.conversions.quaternion_to_rotation_matrix), (quaternion,))
def test_dynamo(self, device, dtype, torch_optimizer):
quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
@@ -304,10 +283,10 @@ class TestQuaternionToRotationMatrix:
actual = op_optimized(quaternion)
expected = op(quaternion)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestQuaternionLogToExp:
+class TestQuaternionLogToExp(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch(self, batch_size, device, dtype):
quaternion_log = torch.zeros(batch_size, 3, device=device, dtype=dtype)
@@ -319,7 +298,7 @@ class TestQuaternionLogToExp:
quaternion_log = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(quaternion_log, eps=eps)
- assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_x(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
@@ -327,7 +306,7 @@ class TestQuaternionLogToExp:
quaternion_log = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((torch.cos(one), torch.sin(one), 0.0, 0.0), device=device, dtype=dtype)
quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(quaternion_log, eps=eps)
- assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_y(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
@@ -335,7 +314,7 @@ class TestQuaternionLogToExp:
quaternion_log = torch.tensor((0.0, 1.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((torch.cos(one), 0.0, torch.sin(one), 0.0), device=device, dtype=dtype)
quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(quaternion_log, eps=eps)
- assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_z(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
@@ -343,7 +322,7 @@ class TestQuaternionLogToExp:
quaternion_log = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
expected = torch.tensor((torch.cos(one), 0.0, 0.0, torch.sin(one)), device=device, dtype=dtype)
quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(quaternion_log, eps=eps)
- assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_back_and_forth(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
@@ -351,19 +330,14 @@ class TestQuaternionLogToExp:
quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(quaternion_log, eps=eps)
quaternion_log_hat = kornia.geometry.conversions.quaternion_exp_to_log(quaternion_exp, eps=eps)
- assert_close(quaternion_log, quaternion_log_hat, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_log, quaternion_log_hat, atol=atol, rtol=rtol)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
eps = torch.finfo(dtype).eps
quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
- quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(
- partial(kornia.geometry.conversions.quaternion_log_to_exp, eps=eps),
- (quaternion,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(partial(kornia.geometry.conversions.quaternion_log_to_exp, eps=eps), (quaternion,))
def test_dynamo(self, device, dtype, torch_optimizer):
quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
@@ -373,10 +347,10 @@ class TestQuaternionLogToExp:
actual = op_optimized(quaternion)
expected = op(quaternion)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestQuaternionExpToLog:
+class TestQuaternionExpToLog(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch(self, batch_size, device, dtype):
eps = torch.finfo(dtype).eps
@@ -389,47 +363,42 @@ class TestQuaternionExpToLog:
quaternion_exp = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(quaternion_exp, eps=eps)
- assert_close(quaternion_log, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_log, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_x(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((kornia.pi / 2.0, 0.0, 0.0), device=device, dtype=dtype)
quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(quaternion_exp, eps=eps)
- assert_close(quaternion_log, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_log, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_y(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
expected = torch.tensor((0.0, kornia.pi / 2.0, 0.0), device=device, dtype=dtype)
quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(quaternion_exp, eps=eps)
- assert_close(quaternion_log, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_log, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_z(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
expected = torch.tensor((0.0, 0.0, kornia.pi / 2.0), device=device, dtype=dtype)
quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(quaternion_exp, eps=eps)
- assert_close(quaternion_log, expected, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_log, expected, atol=atol, rtol=rtol)
def test_back_and_forth(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(quaternion_exp, eps=eps)
quaternion_exp_hat = kornia.geometry.conversions.quaternion_log_to_exp(quaternion_log, eps=eps)
- assert_close(quaternion_exp, quaternion_exp_hat, atol=atol, rtol=rtol)
+ self.assert_close(quaternion_exp, quaternion_exp_hat, atol=atol, rtol=rtol)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
eps = torch.finfo(dtype).eps
quaternion = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
- quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(
- partial(kornia.geometry.conversions.quaternion_exp_to_log, eps=eps),
- (quaternion,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(partial(kornia.geometry.conversions.quaternion_exp_to_log, eps=eps), (quaternion,))
def test_dynamo(self, device, dtype, torch_optimizer):
quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
@@ -439,30 +408,25 @@ class TestQuaternionExpToLog:
actual = op_optimized(quaternion)
expected = op(quaternion)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestAngleAxisToRotationMatrix:
+class TestAngleAxisToRotationMatrix(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 2, 5))
- def test_rand_axis_angle_gradcheck(self, batch_size, device, dtype, atol, rtol):
+ def test_rand_axis_angle_gradcheck(self, batch_size, device, atol, rtol):
+ dtype = torch.float64
# generate input data
axis_angle = torch.rand(batch_size, 3, device=device, dtype=dtype)
- eye_batch = create_eye_batch(batch_size, 3, device=device, dtype=dtype)
+ eye_batch = eye_like(3, axis_angle)
# apply transform
rotation_matrix = kornia.geometry.conversions.axis_angle_to_rotation_matrix(axis_angle)
rotation_matrix_eye = torch.matmul(rotation_matrix, rotation_matrix.transpose(-2, -1))
- assert_close(rotation_matrix_eye, eye_batch, atol=atol, rtol=rtol)
+ self.assert_close(rotation_matrix_eye, eye_batch, atol=atol, rtol=rtol)
# evaluate function gradient
- axis_angle = tensor_to_gradcheck_var(axis_angle) # to var
- assert gradcheck(
- kornia.geometry.conversions.axis_angle_to_rotation_matrix,
- (axis_angle,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.conversions.axis_angle_to_rotation_matrix, (axis_angle,))
def test_axis_angle_to_rotation_matrix(self, device, dtype, atol, rtol):
rmat_1 = torch.tensor(
@@ -489,10 +453,10 @@ class TestAngleAxisToRotationMatrix:
rmat = torch.stack((rmat_2, rmat_1), dim=0)
rvec = torch.stack((rvec_2, rvec_1), dim=0)
- assert_close(kornia.geometry.conversions.axis_angle_to_rotation_matrix(rvec), rmat, atol=atol, rtol=rtol)
+ self.assert_close(kornia.geometry.conversions.axis_angle_to_rotation_matrix(rvec), rmat, atol=atol, rtol=rtol)
-class TestRotationMatrixToAngleAxis:
+class TestRotationMatrixToAngleAxis(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 2, 5))
def test_rand_quaternion_gradcheck(self, batch_size, device, dtype, atol, rtol):
# generate input data
@@ -500,24 +464,19 @@ class TestRotationMatrixToAngleAxis:
quaternion = kornia.geometry.conversions.normalize_quaternion(quaternion + 1e-6)
rotation_matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion=quaternion)
- eye_batch = create_eye_batch(batch_size, 3, device=device, dtype=dtype)
+ eye_batch = eye_like(3, rotation_matrix)
rotation_matrix_eye = torch.matmul(rotation_matrix, rotation_matrix.transpose(-2, -1))
# This didn't pass with atol=0.001, rtol=0.001 for float16 Cuda 11.2 GeForce 1080 Ti
- assert_close(rotation_matrix_eye, eye_batch, atol=atol * 10.0, rtol=rtol * 10.0)
+ self.assert_close(rotation_matrix_eye, eye_batch, atol=atol * 10.0, rtol=rtol * 10.0)
@pytest.mark.parametrize("batch_size", [4])
- def test_gradcheck(self, batch_size, device, dtype):
+ def test_gradcheck(self, batch_size, device):
+ dtype = torch.float64
quaternion = torch.rand(batch_size, 4, device=device, dtype=dtype)
quaternion = kornia.geometry.conversions.normalize_quaternion(quaternion + 1e-6)
rotation_matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion=quaternion)
# evaluate function gradient
- rotation_matrix = tensor_to_gradcheck_var(rotation_matrix) # to var
- assert gradcheck(
- kornia.geometry.conversions.rotation_matrix_to_axis_angle,
- (rotation_matrix,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.conversions.rotation_matrix_to_axis_angle, (rotation_matrix,))
def test_rotation_matrix_to_axis_angle(self, device, dtype, atol, rtol):
rmat_1 = torch.tensor(
@@ -544,56 +503,50 @@ class TestRotationMatrixToAngleAxis:
rmat = torch.stack((rmat_2, rmat_1), dim=0)
rvec = torch.stack((rvec_2, rvec_1), dim=0)
- assert_close(kornia.geometry.conversions.rotation_matrix_to_axis_angle(rmat), rvec, atol=atol, rtol=rtol)
-
-
-def test_pi():
- assert_close(kornia.constants.pi.item(), 3.141592)
-
+ self.assert_close(kornia.geometry.conversions.rotation_matrix_to_axis_angle(rmat), rvec, atol=atol, rtol=rtol)
[email protected]("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
-def test_rad2deg(batch_shape, device, dtype):
- # generate input data
- x_rad = kornia.constants.pi * torch.rand(batch_shape, device=device, dtype=dtype)
- # convert radians/degrees
- x_deg = kornia.geometry.conversions.rad2deg(x_rad)
- x_deg_to_rad = kornia.geometry.conversions.deg2rad(x_deg)
-
- # compute error
- assert_close(x_rad, x_deg_to_rad)
+class TestRadDegConversions(BaseTester):
+ def test_pi(self):
+ self.assert_close(kornia.constants.pi.item(), 3.141592)
+ @pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
+ def test_rad2deg(self, batch_shape, device, dtype):
+ # generate input data
+ x_rad = kornia.constants.pi * torch.rand(batch_shape, device=device, dtype=dtype)
[email protected]("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
-def test_rad2deg_gradcheck(batch_shape, device, dtype):
- x_rad = torch.rand(batch_shape, device=device, dtype=dtype)
- # evaluate function gradient
- assert gradcheck(
- kornia.geometry.conversions.rad2deg, (tensor_to_gradcheck_var(x_rad),), raise_exception=True, fast_mode=True
- )
+ # convert radians/degrees
+ x_deg = kornia.geometry.conversions.rad2deg(x_rad)
+ x_deg_to_rad = kornia.geometry.conversions.deg2rad(x_deg)
+ # compute error
+ self.assert_close(x_rad, x_deg_to_rad)
[email protected]("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
-def test_deg2rad(batch_shape, device, dtype, atol, rtol):
- # generate input data
- x_deg = 180.0 * torch.rand(batch_shape, device=device, dtype=dtype)
+ @pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
+ def test_rad2deg_gradcheck(self, batch_shape, device):
+ dtype = torch.float64
+ x_rad = torch.rand(batch_shape, device=device, dtype=dtype)
+ # evaluate function gradient
+ self.gradcheck(kornia.geometry.conversions.rad2deg, (x_rad,))
- # convert radians/degrees
- x_rad = kornia.geometry.conversions.deg2rad(x_deg)
- x_rad_to_deg = kornia.geometry.conversions.rad2deg(x_rad)
+ @pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
+ def test_deg2rad(self, batch_shape, device, dtype, atol, rtol):
+ # generate input data
+ x_deg = 180.0 * torch.rand(batch_shape, device=device, dtype=dtype)
- assert_close(x_deg, x_rad_to_deg, atol=atol, rtol=rtol)
+ # convert radians/degrees
+ x_rad = kornia.geometry.conversions.deg2rad(x_deg)
+ x_rad_to_deg = kornia.geometry.conversions.rad2deg(x_rad)
+ self.assert_close(x_deg, x_rad_to_deg, atol=atol, rtol=rtol)
[email protected]("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
-def test_deg2rad_gradcheck(batch_shape, device, dtype):
- x_deg = 180.0 * torch.rand(batch_shape, device=device, dtype=dtype)
- assert gradcheck(
- kornia.geometry.conversions.deg2rad, (tensor_to_gradcheck_var(x_deg),), raise_exception=True, fast_mode=True
- )
+ @pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
+ def test_deg2rad_gradcheck(self, batch_shape, device):
+ x_deg = 180.0 * torch.rand(batch_shape, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.conversions.deg2rad, (x_deg,))
-class TestPolCartConversions:
+class TestPolCartConversions(BaseTester):
def test_smoke(self, device, dtype):
x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
assert kornia.geometry.conversions.pol2cart(x, x) is not None
@@ -611,25 +564,15 @@ class TestPolCartConversions:
x_pol2cart, y_pol2cart = kornia.geometry.conversions.pol2cart(rho, phi)
rho_pol2cart, phi_pol2cart = kornia.geometry.conversions.cart2pol(x_pol2cart, y_pol2cart, 0)
- assert_close(rho, rho_pol2cart)
- assert_close(phi, phi_pol2cart)
+ self.assert_close(rho, rho_pol2cart)
+ self.assert_close(phi, phi_pol2cart)
@pytest.mark.parametrize("batch_shape", [(2, 3)])
- def test_gradcheck(self, batch_shape, device, dtype):
- rho = torch.rand(batch_shape, dtype=dtype, device=device)
- phi = kornia.constants.pi * torch.rand(batch_shape, dtype=dtype, device=device)
- assert gradcheck(
- kornia.geometry.conversions.pol2cart,
- (tensor_to_gradcheck_var(rho), tensor_to_gradcheck_var(phi)),
- raise_exception=True,
- fast_mode=True,
- )
- assert gradcheck(
- kornia.geometry.conversions.cart2pol,
- (tensor_to_gradcheck_var(rho), tensor_to_gradcheck_var(phi)),
- raise_exception=True,
- fast_mode=True,
- )
+ def test_gradcheck(self, batch_shape, device):
+ rho = torch.rand(batch_shape, dtype=torch.float64, device=device)
+ phi = kornia.constants.pi * torch.rand(batch_shape, dtype=torch.float64, device=device)
+ self.gradcheck(kornia.geometry.conversions.pol2cart, (rho, phi))
+ self.gradcheck(kornia.geometry.conversions.cart2pol, (rho, phi))
@pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
def test_cart2pol(self, batch_shape, device, dtype):
@@ -643,11 +586,11 @@ class TestPolCartConversions:
rho_cart2pol, phi_cart2pol = kornia.geometry.conversions.cart2pol(x, y, 0)
x_cart2pol, y_cart2pol = kornia.geometry.conversions.pol2cart(rho_cart2pol, phi_cart2pol)
- assert_close(x, x_cart2pol)
- assert_close(y, y_cart2pol)
+ self.assert_close(x, x_cart2pol)
+ self.assert_close(y, y_cart2pol)
-class TestConvertPointsToHomogeneous:
+class TestConvertPointsToHomogeneous(BaseTester):
def test_convert_points(self, device, dtype):
# generate input data
points_h = torch.tensor(
@@ -670,7 +613,7 @@ class TestConvertPointsToHomogeneous:
# to euclidean
points = kornia.geometry.conversions.convert_points_to_homogeneous(points_h)
- assert_close(points, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(points, expected, atol=1e-4, rtol=1e-4)
def test_convert_points_batch(self, device, dtype):
# generate input data
@@ -682,17 +625,14 @@ class TestConvertPointsToHomogeneous:
# to euclidean
points = kornia.geometry.conversions.convert_points_to_homogeneous(points_h)
- assert_close(points, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(points, expected, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
- def test_gradcheck(self, batch_shape, device, dtype):
- points_h = torch.rand(batch_shape, device=device, dtype=dtype)
+ def test_gradcheck(self, batch_shape, device):
+ points_h = torch.rand(batch_shape, device=device, dtype=torch.float64)
# evaluate function gradient
- points_h = tensor_to_gradcheck_var(points_h) # to var
- assert gradcheck(
- kornia.geometry.conversions.convert_points_to_homogeneous, (points_h,), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.conversions.convert_points_to_homogeneous, (points_h,))
def test_dynamo(self, device, dtype, torch_optimizer):
points_h = torch.zeros(1, 2, 3, device=device, dtype=dtype)
@@ -703,10 +643,10 @@ class TestConvertPointsToHomogeneous:
actual = op_optimized(points_h)
expected = op(points_h)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestConvertAtoH:
+class TestConvertAtoH(BaseTester):
def test_convert_points(self, device, dtype):
# generate input data
A = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype).view(1, 2, 3)
@@ -717,20 +657,14 @@ class TestConvertAtoH:
# to euclidean
H = kornia.geometry.conversions.convert_affinematrix_to_homography(A)
- assert_close(H, expected)
+ self.assert_close(H, expected)
@pytest.mark.parametrize("batch_shape", [(10, 2, 3), (16, 2, 3)])
- def test_gradcheck(self, batch_shape, device, dtype):
- points_h = torch.rand(batch_shape, device=device, dtype=dtype)
+ def test_gradcheck(self, batch_shape, device):
+ points_h = torch.rand(batch_shape, device=device, dtype=torch.float64)
# evaluate function gradient
- points_h = tensor_to_gradcheck_var(points_h) # to var
- assert gradcheck(
- kornia.geometry.conversions.convert_affinematrix_to_homography,
- (points_h,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.conversions.convert_affinematrix_to_homography, (points_h,))
def test_dynamo(self, device, dtype, torch_optimizer):
points_h = torch.zeros(1, 2, 3, device=device, dtype=dtype)
@@ -741,10 +675,10 @@ class TestConvertAtoH:
actual = op_optimized(points_h)
expected = op(points_h)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestConvertPointsFromHomogeneous:
+class TestConvertPointsFromHomogeneous(BaseTester):
@pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])
def test_cardinality(self, device, dtype, batch_shape):
points_h = torch.rand(batch_shape, device=device, dtype=dtype)
@@ -765,7 +699,7 @@ class TestConvertPointsFromHomogeneous:
# to euclidean
points = kornia.geometry.conversions.convert_points_from_homogeneous(points_h)
- assert_close(points, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(points, expected, atol=1e-4, rtol=1e-4)
def test_points_batch(self, device, dtype):
# generate input data
@@ -775,33 +709,21 @@ class TestConvertPointsFromHomogeneous:
# to euclidean
points = kornia.geometry.conversions.convert_points_from_homogeneous(points_h)
- assert_close(points, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(points, expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
- points_h = torch.ones(1, 10, 3, device=device, dtype=dtype)
+ def test_gradcheck(self, device):
+ points_h = torch.ones(1, 10, 3, device=device, dtype=torch.float64)
# evaluate function gradient
- points_h = tensor_to_gradcheck_var(points_h) # to var
- assert gradcheck(
- kornia.geometry.conversions.convert_points_from_homogeneous,
- (points_h,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.conversions.convert_points_from_homogeneous, (points_h,))
@pytest.mark.skip("RuntimeError: Jacobian mismatch for output 0 with respect to input 0,")
- def test_gradcheck_zvec_zeros(self, device, dtype):
+ def test_gradcheck_zvec_zeros(self, device):
# generate input data
- points_h = torch.tensor([[1.0, 2.0, 0.0], [0.0, 1.0, 0.1], [2.0, 1.0, 0.1]], device=device, dtype=dtype)
+ points_h = torch.tensor([[1.0, 2.0, 0.0], [0.0, 1.0, 0.1], [2.0, 1.0, 0.1]], device=device, dtype=torch.float64)
# evaluate function gradient
- points_h = tensor_to_gradcheck_var(points_h) # to var
- assert gradcheck(
- kornia.geometry.conversions.convert_points_from_homogeneous,
- (points_h,),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.conversions.convert_points_from_homogeneous, (points_h,))
def test_dynamo(self, device, dtype, torch_optimizer):
points_h = torch.zeros(1, 2, 3, device=device, dtype=dtype)
@@ -812,10 +734,10 @@ class TestConvertPointsFromHomogeneous:
actual = op_optimized(points_h)
expected = op(points_h)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestNormalizePixelCoordinates:
+class TestNormalizePixelCoordinates(BaseTester):
def test_tensor_bhw2(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
height, width = 3, 4
@@ -827,7 +749,7 @@ class TestNormalizePixelCoordinates:
grid_norm = kornia.geometry.conversions.normalize_pixel_coordinates(grid, height, width, eps=eps)
- assert_close(grid_norm, expected, atol=atol, rtol=rtol)
+ self.assert_close(grid_norm, expected, atol=atol, rtol=rtol)
def test_list(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
@@ -842,7 +764,7 @@ class TestNormalizePixelCoordinates:
grid_norm = kornia.geometry.conversions.normalize_pixel_coordinates(grid, height, width, eps=eps)
- assert_close(grid_norm, expected, atol=atol, rtol=rtol)
+ self.assert_close(grid_norm, expected, atol=atol, rtol=rtol)
def test_dynamo(self, device, dtype, torch_optimizer):
if device == torch.device("cpu"):
@@ -857,10 +779,10 @@ class TestNormalizePixelCoordinates:
actual = op_optimized(grid, height, width)
expected = op(grid, height, width)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestDenormalizePixelCoordinates:
+class TestDenormalizePixelCoordinates(BaseTester):
def test_tensor_bhw2(self, device, dtype):
height, width = 3, 4
grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
@@ -871,7 +793,7 @@ class TestDenormalizePixelCoordinates:
grid_norm = kornia.geometry.conversions.denormalize_pixel_coordinates(grid, height, width)
- assert_close(grid_norm, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(grid_norm, expected, atol=1e-4, rtol=1e-4)
def test_list(self, device, dtype):
height, width = 3, 4
@@ -885,7 +807,7 @@ class TestDenormalizePixelCoordinates:
grid_norm = kornia.geometry.conversions.denormalize_pixel_coordinates(grid, height, width)
- assert_close(grid_norm, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(grid_norm, expected, atol=1e-4, rtol=1e-4)
def test_dynamo(self, device, dtype, torch_optimizer):
if device == torch.device("cpu"):
@@ -900,10 +822,10 @@ class TestDenormalizePixelCoordinates:
actual = op_optimized(grid, height, width)
expected = op(grid, height, width)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestProjectPoints:
+class TestProjectPoints(BaseTester):
def test_smoke(self, device, dtype):
point_3d = torch.zeros(1, 3, device=device, dtype=dtype)
camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
@@ -930,19 +852,15 @@ class TestProjectPoints:
)
point_2d = kornia.geometry.camera.project_points(point_3d, camera_matrix)
point_3d_hat = kornia.geometry.camera.unproject_points(point_2d, depth, camera_matrix)
- assert_close(point_3d, point_3d_hat, atol=1e-4, rtol=1e-4)
+ self.assert_close(point_3d, point_3d_hat, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# TODO: point [0, 0, 0] crashes
- points_3d = torch.ones(1, 3, device=device, dtype=dtype)
- camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
+ points_3d = torch.ones(1, 3, device=device, dtype=torch.float64)
+ camera_matrix = torch.eye(3, device=device, dtype=torch.float64).expand(1, -1, -1)
# evaluate function gradient
- points_3d = tensor_to_gradcheck_var(points_3d)
- camera_matrix = tensor_to_gradcheck_var(camera_matrix)
- assert gradcheck(
- kornia.geometry.camera.project_points, (points_3d, camera_matrix), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.camera.project_points, (points_3d, camera_matrix))
def test_dynamo(self, device, dtype, torch_optimizer):
points_3d = torch.zeros(1, 3, device=device, dtype=dtype)
@@ -953,10 +871,10 @@ class TestProjectPoints:
actual = op_optimized(points_3d, camera_matrix)
expected = op(points_3d, camera_matrix)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestDenormalizePointsWithIntrinsics:
+class TestDenormalizePointsWithIntrinsics(BaseTester):
def test_smoke(self, device, dtype):
points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
@@ -976,21 +894,14 @@ class TestDenormalizePointsWithIntrinsics:
)
op = kornia.geometry.conversions.denormalize_points_with_intrinsics
expected = torch.tensor([[192.0, 192.0]], device=device, dtype=dtype)
- assert_close(op(point_2d, camera_matrix), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(op(point_2d, camera_matrix), expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
- points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
- camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
+ def test_gradcheck(self, device):
+ points_2d = torch.zeros(1, 2, device=device, dtype=torch.float64)
+ camera_matrix = torch.eye(3, device=device, dtype=torch.float64).expand(1, -1, -1)
# evaluate function gradient
- points_2d = tensor_to_gradcheck_var(points_2d)
- camera_matrix = tensor_to_gradcheck_var(camera_matrix)
- assert gradcheck(
- kornia.geometry.conversions.denormalize_points_with_intrinsics,
- (points_2d, camera_matrix),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.conversions.denormalize_points_with_intrinsics, (points_2d, camera_matrix))
def test_dynamo(self, device, dtype, torch_optimizer):
points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
@@ -1001,10 +912,10 @@ class TestDenormalizePointsWithIntrinsics:
actual = op_optimized(points_2d, camera_matrix)
expected = op(points_2d, camera_matrix)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestNormalizePointsWithIntrinsics:
+class TestNormalizePointsWithIntrinsics(BaseTester):
def test_smoke(self, device, dtype):
points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
@@ -1026,7 +937,7 @@ class TestNormalizePointsWithIntrinsics:
back = kornia.geometry.conversions.denormalize_points_with_intrinsics
point_2d_norm = op(point_2d, camera_matrix)
point_2d_hat = back(point_2d_norm, camera_matrix)
- assert_close(point_2d, point_2d_hat, atol=1e-4, rtol=1e-4)
+ self.assert_close(point_2d, point_2d_hat, atol=1e-4, rtol=1e-4)
def test_toy(self, device, dtype):
point_2d = torch.tensor([[192.0, 192.0]], device=device, dtype=dtype)
@@ -1036,21 +947,14 @@ class TestNormalizePointsWithIntrinsics:
op = kornia.geometry.conversions.normalize_points_with_intrinsics
out = op(point_2d, camera_matrix)
expected = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)
- assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
- points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
- camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
+ def test_gradcheck(self, device):
+ points_2d = torch.zeros(1, 2, device=device, dtype=torch.float64)
+ camera_matrix = torch.eye(3, device=device, dtype=torch.float64).expand(1, -1, -1)
# evaluate function gradient
- points_2d = tensor_to_gradcheck_var(points_2d)
- camera_matrix = tensor_to_gradcheck_var(camera_matrix)
- assert gradcheck(
- kornia.geometry.conversions.normalize_points_with_intrinsics,
- (points_2d, camera_matrix),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.conversions.normalize_points_with_intrinsics, (points_2d, camera_matrix))
def test_dynamo(self, device, dtype, torch_optimizer):
points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
@@ -1061,10 +965,10 @@ class TestNormalizePointsWithIntrinsics:
actual = op_optimized(points_2d, camera_matrix)
expected = op(points_2d, camera_matrix)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestRt2Extrinsics:
+class TestRt2Extrinsics(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 3])
def test_everything(self, batch_size, device, dtype):
# generate input data
@@ -1078,22 +982,17 @@ class TestRt2Extrinsics:
assert R2.shape == (batch_size, 3, 3)
assert t2.shape == (batch_size, 3, 1)
- assert_close(R, R2, rtol=1e-4, atol=1e-5)
- assert_close(t, t2, rtol=1e-4, atol=1e-5)
+ self.assert_close(R, R2, rtol=1e-4, atol=1e-5)
+ self.assert_close(t, t2, rtol=1e-4, atol=1e-5)
@pytest.mark.parametrize("batch_size", [5])
- def test_gradcheck(self, batch_size, device, dtype):
- R = torch.rand(batch_size, 3, 3, dtype=dtype, device=device)
- t = torch.rand(batch_size, 3, 1, dtype=dtype, device=device)
- assert gradcheck(
- kornia.geometry.conversions.Rt_to_matrix4x4,
- (tensor_to_gradcheck_var(R), tensor_to_gradcheck_var(t)),
- raise_exception=True,
- fast_mode=True,
- )
+ def test_gradcheck(self, batch_size, device):
+ R = torch.rand(batch_size, 3, 3, dtype=torch.float64, device=device)
+ t = torch.rand(batch_size, 3, 1, dtype=torch.float64, device=device)
+ self.gradcheck(kornia.geometry.conversions.Rt_to_matrix4x4, (R, t))
-class TestCamtoworldGraphicsToVision:
+class TestCamtoworldGraphicsToVision(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 3])
def test_everything(self, batch_size, device, dtype):
# generate input data
@@ -1107,38 +1006,34 @@ class TestCamtoworldGraphicsToVision:
[[0, 0, -1, 2], [0, -1, 0, 3], [-1, 0, 0, 4], [0, 0, 0, 1]], device=device, dtype=dtype
)[None].repeat(batch_size, 1, 1)
- assert_close(K_graf, expected, rtol=1e-4, atol=1e-5)
+ self.assert_close(K_graf, expected, rtol=1e-4, atol=1e-5)
R_graf, t_graf = camtoworld_vision_to_graphics_Rt(R_vis, t_vis)
expected_R = torch.tensor([[0, 0, -1], [0, -1, 0], [-1, 0, 0]], device=device, dtype=dtype)[None].repeat(
batch_size, 1, 1
)
expected_t = torch.tensor([2, 3, 4], device=device, dtype=dtype).reshape(1, 3, 1).repeat(batch_size, 1, 1)
- assert_close(t_graf, expected_t, rtol=1e-4, atol=1e-5)
- assert_close(R_graf, expected_R, rtol=1e-4, atol=1e-5)
+ self.assert_close(t_graf, expected_t, rtol=1e-4, atol=1e-5)
+ self.assert_close(R_graf, expected_R, rtol=1e-4, atol=1e-5)
Kvis_back = camtoworld_graphics_to_vision_4x4(K_graf)
- assert_close(Kvis_back, K_vis, rtol=1e-4, atol=1e-5)
+ self.assert_close(Kvis_back, K_vis, rtol=1e-4, atol=1e-5)
R_vis_back, t_vis_back = camtoworld_graphics_to_vision_Rt(R_graf, t_graf)
- assert_close(R_vis_back, R_vis, rtol=1e-4, atol=1e-5)
- assert_close(t_vis_back, t_vis, rtol=1e-4, atol=1e-5)
+ self.assert_close(R_vis_back, R_vis, rtol=1e-4, atol=1e-5)
+ self.assert_close(t_vis_back, t_vis, rtol=1e-4, atol=1e-5)
@pytest.mark.parametrize("batch_size", [4])
- def test_gradcheck(self, batch_size, device, dtype):
- t_vis = torch.tensor([2, 3, 4], device=device, dtype=dtype).view(1, 3, 1).repeat(batch_size, 1, 1)
- angles = torch.tensor([0, kornia.pi / 2.0, 0.0], device=device, dtype=dtype)[None]
+ def test_gradcheck(self, batch_size, device):
+ t_vis = torch.tensor([2, 3, 4], device=device, dtype=torch.float64).view(1, 3, 1).repeat(batch_size, 1, 1)
+ angles = torch.tensor([0, kornia.pi / 2.0, 0.0], device=device, dtype=torch.float64)[None]
R_vis = kornia.geometry.axis_angle_to_rotation_matrix(angles).repeat(batch_size, 1, 1)
K_vis = Rt_to_matrix4x4(R_vis, t_vis)
- assert gradcheck(
- camtoworld_graphics_to_vision_4x4, (tensor_to_gradcheck_var(K_vis)), raise_exception=True, fast_mode=True
- )
- assert gradcheck(
- camtoworld_vision_to_graphics_4x4, (tensor_to_gradcheck_var(K_vis)), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(camtoworld_graphics_to_vision_4x4, (K_vis,))
+ self.gradcheck(camtoworld_vision_to_graphics_4x4, (K_vis,))
-class TestCamtoworldRtToPoseRt:
+class TestCamtoworldRtToPoseRt(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 3])
def test_everything(self, batch_size, device, dtype):
# generate input data
@@ -1152,33 +1047,23 @@ class TestCamtoworldRtToPoseRt:
batch_size, 1, 1
)
expected_tp = torch.tensor([4, -3, -2], device=device, dtype=dtype).view(1, 3, 1).repeat(batch_size, 1, 1)
- assert_close(Rp, expected_Rp, rtol=1e-4, atol=1e-5)
- assert_close(tp, expected_tp, rtol=1e-4, atol=1e-5)
+ self.assert_close(Rp, expected_Rp, rtol=1e-4, atol=1e-5)
+ self.assert_close(tp, expected_tp, rtol=1e-4, atol=1e-5)
Rback, tback = worldtocam_to_camtoworld_Rt(Rp, tp)
- assert_close(Rback, R, rtol=1e-4, atol=1e-5)
- assert_close(tback, t, rtol=1e-4, atol=1e-5)
+ self.assert_close(Rback, R, rtol=1e-4, atol=1e-5)
+ self.assert_close(tback, t, rtol=1e-4, atol=1e-5)
@pytest.mark.parametrize("batch_size", [4])
- def test_gradcheck(self, batch_size, device, dtype):
- t = torch.tensor([2, 3, 4], device=device, dtype=dtype).view(1, 3, 1).repeat(batch_size, 1, 1)
- angles = torch.tensor([0, kornia.pi / 2.0, 0.0], device=device, dtype=dtype)[None]
+ def test_gradcheck(self, batch_size, device):
+ t = torch.tensor([2, 3, 4], device=device, dtype=torch.float64).view(1, 3, 1).repeat(batch_size, 1, 1)
+ angles = torch.tensor([0, kornia.pi / 2.0, 0.0], device=device, dtype=torch.float64)[None]
R = kornia.geometry.axis_angle_to_rotation_matrix(angles).repeat(batch_size, 1, 1)
- assert gradcheck(
- camtoworld_to_worldtocam_Rt,
- (tensor_to_gradcheck_var(R), tensor_to_gradcheck_var(t)),
- raise_exception=True,
- fast_mode=True,
- )
- assert gradcheck(
- worldtocam_to_camtoworld_Rt,
- (tensor_to_gradcheck_var(R), tensor_to_gradcheck_var(t)),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(camtoworld_to_worldtocam_Rt, (R, t))
+ self.gradcheck(worldtocam_to_camtoworld_Rt, (R, t))
-class TestCARKitToColmap:
+class TestCARKitToColmap(BaseTester):
def test_everything(self, device, dtype):
# generate input data
t = torch.tensor([1, 0, 0], device=device, dtype=dtype).view(1, 3, 1)
@@ -1193,8 +1078,8 @@ class TestCARKitToColmap:
expected_angles = torch.tensor([[116.8870620728, 0.0, -71.7524719238]], device=device, dtype=dtype)
expected_t = torch.tensor([[[-0.5256], [0.3558], [0.7727]]], device=device, dtype=dtype)
- assert_close(angles_colmap, expected_angles, rtol=1e-4, atol=1e-5)
- assert_close(t_colmap, expected_t, rtol=1e-4, atol=1e-5)
+ self.assert_close(angles_colmap, expected_angles, rtol=1e-4, atol=1e-5)
+ self.assert_close(t_colmap, expected_t, rtol=1e-4, atol=1e-5)
class TestEulerFromQuaternion(BaseTester):
@@ -1222,17 +1107,14 @@ class TestEulerFromQuaternion(BaseTester):
def test_gradcheck(self, device):
q = Quaternion.random(batch_size=1).to(device, torch.float64)
- assert gradcheck(euler_from_quaternion, (q.w, q.x, q.y, q.z), raise_exception=True, fast_mode=True)
-
- def test_module(self, device, dtype):
- pass
+ self.gradcheck(euler_from_quaternion, (q.w, q.x, q.y, q.z))
def test_dynamo(self, device, dtype, torch_optimizer):
q = Quaternion.random(batch_size=1)
q = q.to(device, dtype)
op = euler_from_quaternion
op_optimized = torch_optimizer(op)
- assert_close(op(q.w, q.x, q.y, q.z), op_optimized(q.w, q.x, q.y, q.z))
+ self.assert_close(op(q.w, q.x, q.y, q.z), op_optimized(q.w, q.x, q.y, q.z))
def test_forth_and_back(self, device, dtype):
q = Quaternion.random(batch_size=2)
@@ -1240,10 +1122,10 @@ class TestEulerFromQuaternion(BaseTester):
roll, pitch, yaw = euler_from_quaternion(q.w, q.x, q.y, q.z)
qw, qx, qy, qz = quaternion_from_euler(roll, pitch, yaw)
# TODO: check hwo to prevent getting inverted angles sometimes
- assert_close(q.w.abs(), qw.abs())
- assert_close(q.x.abs(), qx.abs())
- assert_close(q.y.abs(), qy.abs())
- assert_close(q.z.abs(), qz.abs())
+ self.assert_close(q.w.abs(), qw.abs())
+ self.assert_close(q.x.abs(), qx.abs())
+ self.assert_close(q.y.abs(), qy.abs())
+ self.assert_close(q.z.abs(), qz.abs())
class TestQuaternionFromEuler(BaseTester):
@@ -1270,10 +1152,7 @@ class TestQuaternionFromEuler(BaseTester):
def test_gradcheck(self, device):
roll, pitch, yaw = torch.rand(3, 2, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(quaternion_from_euler, (roll, pitch, yaw), raise_exception=True, fast_mode=True)
-
- def test_module(self, device, dtype):
- pass
+ self.gradcheck(quaternion_from_euler, (roll, pitch, yaw))
def test_dynamo(self, device, dtype, torch_optimizer):
roll, pitch, yaw = torch.rand(3, 2, device=device, dtype=dtype)
@@ -1284,17 +1163,17 @@ class TestQuaternionFromEuler(BaseTester):
actual = op_optimized(roll, pitch, yaw)
expected = op(roll, pitch, yaw)
- assert_close(actual[0], expected[0])
- assert_close(actual[1], expected[1])
- assert_close(actual[2], expected[2])
+ self.assert_close(actual[0], expected[0])
+ self.assert_close(actual[1], expected[1])
+ self.assert_close(actual[2], expected[2])
def test_forth_and_back(self, device, dtype):
roll, pitch, yaw = torch.rand(3, 2, device=device, dtype=dtype)
qw, qx, qy, qz = quaternion_from_euler(roll, pitch, yaw)
roll_new, pitch_new, yaw_new = euler_from_quaternion(qw, qx, qy, qz)
- assert_close(roll, roll_new)
- assert_close(pitch, pitch_new)
- assert_close(yaw, yaw_new)
+ self.assert_close(roll, roll_new)
+ self.assert_close(pitch, pitch_new)
+ self.assert_close(yaw, yaw_new)
def test_values(self, device, dtype):
# num_samples = 5
diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.py
index 967b05c6a..21912f77e 100644
--- a/tests/geometry/test_depth.py
+++ b/tests/geometry/test_depth.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestDepthTo3d:
+
+class TestDepthTo3d(BaseTester):
def test_smoke(self, device, dtype):
depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -39,7 +38,7 @@ class TestDepthTo3d:
# TODO: implement me with batch
points3d_v2 = kornia.geometry.depth.depth_to_3d_v2(depth[0, 0], camera_matrix[0])
- assert_close(points3d[0].permute(1, 2, 0), points3d_v2)
+ self.assert_close(points3d[0].permute(1, 2, 0), points3d_v2)
def test_unproject_meshgrid(self, device, dtype):
# TODO: implement me with batch
@@ -47,7 +46,7 @@ class TestDepthTo3d:
grid = kornia.geometry.unproject_meshgrid(3, 4, camera_matrix, device=device, dtype=dtype)
assert grid.shape == (3, 4, 3)
# test for now that the grid is correct and have homogeneous coords
- assert_close(grid[..., 2], torch.ones_like(grid[..., 2]))
+ self.assert_close(grid[..., 2], torch.ones_like(grid[..., 2]))
def test_unproject_denormalized(self, device, dtype):
# this is for default normalize_points=False
@@ -70,7 +69,7 @@ class TestDepthTo3d:
)
points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix) # default is normalize_points=False
- assert_close(points3d, points3d_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(points3d, points3d_expected, atol=1e-4, rtol=1e-4)
def test_unproject_normalized(self, device, dtype):
# this is for normalize_points=True
@@ -108,7 +107,7 @@ class TestDepthTo3d:
)
points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix, normalize_points=True)
- assert_close(points3d, points3d_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(points3d, points3d_expected, atol=1e-4, rtol=1e-4)
def test_unproject_and_project(self, device, dtype):
depth = 2 * torch.tensor(
@@ -120,23 +119,19 @@ class TestDepthTo3d:
points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix)
points2d = kornia.geometry.camera.project_points(points3d.permute(0, 2, 3, 1), camera_matrix[:, None, None])
points2d_expected = kornia.utils.create_meshgrid(4, 3, False, device=device).to(dtype=dtype)
- assert_close(points2d, points2d_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(points2d, points2d_expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# generate input data
- depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
- depth = utils.tensor_to_gradcheck_var(depth) # to var
+ depth = torch.rand(1, 1, 3, 4, device=device, dtype=torch.float64)
- camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
- camera_matrix = utils.tensor_to_gradcheck_var(camera_matrix) # to var
+ camera_matrix = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
# evaluate function gradient
- assert gradcheck(
- kornia.geometry.depth.depth_to_3d, (depth, camera_matrix), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.depth.depth_to_3d, (depth, camera_matrix))
-class TestDepthToNormals:
+class TestDepthToNormals(BaseTester):
def test_smoke(self, device, dtype):
depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -181,7 +176,7 @@ class TestDepthToNormals:
)
normals = kornia.geometry.depth.depth_to_normals(depth, camera_matrix) # default is normalize_points=False
- assert_close(normals, normals_expected, rtol=1e-3, atol=1e-3)
+ self.assert_close(normals, normals_expected, rtol=1e-3, atol=1e-3)
def test_simple_normalized(self, device, dtype):
# this is for default normalize_points=False
@@ -219,23 +214,19 @@ class TestDepthToNormals:
)
normals = kornia.geometry.depth.depth_to_normals(depth, camera_matrix, normalize_points=True)
- assert_close(normals, normals_expected, rtol=1e-3, atol=1e-3)
+ self.assert_close(normals, normals_expected, rtol=1e-3, atol=1e-3)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# generate input data
- depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
- depth = utils.tensor_to_gradcheck_var(depth) # to var
+ depth = torch.rand(1, 1, 3, 4, device=device, dtype=torch.float64)
- camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
- camera_matrix = utils.tensor_to_gradcheck_var(camera_matrix) # to var
+ camera_matrix = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
# evaluate function gradient
- assert gradcheck(
- kornia.geometry.depth.depth_to_normals, (depth, camera_matrix), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.depth.depth_to_normals, (depth, camera_matrix))
-class TestWarpFrameDepth:
+class TestWarpFrameDepth(BaseTester):
def test_smoke(self, device, dtype):
image_src = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
depth_dst = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
@@ -284,7 +275,7 @@ class TestWarpFrameDepth:
image_dst = kornia.geometry.depth.warp_frame_depth(
image_src, depth_dst, src_trans_dst, camera_matrix
) # default is normalize_points=False
- assert_close(image_dst, image_dst_expected, rtol=1e-3, atol=1e-3)
+ self.assert_close(image_dst, image_dst_expected, rtol=1e-3, atol=1e-3)
def test_translation_normalized(self, device, dtype):
# this is for normalize_points=True
@@ -325,31 +316,23 @@ class TestWarpFrameDepth:
image_dst = kornia.geometry.depth.warp_frame_depth(
image_src, depth_dst, src_trans_dst, camera_matrix, normalize_points=True
)
- assert_close(image_dst, image_dst_expected, rtol=1e-3, atol=1e-3)
+ self.assert_close(image_dst, image_dst_expected, rtol=1e-3, atol=1e-3)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
image_src = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
- image_src = utils.tensor_to_gradcheck_var(image_src) # to var
depth_dst = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
- depth_dst = utils.tensor_to_gradcheck_var(depth_dst) # to var
src_trans_dst = torch.rand(1, 4, 4, device=device, dtype=dtype)
- src_trans_dst = utils.tensor_to_gradcheck_var(src_trans_dst) # to var
camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
- camera_matrix = utils.tensor_to_gradcheck_var(camera_matrix) # to var
# evaluate function gradient
- assert gradcheck(
- kornia.geometry.depth.warp_frame_depth,
- (image_src, depth_dst, src_trans_dst, camera_matrix),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.depth.warp_frame_depth, (image_src, depth_dst, src_trans_dst, camera_matrix))
-class TestDepthFromDisparity:
+class TestDepthFromDisparity(BaseTester):
def test_smoke(self, device, dtype):
disparity = 2 * torch.tensor(
[[[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]], device=device, dtype=dtype
@@ -374,7 +357,7 @@ class TestDepthFromDisparity:
)
depth = kornia.geometry.depth.depth_from_disparity(disparity, baseline, focal)
- assert_close(depth, depth_expected, rtol=1e-3, atol=1e-3)
+ self.assert_close(depth, depth_expected, rtol=1e-3, atol=1e-3)
@pytest.mark.parametrize("batch_size", [2, 4, 5])
def test_cardinality(self, batch_size, device, dtype):
@@ -396,19 +379,11 @@ class TestDepthFromDisparity:
def test_gradcheck(self, device):
# generate input data
- disparity = torch.rand(1, 1, 3, 4, device=device)
- disparity = utils.tensor_to_gradcheck_var(disparity) # to var
+ disparity = torch.rand(1, 1, 3, 4, device=device, dtype=torch.float64)
- baseline = torch.rand(1, device=device)
- baseline = utils.tensor_to_gradcheck_var(baseline) # to var
+ baseline = torch.rand(1, device=device, dtype=torch.float64)
- focal = torch.rand(1, device=device)
- focal = utils.tensor_to_gradcheck_var(focal) # to var
+ focal = torch.rand(1, device=device, dtype=torch.float64)
# evaluate function gradient
- assert gradcheck(
- kornia.geometry.depth.depth_from_disparity,
- (disparity, baseline, focal),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.depth.depth_from_disparity, (disparity, baseline, focal))
diff --git a/tests/geometry/test_depth_warper.py b/tests/geometry/test_depth_warper.py
index 71018a19e..f280d818f 100644
--- a/tests/geometry/test_depth_warper.py
+++ b/tests/geometry/test_depth_warper.py
@@ -1,14 +1,13 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
from kornia.geometry.conversions import normalize_pixel_coordinates
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestDepthWarper:
+
+class TestDepthWarper(BaseTester):
eps = 1e-6
def _create_pinhole_pair(self, batch_size, device, dtype):
@@ -47,7 +46,7 @@ class TestDepthWarper:
dst_proj_src_expected[..., 0, -2] += pinhole_src.cx
dst_proj_src_expected[..., 1, -2] += pinhole_src.cy
dst_proj_src_expected[..., 0, -1] += 1.0 # offset to x-axis
- assert_close(dst_proj_src, dst_proj_src_expected)
+ self.assert_close(dst_proj_src, dst_proj_src_expected)
@pytest.mark.parametrize("batch_size", (1, 2))
def test_warp_grid_offset_x1_depth1(self, batch_size, device, dtype):
@@ -70,9 +69,9 @@ class TestDepthWarper:
grid_norm = normalize_pixel_coordinates(grid, height, width)
# check offset in x-axis
- assert_close(grid_warped[..., -2, 0], grid_norm[..., -1, 0].repeat(batch_size, 1), atol=1e-4, rtol=1e-4)
+ self.assert_close(grid_warped[..., -2, 0], grid_norm[..., -1, 0].repeat(batch_size, 1), atol=1e-4, rtol=1e-4)
# check that y-axis remain the same
- assert_close(grid_warped[..., -1, 1], grid_norm[..., -1, 1].repeat(batch_size, 1), rtol=1e-4, atol=1e-4)
+ self.assert_close(grid_warped[..., -1, 1], grid_norm[..., -1, 1].repeat(batch_size, 1), rtol=1e-4, atol=1e-4)
@pytest.mark.parametrize("batch_size", (1, 2))
def test_warp_grid_offset_x1y1_depth1(self, batch_size, device, dtype):
@@ -96,9 +95,11 @@ class TestDepthWarper:
grid_norm = normalize_pixel_coordinates(grid, height, width)
# check offset in x-axis
- assert_close(grid_warped[..., -2, 0], grid_norm[..., -1, 0].repeat(batch_size, 1), atol=1e-4, rtol=1e-4)
+ self.assert_close(grid_warped[..., -2, 0], grid_norm[..., -1, 0].repeat(batch_size, 1), atol=1e-4, rtol=1e-4)
# check that y-axis remain the same
- assert_close(grid_warped[..., -2, :, 1], grid_norm[..., -1, :, 1].repeat(batch_size, 1), rtol=1e-4, atol=1e-4)
+ self.assert_close(
+ grid_warped[..., -2, :, 1], grid_norm[..., -1, :, 1].repeat(batch_size, 1), rtol=1e-4, atol=1e-4
+ )
@pytest.mark.parametrize("batch_size", (1, 2))
def test_warp_tensor_offset_x1y1(self, batch_size, device, dtype):
@@ -125,7 +126,7 @@ class TestDepthWarper:
patch_src = warper(depth_src, patch_dst)
# compare patches
- assert_close(patch_dst[..., 1:, 1:], patch_src[..., :2, :4], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_dst[..., 1:, 1:], patch_src[..., :2, :4], atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", (1, 2))
def test_compute_projection(self, batch_size, device, dtype):
@@ -151,29 +152,23 @@ class TestDepthWarper:
# test compute_subpixel_step
subpixel_step = warper.compute_subpixel_step()
- assert_close(subpixel_step.item(), 0.1715, rtol=1e-3, atol=1e-3)
+ self.assert_close(subpixel_step.item(), 0.1715, rtol=1e-3, atol=1e-3)
@pytest.mark.parametrize("batch_size", (1, 2))
- def test_gradcheck(self, batch_size, device, dtype):
+ def test_gradcheck(self, batch_size, device):
+ dtype = torch.float64
# prepare data
channels, height, width = 3, 3, 5 # output shape
pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size, device, dtype)
# initialize depth to one
depth_src = torch.ones(batch_size, 1, height, width, device=device, dtype=dtype)
- depth_src = utils.tensor_to_gradcheck_var(depth_src) # to var
# create patch to warp
img_dst = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
- img_dst = utils.tensor_to_gradcheck_var(img_dst) # to var
# evaluate function gradient
- assert gradcheck(
- kornia.geometry.depth.depth_warp,
- (pinhole_dst, pinhole_src, depth_src, img_dst, height, width),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.depth.depth_warp, (pinhole_dst, pinhole_src, depth_src, img_dst, height, width))
# TODO(edgar): we should include a test showing some kind of occlusion
# def test_warp_with_occlusion(self):
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index d69abbc5d..48fdbeade 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -2,10 +2,8 @@ import sys
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils
from kornia.geometry.homography import (
find_homography_dlt,
find_homography_dlt_iterated,
@@ -16,11 +14,13 @@ from kornia.geometry.homography import (
sample_is_valid_for_homography,
symmetric_transfer_error,
)
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version_le
+from testing.base import BaseTester
+from testing.geometry.create import create_random_homography
-class TestSampleValidation:
+
+class TestSampleValidation(BaseTester):
def test_good(self, device, dtype):
pts1 = torch.tensor([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]], device=device, dtype=dtype)[None]
mask = sample_is_valid_for_homography(pts1, pts1)
@@ -43,18 +43,18 @@ class TestSampleValidation:
assert mask.shape == torch.Size([batch_size])
-class TestOneWayError:
+class TestOneWayError(BaseTester):
def test_smoke(self, device, dtype):
pts1 = torch.rand(1, 6, 2, device=device, dtype=dtype)
pts2 = torch.rand(1, 6, 2, device=device, dtype=dtype)
- H = utils.create_random_homography(1, 3).type_as(pts1).to(device)
+ H = create_random_homography(pts1, 3)
assert oneway_transfer_error(pts1, pts2, H).shape == (1, 6)
def test_batch(self, device, dtype):
batch_size = 5
pts1 = torch.rand(batch_size, 3, 2, device=device, dtype=dtype)
pts2 = torch.rand(batch_size, 3, 2, device=device, dtype=dtype)
- H = utils.create_random_homography(1, 3).type_as(pts1).to(device)
+ H = create_random_homography(pts1, 3)
assert oneway_transfer_error(pts1, pts2, H).shape == (batch_size, 3)
def test_gradcheck(self, device):
@@ -62,29 +62,29 @@ class TestOneWayError:
batch_size, num_points, num_dims = 2, 3, 2
points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
- H = utils.create_random_homography(batch_size, 3).type_as(points1).to(device)
- assert gradcheck(oneway_transfer_error, (points1, points2, H), raise_exception=True, fast_mode=True)
+ H = create_random_homography(points1, 3)
+ self.gradcheck(oneway_transfer_error, (points1, points2, H))
def test_shift(self, device, dtype):
pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
pts2 = torch.tensor([[1.0, 0.0], [2.0, 0.0], [2.0, 2.0]], device=device, dtype=dtype)[None]
H = torch.tensor([[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=dtype, device=device)[None]
expected = torch.tensor([0.0, 1.0, 5.0], device=device, dtype=dtype)[None]
- assert_close(oneway_transfer_error(pts1, pts2, H), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(oneway_transfer_error(pts1, pts2, H), expected, atol=1e-4, rtol=1e-4)
-class TestLineSegmentOneWayError:
+class TestLineSegmentOneWayError(BaseTester):
def test_smoke(self, device, dtype):
ls1 = torch.rand(1, 6, 2, 2, device=device, dtype=dtype)
ls2 = torch.rand(1, 6, 2, 2, device=device, dtype=dtype)
- H = utils.create_random_homography(1, 3).type_as(ls1).to(device)
+ H = create_random_homography(ls1, 3)
assert line_segment_transfer_error_one_way(ls1, ls2, H).shape == (1, 6)
def test_batch(self, device, dtype):
batch_size = 5
ls1 = torch.rand(batch_size, 3, 2, 2, device=device, dtype=dtype)
ls2 = torch.rand(batch_size, 3, 2, 2, device=device, dtype=dtype)
- H = utils.create_random_homography(1, 3).type_as(ls1).to(device)
+ H = create_random_homography(ls1, 3)
assert line_segment_transfer_error_one_way(ls1, ls2, H).shape == (batch_size, 3)
def test_gradcheck(self, device):
@@ -92,8 +92,8 @@ class TestLineSegmentOneWayError:
batch_size, num_points, num_dims = 2, 3, 2
ls1 = torch.rand(batch_size, num_points, num_dims, 2, device=device, dtype=torch.float64, requires_grad=True)
ls2 = torch.rand(batch_size, num_points, num_dims, 2, device=device, dtype=torch.float64)
- H = utils.create_random_homography(batch_size, 3).type_as(ls1).to(device)
- assert gradcheck(line_segment_transfer_error_one_way, (ls1, ls2, H), raise_exception=True, fast_mode=True)
+ H = create_random_homography(ls1, 3)
+ self.gradcheck(line_segment_transfer_error_one_way, (ls1, ls2, H))
def test_shift(self, device, dtype):
pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
@@ -105,21 +105,21 @@ class TestLineSegmentOneWayError:
ls2 = torch.stack([pts2, pts2_end], dim=2)
H = torch.tensor([[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=dtype, device=device)[None]
expected = torch.tensor([0.0, 1.0, 1.0], device=device, dtype=dtype)[None]
- assert_close(line_segment_transfer_error_one_way(ls1, ls2, H), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(line_segment_transfer_error_one_way(ls1, ls2, H), expected, atol=1e-4, rtol=1e-4)
-class TestSymmetricTransferError:
+class TestSymmetricTransferError(BaseTester):
def test_smoke(self, device, dtype):
pts1 = torch.rand(1, 6, 2, device=device, dtype=dtype)
pts2 = torch.rand(1, 6, 2, device=device, dtype=dtype)
- H = utils.create_random_homography(1, 3).type_as(pts1).to(device)
+ H = create_random_homography(pts1, 3)
assert symmetric_transfer_error(pts1, pts2, H).shape == (1, 6)
def test_batch(self, device, dtype):
batch_size = 5
pts1 = torch.rand(batch_size, 3, 2, device=device, dtype=dtype)
pts2 = torch.rand(batch_size, 3, 2, device=device, dtype=dtype)
- H = utils.create_random_homography(1, 3).type_as(pts1).to(device)
+ H = create_random_homography(pts1, 3)
assert symmetric_transfer_error(pts1, pts2, H).shape == (batch_size, 3)
def test_gradcheck(self, device):
@@ -127,18 +127,18 @@ class TestSymmetricTransferError:
batch_size, num_points, num_dims = 2, 3, 2
points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
- H = utils.create_random_homography(batch_size, 3).type_as(points1).to(device)
- assert gradcheck(symmetric_transfer_error, (points1, points2, H), raise_exception=True, fast_mode=True)
+ H = create_random_homography(points1, 3)
+ self.gradcheck(symmetric_transfer_error, (points1, points2, H))
def test_shift(self, device, dtype):
pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
pts2 = torch.tensor([[1.0, 0.0], [2.0, 0.0], [2.0, 2.0]], device=device, dtype=dtype)[None]
H = torch.tensor([[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=dtype, device=device)[None]
expected = torch.tensor([0.0, 2.0, 10.0], device=device, dtype=dtype)[None]
- assert_close(symmetric_transfer_error(pts1, pts2, H), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(symmetric_transfer_error(pts1, pts2, H), expected, atol=1e-4, rtol=1e-4)
-class TestFindHomographyDLT:
+class TestFindHomographyDLT(BaseTester):
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -189,7 +189,7 @@ class TestFindHomographyDLT:
H_withweights = find_homography_dlt(points1, points2, weights)
assert H_noweights.shape == (B, 3, 3)
assert H_withweights.shape == (B, 3, 3)
- assert_close(H_noweights, H_withweights, rtol=1e-3, atol=1e-4)
+ self.assert_close(H_noweights, H_withweights, rtol=1e-3, atol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_clean_points_svd(self, batch_size, device, dtype):
@@ -205,7 +205,7 @@ class TestFindHomographyDLT:
# compute transform from source to target
dst_homo_src = find_homography_dlt(points_src, points_dst, weights, "svd")
- assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
+ self.assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_clean_points_lu(self, batch_size, device, dtype):
@@ -221,44 +221,26 @@ class TestFindHomographyDLT:
# compute transform from source to target
dst_homo_src = find_homography_dlt(points_src, points_dst, weights, "lu")
- assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
+ self.assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
@pytest.mark.grad()
def test_gradcheck(self, device):
- points_src = utils.tensor_to_gradcheck_var(
- torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)
- )
- points_dst = utils.tensor_to_gradcheck_var(torch.rand_like(points_src))
- weights = utils.tensor_to_gradcheck_var(torch.ones_like(points_src)[..., 0])
-
- assert gradcheck(
- find_homography_dlt,
- (points_src, points_dst, weights),
- rtol=1e-6,
- atol=1e-6,
- raise_exception=True,
- fast_mode=True,
- )
+ points_src = torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)
+ points_dst = torch.rand_like(points_src)
+ weights = torch.ones_like(points_src)[..., 0]
+
+ self.gradcheck(find_homography_dlt, (points_src, points_dst, weights), rtol=1e-6, atol=1e-6)
@pytest.mark.grad()
def test_gradcheck_lu(self, device):
- points_src = utils.tensor_to_gradcheck_var(
- torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)
- )
- points_dst = utils.tensor_to_gradcheck_var(torch.rand_like(points_src))
- weights = utils.tensor_to_gradcheck_var(torch.ones_like(points_src)[..., 0])
-
- assert gradcheck(
- find_homography_dlt,
- (points_src, points_dst, weights, "lu"),
- rtol=1e-6,
- atol=1e-6,
- raise_exception=True,
- fast_mode=True,
- )
+ points_src = torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)
+
+ points_dst = torch.rand_like(points_src)
+ weights = torch.ones_like(points_src)[..., 0]
+ self.gradcheck(find_homography_dlt, (points_src, points_dst, weights, "lu"), rtol=1e-6, atol=1e-6)
-class TestFindHomographyFromLinesDLT:
+class TestFindHomographyFromLinesDLT(BaseTester):
def test_smoke(self, device, dtype):
points1st = torch.rand(1, 4, 2, device=device, dtype=dtype)
points1end = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -331,7 +313,7 @@ class TestFindHomographyFromLinesDLT:
H_withweights = find_homography_lines_dlt(ls1, ls2, weights)
assert H_noweights.shape == (B, 3, 3)
assert H_withweights.shape == (B, 3, 3)
- assert_close(H_noweights, H_withweights, rtol=1e-3, atol=1e-4)
+ self.assert_close(H_noweights, H_withweights, rtol=1e-3, atol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_clean_points(self, batch_size, device, dtype):
@@ -350,7 +332,9 @@ class TestFindHomographyFromLinesDLT:
# compute transform from source to target
dst_homo_src = find_homography_lines_dlt(ls1, ls2, None)
- assert_close(kornia.geometry.transform_points(dst_homo_src, points_src_st), points_dst_st, rtol=1e-3, atol=1e-4)
+ self.assert_close(
+ kornia.geometry.transform_points(dst_homo_src, points_src_st), points_dst_st, rtol=1e-3, atol=1e-4
+ )
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_clean_points_iter(self, batch_size, device, dtype):
@@ -369,7 +353,9 @@ class TestFindHomographyFromLinesDLT:
# compute transform from source to target
dst_homo_src = find_homography_lines_dlt_iterated(ls1, ls2, None, 5)
- assert_close(kornia.geometry.transform_points(dst_homo_src, points_src_st), points_dst_st, rtol=1e-3, atol=1e-4)
+ self.assert_close(
+ kornia.geometry.transform_points(dst_homo_src, points_src_st), points_dst_st, rtol=1e-3, atol=1e-4
+ )
@pytest.mark.grad()
def test_gradcheck(self, device):
@@ -378,16 +364,14 @@ class TestFindHomographyFromLinesDLT:
points_dst_st = torch.rand_like(points_src_st)
points_dst_end = torch.rand_like(points_src_end)
- weights = utils.tensor_to_gradcheck_var(torch.ones_like(points_src_st)[..., 0])
- ls1 = utils.tensor_to_gradcheck_var(torch.stack([points_src_st, points_src_end], axis=2))
- ls2 = utils.tensor_to_gradcheck_var(torch.stack([points_dst_st, points_dst_end], axis=2))
+ weights = torch.ones_like(points_src_st)[..., 0]
+ ls1 = torch.stack([points_src_st, points_src_end], axis=2)
+ ls2 = torch.stack([points_dst_st, points_dst_end], axis=2)
- assert gradcheck(
- find_homography_lines_dlt, (ls1, ls2, weights), rtol=1e-6, atol=1e-6, raise_exception=True, fast_mode=True
- )
+ self.gradcheck(find_homography_lines_dlt, (ls1, ls2, weights), rtol=1e-6, atol=1e-6)
-class TestFindHomographyDLTIter:
+class TestFindHomographyDLTIter(BaseTester):
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -421,24 +405,15 @@ class TestFindHomographyDLTIter:
# compute transform from source to target
dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 10)
- assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
+ self.assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
@pytest.mark.grad()
def test_gradcheck(self, device):
torch.manual_seed(0)
- points_src = utils.tensor_to_gradcheck_var(
- torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)
- )
- points_dst = utils.tensor_to_gradcheck_var(torch.rand_like(points_src))
- weights = utils.tensor_to_gradcheck_var(torch.ones_like(points_src)[..., 0])
- assert gradcheck(
- find_homography_dlt_iterated,
- (points_src, points_dst, weights),
- rtol=1e-6,
- atol=1e-6,
- raise_exception=True,
- fast_mode=True,
- )
+ points_src = torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)
+ points_dst = torch.rand_like(points_src)
+ weights = torch.ones_like(points_src)[..., 0]
+ self.gradcheck(find_homography_dlt_iterated, (points_src, points_dst, weights), rtol=1e-6, atol=1e-6)
@pytest.mark.grad()
@pytest.mark.parametrize("batch_size", [1, 2])
@@ -460,6 +435,6 @@ class TestFindHomographyDLTIter:
# compute transform from source to target
dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 0.5, 10)
- assert_close(
+ self.assert_close(
kornia.geometry.transform_points(dst_homo_src, points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3
)
diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.py
index 7c684bb3d..6d540b371 100644
--- a/tests/geometry/test_linalg.py
+++ b/tests/geometry/test_linalg.py
@@ -1,87 +1,15 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
import kornia.geometry.linalg as kgl
-import kornia.testing as utils # test utils
-from kornia.testing import BaseTester, assert_close
-
-
-def identity_matrix(batch_size, device, dtype):
- r"""Create a batched homogeneous identity matrix."""
- return torch.eye(4, device=device, dtype=dtype).repeat(batch_size, 1, 1) # Nx4x4
-
-
-def euler_angles_to_rotation_matrix(x, y, z):
- r"""Create a rotation matrix from x, y, z angles."""
- assert x.dim() == 1, x.shape
- assert x.shape == y.shape == z.shape
- ones, zeros = torch.ones_like(x), torch.zeros_like(x)
- # the rotation matrix for the x-axis
- rx_tmp = [
- ones,
- zeros,
- zeros,
- zeros,
- zeros,
- torch.cos(x),
- -torch.sin(x),
- zeros,
- zeros,
- torch.sin(x),
- torch.cos(x),
- zeros,
- zeros,
- zeros,
- zeros,
- ones,
- ]
- rx = torch.stack(rx_tmp, dim=-1).view(-1, 4, 4)
- # the rotation matrix for the y-axis
- ry_tmp = [
- torch.cos(y),
- zeros,
- torch.sin(y),
- zeros,
- zeros,
- ones,
- zeros,
- zeros,
- -torch.sin(y),
- zeros,
- torch.cos(y),
- zeros,
- zeros,
- zeros,
- zeros,
- ones,
- ]
- ry = torch.stack(ry_tmp, dim=-1).view(-1, 4, 4)
- # the rotation matrix for the z-axis
- rz_tmp = [
- torch.cos(z),
- -torch.sin(z),
- zeros,
- zeros,
- torch.sin(z),
- torch.cos(z),
- zeros,
- zeros,
- zeros,
- zeros,
- ones,
- zeros,
- zeros,
- zeros,
- zeros,
- ones,
- ]
- rz = torch.stack(rz_tmp, dim=-1).view(-1, 4, 4)
- return torch.matmul(rz, torch.matmul(ry, rx)) # Bx4x4
-
-
-class TestTransformPoints:
+
+from testing.base import BaseTester
+from testing.geometry.create import create_random_homography
+from testing.geometry.linalg import euler_angles_to_rotation_matrix, identity_matrix
+
+
+class TestTransformPoints(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 5])
@pytest.mark.parametrize("num_points", [2, 3, 5])
@pytest.mark.parametrize("num_dims", [2, 3])
@@ -90,7 +18,7 @@ class TestTransformPoints:
eye_size = num_dims + 1
points_src = torch.rand(batch_size, num_points, num_dims, device=device, dtype=dtype)
- dst_homo_src = utils.create_random_homography(batch_size, eye_size).to(device=device, dtype=dtype)
+ dst_homo_src = create_random_homography(points_src, eye_size)
dst_homo_src = dst_homo_src.to(device)
# transform the points from dst to ref
@@ -101,20 +29,16 @@ class TestTransformPoints:
points_dst_to_src = kgl.transform_points(src_homo_dst, points_dst)
# projected should be equal as initial
- assert_close(points_src, points_dst_to_src, atol=1e-4, rtol=1e-4)
+ self.assert_close(points_src, points_dst_to_src, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# generate input data
batch_size, num_points, num_dims = 2, 3, 2
eye_size = num_dims + 1
- points_src = torch.rand(batch_size, num_points, num_dims, device=device, dtype=dtype)
- dst_homo_src = utils.create_random_homography(batch_size, eye_size).to(device=device, dtype=dtype)
+ points_src = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
+ dst_homo_src = create_random_homography(points_src, eye_size)
# evaluate function gradient
- points_src = utils.tensor_to_gradcheck_var(points_src) # to var
- dst_homo_src = utils.tensor_to_gradcheck_var(dst_homo_src) # to var
- assert gradcheck(
- kornia.geometry.transform_points, (dst_homo_src, points_src), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.transform_points, (dst_homo_src, points_src))
def test_dynamo(self, device, dtype, torch_optimizer):
points = torch.ones(1, 2, 2, device=device, dtype=dtype)
@@ -123,10 +47,10 @@ class TestTransformPoints:
op_script = torch_optimizer(op)
actual = op_script(transform, points)
expected = op(transform, points)
- assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
-class TestComposeTransforms:
+class TestComposeTransforms(BaseTester):
def test_smoke(self, device, dtype):
batch_size = 2
trans_01 = identity_matrix(batch_size=batch_size, device=device, dtype=dtype)
@@ -170,7 +94,7 @@ class TestComposeTransforms:
trans_12[..., :3, -1] += offset # add offset to translation vector
trans_02 = kgl.compose_transformations(trans_01, trans_12)
- assert_close(trans_02, trans_12, atol=1e-4, rtol=1e-4)
+ self.assert_close(trans_02, trans_12, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_translation_Bx4x4(self, batch_size, device, dtype):
@@ -180,19 +104,17 @@ class TestComposeTransforms:
trans_12[..., :3, -1] += offset # add offset to translation vector
trans_02 = kgl.compose_transformations(trans_01, trans_12)
- assert_close(trans_02, trans_12, atol=1e-4, rtol=1e-4)
+ self.assert_close(trans_02, trans_12, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
- def test_gradcheck(self, batch_size, device, dtype):
- trans_01 = identity_matrix(batch_size, device=device, dtype=dtype)
- trans_12 = identity_matrix(batch_size, device=device, dtype=dtype)
+ def test_gradcheck(self, batch_size, device):
+ trans_01 = identity_matrix(batch_size, device=device, dtype=torch.float64)
+ trans_12 = identity_matrix(batch_size, device=device, dtype=torch.float64)
- trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to var
- trans_12 = utils.tensor_to_gradcheck_var(trans_12) # to var
- assert gradcheck(kgl.compose_transformations, (trans_01, trans_12), raise_exception=True, fast_mode=True)
+ self.gradcheck(kgl.compose_transformations, (trans_01, trans_12))
-class TestInverseTransformation:
+class TestInverseTransformation(BaseTester):
def test_smoke(self, device, dtype):
batch_size = 2
trans_01 = identity_matrix(batch_size=batch_size, device=device, dtype=dtype)
@@ -227,7 +149,7 @@ class TestInverseTransformation:
trans_10 = kgl.inverse_transformation(trans_01)
trans_01_hat = kgl.inverse_transformation(trans_10)
- assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)
+ self.assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_translation_Bx4x4(self, batch_size, device, dtype):
@@ -237,7 +159,7 @@ class TestInverseTransformation:
trans_10 = kgl.inverse_transformation(trans_01)
trans_01_hat = kgl.inverse_transformation(trans_10)
- assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)
+ self.assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_rotation_translation_Bx4x4(self, batch_size, device, dtype):
@@ -252,16 +174,15 @@ class TestInverseTransformation:
trans_10 = kgl.inverse_transformation(trans_01)
trans_01_hat = kgl.inverse_transformation(trans_10)
- assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)
+ self.assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
- def test_gradcheck(self, batch_size, device, dtype):
- trans_01 = identity_matrix(batch_size, device=device, dtype=dtype)
- trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to var
- assert gradcheck(kgl.inverse_transformation, (trans_01,), raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, batch_size, device):
+ trans_01 = identity_matrix(batch_size, device=device, dtype=torch.float64)
+ self.gradcheck(kgl.inverse_transformation, (trans_01,))
-class TestRelativeTransformation:
+class TestRelativeTransformation(BaseTester):
def test_smoke(self, device, dtype):
batch_size = 2
trans_01 = identity_matrix(batch_size=batch_size, device=device, dtype=dtype)
@@ -306,7 +227,7 @@ class TestRelativeTransformation:
trans_12 = kgl.relative_transformation(trans_01, trans_02)
trans_02_hat = kgl.compose_transformations(trans_01, trans_12)
- assert_close(trans_02_hat, trans_02, atol=1e-4, rtol=1e-4)
+ self.assert_close(trans_02_hat, trans_02, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_rotation_translation_Bx4x4(self, batch_size, device, dtype):
@@ -322,19 +243,17 @@ class TestRelativeTransformation:
trans_12 = kgl.relative_transformation(trans_01, trans_02)
trans_02_hat = kgl.compose_transformations(trans_01, trans_12)
- assert_close(trans_02_hat, trans_02, atol=1e-4, rtol=1e-4)
+ self.assert_close(trans_02_hat, trans_02, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
- def test_gradcheck(self, batch_size, device, dtype):
- trans_01 = identity_matrix(batch_size, device=device, dtype=dtype)
- trans_02 = identity_matrix(batch_size, device=device, dtype=dtype)
+ def test_gradcheck(self, batch_size, device):
+ trans_01 = identity_matrix(batch_size, device=device, dtype=torch.float64)
+ trans_02 = identity_matrix(batch_size, device=device, dtype=torch.float64)
- trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to var
- trans_02 = utils.tensor_to_gradcheck_var(trans_02) # to var
- assert gradcheck(kgl.relative_transformation, (trans_01, trans_02), raise_exception=True, fast_mode=True)
+ self.gradcheck(kgl.relative_transformation, (trans_01, trans_02))
-class TestPointsLinesDistances:
+class TestPointsLinesDistances(BaseTester):
def test_smoke(self, device, dtype):
pts = torch.rand(1, 1, 2, device=device, dtype=dtype)
lines = torch.rand(1, 1, 3, device=device, dtype=dtype)
@@ -386,12 +305,12 @@ class TestPointsLinesDistances:
],
device=device,
).view(1, 6)
- assert_close(distances, distances_expected, rtol=1e-6, atol=1e-6)
+ self.assert_close(distances, distances_expected, rtol=1e-6, atol=1e-6)
def test_gradcheck(self, device):
pts = torch.rand(2, 3, 2, device=device, requires_grad=True, dtype=torch.float64)
lines = torch.rand(2, 3, 3, device=device, requires_grad=True, dtype=torch.float64)
- assert gradcheck(kgl.point_line_distance, (pts, lines), raise_exception=True, fast_mode=True)
+ self.gradcheck(kgl.point_line_distance, (pts, lines))
class TestEuclideanDistance(BaseTester):
@@ -417,7 +336,7 @@ class TestEuclideanDistance(BaseTester):
def test_gradcheck(self, device):
pt1 = torch.rand(2, 3, device=device, dtype=torch.float64, requires_grad=True)
pt2 = torch.rand(2, 3, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kgl.euclidean_distance, (pt1, pt2), raise_exception=True, fast_mode=True)
+ self.gradcheck(kgl.euclidean_distance, (pt1, pt2))
def test_dynamo(self, device, dtype, torch_optimizer):
pt1 = torch.rand(2, 3, device=device, dtype=dtype)
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index f50a1dd6a..7b6045c17 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -4,7 +4,8 @@ from torch.autograd import gradcheck
from kornia.geometry.line import ParametrizedLine, fit_line
from kornia.geometry.plane import Hyperplane
-from kornia.testing import BaseTester, assert_close
+
+from testing.base import BaseTester, assert_close
class TestParametrizedLine(BaseTester):
diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.py
index 0822a7153..81e070ff3 100644
--- a/tests/geometry/test_plane.py
+++ b/tests/geometry/test_plane.py
@@ -3,7 +3,8 @@ import torch
from kornia.geometry.plane import Hyperplane, fit_plane
from kornia.geometry.vector import Vector3
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
# TODO: implement the rest of methods
diff --git a/tests/geometry/test_pose.py b/tests/geometry/test_pose.py
index e76e9ba99..63fb08dc8 100644
--- a/tests/geometry/test_pose.py
+++ b/tests/geometry/test_pose.py
@@ -3,7 +3,8 @@ import torch
from kornia.geometry import NamedPose
from kornia.geometry.liegroup import Se2, Se3, So2, So3
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestNamedPose(BaseTester):
diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.py
index 8bcd713fe..1bb98bac9 100644
--- a/tests/geometry/test_quaternion.py
+++ b/tests/geometry/test_quaternion.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.geometry.quaternion import Quaternion
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestQuaternion:
diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.py
index f616d5db3..d89dbedc3 100644
--- a/tests/geometry/test_ransac.py
+++ b/tests/geometry/test_ransac.py
@@ -1,14 +1,14 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia.testing as utils # test utils
from kornia.geometry import RANSAC, transform_points
from kornia.geometry.epipolar import sampson_epipolar_distance
-from kornia.testing import assert_close
+from testing.base import BaseTester
+from testing.casts import dict_to
-class TestRANSACHomography:
+
+class TestRANSACHomography(BaseTester):
def test_smoke(self, device, dtype):
torch.random.manual_seed(0)
points1 = torch.rand(4, 2, device=device, dtype=dtype)
@@ -36,14 +36,16 @@ class TestRANSACHomography:
# compute transform from source to target
dst_homo_src, _ = ransac(points_src[0], points_dst[0])
- assert_close(transform_points(dst_homo_src[None], points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3)
+ self.assert_close(
+ transform_points(dst_homo_src[None], points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3
+ )
@pytest.mark.slow
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_real_clean(self, device, dtype, data):
# generate input data
torch.random.manual_seed(0)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
homography_gt = torch.inverse(data_dev["H_gt"])
homography_gt = homography_gt / homography_gt[2, 2]
pts_src = data_dev["pts0"]
@@ -52,7 +54,7 @@ class TestRANSACHomography:
# compute transform from source to target
dst_homo_src, _ = ransac(pts_src, pts_dst)
- assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=1e-2, atol=1.0)
+ self.assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=1e-2, atol=1.0)
@pytest.mark.slow
@pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")
@@ -60,7 +62,7 @@ class TestRANSACHomography:
def test_real_dirty(self, device, dtype, data):
# generate input data
torch.random.manual_seed(0)
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
homography_gt = torch.inverse(data_dev["H_gt"])
homography_gt = homography_gt / homography_gt[2, 2]
pts_src = data_dev["pts0"]
@@ -74,7 +76,7 @@ class TestRANSACHomography:
dst_homo_src, _ = ransac(kp1, kp2)
# Reprojection error of 5px is OK
- assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=0.15, atol=5)
+ self.assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=0.15, atol=5)
@pytest.mark.skip(reason="find_homography_dlt is using try/except block")
def test_jit(self, device, dtype):
@@ -83,10 +85,10 @@ class TestRANSACHomography:
points2 = torch.rand(4, 2, device=device, dtype=dtype)
model = RANSAC("homography").to(device=device, dtype=dtype)
model_jit = torch.jit.script(RANSAC("homography").to(device=device, dtype=dtype))
- assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-4, atol=1e-4)
+ self.assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-4, atol=1e-4)
-class TestRANSACHomographyLineSegments:
+class TestRANSACHomographyLineSegments(BaseTester):
def test_smoke(self, device, dtype):
torch.random.manual_seed(0)
points1 = torch.rand(4, 2, 2, device=device, dtype=dtype)
@@ -120,7 +122,7 @@ class TestRANSACHomographyLineSegments:
# compute transform from source to target
dst_homo_src, _ = ransac(ls1[0], ls2[0])
- assert_close(
+ self.assert_close(
transform_points(dst_homo_src[None], points_src_st[:, :-1]), points_dst_st[:, :-1], rtol=1e-3, atol=1e-3
)
@@ -131,10 +133,10 @@ class TestRANSACHomographyLineSegments:
points2 = torch.rand(4, 2, 2, device=device, dtype=dtype)
model = RANSAC("homography_from_linesegments").to(device=device, dtype=dtype)
model_jit = torch.jit.script(RANSAC("homography_from_linesegments").to(device=device, dtype=dtype))
- assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-4, atol=1e-4)
+ self.assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-4, atol=1e-4)
-class TestRANSACFundamental:
+class TestRANSACFundamental(BaseTester):
def test_smoke(self, device, dtype):
torch.random.manual_seed(0)
points1 = torch.rand(8, 2, device=device, dtype=dtype)
@@ -149,7 +151,7 @@ class TestRANSACFundamental:
def test_real_clean_8pt(self, device, dtype, data):
torch.random.manual_seed(0)
# generate input data
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
pts_src = data_dev["pts0"]
pts_dst = data_dev["pts1"]
# compute transform from source to target
@@ -166,7 +168,7 @@ class TestRANSACFundamental:
def test_real_clean_7pt(self, device, dtype, data):
torch.random.manual_seed(0)
# generate input data
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
pts_src = data_dev["pts0"]
pts_dst = data_dev["pts1"]
# compute transform from source to target
@@ -183,7 +185,7 @@ class TestRANSACFundamental:
def test_real_dirty_8pt(self, device, dtype, data):
torch.random.manual_seed(0)
# generate input data
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
pts_src = data_dev["pts0"]
pts_dst = data_dev["pts1"]
@@ -204,7 +206,7 @@ class TestRANSACFundamental:
def test_real_dirty_7pt(self, device, dtype, data):
torch.random.manual_seed(0)
# generate input data
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
pts_src = data_dev["pts0"]
pts_dst = data_dev["pts1"]
@@ -226,7 +228,7 @@ class TestRANSACFundamental:
points2 = torch.rand(8, 2, device=device, dtype=dtype)
model = RANSAC("fundamental").to(device=device, dtype=dtype)
model_jit = torch.jit.script(model)
- assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-3, atol=1e-3)
+ self.assert_close(model(points1, points2)[0], model_jit(points1, points2)[0], rtol=1e-3, atol=1e-3)
@pytest.mark.skip(reason="RANSAC is random algorithm, so Jacobian is not defined")
def test_gradcheck(self, device):
@@ -238,4 +240,4 @@ class TestRANSACFundamental:
def gradfun(p1, p2):
return model(p1, p2)[0]
- assert gradcheck(gradfun, (points1, points2), raise_exception=True)
+ self.gradcheck(gradfun, (points1, points2), fast_mode=False, requires_grad=(True, False, False))
diff --git a/tests/geometry/test_vector.py b/tests/geometry/test_vector.py
index 3ca731406..b0d2c4c1d 100644
--- a/tests/geometry/test_vector.py
+++ b/tests/geometry/test_vector.py
@@ -2,7 +2,8 @@ import pytest
import torch
from kornia.geometry.vector import Scalar, Vector2, Vector3
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestVector3(BaseTester):
diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.py
index 64f3e9067..e15607e82 100644
--- a/tests/geometry/transform/test_affine.py
+++ b/tests/geometry/transform/test_affine.py
@@ -1,32 +1,31 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestResize:
+
+class TestResize(BaseTester):
def test_smoke(self, device, dtype):
inp = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
out = kornia.geometry.transform.resize(inp, (3, 4), align_corners=False)
- assert_close(inp, out, atol=1e-4, rtol=1e-4)
+ self.assert_close(inp, out, atol=1e-4, rtol=1e-4)
# 2D
inp = torch.rand(3, 4, device=device, dtype=dtype)
out = kornia.geometry.transform.resize(inp, (3, 4), align_corners=False)
- assert_close(inp, out, atol=1e-4, rtol=1e-4)
+ self.assert_close(inp, out, atol=1e-4, rtol=1e-4)
# 3D
inp = torch.rand(3, 3, 4, device=device, dtype=dtype)
out = kornia.geometry.transform.resize(inp, (3, 4), align_corners=False)
- assert_close(inp, out, atol=1e-4, rtol=1e-4)
+ self.assert_close(inp, out, atol=1e-4, rtol=1e-4)
# arbitrary dim
inp = torch.rand(1, 2, 3, 2, 1, 3, 3, 4, device=device, dtype=dtype)
out = kornia.geometry.transform.resize(inp, (3, 4), align_corners=False)
- assert_close(inp, out, atol=1e-4, rtol=1e-4)
+ self.assert_close(inp, out, atol=1e-4, rtol=1e-4)
def test_upsize(self, device, dtype):
inp = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
@@ -172,24 +171,18 @@ class TestResize:
out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="horz")
assert out.shape == (1, 3, 4, 10)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
new_size = 4
- input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(
- kornia.geometry.transform.Resize(new_size, align_corners=False),
- (input,),
- raise_exception=True,
- fast_mode=True,
- )
+ input = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.Resize(new_size, align_corners=False), (input,))
-class TestRescale:
+class TestRescale(BaseTester):
def test_smoke(self, device, dtype):
input = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
output = kornia.geometry.transform.rescale(input, (1.0, 1.0), align_corners=False)
- assert_close(input, output, atol=1e-4, rtol=1e-4)
+ self.assert_close(input, output, atol=1e-4, rtol=1e-4)
def test_upsize(self, device, dtype):
input = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
@@ -221,7 +214,7 @@ class TestRescale:
device=device,
dtype=dtype,
)
- assert_close(out, expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(out, expected, atol=1e-3, rtol=1e-3)
def test_downscale_values_AA(self, device, dtype):
inp_x = torch.arange(20, device=device, dtype=dtype) / 20.0
@@ -243,26 +236,19 @@ class TestRescale:
device=device,
dtype=dtype,
)
- assert_close(out, expected, atol=1e-3, rtol=1e-3)
+ self.assert_close(out, expected, atol=1e-3, rtol=1e-3)
def test_one_param(self, device, dtype):
input = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
output = kornia.geometry.transform.rescale(input, 2.0, align_corners=False)
assert output.shape == (1, 3, 6, 8)
- def test_gradcheck(self, device, dtype):
- input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input)
- assert gradcheck(
- kornia.geometry.transform.Rescale(2.0, align_corners=False),
- (input,),
- nondet_tol=1e-8,
- raise_exception=True,
- fast_mode=True,
- )
+ def test_gradcheck(self, device):
+ input = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.Rescale(2.0, align_corners=False), (input,), nondet_tol=1e-8)
-class TestRotate:
+class TestRotate(BaseTester):
def test_angle90(self, device, dtype):
# prepare input data
inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], device=device, dtype=dtype)
@@ -270,7 +256,7 @@ class TestRotate:
# prepare transformation
angle = torch.tensor([90.0], device=device, dtype=dtype)
transform = kornia.geometry.transform.Rotate(angle, align_corners=True)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_angle90_batch2(self, device, dtype):
# prepare input data
@@ -285,7 +271,7 @@ class TestRotate:
# prepare transformation
angle = torch.tensor([90.0, -90.0], device=device, dtype=dtype)
transform = kornia.geometry.transform.Rotate(angle, align_corners=True)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_angle90_batch2_broadcast(self, device, dtype):
# prepare input data
@@ -300,17 +286,15 @@ class TestRotate:
# prepare transformation
angle = torch.tensor([90.0], device=device, dtype=dtype)
transform = kornia.geometry.transform.Rotate(angle, align_corners=True)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
- angle = torch.tensor([90.0], device=device, dtype=dtype)
- angle = utils.tensor_to_gradcheck_var(angle, requires_grad=False) # to var
+ angle = torch.tensor([90.0], device=device, dtype=torch.float64)
# evaluate function gradient
- input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.geometry.transform.rotate, (input, angle), raise_exception=True, fast_mode=True)
+ input = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.rotate, (input, angle))
@pytest.mark.skip("Need deep look into it since crashes everywhere.")
@pytest.mark.skip(reason="turn off all jit for a while")
@@ -320,10 +304,10 @@ class TestRotate:
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
rot = kornia.geometry.transform.Rotate(angle)
rot_traced = torch.jit.trace(kornia.geometry.transform.Rotate(angle), img)
- assert_close(rot(img), rot_traced(img))
+ self.assert_close(rot(img), rot_traced(img))
-class TestTranslate:
+class TestTranslate(BaseTester):
def test_dxdy(self, device, dtype):
# prepare input data
inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], device=device, dtype=dtype)
@@ -331,7 +315,7 @@ class TestTranslate:
# prepare transformation
translation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Translate(translation, align_corners=True)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_dxdy_batch(self, device, dtype):
# prepare input data
@@ -346,7 +330,7 @@ class TestTranslate:
# prepare transformation
translation = torch.tensor([[1.0, 0.0], [1.0, 1.0]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Translate(translation, align_corners=True)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_dxdy_batch_broadcast(self, device, dtype):
# prepare input data
@@ -361,19 +345,15 @@ class TestTranslate:
# prepare transformation
translation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Translate(translation, align_corners=True)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
- translation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)
- translation = utils.tensor_to_gradcheck_var(translation, requires_grad=False) # to var
+ translation = torch.tensor([[1.0, 0.0]], device=device, dtype=torch.float64)
# evaluate function gradient
- input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(
- kornia.geometry.transform.translate, (input, translation), raise_exception=True, fast_mode=True
- )
+ input = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.translate, (input, translation), requires_grad=(True, False))
@pytest.mark.skip("Need deep look into it since crashes everywhere.")
@pytest.mark.skip(reason="turn off all jit for a while")
@@ -383,10 +363,10 @@ class TestTranslate:
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
trans = kornia.geometry.transform.Translate(translation)
trans_traced = torch.jit.trace(kornia.geometry.transform.Translate(translation), img)
- assert_close(trans(img), trans_traced(img), atol=1e-4, rtol=1e-4)
+ self.assert_close(trans(img), trans_traced(img), atol=1e-4, rtol=1e-4)
-class TestScale:
+class TestScale(BaseTester):
def test_scale_factor_2(self, device, dtype):
# prepare input data
inp = torch.tensor(
@@ -397,7 +377,7 @@ class TestScale:
# prepare transformation
scale_factor = torch.tensor([[2.0, 2.0]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Scale(scale_factor)
- assert_close(transform(inp).sum().item(), 12.25, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp).sum().item(), 12.25, atol=1e-4, rtol=1e-4)
def test_scale_factor_05(self, device, dtype):
# prepare input data
@@ -414,7 +394,7 @@ class TestScale:
# prepare transformation
scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Scale(scale_factor)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_scale_factor_05_batch2(self, device, dtype):
# prepare input data
@@ -431,7 +411,7 @@ class TestScale:
# prepare transformation
scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Scale(scale_factor)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_scale_factor_05_batch2_broadcast(self, device, dtype):
# prepare input data
@@ -448,17 +428,15 @@ class TestScale:
# prepare transformation
scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Scale(scale_factor)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
- scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
- scale_factor = utils.tensor_to_gradcheck_var(scale_factor, requires_grad=False) # to var
+ scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=torch.float64)
# evaluate function gradient
- input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.geometry.transform.scale, (input, scale_factor), raise_exception=True, fast_mode=True)
+ input = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.scale, (input, scale_factor), requires_grad=(True, False))
@pytest.mark.skip("Need deep look into it since crashes everywhere.")
@pytest.mark.skip(reason="turn off all jit for a while")
@@ -468,10 +446,10 @@ class TestScale:
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
trans = kornia.geometry.transform.Scale(scale_factor)
trans_traced = torch.jit.trace(kornia.Scale(scale_factor), img)
- assert_close(trans(img), trans_traced(img), atol=1e-4, rtol=1e-4)
+ self.assert_close(trans(img), trans_traced(img), atol=1e-4, rtol=1e-4)
-class TestShear:
+class TestShear(BaseTester):
def test_shear_x(self, device, dtype):
# prepare input data
inp = torch.tensor(
@@ -488,7 +466,7 @@ class TestShear:
# prepare transformation
shear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Shear(shear, align_corners=False)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_shear_y(self, device, dtype):
# prepare input data
@@ -506,7 +484,7 @@ class TestShear:
# prepare transformation
shear = torch.tensor([[0.0, 0.5]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Shear(shear, align_corners=False)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_shear_batch2(self, device, dtype):
# prepare input data
@@ -528,7 +506,7 @@ class TestShear:
# prepare transformation
shear = torch.tensor([[0.5, 0.0], [0.0, 0.5]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Shear(shear, align_corners=False)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_shear_batch2_broadcast(self, device, dtype):
# prepare input data
@@ -547,17 +525,15 @@ class TestShear:
# prepare transformation
shear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)
transform = kornia.geometry.transform.Shear(shear, align_corners=False)
- assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
- shear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)
- shear = utils.tensor_to_gradcheck_var(shear, requires_grad=False) # to var
+ shear = torch.tensor([[0.5, 0.0]], device=device, dtype=torch.float64)
# evaluate function gradient
- input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.geometry.transform.shear, (input, shear), raise_exception=True, fast_mode=True)
+ input = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.shear, (input, shear), requires_grad=(True, False))
@pytest.mark.skip("Need deep look into it since crashes everywhere.")
@pytest.mark.skip(reason="turn off all jit for a while")
@@ -567,10 +543,10 @@ class TestShear:
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
trans = kornia.geometry.transform.Shear(shear, align_corners=False)
trans_traced = torch.jit.trace(kornia.geometry.transform.Shear(shear), img)
- assert_close(trans(img), trans_traced(img), atol=1e-4, rtol=1e-4)
+ self.assert_close(trans(img), trans_traced(img), atol=1e-4, rtol=1e-4)
-class TestAffine2d:
+class TestAffine2d(BaseTester):
def test_affine_no_args(self):
with pytest.raises(RuntimeError):
kornia.geometry.transform.Affine()
@@ -592,7 +568,7 @@ class TestAffine2d:
transform = kornia.geometry.transform.Affine(angle=angle).to(device=device, dtype=dtype)
actual = transform(input)
expected = kornia.geometry.transform.rotate(input, angle)
- assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
def test_affine_translate(self, device, dtype):
# TODO: Remove when #666 is implemented
@@ -605,7 +581,7 @@ class TestAffine2d:
transform = kornia.geometry.transform.Affine(translation=translation).to(device=device, dtype=dtype)
actual = transform(input)
expected = kornia.geometry.transform.translate(input, translation)
- assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
def test_affine_scale(self, device, dtype):
# TODO: Remove when #666 is implemented
@@ -619,7 +595,7 @@ class TestAffine2d:
transform = kornia.geometry.transform.Affine(scale_factor=scale_factor).to(device=device, dtype=dtype)
actual = transform(input)
expected = kornia.geometry.transform.scale(input, scale_factor)
- assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
@pytest.mark.skip(
"_compute_shear_matrix and get_affine_matrix2d yield different results. "
@@ -633,7 +609,7 @@ class TestAffine2d:
transform = kornia.geometry.transform.Affine(shear=shear).to(device, dtype)
actual = transform(input)
expected = kornia.geometry.transform.shear(input, shear)
- assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
def test_affine_rotate_translate(self, device, dtype):
# TODO: Remove when #666 is implemented
@@ -660,7 +636,7 @@ class TestAffine2d:
device=device, dtype=dtype
)
actual = transform(input)
- assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
def test_compose_affine_matrix_3x3(self, device, dtype):
"""To get parameters:
@@ -710,10 +686,10 @@ class TestAffine2d:
T([math.radians(shear[1])]).view(-1, 1),
)
matrix_kornia = matrix_kornia.inverse()[0, :2].detach().cpu()
- assert_close(matrix_kornia, matrix_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(matrix_kornia, matrix_expected, atol=1e-4, rtol=1e-4)
-class TestGetAffineMatrix:
+class TestGetAffineMatrix(BaseTester):
def test_smoke(self, device, dtype):
H, W = 5, 5
translation = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)
@@ -730,10 +706,10 @@ class TestGetAffineMatrix:
expected[..., 1:4] = 1.0
out = kornia.geometry.transform.warp_affine(img, affine_mat[:, :2], (H, W))
- assert_close(out, expected)
+ self.assert_close(out, expected)
-class TestGetShearMatrix:
+class TestGetShearMatrix(BaseTester):
def test_get_shear_matrix2d_with_controlled_values(self, device, dtype):
# Define controlled values for shear angles and center
sx = torch.tensor([0.5], device=device, dtype=dtype)
@@ -748,4 +724,4 @@ class TestGetShearMatrix:
[[[1.0, -0.5463, 0.0], [-0.2553, 1.1395, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
)
- assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index caf97b51d..72e90a17c 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -1,12 +1,11 @@
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestCropAndResize:
+
+class TestCropAndResize(BaseTester):
def test_align_corners_true(self, device, dtype):
inp = torch.tensor(
[[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
@@ -22,7 +21,7 @@ class TestCropAndResize:
# default should use align_coners True
patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (height, width))
- assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
def test_align_corners_false(self, device, dtype):
inp = torch.tensor(
@@ -37,7 +36,7 @@ class TestCropAndResize:
boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (height, width), align_corners=False)
- assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
def test_crop_batch(self, device, dtype):
inp = torch.tensor(
@@ -60,7 +59,7 @@ class TestCropAndResize:
) # 2x4x2
patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (2, 2))
- assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
def test_crop_batch_broadcast(self, device, dtype):
inp = torch.tensor(
@@ -79,17 +78,15 @@ class TestCropAndResize:
boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (2, 2))
- assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
- def test_gradcheck(self, device, dtype):
- img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ def test_gradcheck(self, device):
+ img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
- boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
- boxes = utils.tensor_to_gradcheck_var(boxes, requires_grad=False) # to var
+ boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=torch.float64)
- assert gradcheck(
- kornia.geometry.transform.crop_and_resize, (img, boxes, (4, 2)), raise_exception=True, fast_mode=True
+ self.gradcheck(
+ kornia.geometry.transform.crop_and_resize, (img, boxes, (4, 2)), requires_grad=(True, False, False)
)
def test_dynamo(self, device, dtype, torch_optimizer):
@@ -107,10 +104,10 @@ class TestCropAndResize:
crop_height, crop_width = 4, 2
actual = op_optimized(img, boxes, (crop_height, crop_width))
expected = op(img, boxes, (crop_height, crop_width))
- assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
-class TestCenterCrop:
+class TestCenterCrop(BaseTester):
def test_center_crop_h2_w4(self, device, dtype):
inp = torch.tensor(
[[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
@@ -121,7 +118,7 @@ class TestCenterCrop:
expected = torch.tensor([[[[5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]]]], device=device, dtype=dtype)
out_crop = kornia.geometry.transform.center_crop(inp, (2, 4))
- assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
def test_center_crop_h4_w2(self, device, dtype):
inp = torch.tensor(
@@ -134,7 +131,7 @@ class TestCenterCrop:
expected = torch.tensor([[[[2.0, 3.0], [6.0, 7.0], [10.0, 11.0], [14.0, 15.0]]]], device=device, dtype=dtype)
out_crop = kornia.geometry.transform.center_crop(inp, (height, width))
- assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
def test_center_crop_h4_w2_batch(self, device, dtype):
inp = torch.tensor(
@@ -156,13 +153,12 @@ class TestCenterCrop:
)
out_crop = kornia.geometry.transform.center_crop(inp, (4, 2))
- assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
- def test_gradcheck(self, device, dtype):
- img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ def test_gradcheck(self, device):
+ img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
- assert gradcheck(kornia.geometry.transform.center_crop, (img, (4, 2)), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.geometry.transform.center_crop, (img, (4, 2)))
def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
@@ -173,10 +169,10 @@ class TestCenterCrop:
actual = op_script(img, (4, 2))
expected = op(img, (4, 2))
- assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
-class TestCropByBoxes:
+class TestCropByBoxes(BaseTester):
def test_crop_by_boxes_no_resizing(self, device, dtype):
inp = torch.tensor(
[[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
@@ -191,7 +187,7 @@ class TestCropByBoxes:
expected = torch.tensor([[[[6.0, 7.0], [10.0, 11.0]]]], device=device, dtype=dtype)
patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
- assert_close(patches, expected)
+ self.assert_close(patches, expected)
def test_crop_by_boxes_resizing(self, device, dtype):
inp = torch.tensor(
@@ -207,19 +203,18 @@ class TestCropByBoxes:
expected = torch.tensor([[[[6.0, 6.5, 7.0], [10.0, 10.5, 11.0]]]], device=device, dtype=dtype)
patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst)
- assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
inp = torch.randn((1, 1, 3, 3), device=device, dtype=dtype)
src = torch.tensor([[[1.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0]]], device=device, dtype=dtype)
dst = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype)
- inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
-
- assert gradcheck(kornia.geometry.transform.crop_by_boxes, (inp, src, dst), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.geometry.transform.crop_by_boxes, (inp, src, dst), requires_grad=(True, False, False))
-class TestCropByTransform:
+class TestCropByTransform(BaseTester):
def test_crop_by_transform_no_resizing(self, device, dtype):
inp = torch.tensor(
[[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
@@ -234,7 +229,7 @@ class TestCropByTransform:
expected = torch.tensor([[[[6.0, 7.0], [10.0, 11.0]]]], device=device, dtype=dtype)
patches = kornia.geometry.transform.crop_by_transform_mat(inp, transform, (2, 2))
- assert_close(patches, expected)
+ self.assert_close(patches, expected)
def test_crop_by_boxes_resizing(self, device, dtype):
inp = torch.tensor(
@@ -250,19 +245,16 @@ class TestCropByTransform:
expected = torch.tensor([[[[6.0, 6.5, 7.0], [10.0, 10.5, 11.0]]]], device=device, dtype=dtype)
patches = kornia.geometry.transform.crop_by_transform_mat(inp, transform, (2, 3))
- assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
- def test_gradcheck(self, device, dtype):
- inp = torch.randn((1, 1, 3, 3), device=device, dtype=dtype)
+ def test_gradcheck(self, device):
+ inp = torch.randn((1, 1, 3, 3), device=device, dtype=torch.float64)
transform = torch.tensor(
- [[[2.0, 0.0, -2.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ [[[2.0, 0.0, -2.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=torch.float64
) # 1x3x3
- inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
-
- assert gradcheck(
+ self.gradcheck(
kornia.geometry.transform.crop_by_transform_mat,
(inp, transform, (2, 2)),
- raise_exception=True,
- fast_mode=True,
+ requires_grad=(True, False, False),
)
diff --git a/tests/geometry/transform/test_crop3d.py b/tests/geometry/transform/test_crop3d.py
index b83096526..9eb2bdde1 100644
--- a/tests/geometry/transform/test_crop3d.py
+++ b/tests/geometry/transform/test_crop3d.py
@@ -1,14 +1,13 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version
+from testing.base import BaseTester
-class TestCropAndResize3D:
+
+class TestCropAndResize3D(BaseTester):
def test_crop(self, device, dtype):
inp = torch.arange(0.0, 64.0, device=device, dtype=dtype).view(1, 1, 4, 4, 4)
@@ -26,7 +25,7 @@ class TestCropAndResize3D:
) # 1x8x3
patches = kornia.geometry.transform.crop_and_resize3d(inp, boxes, (depth, height, width))
- assert_close(patches, expected)
+ self.assert_close(patches, expected)
def test_crop_batch(self, device, dtype):
inp = torch.cat(
@@ -57,22 +56,18 @@ class TestCropAndResize3D:
) # 2x8x3
patches = kornia.geometry.transform.crop_and_resize3d(inp, boxes, (depth, height, width), align_corners=True)
- assert_close(patches, expected)
+ self.assert_close(patches, expected)
- def test_gradcheck(self, device, dtype):
- img = torch.arange(0.0, 64.0, device=device, dtype=dtype).view(1, 1, 4, 4, 4)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ def test_gradcheck(self, device):
+ img = torch.arange(0.0, 64.0, device=device, dtype=torch.float64).view(1, 1, 4, 4, 4)
boxes = torch.tensor(
[[[0, 0, 1], [3, 0, 1], [3, 2, 1], [0, 2, 1], [0, 0, 3], [3, 0, 3], [3, 2, 3], [0, 2, 3]]],
device=device,
- dtype=dtype,
+ dtype=torch.float64,
) # 1x8x3
- boxes = utils.tensor_to_gradcheck_var(boxes, requires_grad=False) # to var
- assert gradcheck(
- kornia.geometry.transform.crop_and_resize3d, (img, boxes, (4, 3, 2)), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.transform.crop_and_resize3d, (img, boxes, (4, 3, 2)))
def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
@@ -89,10 +84,10 @@ class TestCropAndResize3D:
actual = op_script(img, boxes, (4, 3, 2))
expected = op(img, boxes, (4, 3, 2))
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestCenterCrop3D:
+class TestCenterCrop3D(BaseTester):
@pytest.mark.parametrize("crop_size", [(3, 5, 7), (5, 3, 7), (7, 3, 5)])
def test_center_crop_357(self, crop_size, device, dtype):
inp = torch.arange(0.0, 343.0, device=device, dtype=dtype).view(1, 1, 7, 7, 7)
@@ -104,7 +99,7 @@ class TestCenterCrop3D:
(inp.size(4) // 2 - crop_size[2] // 2) : (inp.size(4) // 2 + crop_size[2] // 2 + 1),
]
out_crop = kornia.geometry.transform.center_crop3d(inp, crop_size, align_corners=True)
- assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
@pytest.mark.parametrize("crop_size", [(3, 5, 7), (5, 3, 7), (7, 3, 5)])
def test_center_crop_357_batch(self, crop_size, device, dtype):
@@ -122,15 +117,12 @@ class TestCenterCrop3D:
(inp.size(4) // 2 - crop_size[2] // 2) : (inp.size(4) // 2 + crop_size[2] // 2 + 1),
]
out_crop = kornia.geometry.transform.center_crop3d(inp, crop_size, align_corners=True)
- assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
- def test_gradcheck(self, device, dtype):
- img = torch.arange(0.0, 343.0, device=device, dtype=dtype).view(1, 1, 7, 7, 7)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ def test_gradcheck(self, device):
+ img = torch.arange(0.0, 343.0, device=device, dtype=torch.float64).view(1, 1, 7, 7, 7)
- assert gradcheck(
- kornia.geometry.transform.center_crop3d, (img, (3, 5, 7)), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.transform.center_crop3d, (img, (3, 5, 7)))
@pytest.mark.skipif(
torch_version() == "2.1.0",
@@ -147,10 +139,10 @@ class TestCenterCrop3D:
actual = op_script(img, (4, 3, 2))
expected = kornia.geometry.transform.center_crop3d(img, (4, 3, 2))
- assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
-class TestCropByBoxes3D:
+class TestCropByBoxes3D(BaseTester):
def test_crop_by_boxes_no_resizing(self, device, dtype):
inp = torch.arange(0.0, 343.0, device=device, dtype=dtype).view(1, 1, 7, 7, 7)
src_box = torch.tensor(
@@ -189,7 +181,7 @@ class TestCropByBoxes3D:
expected = inp[:, :, 1:3, 1:4, 1:4]
patches = kornia.geometry.transform.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)
- assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
def test_crop_by_boxes_resizing(self, device, dtype):
inp = torch.arange(0.0, 343.0, device=device, dtype=dtype).view(1, 1, 7, 7, 7)
@@ -233,7 +225,7 @@ class TestCropByBoxes3D:
)
patches = kornia.geometry.transform.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)
- assert_close(patches, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(patches, expected, rtol=1e-4, atol=1e-4)
def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
@@ -276,9 +268,10 @@ class TestCropByBoxes3D:
actual = op_script(inp, src_box, dst_box, align_corners=True)
expected = op(inp, src_box, dst_box, align_corners=True)
- assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
inp = torch.randn((1, 1, 7, 7, 7), device=device, dtype=dtype)
src_box = torch.tensor(
[
@@ -313,8 +306,6 @@ class TestCropByBoxes3D:
dtype=dtype,
) # 1x8x3
- inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
-
- assert gradcheck(
- kornia.geometry.transform.crop_by_boxes3d, (inp, src_box, dst_box), raise_exception=True, fast_mode=True
+ self.gradcheck(
+ kornia.geometry.transform.crop_by_boxes3d, (inp, src_box, dst_box), requires_grad=(True, False, False)
)
diff --git a/tests/geometry/transform/test_elastic_transform.py b/tests/geometry/transform/test_elastic_transform.py
index 9f08437de..187a86975 100644
--- a/tests/geometry/transform/test_elastic_transform.py
+++ b/tests/geometry/transform/test_elastic_transform.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
from kornia.geometry.transform import elastic_transform2d
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestElasticTransform:
diff --git a/tests/geometry/transform/test_flip.py b/tests/geometry/transform/test_flip.py
index 8eb00f382..23b7ce916 100644
--- a/tests/geometry/transform/test_flip.py
+++ b/tests/geometry/transform/test_flip.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestVflip:
+
+class TestVflip(BaseTester):
def smoke_test(self, device, dtype):
f = kornia.geometry.transform.Vflip()
repr = "Vflip()"
@@ -21,7 +20,7 @@ class TestVflip:
[[0.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype
) # 3 x 3
- assert_close(f(input), expected)
+ self.assert_close(f(input), expected)
def test_batch_vflip(self, device, dtype):
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
@@ -35,7 +34,7 @@ class TestVflip:
expected = expected.repeat(2, 1, 1) # 2 x 3 x 3
- assert_close(f(input), expected)
+ self.assert_close(f(input), expected)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
@@ -61,17 +60,14 @@ class TestVflip:
actual = op_trace(input)
- assert_close(actual, expected)
-
- def test_gradcheck(self, device, dtype):
- input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
-
- input = utils.tensor_to_gradcheck_var(input) # to var
+ self.assert_close(actual, expected)
- assert gradcheck(kornia.geometry.transform.Vflip(), (input,), raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, device):
+ input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.Vflip(), (input,))
-class TestHflip:
+class TestHflip(BaseTester):
def smoke_test(self, device, dtype):
f = kornia.geometry.transform.Hflip()
repr = "Hflip()"
@@ -85,7 +81,7 @@ class TestHflip:
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 0.0]], device=device, dtype=dtype
) # 3 x 3
- assert_close(f(input), expected)
+ self.assert_close(f(input), expected)
def test_batch_hflip(self, device, dtype):
input = torch.tensor(
@@ -101,7 +97,7 @@ class TestHflip:
expected = expected.repeat(2, 1, 1) # 2 x 3 x 3
- assert_close(f(input), expected)
+ self.assert_close(f(input), expected)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
@@ -127,17 +123,14 @@ class TestHflip:
actual = op_trace(input)
- assert_close(actual, expected)
-
- def test_gradcheck(self, device, dtype):
- input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
+ self.assert_close(actual, expected)
- input = utils.tensor_to_gradcheck_var(input) # to var
+ def test_gradcheck(self, device):
+ input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.Hflip(), (input,))
- assert gradcheck(kornia.geometry.transform.Hflip(), (input,), raise_exception=True, fast_mode=True)
-
-class TestRot180:
+class TestRot180(BaseTester):
def smoke_test(self, device, dtype):
f = kornia.geometry.transform.Rot180()
repr = "Rot180()"
@@ -151,7 +144,7 @@ class TestRot180:
[[1.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype
) # 3 x 3
- assert_close(f(input), expected)
+ self.assert_close(f(input), expected)
def test_batch_rot180(self, device, dtype):
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
@@ -165,7 +158,7 @@ class TestRot180:
expected = expected.repeat(2, 1, 1) # 2 x 3 x 3
- assert_close(f(input), expected)
+ self.assert_close(f(input), expected)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
@@ -191,11 +184,11 @@ class TestRot180:
actual = op_trace(input)
- assert_close(actual, expected)
-
- def test_gradcheck(self, device, dtype):
- input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
+ self.assert_close(actual, expected)
- input = utils.tensor_to_gradcheck_var(input) # to var
+ def test_gradcheck(self, device):
+ input = torch.tensor(
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=torch.float64
+ ) # 3 x 3
- assert gradcheck(kornia.geometry.transform.Rot180(), (input,), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.geometry.transform.Rot180(), (input,))
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index 3a98ba4af..912d58418 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -1,14 +1,15 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
from kornia.utils.helpers import _torch_inverse_cast
+from kornia.utils.misc import eye_like
+from testing.base import BaseTester
+from testing.error import compute_patch_abs_error
-class TestHomographyWarper:
+
+class TestHomographyWarper(BaseTester):
num_tests = 10
threshold = 0.1
@@ -16,26 +17,28 @@ class TestHomographyWarper:
# create input data
height, width = 2, 5
patch_src = torch.rand(1, 1, height, width, device=device, dtype=dtype)
- dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=3, device=device, dtype=dtype)
+ dst_homo_src = eye_like(3, patch_src)
# instantiate warper
warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=True)
# warp from source to destination
patch_dst = warper(patch_src, dst_homo_src)
- assert_close(patch_src, patch_dst)
+ self.assert_close(patch_src, patch_dst)
@pytest.mark.parametrize("batch_size", [1, 3])
def test_normalize_homography_identity(self, batch_size, device, dtype):
# create input data
height, width = 2, 5
- dst_homo_src = utils.create_eye_batch(batch_size=batch_size, eye_size=3, device=device, dtype=dtype)
-
res = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- assert_close(kornia.geometry.conversions.normal_transform_pixel(height, width, device=device, dtype=dtype), res)
+ dst_homo_src = eye_like(3, res.expand(batch_size, -1, -1, -1))
+
+ self.assert_close(
+ kornia.geometry.conversions.normal_transform_pixel(height, width, device=device, dtype=dtype), res
+ )
norm_homo = kornia.geometry.conversions.normalize_homography(dst_homo_src, (height, width), (height, width))
- assert_close(norm_homo, dst_homo_src)
+ self.assert_close(norm_homo, dst_homo_src)
# change output scale
norm_homo = kornia.geometry.conversions.normalize_homography(
@@ -44,19 +47,22 @@ class TestHomographyWarper:
res = torch.tensor(
[[[4.0, 0.0, 3.0], [0.0, 1 / 3, -2 / 3], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
).repeat(batch_size, 1, 1)
- assert_close(norm_homo, res, atol=1e-4, rtol=1e-4)
+ self.assert_close(norm_homo, res, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 3])
def test_denormalize_homography_identity(self, batch_size, device, dtype):
# create input data
height, width = 2, 5
- dst_homo_src = utils.create_eye_batch(batch_size=batch_size, eye_size=3, device=device, dtype=dtype)
res = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- assert_close(kornia.geometry.conversions.normal_transform_pixel(height, width, device=device, dtype=dtype), res)
+ dst_homo_src = eye_like(3, res.expand(batch_size, -1, -1, -1))
+
+ self.assert_close(
+ kornia.geometry.conversions.normal_transform_pixel(height, width, device=device, dtype=dtype), res
+ )
denorm_homo = kornia.geometry.conversions.denormalize_homography(dst_homo_src, (height, width), (height, width))
- assert_close(denorm_homo, dst_homo_src)
+ self.assert_close(denorm_homo, dst_homo_src)
# change output scale
denorm_homo = kornia.geometry.conversions.denormalize_homography(
@@ -65,7 +71,7 @@ class TestHomographyWarper:
res = torch.tensor([[[0.25, 0.0, 0.0], [0.0, 3.0, 0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype).repeat(
batch_size, 1, 1
)
- assert_close(denorm_homo, res, atol=1e-4, rtol=1e-4)
+ self.assert_close(denorm_homo, res, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 3])
def test_normalize_homography_general(self, batch_size, device, dtype):
@@ -82,7 +88,7 @@ class TestHomographyWarper:
res = torch.tensor([[[0.5, 0.0, 0.0], [0.0, 2.0, 5.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype).expand(
batch_size, -1, -1
)
- assert_close(norm_homo, res)
+ self.assert_close(norm_homo, res)
@pytest.mark.parametrize("batch_size", [1, 3])
def test_denormalize_homography_general(self, batch_size, device, dtype):
@@ -99,7 +105,7 @@ class TestHomographyWarper:
res = torch.tensor([[[0.5, 0.0, 3.0], [0.0, 2.0, 0.5], [0.0, 0.0, 1.0]]], device=device, dtype=dtype).expand(
batch_size, -1, -1
)
- assert_close(denorm_homo, res)
+ self.assert_close(denorm_homo, res)
@pytest.mark.parametrize("batch_size", [1, 3])
def test_consistency(self, batch_size, device, dtype):
@@ -116,44 +122,44 @@ class TestHomographyWarper:
norm_denorm_homo = kornia.geometry.conversions.normalize_homography(
denorm_homo, (height, width), (height, width)
)
- assert_close(dst_homo_src, norm_denorm_homo)
+ self.assert_close(dst_homo_src, norm_denorm_homo)
norm_homo = kornia.geometry.conversions.normalize_homography(dst_homo_src, (height, width), (height, width))
denorm_norm_homo = kornia.geometry.conversions.denormalize_homography(
norm_homo, (height, width), (height, width)
)
- assert_close(dst_homo_src, denorm_norm_homo)
+ self.assert_close(dst_homo_src, denorm_norm_homo)
@pytest.mark.parametrize("offset", [1, 3, 7])
@pytest.mark.parametrize("shape", [(4, 5), (2, 6), (4, 3), (5, 7)])
def test_warp_grid_translation(self, shape, offset, device, dtype):
# create input data
height, width = shape
- dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=3, device=device, dtype=dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, dtype=dtype)
+ dst_homo_src = eye_like(3, grid)
dst_homo_src[..., 0, 2] = offset # apply offset in x
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False)
flow = kornia.geometry.transform.warp_grid(grid, dst_homo_src)
# the grid the src plus the offset should be equal to the flow
# on the x-axis, y-axis remains the same.
- assert_close(grid[..., 0].to(device=device, dtype=dtype) + offset, flow[..., 0])
- assert_close(grid[..., 1].to(device=device, dtype=dtype), flow[..., 1])
+ self.assert_close(grid[..., 0].to(device=device, dtype=dtype) + offset, flow[..., 0])
+ self.assert_close(grid[..., 1].to(device=device, dtype=dtype), flow[..., 1])
@pytest.mark.parametrize("batch_shape", [(1, 1, 4, 5), (2, 2, 4, 6), (3, 1, 5, 7)])
def test_identity_resize(self, batch_shape, device, dtype):
# create input data
batch_size, channels, height, width = batch_shape
patch_src = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- dst_homo_src = utils.create_eye_batch(batch_size, eye_size=3, device=device, dtype=dtype)
+ dst_homo_src = eye_like(3, patch_src)
# instantiate warper warp from source to destination
warper = kornia.geometry.transform.HomographyWarper(height // 2, width // 2, align_corners=True)
patch_dst = warper(patch_src, dst_homo_src)
# check the corners
- assert_close(patch_src[..., 0, 0], patch_dst[..., 0, 0], atol=1e-4, rtol=1e-4)
- assert_close(patch_src[..., 0, -1], patch_dst[..., 0, -1], atol=1e-4, rtol=1e-4)
- assert_close(patch_src[..., -1, 0], patch_dst[..., -1, 0], atol=1e-4, rtol=1e-4)
- assert_close(patch_src[..., -1, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_src[..., 0, 0], patch_dst[..., 0, 0], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_src[..., 0, -1], patch_dst[..., 0, -1], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_src[..., -1, 0], patch_dst[..., -1, 0], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_src[..., -1, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("shape", [(4, 5), (2, 6), (4, 3), (5, 7)])
def test_translation(self, shape, device, dtype):
@@ -161,13 +167,14 @@ class TestHomographyWarper:
offset = 2.0 # in pixel
height, width = shape
patch_src = torch.rand(1, 1, height, width, device=device, dtype=dtype)
- dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=3, device=device, dtype=dtype)
+ dst_homo_src = eye_like(3, patch_src)
+
dst_homo_src[..., 0, 2] = offset / (width - 1) # apply offset in x
# instantiate warper and from source to destination
warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=True)
patch_dst = warper(patch_src, dst_homo_src)
- assert_close(patch_src[..., 1:], patch_dst[..., :-1], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_src[..., 1:], patch_dst[..., :-1], atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_shape", [(1, 1, 3, 5), (2, 2, 4, 3), (3, 1, 2, 3)])
def test_rotation(self, batch_shape, device, dtype):
@@ -187,10 +194,10 @@ class TestHomographyWarper:
patch_dst = warper(patch_src, dst_homo_src)
# check the corners
- assert_close(patch_src[..., 0, 0], patch_dst[..., 0, -1], atol=1e-4, rtol=1e-4)
- assert_close(patch_src[..., 0, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)
- assert_close(patch_src[..., -1, 0], patch_dst[..., 0, 0], atol=1e-4, rtol=1e-4)
- assert_close(patch_src[..., -1, -1], patch_dst[..., -1, 0], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_src[..., 0, 0], patch_dst[..., 0, -1], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_src[..., 0, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_src[..., -1, 0], patch_dst[..., 0, 0], atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_src[..., -1, -1], patch_dst[..., -1, 0], atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 3])
def test_homography_warper(self, batch_size, device, dtype):
@@ -201,7 +208,7 @@ class TestHomographyWarper:
patch_src = torch.ones(batch_size, 1, height, width, device=device, dtype=dtype)
# create base homography
- dst_homo_src = utils.create_eye_batch(batch_size, eye_size, device=device, dtype=dtype)
+ dst_homo_src = eye_like(eye_size, patch_src)
# instantiate warper
warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=True)
@@ -219,10 +226,10 @@ class TestHomographyWarper:
# same transform precomputing the grid
warper.precompute_warp_grid(_torch_inverse_cast(dst_homo_src_i))
patch_dst_to_src_precomputed = warper(patch_dst)
- assert_close(patch_dst_to_src_precomputed, patch_dst_to_src, atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_dst_to_src_precomputed, patch_dst_to_src, atol=1e-4, rtol=1e-4)
# projected should be equal as initial
- error = utils.compute_patch_error(patch_src, patch_dst_to_src, height, width)
+ error = compute_patch_abs_error(patch_src, patch_dst_to_src, height, width)
assert error.item() < self.threshold
@@ -231,27 +238,25 @@ class TestHomographyWarper:
patch_dst, _torch_inverse_cast(dst_homo_src_i), (height, width), align_corners=True
)
- assert_close(patch_dst_to_src, patch_dst_to_src_functional, atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_dst_to_src, patch_dst_to_src_functional, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_shape", [(1, 1, 7, 5), (2, 3, 8, 5), (1, 1, 7, 16)])
- def test_gradcheck(self, batch_shape, device, dtype):
+ def test_gradcheck(self, batch_shape, device):
+ dtype = torch.float64
# generate input data
eye_size = 3 # identity 3x3
# create checkerboard
patch_src = torch.rand(batch_shape, device=device, dtype=dtype)
- patch_src = utils.tensor_to_gradcheck_var(patch_src) # to var
# create base homography
batch_size, _, height, width = patch_src.shape
- dst_homo_src = utils.create_eye_batch(batch_size, eye_size, device=device, dtype=dtype)
- dst_homo_src = utils.tensor_to_gradcheck_var(dst_homo_src, requires_grad=False) # to var
+ dst_homo_src = eye_like(eye_size, patch_src)
# instantiate warper
warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=True)
-
# evaluate function gradient
- assert gradcheck(warper, (patch_src, dst_homo_src), nondet_tol=1e-8, raise_exception=True, fast_mode=True)
+ self.gradcheck(warper, (patch_src, dst_homo_src), requires_grad=(True, False), nondet_tol=1e-8)
@pytest.mark.parametrize("batch_size", [1, 2, 3])
@pytest.mark.parametrize("align_corners", [True, False])
@@ -264,7 +269,7 @@ class TestHomographyWarper:
patch_src = torch.rand(batch_size, 1, height, width, device=device, dtype=dtype)
# create base homography
- dst_homo_src = utils.create_eye_batch(batch_size, eye_size, device=device, dtype=dtype)
+ dst_homo_src = eye_like(eye_size, patch_src)
for _ in range(self.num_tests):
# generate homography noise
@@ -288,10 +293,10 @@ class TestHomographyWarper:
normalized_coordinates=normalized_coordinates,
)
- assert_close(patch_dst, patch_dst_optimized, atol=1e-4, rtol=1e-4)
+ self.assert_close(patch_dst, patch_dst_optimized, atol=1e-4, rtol=1e-4)
-class TestHomographyNormalTransform:
+class TestHomographyNormalTransform(BaseTester):
expected_2d_0 = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2.0, -1.0], [0.0, 0.0, 1.0]]])
expected_2d_1 = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2e14, -1.0], [0.0, 0.0, 1.0]]])
@@ -308,7 +313,7 @@ class TestHomographyNormalTransform:
def test_transform2d(self, height, width, expected, device, dtype):
output = kornia.geometry.conversions.normal_transform_pixel(height, width, device=device, dtype=dtype)
- assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("height", [1, 2, 5])
@pytest.mark.parametrize("width", [1, 2, 5])
@@ -322,12 +327,12 @@ class TestHomographyNormalTransform:
expected = torch.tensor([[-1.0, -1.0], [1.0, 1.0]], device=device, dtype=dtype)
transform = kornia.geometry.conversions.normal_transform_pixel(height, width, device=device, dtype=dtype)
output = kornia.geometry.linalg.transform_points(transform, input)
- assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("height,width,depth,expected", [(2, 6, 4, expected_3d_0), (1, 6, 4, expected_3d_1)])
def test_transform3d(self, height, width, depth, expected, device, dtype):
output = kornia.geometry.conversions.normal_transform_pixel3d(depth, height, width, device=device, dtype=dtype)
- assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("height", [1, 2, 5])
@pytest.mark.parametrize("width", [1, 2, 5])
@@ -344,10 +349,10 @@ class TestHomographyNormalTransform:
depth, height, width, device=device, dtype=dtype
)
output = kornia.geometry.linalg.transform_points(transform, input)
- assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ self.assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
-class TestHomographyWarper3D:
+class TestHomographyWarper3D(BaseTester):
num_tests = 10
threshold = 0.1
@@ -355,27 +360,31 @@ class TestHomographyWarper3D:
def test_normalize_homography_identity(self, batch_size, device, dtype):
# create input data
input_shape = (4, 8, 5)
- dst_homo_src = utils.create_eye_batch(batch_size=batch_size, eye_size=4).to(device=device, dtype=dtype)
res = torch.tensor(
[[[0.5000, 0.0, 0.0, -1.0], [0.0, 0.2857, 0.0, -1.0], [0.0, 0.0, 0.6667, -1.0], [0.0, 0.0, 0.0, 1.0]]],
device=device,
dtype=dtype,
)
- norm = kornia.geometry.conversions.normal_transform_pixel3d(input_shape[0], input_shape[1], input_shape[2]).to(
- device=device, dtype=dtype
- )
- assert_close(norm, res, rtol=1e-4, atol=1e-4)
+ norm = kornia.geometry.conversions.normal_transform_pixel3d(
+ input_shape[0],
+ input_shape[1],
+ input_shape[2],
+ ).to(device=device, dtype=dtype)
+
+ dst_homo_src = eye_like(4, norm.expand(batch_size, -1, -1, -1))
+
+ self.assert_close(norm, res, rtol=1e-4, atol=1e-4)
norm_homo = kornia.geometry.conversions.normalize_homography3d(dst_homo_src, input_shape, input_shape).to(
device=device, dtype=dtype
)
- assert_close(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
+ self.assert_close(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
norm_homo = kornia.geometry.conversions.normalize_homography3d(dst_homo_src, input_shape, input_shape).to(
device=device, dtype=dtype
)
- assert_close(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
+ self.assert_close(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
# change output scale
norm_homo = kornia.geometry.conversions.normalize_homography3d(
@@ -386,7 +395,8 @@ class TestHomographyWarper3D:
device=device,
dtype=dtype,
).repeat(batch_size, 1, 1)
- assert_close(norm_homo, res, rtol=1e-4, atol=1e-4)
+
+ self.assert_close(norm_homo, res, rtol=1e-4, atol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 3])
def test_normalize_homography_general(self, batch_size, device, dtype):
@@ -406,20 +416,23 @@ class TestHomographyWarper3D:
device=device,
dtype=dtype,
).expand(batch_size, -1, -1)
- assert_close(norm_homo, res)
+ self.assert_close(norm_homo, res)
@pytest.mark.parametrize("offset", [1, 3, 7])
@pytest.mark.parametrize("shape", [(4, 5, 6), (2, 4, 6), (4, 3, 9), (5, 7, 8)])
def test_warp_grid_translation(self, shape, offset, device, dtype):
# create input data
depth, height, width = shape
- dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=4, device=device, dtype=dtype)
+ grid = kornia.utils.create_meshgrid3d(
+ depth, height, width, normalized_coordinates=False, dtype=dtype, device=device
+ )
+ dst_homo_src = eye_like(4, grid)
dst_homo_src[..., 0, 3] = offset # apply offset in x
- grid = kornia.utils.create_meshgrid3d(depth, height, width, normalized_coordinates=False)
+
flow = kornia.geometry.transform.warp_grid3d(grid, dst_homo_src)
# the grid the src plus the offset should be equal to the flow
# on the x-axis, y-axis remains the same.
- assert_close(grid[..., 0].to(device=device, dtype=dtype) + offset, flow[..., 0], atol=1e-4, rtol=1e-4)
- assert_close(grid[..., 1].to(device=device, dtype=dtype), flow[..., 1], atol=1e-4, rtol=1e-4)
- assert_close(grid[..., 2].to(device=device, dtype=dtype), flow[..., 2], atol=1e-4, rtol=1e-4)
+ self.assert_close(grid[..., 0].to(device=device, dtype=dtype) + offset, flow[..., 0], atol=1e-4, rtol=1e-4)
+ self.assert_close(grid[..., 1].to(device=device, dtype=dtype), flow[..., 1], atol=1e-4, rtol=1e-4)
+ self.assert_close(grid[..., 2].to(device=device, dtype=dtype), flow[..., 2], atol=1e-4, rtol=1e-4)
diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.py
index 7bf3a8223..6fb145a99 100644
--- a/tests/geometry/transform/test_image_registrator.py
+++ b/tests/geometry/transform/test_image_registrator.py
@@ -4,26 +4,27 @@ import pytest
import torch
import kornia
-import kornia.testing as utils # test utils
from kornia.geometry import transform_points
from kornia.geometry.conversions import denormalize_homography
from kornia.geometry.transform import ImageRegistrator
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version
+from testing.base import BaseTester
+from testing.casts import dict_to
-class TestSimilarity:
+
+class TestSimilarity(BaseTester):
def test_smoke(self, device, dtype):
expected = torch.eye(3, device=device, dtype=dtype)[None]
for r, sc, sh in zip([True, False], [True, False], [True, False]):
sim = kornia.geometry.transform.Similarity(r, sc, sh).to(device, dtype)
- assert_close(sim(), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(sim(), expected, atol=1e-4, rtol=1e-4)
def test_smoke_inverse(self, device, dtype):
expected = torch.eye(3, device=device, dtype=dtype)[None]
for r, sc, sh in zip([True, False], [True, False], [True, False]):
s = kornia.geometry.transform.Similarity(r, sc, sh).to(device, dtype)
- assert_close(s.forward_inverse(), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(s.forward_inverse(), expected, atol=1e-4, rtol=1e-4)
def test_scale(self, device, dtype):
sc = 0.5
@@ -31,8 +32,8 @@ class TestSimilarity:
sim.scale.data *= sc
expected = torch.tensor([[0.5, 0, 0.0], [0, 0.5, 0], [0, 0, 1]], device=device, dtype=dtype)[None]
inv_expected = torch.tensor([[2.0, 0, 0.0], [0, 2.0, 0], [0, 0, 1]], device=device, dtype=dtype)[None]
- assert_close(sim.forward_inverse(), inv_expected, atol=1e-4, rtol=1e-4)
- assert_close(sim(), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(sim.forward_inverse(), inv_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(sim(), expected, atol=1e-4, rtol=1e-4)
def test_repr(self, device, dtype):
for r, sc, sh in zip([True, False], [True, False], [True, False]):
@@ -40,23 +41,23 @@ class TestSimilarity:
assert s is not None
-class TestHomography:
+class TestHomography(BaseTester):
def test_smoke(self, device, dtype):
expected = torch.eye(3, device=device, dtype=dtype)[None]
h = kornia.geometry.transform.Homography().to(device, dtype)
- assert_close(h(), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(h(), expected, atol=1e-4, rtol=1e-4)
def test_smoke_inverse(self, device, dtype):
expected = torch.eye(3, device=device, dtype=dtype)[None]
h = kornia.geometry.transform.Homography().to(device, dtype)
- assert_close(h.forward_inverse(), expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(h.forward_inverse(), expected, atol=1e-4, rtol=1e-4)
def test_repr(self, device, dtype):
h = kornia.geometry.transform.Homography().to(device, dtype)
assert h is not None
-class TestImageRegistrator:
+class TestImageRegistrator(BaseTester):
@pytest.mark.parametrize("model_type", ["homography", "similarity", "translation", "scale", "rotation"])
def test_smoke(self, device, dtype, model_type):
ir = kornia.geometry.transform.ImageRegistrator(model_type).to(device, dtype)
@@ -73,7 +74,7 @@ class TestImageRegistrator:
img_dst = kornia.geometry.homography_warp(img_src, homography, (height, width), align_corners=False)
IR = ImageRegistrator("Similarity", num_iterations=500, lr=3e-4, pyramid_levels=2).to(device, dtype)
model = IR.register(img_src, img_dst)
- assert_close(model, homography, atol=1e-3, rtol=1e-3)
+ self.assert_close(model, homography, atol=1e-3, rtol=1e-3)
model, intermediate = IR.register(img_src, img_dst, output_intermediate_models=True)
assert len(intermediate) == 2
@@ -83,7 +84,7 @@ class TestImageRegistrator:
torch_version() == "2.0.0" and "win" in sys.platform, reason="Tensor not matching on win with torch 2.0"
)
def test_registration_real(self, device, dtype, data):
- data_dev = utils.dict_to(data, device, dtype)
+ data_dev = dict_to(data, device, dtype)
IR = ImageRegistrator("homography", num_iterations=1200, lr=2e-2, pyramid_levels=5).to(device, dtype)
model = IR.register(data_dev["image0"], data_dev["image1"])
homography_gt = torch.inverse(data_dev["H_gt"])
@@ -100,4 +101,4 @@ class TestImageRegistrator:
# The tolerance is huge, because the error is in pixels
# and transformation is quite significant, so
# 15 px reprojection error is not super huge
- assert_close(bbox_in_2_gt, bbox_in_2_gt_est, atol=15, rtol=0.1)
+ self.assert_close(bbox_in_2_gt, bbox_in_2_gt_est, atol=15, rtol=0.1)
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 7ce7a571b..957798af0 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -2,14 +2,13 @@ import sys
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version, torch_version_lt
from kornia.utils.helpers import _torch_inverse_cast
+from testing.base import BaseTester
+
class DummyNNModule(torch.nn.Module):
def __init__(self, h: int, w: int, align_corners: bool, padding_mode: str):
@@ -21,7 +20,7 @@ class DummyNNModule(torch.nn.Module):
return kornia.geometry.transform.warp_affine(x, y, dsize=(self.h, self.w), align_corners=False)
-class TestGetPerspectiveTransform:
+class TestGetPerspectiveTransform(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_smoke(self, device, dtype, batch_size):
points_src = torch.rand(batch_size, 4, 2, device=device, dtype=dtype)
@@ -70,7 +69,7 @@ class TestGetPerspectiveTransform:
# compute transform from source to target
dst_trans_src = kornia.geometry.get_perspective_transform(points_src, points_dst)
points_dst_hat = kornia.geometry.transform_points(dst_trans_src, points_src)
- assert_close(points_dst, points_dst_hat)
+ self.assert_close(points_dst, points_dst_hat)
def test_hflip(self, device, dtype):
points_src = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype)
@@ -82,7 +81,7 @@ class TestGetPerspectiveTransform:
point_left = torch.tensor([[[0.0, 0.0]]], device=device, dtype=dtype)
point_right = torch.tensor([[[1.0, 0.0]]], device=device, dtype=dtype)
- assert_close(kornia.geometry.transform_points(dst_trans_src, point_left), point_right)
+ self.assert_close(kornia.geometry.transform_points(dst_trans_src, point_left), point_right)
def test_dynamo(self, device, dtype, torch_optimizer):
points_src = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -91,77 +90,99 @@ class TestGetPerspectiveTransform:
op = kornia.geometry.get_perspective_transform
op_optimized = torch_optimizer(op)
- assert_close(op(points_src, points_dst), op_optimized(points_src, points_dst))
+ self.assert_close(op(points_src, points_dst), op_optimized(points_src, points_dst))
@pytest.mark.skipif(torch_version_lt(1, 11, 0), reason="backward for LSTSQ not supported in pytorch < 1.11.0")
def test_gradcheck(self, device):
# compute gradient check
points_src = torch.rand(1, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
points_dst = torch.rand(1, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(
- kornia.geometry.get_perspective_transform, (points_src, points_dst), raise_exception=True, fast_mode=True
- )
+ self.gradcheck(kornia.geometry.get_perspective_transform, (points_src, points_dst))
+
+
+class TestRotationMatrix2d(BaseTester):
+ @pytest.mark.parametrize("batch_size", [1, 2, 5])
+ def test_90deg_rotation(self, batch_size, device, dtype):
+ # generate input data
+ center_base = torch.zeros(batch_size, 2, device=device, dtype=dtype)
+ angle_base = torch.ones(batch_size, device=device, dtype=dtype)
+ scale_base = torch.ones(batch_size, 2, device=device, dtype=dtype)
+
+ # 90 deg rotation
+ center = center_base
+ angle = 90.0 * angle_base
+ scale = scale_base
+ M = kornia.geometry.get_rotation_matrix2d(center, angle, scale)
+
+ for i in range(batch_size):
+ self.assert_close(M[i, 0, 0].item(), 0.0, rtol=1e-4, atol=1e-4)
+ self.assert_close(M[i, 0, 1].item(), 1.0, rtol=1e-4, atol=1e-4)
+ self.assert_close(M[i, 1, 0].item(), -1.0, rtol=1e-4, atol=1e-4)
+ self.assert_close(M[i, 1, 1].item(), 0.0, rtol=1e-4, atol=1e-4)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 5])
+ def test_rotation_90deg_and_scale(self, batch_size, device, dtype):
+ # generate input data
+ center_base = torch.zeros(batch_size, 2, device=device, dtype=dtype)
+ angle_base = torch.ones(batch_size, device=device, dtype=dtype)
+ scale_base = torch.ones(batch_size, 2, device=device, dtype=dtype)
+
+ # 90 deg rotation + 2x scale
+ center = center_base
+ angle = 90.0 * angle_base
+ scale = 2.0 * scale_base
+ M = kornia.geometry.get_rotation_matrix2d(center, angle, scale)
+
+ for i in range(batch_size):
+ self.assert_close(M[i, 0, 0].item(), 0.0, rtol=1e-4, atol=1e-4)
+ self.assert_close(M[i, 0, 1].item(), 2.0, rtol=1e-4, atol=1e-4)
+ self.assert_close(M[i, 1, 0].item(), -2.0, rtol=1e-4, atol=1e-4)
+ self.assert_close(M[i, 1, 1].item(), 0.0, rtol=1e-4, atol=1e-4)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 5])
+ def test_rotation_45deg(self, batch_size, device, dtype):
+ # generate input data
+ center_base = torch.zeros(batch_size, 2, device=device, dtype=dtype)
+ angle_base = torch.ones(batch_size, device=device, dtype=dtype)
+ scale_base = torch.ones(batch_size, 2, device=device, dtype=dtype)
+
+ # 45 deg rotation
+ center = center_base
+ angle = 45.0 * angle_base
+ scale = scale_base
+
+ M = kornia.geometry.get_rotation_matrix2d(center, angle, scale)
+
+ for i in range(batch_size):
+ self.assert_close(M[i, 0, 0].item(), 0.7071)
+ self.assert_close(M[i, 0, 1].item(), 0.7071)
+ self.assert_close(M[i, 1, 0].item(), -0.7071)
+ self.assert_close(M[i, 1, 1].item(), 0.7071)
+
+ @pytest.mark.parametrize("batch_size", [1])
+ def test_gradcheck(self, batch_size, device):
+ dtype = torch.float64
+ # generate input data
+ center_base = torch.zeros(batch_size, 2, device=device, dtype=dtype)
+ angle_base = torch.ones(batch_size, device=device, dtype=dtype)
+ scale_base = torch.ones(batch_size, 2, device=device, dtype=dtype)
+ # 45 deg rotation
+ center = center_base
+ angle = 45.0 * angle_base
+ scale = scale_base
[email protected]("batch_size", [1, 2, 5])
-def test_rotation_matrix2d(batch_size, device, dtype):
- # generate input data
- center_base = torch.zeros(batch_size, 2, device=device, dtype=dtype)
- angle_base = torch.ones(batch_size, device=device, dtype=dtype)
- scale_base = torch.ones(batch_size, 2, device=device, dtype=dtype)
-
- # 90 deg rotation
- center = center_base
- angle = 90.0 * angle_base
- scale = scale_base
- M = kornia.geometry.get_rotation_matrix2d(center, angle, scale)
-
- for i in range(batch_size):
- assert_close(M[i, 0, 0].item(), 0.0, rtol=1e-4, atol=1e-4)
- assert_close(M[i, 0, 1].item(), 1.0, rtol=1e-4, atol=1e-4)
- assert_close(M[i, 1, 0].item(), -1.0, rtol=1e-4, atol=1e-4)
- assert_close(M[i, 1, 1].item(), 0.0, rtol=1e-4, atol=1e-4)
-
- # 90 deg rotation + 2x scale
- center = center_base
- angle = 90.0 * angle_base
- scale = 2.0 * scale_base
- M = kornia.geometry.get_rotation_matrix2d(center, angle, scale)
-
- for i in range(batch_size):
- assert_close(M[i, 0, 0].item(), 0.0, rtol=1e-4, atol=1e-4)
- assert_close(M[i, 0, 1].item(), 2.0, rtol=1e-4, atol=1e-4)
- assert_close(M[i, 1, 0].item(), -2.0, rtol=1e-4, atol=1e-4)
- assert_close(M[i, 1, 1].item(), 0.0, rtol=1e-4, atol=1e-4)
-
- # 45 deg rotation
- center = center_base
- angle = 45.0 * angle_base
- scale = scale_base
- M = kornia.geometry.get_rotation_matrix2d(center, angle, scale)
-
- for i in range(batch_size):
- assert_close(M[i, 0, 0].item(), 0.7071)
- assert_close(M[i, 0, 1].item(), 0.7071)
- assert_close(M[i, 1, 0].item(), -0.7071)
- assert_close(M[i, 1, 1].item(), 0.7071)
-
- # evaluate function gradient
- center = utils.tensor_to_gradcheck_var(center) # to var
- angle = utils.tensor_to_gradcheck_var(angle) # to var
- scale = utils.tensor_to_gradcheck_var(scale) # to var
- assert gradcheck(
- kornia.geometry.get_rotation_matrix2d, (center, angle, scale), raise_exception=True, fast_mode=True
- )
-
-
-class TestWarpAffine:
+ # evaluate function gradient
+ self.gradcheck(kornia.geometry.get_rotation_matrix2d, (center, angle, scale))
+
+
+class TestWarpAffine(BaseTester):
def test_smoke(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 4
aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None] # 1x2x3
img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img_a = kornia.geometry.warp_affine(img_b, aff_ab, (height, width))
- assert_close(img_b, img_a)
+ self.assert_close(img_b, img_a)
@pytest.mark.parametrize("batch_shape", ([1, 3, 2, 5], [2, 4, 3, 4], [3, 5, 6, 2]))
@pytest.mark.parametrize("out_shape", ([2, 5], [3, 4], [6, 2]))
@@ -205,7 +226,7 @@ class TestWarpAffine:
# Same as opencv: cv2.warpAffine(kornia.tensor_to_image(img_b), aff_ab[0].numpy(), (w, h))
img_a = kornia.geometry.warp_affine(img_b, aff_ab, (h, w))
- assert_close(img_a, expected)
+ self.assert_close(img_a, expected)
def test_rotation_inverse(self, device, dtype):
h, w = 4, 4
@@ -226,7 +247,7 @@ class TestWarpAffine:
aff_ab_3x3 = kornia.geometry.conversions.convert_affinematrix_to_homography(aff_ab_2x3)
aff_ba_2x3 = _torch_inverse_cast(aff_ab_3x3)[..., :2, :]
img_b_hat = kornia.geometry.warp_affine(img_a, aff_ba_2x3, (h, w))
- assert_close(img_b_hat, img_b, atol=1e-3, rtol=1e-3)
+ self.assert_close(img_b_hat, img_b, atol=1e-3, rtol=1e-3)
def test_dynamo(self, device, dtype, torch_optimizer):
aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None]
@@ -234,17 +255,13 @@ class TestWarpAffine:
args = (img, aff_ab, (4, 5))
op = kornia.geometry.warp_affine
op_optimized = torch_optimizer(op)
- assert_close(op(*args), op_optimized(*args))
+ self.assert_close(op(*args), op_optimized(*args))
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 3, 4
- aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None] + 1e-6 # 1x2x3
- img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- aff_ab = utils.tensor_to_gradcheck_var(aff_ab) # to var
- img_b = utils.tensor_to_gradcheck_var(img_b) # to var
- assert gradcheck(
- kornia.geometry.warp_affine, (img_b, aff_ab, (height, width)), raise_exception=True, fast_mode=True
- )
+ aff_ab = torch.eye(2, 3, device=device, dtype=torch.float64)[None] + 1e-6 # 1x2x3
+ img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.warp_affine, (img_b, aff_ab, (height, width)))
def test_fill_padding_translation(self, device, dtype):
offset = 1.0
@@ -260,8 +277,8 @@ class TestWarpAffine:
img_a = kornia.geometry.warp_affine(img_b, aff_ab, (h, w), padding_mode="fill", fill_value=fill_value)
top_row_mean = img_a[..., :1, :].mean(dim=[0, 2, 3])
first_col_mean = img_a[..., :1].mean(dim=[0, 2, 3])
- assert_close(top_row_mean, fill_value)
- assert_close(first_col_mean, fill_value)
+ self.assert_close(top_row_mean, fill_value)
+ self.assert_close(first_col_mean, fill_value)
@pytest.mark.parametrize("num_channels", [1, 3, 5])
def test_fill_padding_channels(self, device, dtype, num_channels):
@@ -276,7 +293,7 @@ class TestWarpAffine:
img_a = kornia.geometry.warp_affine(img_b, aff_ab, (h, w), padding_mode="fill", fill_value=fill_value)
- assert_close(img_a[:, :, :1, :1].squeeze(), fill_value.squeeze())
+ self.assert_close(img_a[:, :, :1, :1].squeeze(), fill_value.squeeze())
@pytest.mark.parametrize("align_corners", (True, False))
@pytest.mark.parametrize("padding_mode", ("zeros", "fill"))
@@ -291,16 +308,16 @@ class TestWarpAffine:
script_net = torch.jit.script(net)
assert isinstance(script_net, torch.jit.ScriptModule)
- assert_close(script_net(img_b, aff_ab), net(img_b, aff_ab))
+ self.assert_close(script_net(img_b, aff_ab), net(img_b, aff_ab))
-class TestWarpPerspective:
+class TestWarpPerspective(BaseTester):
def test_smoke(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 4
img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
H_ab = kornia.eye_like(3, img_b)
img_a = kornia.geometry.warp_perspective(img_b, H_ab, (height, width))
- assert_close(img_b, img_a)
+ self.assert_close(img_b, img_a)
@pytest.mark.parametrize("batch_shape", ([1, 3, 2, 5], [2, 4, 3, 4], [3, 5, 6, 2]))
@pytest.mark.parametrize("out_shape", ([2, 5], [3, 4], [6, 2]))
@@ -344,7 +361,7 @@ class TestWarpPerspective:
# Same as opencv: cv2.warpPerspective(kornia.tensor_to_image(img_b), homo_ab[0].numpy(), (w, h))
img_a = kornia.geometry.warp_perspective(img_b, homo_ab, (h, w))
- assert_close(img_a, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(img_a, expected, atol=1e-4, rtol=1e-4)
def test_translation_normalized(self, device, dtype):
offset = 1.0
@@ -359,7 +376,7 @@ class TestWarpPerspective:
# Same as opencv: cv2.warpPerspective(kornia.tensor_to_image(img_b), homo_ab[0].numpy(), (w, h))
img_a = kornia.geometry.transform.homography_warp(img_b, homo_ab, (h, w), normalized_homography=False)
- assert_close(img_a, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(img_a, expected, atol=1e-4, rtol=1e-4)
def test_rotation_inverse(self, device, dtype):
h, w = 4, 4
@@ -381,7 +398,7 @@ class TestWarpPerspective:
# invert the transform
H_ba = _torch_inverse_cast(H_ab)
img_b_hat = kornia.geometry.warp_perspective(img_a, H_ba, (h, w))
- assert_close(img_b_hat, img_b, rtol=1e-4, atol=1e-4)
+ self.assert_close(img_b_hat, img_b, rtol=1e-4, atol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 5])
@pytest.mark.parametrize("channels", [1, 5])
@@ -414,7 +431,7 @@ class TestWarpPerspective:
# warp and assert
patch_warped = kornia.geometry.warp_perspective(patch, dst_trans_src, (dst_h, dst_w))
- assert_close(patch_warped, expected)
+ self.assert_close(patch_warped, expected)
def test_crop_center_resize(self, device, dtype):
# generate input data
@@ -455,7 +472,7 @@ class TestWarpPerspective:
# warp and assert
patch_warped = kornia.geometry.warp_perspective(patch, dst_trans_src, (dst_h, dst_w))
- assert_close(patch_warped, expected)
+ self.assert_close(patch_warped, expected)
def test_dynamo(self, device, dtype, torch_optimizer):
if dtype == torch.float64 and torch_version() in {"2.0.0", "2.0.1"} and sys.platform == "linux":
@@ -465,17 +482,15 @@ class TestWarpPerspective:
args = (img, H_ab, (4, 5))
op = kornia.geometry.warp_perspective
op_optimized = torch_optimizer(op)
- assert_close(op(*args), op_optimized(*args))
+ self.assert_close(op(*args), op_optimized(*args))
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 3, 4
- img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
+ img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
H_ab = kornia.eye_like(3, img_b)
- img_b = utils.tensor_to_gradcheck_var(img_b) # to var
# TODO(dmytro/edgar): firgure out why gradient don't propagate for the tranaform
- H_ab = utils.tensor_to_gradcheck_var(H_ab, requires_grad=False) # to var
- assert gradcheck(
- kornia.geometry.warp_perspective, (img_b, H_ab, (height, width)), raise_exception=True, fast_mode=True
+ self.gradcheck(
+ kornia.geometry.warp_perspective, (img_b, H_ab, (height, width)), requires_grad=(True, False, False)
)
def test_fill_padding_translation(self, device, dtype):
@@ -492,11 +507,11 @@ class TestWarpPerspective:
img_a = kornia.geometry.warp_perspective(img_b, homo_ab, (h, w), padding_mode="fill", fill_value=fill_value)
top_row_mean = img_a[..., :1, :].mean(dim=[0, 2, 3])
first_col_mean = img_a[..., :1].mean(dim=[0, 2, 3])
- assert_close(top_row_mean, fill_value)
- assert_close(first_col_mean, fill_value)
+ self.assert_close(top_row_mean, fill_value)
+ self.assert_close(first_col_mean, fill_value)
-class TestRemap:
+class TestRemap(BaseTester):
def test_smoke(self, device, dtype):
height, width = 3, 4
input_org = torch.ones(1, 1, height, width, device=device, dtype=dtype)
@@ -504,7 +519,7 @@ class TestRemap:
input_warped = kornia.geometry.remap(
input_org, grid[..., 0], grid[..., 1], normalized_coordinates=False, align_corners=True
)
- assert_close(input_org, input_warped, rtol=1e-4, atol=1e-4)
+ self.assert_close(input_org, input_warped, rtol=1e-4, atol=1e-4)
def test_different_size(self, device, dtype):
height, width = 3, 4
@@ -527,7 +542,7 @@ class TestRemap:
grid += 1.0 # apply shift in both x/y direction
input_warped = kornia.geometry.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
- assert_close(input_warped, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(input_warped, expected, rtol=1e-4, atol=1e-4)
def test_shift_batch(self, device, dtype):
height, width = 3, 4
@@ -551,7 +566,7 @@ class TestRemap:
grid[1, ..., 1] += 1.0 # apply shift in the y direction
input_warped = kornia.geometry.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
- assert_close(input_warped, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(input_warped, expected, rtol=1e-4, atol=1e-4)
def test_shift_batch_broadcast(self, device, dtype):
height, width = 3, 4
@@ -566,7 +581,7 @@ class TestRemap:
grid += 1.0 # apply shift in both x/y direction
input_warped = kornia.geometry.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
- assert_close(input_warped, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(input_warped, expected, rtol=1e-4, atol=1e-4)
def test_normalized_coordinates(self, device, dtype):
height, width = 3, 4
@@ -586,21 +601,20 @@ class TestRemap:
input_warped = kornia.geometry.remap(
inp, grid[..., 0], grid[..., 1], align_corners=True, normalized_coordinates=normalized_coordinates
)
- assert_close(input_warped, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(input_warped, expected, rtol=1e-4, atol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 3, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
- grid = utils.tensor_to_gradcheck_var(grid, requires_grad=False) # to var
+ grid = kornia.utils.create_meshgrid(
+ height, width, normalized_coordinates=False, device=device, dtype=torch.float64
+ )
- assert gradcheck(
+ self.gradcheck(
kornia.geometry.remap,
(img, grid[..., 0], grid[..., 1], "bilinear", "zeros", True),
- raise_exception=True,
- fast_mode=True,
+ requires_grad=(True, False, False, False, False, False),
)
@pytest.mark.skip(reason="Not fully support dynamo")
@@ -618,14 +632,14 @@ class TestRemap:
inputs = (img, grid[..., 0], grid[..., 1], "bilinear", "zeros", True)
actual = op_script(*inputs)
expected = op(*inputs)
- assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
-class TestInvertAffineTransform:
+class TestInvertAffineTransform(BaseTester):
def test_smoke(self, device, dtype):
matrix = torch.eye(2, 3, device=device, dtype=dtype)[None]
matrix_inv = kornia.geometry.invert_affine_transform(matrix)
- assert_close(matrix, matrix_inv, rtol=1e-4, atol=1e-4)
+ self.assert_close(matrix, matrix_inv, rtol=1e-4, atol=1e-4)
def test_rot90(self, device, dtype):
angle = torch.tensor([90.0], device=device, dtype=dtype)
@@ -634,7 +648,7 @@ class TestInvertAffineTransform:
expected = torch.tensor([[[0.0, -1.0, 0.0], [1.0, 0.0, 0.0]]], device=device, dtype=dtype)
matrix = kornia.geometry.get_rotation_matrix2d(center, angle, scale)
matrix_inv = kornia.geometry.invert_affine_transform(matrix)
- assert_close(matrix_inv, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(matrix_inv, expected, rtol=1e-4, atol=1e-4)
def test_rot90_batch(self, device, dtype):
angle = torch.tensor([90.0], device=device, dtype=dtype)
@@ -643,12 +657,11 @@ class TestInvertAffineTransform:
expected = torch.tensor([[[0.0, -1.0, 0.0], [1.0, 0.0, 0.0]]], device=device, dtype=dtype).repeat(2, 1, 1)
matrix = kornia.geometry.get_rotation_matrix2d(center, angle, scale).repeat(2, 1, 1)
matrix_inv = kornia.geometry.invert_affine_transform(matrix)
- assert_close(matrix_inv, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(matrix_inv, expected, rtol=1e-4, atol=1e-4)
- def test_gradcheck(self, device, dtype):
- matrix = torch.eye(2, 3, device=device, dtype=dtype)[None]
- matrix = utils.tensor_to_gradcheck_var(matrix) # to var
- assert gradcheck(kornia.geometry.invert_affine_transform, (matrix,), raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, device):
+ matrix = torch.eye(2, 3, device=device, dtype=torch.float64)[None]
+ self.gradcheck(kornia.geometry.invert_affine_transform, (matrix,))
def test_dynamo(self, device, dtype, torch_optimizer):
op = kornia.geometry.invert_affine_transform
@@ -657,4 +670,4 @@ class TestInvertAffineTransform:
matrix = torch.eye(2, 3, device=device, dtype=dtype)[None]
actual = op_script(matrix)
expected = op(matrix)
- assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index caa0d6ffc..07ab1a3ab 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -1,15 +1,14 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
import kornia.geometry.transform as proj
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
from kornia.utils.helpers import _torch_inverse_cast
+from testing.base import BaseTester
-class TestWarpAffine3d:
+
+class TestWarpAffine3d(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.rand(1, 3, 3, 4, 5, device=device, dtype=dtype)
P = torch.rand(1, 3, 4, device=device, dtype=dtype)
@@ -30,7 +29,7 @@ class TestWarpAffine3d:
# generate input data
sample = torch.rand(1, 3, 3, 4, 5, device=device, dtype=torch.float64, requires_grad=True)
P = torch.rand(1, 3, 4, device=device, dtype=torch.float64)
- assert gradcheck(proj.warp_affine3d, (sample, P, (3, 3, 3)), raise_exception=True, fast_mode=True)
+ self.gradcheck(proj.warp_affine3d, (sample, P, (3, 3, 3)))
def test_forth_back(self, device, dtype):
out_shape = (3, 4, 5)
@@ -39,7 +38,7 @@ class TestWarpAffine3d:
P = kornia.geometry.convert_affinematrix_to_homography3d(P)
P_hat = (_torch_inverse_cast(P) @ P)[:, :3]
output = proj.warp_affine3d(sample, P_hat, out_shape, flags="nearest")
- assert_close(output, sample, rtol=1e-4, atol=1e-4)
+ self.assert_close(output, sample, rtol=1e-4, atol=1e-4)
def test_rotate_x(self, device, dtype):
sample = torch.tensor(
@@ -78,7 +77,7 @@ class TestWarpAffine3d:
scales: torch.Tensor = torch.ones_like(angles, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angles, scales)
output = proj.warp_affine3d(sample, P, (3, 3, 3))
- assert_close(output, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(output, expected, rtol=1e-4, atol=1e-4)
def test_rotate_y(self, device, dtype):
sample = torch.tensor(
@@ -117,7 +116,7 @@ class TestWarpAffine3d:
scales: torch.Tensor = torch.ones_like(angles, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angles, scales)
output = proj.warp_affine3d(sample, P, (3, 3, 3))
- assert_close(output, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(output, expected, rtol=1e-4, atol=1e-4)
def test_rotate_z(self, device, dtype):
sample = torch.tensor(
@@ -156,7 +155,7 @@ class TestWarpAffine3d:
scales: torch.Tensor = torch.ones_like(angles, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angles, scales)
output = proj.warp_affine3d(sample, P, (3, 3, 3))
- assert_close(output, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(output, expected, rtol=1e-4, atol=1e-4)
def test_rotate_y_large(self, device, dtype):
"""Rotates 90deg anti-clockwise."""
@@ -206,10 +205,10 @@ class TestWarpAffine3d:
scales: torch.Tensor = torch.ones_like(angles, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angles, scales)
output = proj.warp_affine3d(sample, P, (3, 3, 3))
- assert_close(output, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(output, expected, rtol=1e-4, atol=1e-4)
-class TestGetRotationMatrix3d:
+class TestGetRotationMatrix3d(BaseTester):
def test_smoke(self, device, dtype):
center = torch.rand(1, 3, device=device, dtype=dtype)
angle = torch.rand(1, 3, device=device, dtype=dtype)
@@ -234,7 +233,7 @@ class TestGetRotationMatrix3d:
P_expected = torch.tensor(
[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], device=device, dtype=dtype
).unsqueeze(0)
- assert_close(P, P_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(P, P_expected, atol=1e-4, rtol=1e-4)
def test_rot90x(self, device, dtype):
center = torch.zeros(1, 3, device=device, dtype=dtype)
@@ -244,7 +243,7 @@ class TestGetRotationMatrix3d:
P_expected = torch.tensor(
[[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 1.0, 0.0, 0.0]], device=device, dtype=dtype
).unsqueeze(0)
- assert_close(P, P_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(P, P_expected, atol=1e-4, rtol=1e-4)
def test_rot90y(self, device, dtype):
center = torch.zeros(1, 3, device=device, dtype=dtype)
@@ -254,7 +253,7 @@ class TestGetRotationMatrix3d:
P_expected = torch.tensor(
[[0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype
).unsqueeze(0)
- assert_close(P, P_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(P, P_expected, atol=1e-4, rtol=1e-4)
def test_rot90z(self, device, dtype):
center = torch.zeros(1, 3, device=device, dtype=dtype)
@@ -264,17 +263,17 @@ class TestGetRotationMatrix3d:
P_expected = torch.tensor(
[[0.0, -1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], device=device, dtype=dtype
).unsqueeze(0)
- assert_close(P, P_expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(P, P_expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# generate input data
center = torch.rand(1, 3, device=device, dtype=torch.float64, requires_grad=True)
angle = torch.rand(1, 3, device=device, dtype=torch.float64)
scales: torch.Tensor = torch.ones_like(angle, device=device, dtype=torch.float64)
- assert gradcheck(proj.get_projective_transform, (center, angle, scales), raise_exception=True, fast_mode=True)
+ self.gradcheck(proj.get_projective_transform, (center, angle, scales))
-class TestPerspectiveTransform3D:
+class TestPerspectiveTransform3D(BaseTester):
@pytest.mark.skip("Not working")
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_get_perspective_transform3d(self, batch_size, device, dtype):
@@ -293,16 +292,12 @@ class TestPerspectiveTransform3D:
# TODO: get_perspective_transform3d seems to be correct since it would result in the
# expected output for cropping volumes. Not sure what is going on here.
- assert_close(
+ self.assert_close(
kornia.geometry.linalg.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-4, atol=1e-4
)
# compute gradient check
- points_src = utils.tensor_to_gradcheck_var(points_src) # to var
- points_dst = utils.tensor_to_gradcheck_var(points_dst) # to var
- assert gradcheck(
- kornia.geometry.transform.get_perspective_transform3d, (points_src, points_dst), raise_exception=True
- )
+ self.gradcheck(kornia.geometry.transform.get_perspective_transform3d, (points_src, points_dst), fast_mode=False)
@pytest.mark.parametrize("batch_size", [1, 2])
def test_get_perspective_transform3d_2(self, batch_size, device, dtype):
@@ -357,14 +352,7 @@ class TestPerspectiveTransform3D:
dtype=dtype,
)
- assert_close(out, expected, rtol=1e-4, atol=1e-4)
+ self.assert_close(out, expected, rtol=1e-4, atol=1e-4)
# compute gradient check
- points_src = utils.tensor_to_gradcheck_var(src) # to var
- points_dst = utils.tensor_to_gradcheck_var(dst) # to var
- assert gradcheck(
- kornia.geometry.transform.get_perspective_transform3d,
- (points_src, points_dst),
- raise_exception=True,
- fast_mode=True,
- )
+ self.gradcheck(kornia.geometry.transform.get_perspective_transform3d, (src, dst))
diff --git a/tests/geometry/transform/test_pyramid.py b/tests/geometry/transform/test_pyramid.py
index 92108710b..dbcb340b5 100644
--- a/tests/geometry/transform/test_pyramid.py
+++ b/tests/geometry/transform/test_pyramid.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import BaseTester, assert_close
+from testing.base import BaseTester
-class TestPyrUp:
+
+class TestPyrUp(BaseTester):
def test_shape(self, device, dtype):
inp = torch.zeros(1, 2, 4, 4, device=device, dtype=dtype)
pyr = kornia.geometry.PyrUp()
@@ -18,13 +17,12 @@ class TestPyrUp:
pyr = kornia.geometry.PyrUp()
assert pyr(inp).shape == (2, 2, 8, 8)
- def test_gradcheck(self, device, dtype):
- img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.geometry.pyrup, (img,), nondet_tol=1e-8, raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, device):
+ img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.pyrup, (img,), nondet_tol=1e-8)
-class TestPyrDown:
+class TestPyrDown(BaseTester):
def test_shape(self, device, dtype):
inp = torch.zeros(1, 2, 4, 4, device=device, dtype=dtype)
pyr = kornia.geometry.PyrDown()
@@ -44,16 +42,15 @@ class TestPyrDown:
inp = torch.zeros(1, 1, 6, 6, device=device, dtype=dtype)
inp[:, :, 2:4, 2:4] = 1.0
pyr_out = kornia.geometry.PyrDown()(inp).squeeze()
- assert_close(pyr_out, pyr_out.flip(0))
- assert_close(pyr_out, pyr_out.flip(1))
+ self.assert_close(pyr_out, pyr_out.flip(0))
+ self.assert_close(pyr_out, pyr_out.flip(1))
- def test_gradcheck(self, device, dtype):
- img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.geometry.pyrdown, (img,), nondet_tol=1e-8, raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, device):
+ img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.pyrdown, (img,), nondet_tol=1e-8)
-class TestScalePyramid:
+class TestScalePyramid(BaseTester):
def test_shape_tuple(self, device, dtype):
inp = torch.zeros(3, 2, 41, 41, device=device, dtype=dtype)
SP = kornia.geometry.ScalePyramid(n_levels=1, min_size=30)
@@ -101,22 +98,21 @@ class TestScalePyramid:
for _, pyr_level in enumerate(sp):
for _, img in enumerate(pyr_level):
img = img.squeeze()
- assert_close(img, img.flip(1))
- assert_close(img, img.flip(2))
+ self.assert_close(img, img.flip(1))
+ self.assert_close(img, img.flip(2))
- def test_gradcheck(self, device, dtype):
- img = torch.rand(1, 2, 7, 9, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
+ def test_gradcheck(self, device):
+ img = torch.rand(1, 2, 7, 9, device=device, dtype=torch.float64)
from kornia.geometry import ScalePyramid as SP
def sp_tuple(img):
sp, _, _ = SP()(img)
return tuple(sp)
- assert gradcheck(sp_tuple, (img,), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
+ self.gradcheck(sp_tuple, (img,), nondet_tol=1e-4)
-class TestBuildPyramid:
+class TestBuildPyramid(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.ones(1, 2, 4, 5, device=device, dtype=dtype)
pyramid = kornia.geometry.transform.build_pyramid(sample, max_level=1)
@@ -137,17 +133,14 @@ class TestBuildPyramid:
expected_shape = (batch_size, channels, height // denom, width // denom)
assert img.shape == expected_shape
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
max_level = 1
batch_size, channels, height, width = 1, 2, 7, 9
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.geometry.transform.build_pyramid, (img, max_level), raise_exception=True, fast_mode=True
- )
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.build_pyramid, (img, max_level))
-class TestBuildLaplacianPyramid:
+class TestBuildLaplacianPyramid(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.ones(1, 2, 4, 5, device=device, dtype=dtype)
pyramid = kornia.geometry.transform.build_laplacian_pyramid(sample, max_level=1)
@@ -168,18 +161,11 @@ class TestBuildLaplacianPyramid:
expected_shape = (batch_size, channels, height // denom, width // denom)
assert img.shape == expected_shape
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
max_level = 1
batch_size, channels, height, width = 1, 2, 7, 9
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.geometry.transform.build_laplacian_pyramid,
- (img, max_level),
- nondet_tol=1e-8,
- raise_exception=True,
- fast_mode=True,
- )
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.transform.build_laplacian_pyramid, (img, max_level), nondet_tol=1e-8)
class TestUpscaleDouble(BaseTester):
@@ -211,14 +197,7 @@ class TestUpscaleDouble(BaseTester):
@pytest.mark.grad()
def test_gradcheck(self, device):
x = self.prepare_data((1, 2, 5, 5), device)
- x = utils.tensor_to_gradcheck_var(x)
- assert gradcheck(
- kornia.geometry.transform.upscale_double, (x,), rtol=5e-2, raise_exception=True, fast_mode=True
- )
-
- @pytest.mark.skip(reason="not implemented yet")
- def test_module(self, device, dtype):
- pass
+ self.gradcheck(kornia.geometry.transform.upscale_double, (x,), rtol=5e-2)
@pytest.mark.parametrize("shape", ((5, 5), (2, 5, 5), (1, 2, 5, 5)))
def test_upscale_double_and_back(self, shape, device, dtype):
diff --git a/tests/geometry/transform/test_thin_plate_spline.py b/tests/geometry/transform/test_thin_plate_spline.py
index c42e789a7..d8cfe8b66 100644
--- a/tests/geometry/transform/test_thin_plate_spline.py
+++ b/tests/geometry/transform/test_thin_plate_spline.py
@@ -3,9 +3,10 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version_ge
+from testing.base import assert_close
+
def _sample_points(batch_size, device, dtype=torch.float32):
src = torch.tensor([[[0.0, 0.0], [0.0, 10.0], [10.0, 0.0], [10.0, 10.0], [5.0, 5.0]]], device=device, dtype=dtype)
diff --git a/tests/image/test_image.py b/tests/image/test_image.py
index 1c64f35c8..7f984d089 100644
--- a/tests/image/test_image.py
+++ b/tests/image/test_image.py
@@ -6,9 +6,10 @@ import torch
from kornia.image.base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat
from kornia.image.image import Image
-from kornia.testing import assert_close
from kornia.utils._compat import torch_version_le
+from testing.base import assert_close
+
class TestImage:
def test_smoke(self, device):
diff --git a/tests/integration/test_conversions.py b/tests/integration/test_conversions.py
index 39a910e2d..dbe74f508 100644
--- a/tests/integration/test_conversions.py
+++ b/tests/integration/test_conversions.py
@@ -3,7 +3,8 @@ import pytest
import torch
import kornia
-from kornia.testing import assert_close
+
+from testing.base import assert_close
@pytest.fixture()
diff --git a/tests/integration/test_soft_argmax2d.py b/tests/integration/test_soft_argmax2d.py
index 44911d7d5..f404853d0 100644
--- a/tests/integration/test_soft_argmax2d.py
+++ b/tests/integration/test_soft_argmax2d.py
@@ -5,7 +5,8 @@ import torch
from torch import nn, optim
import kornia
-from kornia.testing import assert_close
+
+from testing.base import assert_close
logger = logging.getLogger(__name__)
diff --git a/tests/losses/test_hd.py b/tests/losses/test_hd.py
index b5490cbb8..a1722851a 100644
--- a/tests/losses/test_hd.py
+++ b/tests/losses/test_hd.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils
-from kornia.testing import assert_close
+from testing.base import BaseTester
-class TestHausdorffLoss:
+
+class TestHausdorffLoss(BaseTester):
@pytest.mark.parametrize("reduction", ["mean", "none", "sum"])
@pytest.mark.parametrize(
"hd,shape", [[kornia.losses.HausdorffERLoss, (10, 10)], [kornia.losses.HausdorffERLoss3D, (10, 10, 10)]]
@@ -57,7 +56,7 @@ class TestHausdorffLoss:
expected = torch.tensor(0.025, device=device, dtype=dtype)
actual = loss(logits, labels)
- assert_close(actual, expected, rtol=0.005, atol=0.005)
+ self.assert_close(actual, expected, rtol=0.005, atol=0.005)
def test_numeric_3d(self, device, dtype):
num_classes = 3
@@ -69,7 +68,7 @@ class TestHausdorffLoss:
expected = torch.tensor(0.011, device=device, dtype=dtype)
actual = loss(logits, labels)
- assert_close(actual, expected, rtol=1e-2, atol=1e-2)
+ self.assert_close(actual, expected, rtol=1e-2, atol=1e-2)
@pytest.mark.parametrize(
"hd,shape", [[kornia.losses.HausdorffERLoss, (5, 5)], [kornia.losses.HausdorffERLoss3D, (5, 5, 5)]]
@@ -80,5 +79,4 @@ class TestHausdorffLoss:
labels = (torch.rand(2, 1, *shape, device=device) * (num_classes - 1)).long()
loss = hd(k=2)
- logits = utils.tensor_to_gradcheck_var(logits) # to var
- assert gradcheck(loss, (logits, labels), raise_exception=True, fast_mode=True)
+ self.gradcheck(loss, (logits, labels), dtypes=[torch.float64, torch.int64])
diff --git a/tests/losses/test_losses.py b/tests/losses/test_losses.py
index f8f662d08..dc1d34ffb 100644
--- a/tests/losses/test_losses.py
+++ b/tests/losses/test_losses.py
@@ -3,14 +3,14 @@ import math
import pytest
import torch
import torch.nn.functional as F
-from torch.autograd import gradcheck
import kornia
-from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
from kornia.utils import torch_meshgrid
+from testing.base import BaseTester
-class TestBinaryFocalLossWithLogits:
+
+class TestBinaryFocalLossWithLogits(BaseTester):
@pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
def test_value_same_as_torch_bce_loss(self, device, dtype, reduction):
logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
@@ -20,7 +20,7 @@ class TestBinaryFocalLossWithLogits:
logits, labels, alpha=None, gamma=0, reduction=reduction
)
torch_bce_loss = F.binary_cross_entropy_with_logits(logits, labels, reduction=reduction)
- assert_close(focal_equivalent_bce_loss, torch_bce_loss)
+ self.assert_close(focal_equivalent_bce_loss, torch_bce_loss)
@pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
def test_value_same_as_torch_bce_loss_pos_weight_weight(self, device, dtype, reduction):
@@ -37,7 +37,7 @@ class TestBinaryFocalLossWithLogits:
torch_bce_loss = F.binary_cross_entropy_with_logits(
logits, labels, reduction=reduction, pos_weight=pos_weight, weight=weight
)
- assert_close(focal_equivalent_bce_loss, torch_bce_loss)
+ self.assert_close(focal_equivalent_bce_loss, torch_bce_loss)
@pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3, 2)), ("mean", ()), ("sum", ())])
@pytest.mark.parametrize("alpha", [None, 0.2, 0.5])
@@ -76,16 +76,15 @@ class TestBinaryFocalLossWithLogits:
args = (0.25, 2.0)
actual = op_optimized(logits, labels, *args)
expected = op(logits, labels, *args)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
- def test_gradcheck(self, device, dtype):
- logits = torch.rand(2, 3, 2).to(device, dtype)
- logits = tensor_to_gradcheck_var(logits) # to var
- labels = torch.rand(2, 3, 2).to(device, dtype)
+ def test_gradcheck(self, device):
+ logits = torch.rand(2, 3, 2, device=device, dtype=torch.float64)
+ labels = torch.rand(2, 3, 2, device=device, dtype=torch.float64)
args = (0.25, 2.0)
op = kornia.losses.binary_focal_loss_with_logits
- assert gradcheck(op, (logits, labels, *args), raise_exception=True, fast_mode=True)
+ self.gradcheck(op, (logits, labels, *args))
def test_module(self, device, dtype):
logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
@@ -94,7 +93,7 @@ class TestBinaryFocalLossWithLogits:
args = (0.25, 2.0)
op = kornia.losses.binary_focal_loss_with_logits
op_module = kornia.losses.BinaryFocalLossWithLogits(*args)
- assert_close(op_module(logits, labels), op(logits, labels, *args))
+ self.assert_close(op_module(logits, labels), op(logits, labels, *args))
def test_numeric_stability(self, device, dtype):
logits = torch.tensor([[100.0, -100]], dtype=dtype, device=device)
@@ -103,10 +102,10 @@ class TestBinaryFocalLossWithLogits:
args = (0.25, 2.0)
actual = kornia.losses.binary_focal_loss_with_logits(logits, labels, *args)
expected = torch.tensor([[0.0, 0.0]], dtype=dtype, device=device)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestFocalLoss:
+class TestFocalLoss(BaseTester):
@pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3, 3, 2)), ("mean", ()), ("sum", ())])
@pytest.mark.parametrize("alpha", [None, 0.2, 0.5])
@pytest.mark.parametrize("gamma", [0.0, 1.0, 2.0])
@@ -152,16 +151,16 @@ class TestFocalLoss:
args = (0.25, 2.0)
actual = op_optimized(logits, labels, *args)
expected = op(logits, labels, *args)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
num_classes = 3
- logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
- logits = tensor_to_gradcheck_var(logits) # to var
- labels = torch.randint(num_classes, (2, 3, 2), device=device)
+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=torch.float64)
+ labels = torch.randint(num_classes, (2, 3, 2), device=device).long()
- args = (0.25, 2.0)
- assert gradcheck(kornia.losses.focal_loss, (logits, labels, *args), raise_exception=True, fast_mode=True)
+ self.gradcheck(
+ kornia.losses.focal_loss, (logits, labels, 0.25, 2.0), dtypes=[torch.float64, torch.int64, None, None]
+ )
def test_module(self, device, dtype):
num_classes = 3
@@ -171,10 +170,10 @@ class TestFocalLoss:
args = (0.25, 2.0)
op = kornia.losses.focal_loss
op_module = kornia.losses.FocalLoss(*args)
- assert_close(op_module(logits, labels), op(logits, labels, *args))
+ self.assert_close(op_module(logits, labels), op(logits, labels, *args))
-class TestTverskyLoss:
+class TestTverskyLoss(BaseTester):
def test_smoke(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -213,18 +212,16 @@ class TestTverskyLoss:
criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5)
loss = criterion(logits, labels)
- assert_close(loss, torch.zeros_like(loss), atol=1e-3, rtol=1e-3)
+ self.assert_close(loss, torch.zeros_like(loss), atol=1e-3, rtol=1e-3)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
num_classes = 3
alpha, beta = 0.5, 0.5 # for tversky loss
- logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
- labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.to(device).long()
+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=torch.float64)
+ labels = torch.randint(0, num_classes, (2, 3, 2), device=device)
- logits = tensor_to_gradcheck_var(logits) # to var
- assert gradcheck(
- kornia.losses.tversky_loss, (logits, labels, alpha, beta), raise_exception=True, fast_mode=True
+ self.gradcheck(
+ kornia.losses.tversky_loss, (logits, labels, alpha, beta), dtypes=[torch.float64, torch.int64, None, None]
)
def test_dynamo(self, device, dtype, torch_optimizer):
@@ -239,7 +236,7 @@ class TestTverskyLoss:
actual = op_optimized(logits, labels, *params)
expected = op(logits, labels, *params)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
def test_module(self, device, dtype):
num_classes = 3
@@ -253,10 +250,10 @@ class TestTverskyLoss:
actual = op_module(logits, labels)
expected = op(logits, labels, *params)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestDiceLoss:
+class TestDiceLoss(BaseTester):
def test_smoke(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -276,7 +273,7 @@ class TestDiceLoss:
criterion = kornia.losses.DiceLoss()
loss = criterion(logits, labels)
- assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
+ self.assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
def test_exception(self):
with pytest.raises(ValueError) as errinf:
@@ -313,7 +310,7 @@ class TestDiceLoss:
criterion = kornia.losses.DiceLoss(average="micro", eps=eps)
loss = criterion(logits, labels)
- assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
+ self.assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
def test_averaging_macro(self, device, dtype):
num_classes = 2
@@ -342,16 +339,13 @@ class TestDiceLoss:
criterion = kornia.losses.DiceLoss(average="macro", eps=eps)
loss = criterion(logits, labels)
- assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
+ self.assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
num_classes = 3
- logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
- labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.to(device).long()
-
- logits = tensor_to_gradcheck_var(logits) # to var
- assert gradcheck(kornia.losses.dice_loss, (logits, labels), raise_exception=True, fast_mode=True)
+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=torch.float64)
+ labels = torch.randint(0, num_classes, (2, 3, 2), device=device)
+ self.gradcheck(kornia.losses.dice_loss, (logits, labels), dtypes=[torch.float64, torch.int64])
def test_dynamo(self, device, dtype, torch_optimizer):
num_classes = 3
@@ -362,7 +356,7 @@ class TestDiceLoss:
op = kornia.losses.dice_loss
op_optimized = torch_optimizer(op)
- assert_close(op(logits, labels), op_optimized(logits, labels))
+ self.assert_close(op(logits, labels), op_optimized(logits, labels))
def test_module(self, device, dtype):
num_classes = 3
@@ -373,10 +367,10 @@ class TestDiceLoss:
op = kornia.losses.dice_loss
op_module = kornia.losses.DiceLoss()
- assert_close(op(logits, labels), op_module(logits, labels))
+ self.assert_close(op(logits, labels), op_module(logits, labels))
-class TestDepthSmoothnessLoss:
+class TestDepthSmoothnessLoss(BaseTester):
@pytest.mark.parametrize("data_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])
def test_smoke(self, device, dtype, data_shape):
image = torch.rand(data_shape, device=device, dtype=dtype)
@@ -423,7 +417,7 @@ class TestDepthSmoothnessLoss:
op = kornia.losses.inverse_depth_smoothness_loss
op_optimized = torch_optimizer(op)
- assert_close(op(image, depth), op_optimized(image, depth))
+ self.assert_close(op(image, depth), op_optimized(image, depth))
def test_module(self, device, dtype):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -432,19 +426,15 @@ class TestDepthSmoothnessLoss:
op = kornia.losses.inverse_depth_smoothness_loss
op_module = kornia.losses.InverseDepthSmoothnessLoss()
- assert_close(op(image, depth), op_module(image, depth))
+ self.assert_close(op(image, depth), op_module(image, depth))
- def test_gradcheck(self, device, dtype):
- image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- depth = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- depth = tensor_to_gradcheck_var(depth) # to var
- image = tensor_to_gradcheck_var(image) # to var
- assert gradcheck(
- kornia.losses.inverse_depth_smoothness_loss, (depth, image), raise_exception=True, fast_mode=True
- )
+ def test_gradcheck(self, device):
+ image = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)
+ depth = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.losses.inverse_depth_smoothness_loss, (depth, image))
-class TestDivergenceLoss:
+class TestDivergenceLoss(BaseTester):
@pytest.mark.parametrize(
"pred,target,expected",
[
@@ -457,7 +447,7 @@ class TestDivergenceLoss:
def test_js_div_loss_2d(self, device, dtype, pred, target, expected):
actual = kornia.losses.js_div_loss_2d(pred.to(device, dtype), target.to(device, dtype))
expected = torch.tensor(expected).to(device, dtype)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
@pytest.mark.parametrize(
"pred,target,expected",
@@ -471,7 +461,7 @@ class TestDivergenceLoss:
def test_kl_div_loss_2d(self, device, dtype, pred, target, expected):
actual = kornia.losses.kl_div_loss_2d(pred.to(device, dtype), target.to(device, dtype))
expected = torch.tensor(expected).to(device, dtype)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
@pytest.mark.parametrize(
"pred,target,expected",
@@ -484,7 +474,7 @@ class TestDivergenceLoss:
)
def test_kl_div_loss_2d_without_reduction(self, device, dtype, pred, target, expected):
actual = kornia.losses.kl_div_loss_2d(pred.to(device, dtype), target.to(device, dtype), reduction="none")
- assert_close(actual, expected.to(device, dtype))
+ self.assert_close(actual, expected.to(device, dtype))
@pytest.mark.parametrize(
"pred,target,expected",
@@ -500,7 +490,7 @@ class TestDivergenceLoss:
target = target.to(device, dtype).view(target.shape[::-1]).transpose(-2, -1)
actual = kornia.losses.kl_div_loss_2d(pred, target)
expected = torch.tensor(expected).to(device, dtype)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
@pytest.mark.parametrize(
"pred,target,expected",
@@ -516,25 +506,23 @@ class TestDivergenceLoss:
target = target.to(device, dtype).view(target.shape[::-1]).transpose(-2, -1)
actual = kornia.losses.js_div_loss_2d(pred, target)
expected = torch.tensor(expected).to(device, dtype)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
- def test_gradcheck_kl(self, device, dtype):
+ def test_gradcheck_kl(self, device):
+ dtype = torch.float64
pred = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
target = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
# evaluate function gradient
- pred = tensor_to_gradcheck_var(pred) # to var
- target = tensor_to_gradcheck_var(target) # to var
- assert gradcheck(kornia.losses.kl_div_loss_2d, (pred, target), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.losses.kl_div_loss_2d, (pred, target))
- def test_gradcheck_js(self, device, dtype):
+ def test_gradcheck_js(self, device):
+ dtype = torch.float64
pred = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
target = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
# evaluate function gradient
- pred = tensor_to_gradcheck_var(pred) # to var
- target = tensor_to_gradcheck_var(target) # to var
- assert gradcheck(kornia.losses.js_div_loss_2d, (pred, target), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.losses.js_div_loss_2d, (pred, target))
def test_dynamo_kl(self, device, dtype, torch_optimizer):
pred = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
@@ -542,7 +530,7 @@ class TestDivergenceLoss:
args = (pred, target)
op = kornia.losses.kl_div_loss_2d
op_optimized = torch_optimizer(op)
- assert_close(op(*args), op_optimized(*args), rtol=0, atol=1e-5)
+ self.assert_close(op(*args), op_optimized(*args), rtol=0, atol=1e-5)
def test_dynamo_js(self, device, dtype, torch_optimizer):
pred = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
@@ -550,10 +538,10 @@ class TestDivergenceLoss:
args = (pred, target)
op = kornia.losses.js_div_loss_2d
op_optimized = torch_optimizer(op)
- assert_close(op(*args), op_optimized(*args), rtol=0, atol=1e-5)
+ self.assert_close(op(*args), op_optimized(*args), rtol=0, atol=1e-5)
-class TestTotalVariation:
+class TestTotalVariation(BaseTester):
# Total variation of constant vectors is 0
@pytest.mark.parametrize(
"pred, expected",
@@ -564,7 +552,7 @@ class TestTotalVariation:
)
def test_tv_on_constant(self, device, dtype, pred, expected):
actual = kornia.losses.total_variation(pred.to(device, dtype))
- assert_close(actual, expected.to(device, dtype))
+ self.assert_close(actual, expected.to(device, dtype))
# Total variation of constant vectors is 0
@pytest.mark.parametrize(
@@ -576,7 +564,7 @@ class TestTotalVariation:
)
def test_tv_on_constant_int(self, device, pred, expected):
actual = kornia.losses.total_variation(pred.to(device, dtype=torch.int32), reduction="mean")
- assert_close(actual, expected.to(device))
+ self.assert_close(actual, expected.to(device))
# Total variation for 3D tensors
@pytest.mark.parametrize(
@@ -615,7 +603,7 @@ class TestTotalVariation:
)
def test_tv_on_3d(self, device, dtype, pred, expected):
actual = kornia.losses.total_variation(pred.to(device, dtype))
- assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
+ self.assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
# Total variation for 4D tensors
@pytest.mark.parametrize(
@@ -652,7 +640,7 @@ class TestTotalVariation:
)
def test_tv_on_4d(self, device, dtype, pred, expected):
actual = kornia.losses.total_variation(pred.to(device, dtype))
- assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
+ self.assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
@pytest.mark.parametrize("pred", [torch.rand(3, 5, 5), torch.rand(4, 3, 5, 5), torch.rand(4, 2, 3, 5, 5)])
def test_tv_shapes(self, device, dtype, pred):
@@ -663,14 +651,14 @@ class TestTotalVariation:
actual_lesser_dims.append(slice_tv)
actual_lesser_dims = torch.stack(actual_lesser_dims, dim=0)
actual_higher_dims = kornia.losses.total_variation(pred)
- assert_close(actual_lesser_dims, actual_higher_dims.to(device, dtype), rtol=1e-3, atol=1e-3)
+ self.assert_close(actual_lesser_dims, actual_higher_dims.to(device, dtype), rtol=1e-3, atol=1e-3)
@pytest.mark.parametrize("reduction, expected", [("sum", torch.tensor(20)), ("mean", torch.tensor(1))])
def test_tv_reduction(self, device, dtype, reduction, expected):
pred, _ = torch_meshgrid([torch.arange(5), torch.arange(5)], "ij")
pred = pred.to(device, dtype)
actual = kornia.losses.total_variation(pred, reduction=reduction)
- assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
+ self.assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
# Expect TypeError to be raised when non-torch tensors are passed
@pytest.mark.parametrize("pred", [1, [1, 2]])
@@ -684,7 +672,7 @@ class TestTotalVariation:
op = kornia.losses.total_variation
op_optimized = torch_optimizer(op)
- assert_close(op(image), op_optimized(image))
+ self.assert_close(op(image), op_optimized(image))
def test_module(self, device, dtype):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -692,15 +680,15 @@ class TestTotalVariation:
op = kornia.losses.total_variation
op_module = kornia.losses.TotalVariation()
- assert_close(op(image), op_module(image))
+ self.assert_close(op(image), op_module(image))
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- image = tensor_to_gradcheck_var(image) # to var
- assert gradcheck(kornia.losses.total_variation, (image,), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.losses.total_variation, (image,))
-class TestPSNRLoss:
+class TestPSNRLoss(BaseTester):
def test_smoke(self, device, dtype):
pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
@@ -728,7 +716,7 @@ class TestPSNRLoss:
pred = torch.ones(1, device=device, dtype=dtype)
expected = torch.tensor(-20.0, device=device, dtype=dtype)
actual = kornia.losses.psnr_loss(pred, 1.2 * pred, 2.0)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
def test_dynamo(self, device, dtype, torch_optimizer):
pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
@@ -739,7 +727,7 @@ class TestPSNRLoss:
op = kornia.losses.psnr_loss
op_optimized = torch_optimizer(op)
- assert_close(op(*args), op_optimized(*args))
+ self.assert_close(op(*args), op_optimized(*args))
def test_module(self, device, dtype):
pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
@@ -750,17 +738,16 @@ class TestPSNRLoss:
op = kornia.losses.psnr_loss
op_module = kornia.losses.PSNRLoss(1.0)
- assert_close(op(*args), op_module(pred, target))
+ self.assert_close(op(*args), op_module(pred, target))
def test_gradcheck(self, device, dtype):
+ dtype = torch.float64
pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
- pred = tensor_to_gradcheck_var(pred) # to var
- target = tensor_to_gradcheck_var(target) # to var
- assert gradcheck(kornia.losses.psnr_loss, (pred, target, 1.0), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.losses.psnr_loss, (pred, target, 1.0))
-class TestLovaszHingeLoss:
+class TestLovaszHingeLoss(BaseTester):
def test_smoke(self, device, dtype):
num_classes = 1
logits = torch.rand(2, num_classes, 1, 1, device=device, dtype=dtype)
@@ -798,16 +785,15 @@ class TestLovaszHingeLoss:
criterion = kornia.losses.LovaszHingeLoss()
loss = criterion(prediction, labels)
- assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
+ self.assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
+ dtype = torch.float64
num_classes = 1
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
- labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.to(device).long()
+ labels = torch.randint(0, num_classes, (2, 3, 2), device=device, dtype=dtype)
- logits = tensor_to_gradcheck_var(logits) # to var
- assert gradcheck(kornia.losses.lovasz_hinge_loss, (logits, labels), raise_exception=True, fast_mode=True)
+ self.gradcheck(kornia.losses.lovasz_hinge_loss, (logits, labels))
def test_dynamo(self, device, dtype, torch_optimizer):
num_classes = 1
@@ -818,7 +804,7 @@ class TestLovaszHingeLoss:
op = kornia.losses.lovasz_hinge_loss
op_optimized = torch_optimizer(op)
- assert_close(op(logits, labels), op_optimized(logits, labels))
+ self.assert_close(op(logits, labels), op_optimized(logits, labels))
def test_module(self, device, dtype):
num_classes = 1
@@ -829,10 +815,10 @@ class TestLovaszHingeLoss:
op = kornia.losses.lovasz_hinge_loss
op_module = kornia.losses.LovaszHingeLoss()
- assert_close(op(logits, labels), op_module(logits, labels))
+ self.assert_close(op(logits, labels), op_module(logits, labels))
-class TestLovaszSoftmaxLoss:
+class TestLovaszSoftmaxLoss(BaseTester):
def test_smoke(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 1, 1, device=device, dtype=dtype)
@@ -885,17 +871,14 @@ class TestLovaszSoftmaxLoss:
criterion = kornia.losses.LovaszSoftmaxLoss()
loss = criterion(prediction, labels)
- print(loss)
- assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
- def test_gradcheck(self, device, dtype):
- num_classes = 4
- logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
- labels = torch.rand(2, 3, 2) * num_classes
- labels = labels.to(device).long()
+ self.assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
- logits = tensor_to_gradcheck_var(logits) # to var
- assert gradcheck(kornia.losses.lovasz_softmax_loss, (logits, labels), raise_exception=True, fast_mode=True)
+ def test_gradcheck(self, device):
+ num_classes = 4
+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=torch.float64)
+ labels = torch.randint(0, num_classes, (2, 3, 2), device=device)
+ self.gradcheck(kornia.losses.lovasz_softmax_loss, (logits, labels), dtypes=[torch.float64, torch.int64])
@pytest.mark.skip(reason="Not matching results")
def test_dynamo(self, device, dtype, torch_optimizer):
@@ -907,7 +890,7 @@ class TestLovaszSoftmaxLoss:
op = kornia.losses.lovasz_softmax_loss
op_optimized = torch_optimizer(op)
- assert_close(op(logits, labels), op_optimized(logits, labels))
+ self.assert_close(op(logits, labels), op_optimized(logits, labels))
def test_module(self, device, dtype):
num_classes = 5
@@ -918,7 +901,7 @@ class TestLovaszSoftmaxLoss:
op = kornia.losses.lovasz_softmax_loss
op_module = kornia.losses.LovaszSoftmaxLoss()
- assert_close(op(logits, labels), op_module(logits, labels))
+ self.assert_close(op(logits, labels), op_module(logits, labels))
class TestWelschLoss(BaseTester):
@@ -941,11 +924,10 @@ class TestWelschLoss(BaseTester):
assert actual.shape == ()
def test_gradcheck(self, device):
- img1 = torch.rand(2, 3, 3, 3, device=device)
- img2 = torch.rand(2, 3, 3, 3, device=device)
+ img1 = torch.rand(2, 3, 3, 3, device=device, dtype=torch.float64)
+ img2 = torch.rand(2, 3, 3, 3, device=device, dtype=torch.float64)
- img1 = tensor_to_gradcheck_var(img1) # to var
- assert self.gradcheck(kornia.losses.welsch_loss, (img1, img2))
+ self.gradcheck(kornia.losses.welsch_loss, (img1, img2))
def test_dynamo(self, device, dtype, torch_optimizer):
img1 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
@@ -1057,11 +1039,9 @@ class TestCauchyLoss(BaseTester):
assert actual.shape == ()
def test_gradcheck(self, device):
- img1 = torch.rand(2, 3, 3, 3, device=device)
- img2 = torch.rand(2, 3, 3, 3, device=device)
+ img1 = torch.rand(2, 3, 3, 3, device=device, dtype=torch.float64)
+ img2 = torch.rand(2, 3, 3, 3, device=device, dtype=torch.float64)
- img1 = tensor_to_gradcheck_var(img1) # to var
- img2 = tensor_to_gradcheck_var(img2) # to var
self.gradcheck(kornia.losses.cauchy_loss, (img1, img2))
def test_dynamo(self, device, dtype, torch_optimizer):
@@ -1151,11 +1131,9 @@ class TestGemanMcclureLossLoss(BaseTester):
assert actual.shape == ()
def test_gradcheck(self, device):
- img1 = torch.rand(2, 3, 3, 3, device=device)
- img2 = torch.rand(2, 3, 3, 3, device=device)
+ img1 = torch.rand(2, 3, 3, 3, device=device, dtype=torch.float64)
+ img2 = torch.rand(2, 3, 3, 3, device=device, dtype=torch.float64)
- img1 = tensor_to_gradcheck_var(img1) # to var
- img2 = tensor_to_gradcheck_var(img2) # to var
self.gradcheck(kornia.losses.geman_mcclure_loss, (img1, img2))
def test_dynamo(self, device, dtype, torch_optimizer):
@@ -1245,11 +1223,9 @@ class TestCharbonnierLoss(BaseTester):
assert actual.shape == ()
def test_gradcheck(self, device):
- img1 = torch.rand(2, 3, 3, 3, device=device)
- img2 = torch.rand(2, 3, 3, 3, device=device)
+ img1 = torch.rand(2, 3, 3, 3, device=device, dtype=torch.float64)
+ img2 = torch.rand(2, 3, 3, 3, device=device, dtype=torch.float64)
- img1 = tensor_to_gradcheck_var(img1) # to var
- img2 = tensor_to_gradcheck_var(img2) # to var
self.gradcheck(kornia.losses.charbonnier_loss, (img1, img2))
def test_dynamo(self, device, dtype, torch_optimizer):
diff --git a/tests/losses/test_ssim.py b/tests/losses/test_ssim.py
index f61b701bf..b872c7c59 100644
--- a/tests/losses/test_ssim.py
+++ b/tests/losses/test_ssim.py
@@ -1,13 +1,12 @@
import pytest
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import BaseTester, assert_close
+from testing.base import BaseTester
-class TestSSIMLoss:
+
+class TestSSIMLoss(BaseTester):
def test_ssim_equal_none(self, device, dtype):
# input data
img1 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
@@ -16,9 +15,8 @@ class TestSSIMLoss:
ssim1 = kornia.losses.ssim_loss(img1, img1, window_size=5, reduction="none")
ssim2 = kornia.losses.ssim_loss(img2, img2, window_size=5, reduction="none")
- tol_val: float = utils._get_precision_by_name(device, "xla", 1e-1, 1e-4)
- assert_close(ssim1, torch.zeros_like(img1), rtol=tol_val, atol=tol_val)
- assert_close(ssim2, torch.zeros_like(img2), rtol=tol_val, atol=tol_val)
+ self.assert_close(ssim1, torch.zeros_like(img1), low_tolerance=True) # rtol=tol_val, atol=tol_val)
+ self.assert_close(ssim2, torch.zeros_like(img2), low_tolerance=True) # rtol=tol_val, atol=tol_val)
@pytest.mark.parametrize("window_size", [5, 11])
@pytest.mark.parametrize("reduction_type", ["mean", "sum", "none"])
@@ -32,13 +30,12 @@ class TestSSIMLoss:
loss = kornia.losses.ssim_loss(img, img, window_size, reduction=reduction_type)
- tol_val: float = utils._get_precision_by_name(device, "xla", 1e-1, 1e-4)
if reduction_type == "none":
expected = torch.zeros_like(img)
else:
expected = torch.tensor(0.0, device=device, dtype=dtype)
- assert_close(loss, expected, rtol=tol_val, atol=tol_val)
+ self.assert_close(loss, expected)
def test_module(self, device, dtype):
img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -49,25 +46,21 @@ class TestSSIMLoss:
op = kornia.losses.ssim_loss
op_module = kornia.losses.SSIMLoss(*args[2:])
- assert_close(op(*args), op_module(*args[:2]))
+ self.assert_close(op(*args), op_module(*args[:2]))
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# input data
window_size = 3
- img1 = torch.rand(1, 1, 5, 4, device=device, dtype=dtype)
- img2 = torch.rand(1, 1, 5, 4, device=device, dtype=dtype)
+ img1 = torch.rand(1, 1, 5, 4, device=device, dtype=torch.float64)
+ img2 = torch.rand(1, 1, 5, 4, device=device, dtype=torch.float64)
# evaluate function gradient
- img1 = utils.tensor_to_gradcheck_var(img1) # to var
- img2 = utils.tensor_to_gradcheck_var(img2) # to var
# TODO: review method since it needs `nondet_tol` in cuda sometimes.
- assert gradcheck(
- kornia.losses.ssim_loss, (img1, img2, window_size), raise_exception=True, nondet_tol=1e-8, fast_mode=True
- )
+ self.gradcheck(kornia.losses.ssim_loss, (img1, img2, window_size), nondet_tol=1e-8)
-class TestMS_SSIMLoss:
+class TestMS_SSIMLoss(BaseTester):
def test_msssim_equal_none(self, device, dtype):
# input data
img1 = torch.rand(1, 3, 10, 16, device=device, dtype=dtype)
@@ -77,8 +70,8 @@ class TestMS_SSIMLoss:
msssim1 = msssim(img1, img1)
msssim2 = msssim(img2, img2)
- assert_close(msssim1.item(), 0.0)
- assert_close(msssim2.item(), 0.0)
+ self.assert_close(msssim1.item(), 0.0)
+ self.assert_close(msssim2.item(), 0.0)
def test_exception(self):
criterion = kornia.losses.MS_SSIMLoss()
@@ -104,7 +97,7 @@ class TestMS_SSIMLoss:
msssiml1 = kornia.losses.MS_SSIMLoss(reduction=reduction_type).to(device, dtype)
loss = msssiml1(img, img)
- assert_close(loss.sum().item(), 0.0)
+ self.assert_close(loss.sum().item(), 0.0)
def test_gradcheck(self, device):
# input data
@@ -113,12 +106,9 @@ class TestMS_SSIMLoss:
img2 = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)
# evaluate function gradient
- img1 = utils.tensor_to_gradcheck_var(img1) # to var
- img2 = utils.tensor_to_gradcheck_var(img2) # to var
-
loss = kornia.losses.MS_SSIMLoss().to(device, dtype)
- assert gradcheck(loss, (img1, img2), raise_exception=True, nondet_tol=1e-8, fast_mode=True)
+ self.gradcheck(loss, (img1, img2), nondet_tol=1e-8)
def test_jit(self, device, dtype):
img1 = torch.rand(1, 3, 10, 10, device=device, dtype=dtype)
@@ -129,7 +119,7 @@ class TestMS_SSIMLoss:
op = kornia.losses.MS_SSIMLoss().to(device, dtype)
op_script = torch.jit.script(op)
- assert_close(op(*args), op_script(*args))
+ self.assert_close(op(*args), op_script(*args))
class TestSSIM3DLoss(BaseTester):
@@ -192,12 +182,9 @@ class TestSSIM3DLoss(BaseTester):
img = torch.rand(1, 1, 5, 4, 3, device=device)
# evaluate function gradient
- img = utils.tensor_to_gradcheck_var(img) # to var
# TODO: review method since it needs `nondet_tol` in cuda sometimes.
- assert gradcheck(
- kornia.losses.ssim3d_loss, (img, img, 3), raise_exception=True, nondet_tol=1e-8, fast_mode=True
- )
+ self.gradcheck(kornia.losses.ssim3d_loss, (img, img, 3), nondet_tol=1e-8)
@pytest.mark.parametrize("shape", [(1, 2, 3, 5, 5), (2, 4, 2, 5, 5)])
def test_cardinality(self, shape, device, dtype):
diff --git a/tests/morphology/test_bottom_hat.py b/tests/morphology/test_bottom_hat.py
index 85977783b..b35f6acc4 100644
--- a/tests/morphology/test_bottom_hat.py
+++ b/tests/morphology/test_bottom_hat.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
from kornia.morphology import bottom_hat
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestBottomHat:
diff --git a/tests/morphology/test_closing.py b/tests/morphology/test_closing.py
index a0a0672f9..b9d8da2fc 100644
--- a/tests/morphology/test_closing.py
+++ b/tests/morphology/test_closing.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
from kornia.morphology import closing
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestClosing:
diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.py
index df99f007f..a851f547c 100644
--- a/tests/morphology/test_dilation.py
+++ b/tests/morphology/test_dilation.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
from kornia.morphology import dilation
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestDilate:
diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.py
index 97871a7c8..5ac4a680f 100644
--- a/tests/morphology/test_erosion.py
+++ b/tests/morphology/test_erosion.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
from kornia.morphology import erosion
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestErode:
diff --git a/tests/morphology/test_gradient.py b/tests/morphology/test_gradient.py
index 4df07a087..9e48f3402 100644
--- a/tests/morphology/test_gradient.py
+++ b/tests/morphology/test_gradient.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
from kornia.morphology import gradient
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestGradient:
diff --git a/tests/morphology/test_opening.py b/tests/morphology/test_opening.py
index 8ca4ec12f..b7d73c31c 100644
--- a/tests/morphology/test_opening.py
+++ b/tests/morphology/test_opening.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
from kornia.morphology import opening
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestOpening:
diff --git a/tests/morphology/test_top_hat.py b/tests/morphology/test_top_hat.py
index 3eae3bf9a..06c40074b 100644
--- a/tests/morphology/test_top_hat.py
+++ b/tests/morphology/test_top_hat.py
@@ -3,7 +3,8 @@ import torch
from torch.autograd import gradcheck
from kornia.morphology import top_hat
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestTopHat:
diff --git a/tests/nerf/test_camera_utils.py b/tests/nerf/test_camera_utils.py
index 78ab727ec..26823408c 100755
--- a/tests/nerf/test_camera_utils.py
+++ b/tests/nerf/test_camera_utils.py
@@ -6,7 +6,8 @@ import torch
from kornia.geometry.conversions import quaternion_to_rotation_matrix
from kornia.nerf.camera_utils import create_spiral_path, parse_colmap_output
-from kornia.testing import assert_close
+
+from testing.base import assert_close
_ref = {
"cameras": (
diff --git a/tests/nerf/test_data_utils.py b/tests/nerf/test_data_utils.py
index 5d3f47413..15b3e8940 100755
--- a/tests/nerf/test_data_utils.py
+++ b/tests/nerf/test_data_utils.py
@@ -5,7 +5,9 @@ import torch
from kornia.core import Device, Tensor
from kornia.geometry.camera import PinholeCamera
from kornia.nerf.data_utils import RayDataset, instantiate_ray_dataloader
-from kornia.testing import assert_close
+
+from testing.base import assert_close
+
from tests.nerf.test_rays import create_four_cameras
diff --git a/tests/nerf/test_nerf_solver.py b/tests/nerf/test_nerf_solver.py
index 7a4e4bb52..b2c0bfcb0 100755
--- a/tests/nerf/test_nerf_solver.py
+++ b/tests/nerf/test_nerf_solver.py
@@ -5,7 +5,9 @@ from kornia.core import Tensor
from kornia.geometry.camera import PinholeCamera
from kornia.nerf.nerf_model import NerfModelRenderer
from kornia.nerf.nerf_solver import NerfSolver
-from kornia.testing import assert_close
+
+from testing.base import assert_close
+
from tests.nerf.test_data_utils import create_random_images_for_cameras, create_red_images_for_cameras
from tests.nerf.test_rays import create_four_cameras, create_one_camera
diff --git a/tests/nerf/test_rays.py b/tests/nerf/test_rays.py
index 9c0840a12..bf222e6f1 100755
--- a/tests/nerf/test_rays.py
+++ b/tests/nerf/test_rays.py
@@ -13,7 +13,8 @@ from kornia.nerf.samplers import (
sample_lengths,
sample_ray_points,
)
-from kornia.testing import assert_close
+
+from testing.base import assert_close
def create_camera_dimensions(device, dtype):
diff --git a/tests/nerf/test_renderer.py b/tests/nerf/test_renderer.py
index b61482b2c..d29435a5c 100755
--- a/tests/nerf/test_renderer.py
+++ b/tests/nerf/test_renderer.py
@@ -4,7 +4,8 @@ import torch
from kornia.core import Device, Tensor
from kornia.nerf.volume_renderer import IrregularRenderer, RegularRenderer
-from kornia.testing import assert_close
+
+from testing.base import assert_close
def _create_regular_point_cloud(
diff --git a/tests/sensors/camera/test_camera_model.py b/tests/sensors/camera/test_camera_model.py
index 0b2400ac1..e062b8a5d 100644
--- a/tests/sensors/camera/test_camera_model.py
+++ b/tests/sensors/camera/test_camera_model.py
@@ -4,7 +4,8 @@ import torch
from kornia.geometry.vector import Vector3
from kornia.image import ImageSize
from kornia.sensors.camera import CameraModel, CameraModelType
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestPinholeCamera(BaseTester):
diff --git a/tests/sensors/camera/test_distortion_model.py b/tests/sensors/camera/test_distortion_model.py
index 8258481c2..f5b0952fb 100644
--- a/tests/sensors/camera/test_distortion_model.py
+++ b/tests/sensors/camera/test_distortion_model.py
@@ -3,7 +3,8 @@ import torch
from kornia.geometry.vector import Vector2
from kornia.sensors.camera.distortion_model import AffineTransform
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestAffineTransform(BaseTester):
diff --git a/tests/sensors/camera/test_projection_model.py b/tests/sensors/camera/test_projection_model.py
index b46c16605..bda7f734a 100644
--- a/tests/sensors/camera/test_projection_model.py
+++ b/tests/sensors/camera/test_projection_model.py
@@ -3,7 +3,8 @@ import torch
from kornia.geometry.vector import Vector2, Vector3
from kornia.sensors.camera.projection_model import Z1Projection
-from kornia.testing import BaseTester
+
+from testing.base import BaseTester
class TestProjection(BaseTester):
diff --git a/tests/test_metrics.py b/tests/test_metrics.py
index 0bef2dbe6..3023bbb45 100644
--- a/tests/test_metrics.py
+++ b/tests/test_metrics.py
@@ -2,10 +2,11 @@ import pytest
import torch
import kornia
-from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
+from testing.base import BaseTester
-class TestMeanIoU:
+
+class TestMeanIoU(BaseTester):
def test_two_classes_perfect(self, device, dtype):
batch_size = 1
num_classes = 2
@@ -15,7 +16,7 @@ class TestMeanIoU:
mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor([[1.0, 1.0]], device=device, dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
- assert_close(mean_iou, mean_iou_real)
+ self.assert_close(mean_iou, mean_iou_real)
def test_two_classes_perfect_batch2(self, device, dtype):
batch_size = 2
@@ -26,7 +27,7 @@ class TestMeanIoU:
mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor([[1.0, 1.0], [1.0, 1.0]], device=device, dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
- assert_close(mean_iou, mean_iou_real)
+ self.assert_close(mean_iou, mean_iou_real)
def test_two_classes(self, device, dtype):
batch_size = 1
@@ -38,7 +39,7 @@ class TestMeanIoU:
mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor([[0.75, 0.80]], device=device, dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
- assert_close(mean_iou, mean_iou_real)
+ self.assert_close(mean_iou, mean_iou_real)
def test_four_classes_2d_perfect(self, device, dtype):
batch_size = 1
@@ -53,7 +54,7 @@ class TestMeanIoU:
mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor([[1.0, 1.0, 1.0, 1.0]], device=device, dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
- assert_close(mean_iou, mean_iou_real)
+ self.assert_close(mean_iou, mean_iou_real)
def test_four_classes_one_missing(self, device, dtype):
batch_size = 1
@@ -68,10 +69,10 @@ class TestMeanIoU:
mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)
mean_iou_real = torch.tensor([[0.0, 1.0, 0.5, 0.5]], device=device, dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
- assert_close(mean_iou, mean_iou_real)
+ self.assert_close(mean_iou, mean_iou_real)
-class TestConfusionMatrix:
+class TestConfusionMatrix(BaseTester):
def test_two_classes(self, device, dtype):
num_classes = 2
actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]], device=device, dtype=torch.long)
@@ -79,7 +80,7 @@ class TestConfusionMatrix:
conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor([[[3, 1], [0, 4]]], device=device, dtype=torch.float32)
- assert_close(conf_mat, conf_mat_real)
+ self.assert_close(conf_mat, conf_mat_real)
def test_two_classes_batch2(self, device, dtype):
batch_size = 2
@@ -89,7 +90,7 @@ class TestConfusionMatrix:
conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor([[[3, 1], [0, 4]], [[3, 1], [0, 4]]], device=device, dtype=torch.float32)
- assert_close(conf_mat, conf_mat_real)
+ self.assert_close(conf_mat, conf_mat_real)
def test_three_classes(self, device, dtype):
num_classes = 3
@@ -98,7 +99,7 @@ class TestConfusionMatrix:
conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)
conf_mat_real = torch.tensor([[[4, 1, 2], [3, 0, 2], [1, 2, 1]]], device=device, dtype=torch.float32)
- assert_close(conf_mat, conf_mat_real)
+ self.assert_close(conf_mat, conf_mat_real)
def test_four_classes_one_missing(self, device, dtype):
num_classes = 4
@@ -109,7 +110,7 @@ class TestConfusionMatrix:
conf_mat_real = torch.tensor(
[[[0, 0, 0, 0], [0, 4, 1, 2], [0, 3, 0, 2], [0, 1, 2, 1]]], device=device, dtype=torch.float32
)
- assert_close(conf_mat, conf_mat_real)
+ self.assert_close(conf_mat, conf_mat_real)
def test_three_classes_normalized(self, device, dtype):
num_classes = 3
@@ -125,7 +126,7 @@ class TestConfusionMatrix:
dtype=torch.float32,
)
- assert_close(conf_mat, conf_mat_real)
+ self.assert_close(conf_mat, conf_mat_real)
def test_four_classes_2d_perfect(self, device, dtype):
num_classes = 4
@@ -140,7 +141,7 @@ class TestConfusionMatrix:
conf_mat_real = torch.tensor(
[[[4, 0, 0, 0], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]], device=device, dtype=torch.float32
)
- assert_close(conf_mat, conf_mat_real)
+ self.assert_close(conf_mat, conf_mat_real)
def test_four_classes_2d_one_class_nonperfect(self, device, dtype):
num_classes = 4
@@ -155,7 +156,7 @@ class TestConfusionMatrix:
conf_mat_real = torch.tensor(
[[[3, 0, 0, 1], [1, 3, 0, 0], [0, 0, 4, 0], [0, 1, 0, 3]]], device=device, dtype=torch.float32
)
- assert_close(conf_mat, conf_mat_real)
+ self.assert_close(conf_mat, conf_mat_real)
def test_four_classes_2d_one_class_missing(self, device, dtype):
num_classes = 4
@@ -170,7 +171,7 @@ class TestConfusionMatrix:
conf_mat_real = torch.tensor(
[[[0, 0, 0, 4], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]], device=device, dtype=torch.float32
)
- assert_close(conf_mat, conf_mat_real)
+ self.assert_close(conf_mat, conf_mat_real)
def test_four_classes_2d_one_class_no_predicted(self, device, dtype):
num_classes = 4
@@ -185,50 +186,50 @@ class TestConfusionMatrix:
conf_mat_real = torch.tensor(
[[[0, 0, 4, 4], [0, 0, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]], device=device, dtype=torch.float32
)
- assert_close(conf_mat, conf_mat_real)
+ self.assert_close(conf_mat, conf_mat_real)
-class TestPsnr:
+class TestPsnr(BaseTester):
def test_metric(self, device, dtype):
sample = torch.ones(1, device=device, dtype=dtype)
expected = torch.tensor(20.0, device=device, dtype=dtype)
actual = kornia.metrics.psnr(sample, 1.2 * sample, 2.0)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
-class TestAepe:
+class TestAepe(BaseTester):
def test_metric_mean_reduction(self, device, dtype):
sample = torch.ones(4, 4, 2, device=device, dtype=dtype)
expected = torch.tensor(0.565685424, device=device, dtype=dtype)
actual = kornia.metrics.aepe(sample, 1.4 * sample, reduction="mean")
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
def test_metric_sum_reduction(self, device, dtype):
sample = torch.ones(4, 4, 2, device=device, dtype=dtype)
expected = torch.tensor(1.4142, device=device, dtype=dtype) * 4**2
actual = kornia.metrics.aepe(sample, 2.0 * sample, reduction="sum")
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
def test_metric_no_reduction(self, device, dtype):
sample = torch.ones(4, 4, 2, device=device, dtype=dtype)
expected = torch.zeros(4, 4, device=device, dtype=dtype) + 1.4142
actual = kornia.metrics.aepe(sample, 2.0 * sample, reduction="none")
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
def test_perfect_fit(self, device, dtype):
sample = torch.ones(4, 4, 2, device=device, dtype=dtype)
expected = torch.zeros(4, 4, device=device, dtype=dtype)
actual = kornia.metrics.aepe(sample, sample, reduction="none")
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
def test_aepe_alias(self, device, dtype):
sample = torch.ones(4, 4, 2, device=device, dtype=dtype)
expected = torch.zeros(4, 4, device=device, dtype=dtype)
actual_aepe = kornia.metrics.aepe(sample, sample, reduction="none")
actual_alias = kornia.metrics.average_endpoint_error(sample, sample, reduction="none")
- assert_close(actual_aepe, expected)
- assert_close(actual_alias, expected)
- assert_close(actual_aepe, actual_alias)
+ self.assert_close(actual_aepe, expected)
+ self.assert_close(actual_alias, expected)
+ self.assert_close(actual_aepe, actual_alias)
def test_exception(self, device, dtype):
with pytest.raises(TypeError) as errinfo:
@@ -254,7 +255,7 @@ class TestAepe:
assert criterion(input, target) is not None
-class TestMeanAveragePrecision:
+class TestMeanAveragePrecision(BaseTester):
def test_smoke(self, device, dtype):
boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)
labels = torch.tensor([1], device=device, dtype=torch.long)
@@ -265,8 +266,8 @@ class TestMeanAveragePrecision:
mean_ap = kornia.metrics.mean_average_precision([boxes], [labels], [scores], [gt_boxes], [gt_labels], 2)
- assert_close(mean_ap[0], torch.tensor(1.0, device=device, dtype=dtype))
- assert_close(mean_ap[1][1], 1.0)
+ self.assert_close(mean_ap[0], torch.tensor(1.0, device=device, dtype=dtype))
+ self.assert_close(mean_ap[1][1], 1.0)
def test_raise(self, device, dtype):
boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)
@@ -404,9 +405,8 @@ class TestSSIM3d(BaseTester):
self.assert_close(ops_out, mod_out)
def test_gradcheck(self, device):
- img = torch.rand(1, 1, 3, 3, 3, device=device)
+ img = torch.rand(1, 1, 3, 3, 3, device=device, dtype=torch.float64)
op = kornia.metrics.ssim3d
- img = tensor_to_gradcheck_var(img)
- assert self.gradcheck(op, (img, img, 3), nondet_tol=1e-8)
+ self.gradcheck(op, (img, img, 3), nondet_tol=1e-8)
diff --git a/tests/tracking/test_planar_tracking.py b/tests/tracking/test_planar_tracking.py
index ef8ec533d..2d6944ddc 100644
--- a/tests/tracking/test_planar_tracking.py
+++ b/tests/tracking/test_planar_tracking.py
@@ -3,10 +3,11 @@ import torch
from kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, SIFTFeature
from kornia.geometry import rescale, transform_points
-from kornia.testing import assert_close
from kornia.tracking import HomographyTracker
from kornia.utils._compat import torch_version_le
+from testing.base import assert_close
+
@pytest.fixture()
def data_url():
diff --git a/tests/utils/test_draw.py b/tests/utils/test_draw.py
index 6299d6229..3490f26dc 100644
--- a/tests/utils/test_draw.py
+++ b/tests/utils/test_draw.py
@@ -3,10 +3,11 @@ import math
import pytest
import torch
-from kornia.testing import assert_close
from kornia.utils import create_meshgrid, draw_convex_polygon, draw_rectangle
from kornia.utils.draw import draw_line, draw_point2d
+from testing.base import assert_close
+
class TestDrawPoint:
"""Test drawing individual pixels."""
diff --git a/tests/utils/test_grid.py b/tests/utils/test_grid.py
index b83058756..d20ee870b 100644
--- a/tests/utils/test_grid.py
+++ b/tests/utils/test_grid.py
@@ -2,7 +2,8 @@ import pytest
import torch
import kornia
-from kornia.testing import assert_close
+
+from testing.base import assert_close
def test_create_meshgrid(device, dtype):
diff --git a/tests/utils/test_helpers.py b/tests/utils/test_helpers.py
index 10e91c11d..70a00dea9 100644
--- a/tests/utils/test_helpers.py
+++ b/tests/utils/test_helpers.py
@@ -1,7 +1,6 @@
import pytest
import torch
-from kornia.testing import assert_close
from kornia.utils import _extract_device_dtype
from kornia.utils.helpers import (
_torch_histc_cast,
@@ -12,6 +11,8 @@ from kornia.utils.helpers import (
safe_solve_with_mask,
)
+from testing.base import assert_close
+
@pytest.mark.parametrize(
"tensor_list,out_device,out_dtype,will_throw_error",
diff --git a/tests/utils/test_image_utils.py b/tests/utils/test_image_utils.py
index adda12456..8fcb441a1 100644
--- a/tests/utils/test_image_utils.py
+++ b/tests/utils/test_image_utils.py
@@ -5,7 +5,8 @@ import pytest
import torch
import kornia
-from kornia.testing import assert_close
+
+from testing.base import assert_close
@pytest.mark.parametrize(
diff --git a/tests/utils/test_memory.py b/tests/utils/test_memory.py
index 79324508f..6c58bf332 100644
--- a/tests/utils/test_memory.py
+++ b/tests/utils/test_memory.py
@@ -1,11 +1,11 @@
import torch
-from torch.autograd import gradcheck
import kornia
-import kornia.testing as utils
+from testing.base import BaseTester
-class TestBatchedForward:
+
+class TestBatchedForward(BaseTester):
def test_runbatch(self, device):
patches = torch.rand(34, 1, 32, 32)
sift = kornia.feature.SIFTDescriptor(32)
@@ -22,12 +22,7 @@ class TestBatchedForward:
def test_gradcheck(self, device):
batch_size, channels, height, width = 3, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(
- kornia.utils.memory.batched_forward,
- (kornia.feature.BlobHessian(), img, device, 2),
- raise_exception=True,
- nondet_tol=1e-4,
- fast_mode=True,
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
+ self.gradcheck(
+ kornia.utils.memory.batched_forward, (kornia.feature.BlobHessian(), img, device, 2), nondet_tol=1e-4
)
diff --git a/tests/utils/test_one_hot.py b/tests/utils/test_one_hot.py
index 7b7aa0c53..e8640617a 100644
--- a/tests/utils/test_one_hot.py
+++ b/tests/utils/test_one_hot.py
@@ -1,7 +1,8 @@
import torch
import kornia
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestOneHot:
diff --git a/tests/utils/test_pointcloud_io.py b/tests/utils/test_pointcloud_io.py
index 59557e2aa..1f1b3039a 100644
--- a/tests/utils/test_pointcloud_io.py
+++ b/tests/utils/test_pointcloud_io.py
@@ -3,7 +3,8 @@ import os
import torch
import kornia
-from kornia.testing import assert_close
+
+from testing.base import assert_close
class TestSaveLoadPointCloud: