๐ Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Refactor library namespaces [pre-release][0.6-rc1] (#1412)
Edgar Ribaa2dfda66fb86
diff --git a/.github/workflows/tests_cpu.yml b/.github/workflows/tests_cpu.ymlindex 8cde3e5af..561415f48 100644--- a/.github/workflows/tests_cpu.yml+++ b/.github/workflows/tests_cpu.yml@@ -5,7 +5,6 @@ on:branches: [master]pull_request:branches: [master]- types: [opened, reopened, synchronize, ready_for_review, review_requested]schedule:- cron: "0 4 * * *"@@ -16,8 +15,8 @@ jobs:fail-fast: falsematrix:os: [ubuntu-latest, macos-latest, windows-latest]- python-version: [3.6, 3.7, 3.8, 3.9]- pytorch-version: [1.8.1, 1.9.0, 1.9.1]+ python-version: [3.6, 3.8, 3.9]+ pytorch-version: [1.8.1, 1.9.1]steps:- uses: actions/checkout@v2- name: Setup conda dependenciesdiff --git a/.github/workflows/tests_nightly.yml b/.github/workflows/tests_nightly.ymlindex f98638526..b25a75b1a 100644--- a/.github/workflows/tests_nightly.yml+++ b/.github/workflows/tests_nightly.yml@@ -28,7 +28,7 @@ jobs:run: |conda install curl -c conda-forgeconda install pytorch cpuonly -c pytorch-nightly- pip install -r requirements/dev.txt+ pip install .[all]- name: Run Testsshell: bash -l {0}run: pytest -v --device cpu --dtype float32,float64 ./test --flake8 --mypydiff --git a/.gitignore b/.gitignoreindex e4c31eb81..3ecc12661 100644--- a/.gitignore+++ b/.gitignore@@ -1,6 +1,5 @@build/dist/-*version.pykornia.egg-info/.idea*/**/__pycache__diff --git a/README.md b/README.mdindex ea0bfe1ef..e2e5bab81 100644--- a/README.md+++ b/README.md@@ -23,7 +23,7 @@ English | [็ฎไฝไธญๆ](README_zh-CN.md)[](https://join.slack.com/t/kornia/shared_invite/zt-csobk21g-CnydWe5fmvkcktIeRFGCEQ)[](https://twitter.com/kornia_foss)-[](https://github.com/kornia/kornia/actions/workflows/tests_cpu_versions.yml)+[](https://github.com/kornia/kornia/actions/workflows/tests_cpu.yml)[](https://github.com/kornia/kornia/actions/workflows/tests_cuda.yml)[](https://codecov.io/gh/kornia/kornia)[](https://kornia.readthedocs.io/en/latest/?badge=latest)diff --git a/docs/generate_example_images.py b/docs/generate_example_images.pyindex a7c5288d5..3a66e4c74 100644--- a/docs/generate_example_images.py+++ b/docs/generate_example_images.py@@ -146,7 +146,7 @@ def main():# import function and applyfn = getattr(mod, fn_name)if fn_name == "grayscale_to_rgb":- out = fn(K.rgb_to_grayscale(img2), *args)+ out = fn(K.color.rgb_to_grayscale(img2), *args)else:out = fn(img2, *args)# perform normalization to visualize@@ -162,7 +162,7 @@ def main():# save the output imageif fn_name == "grayscale_to_rgb":out = torch.cat(- [K.rgb_to_grayscale(img2[0]).repeat(3, 1, 1), *(out[i] for i in range(out.size(0)))], dim=-1+ [K.color.rgb_to_grayscale(img2[0]).repeat(3, 1, 1), *(out[i] for i in range(out.size(0)))], dim=-1)else:out = torch.cat([img2[0], *(out[i] for i in range(out.size(0)))], dim=-1)diff --git a/docs/source/_static/image_registration.py b/docs/source/_static/image_registration.pyindex 478ec4199..0345f6ffc 100644--- a/docs/source/_static/image_registration.py+++ b/docs/source/_static/image_registration.py@@ -2,7 +2,6 @@ import osimport cv2import imageio-import matplotlib.pyplot as pltimport torchimport kornia as K@@ -18,6 +17,7 @@ def load_timg(file_name):tensor = K.image_to_tensor(img, None).float() / 255.return K.color.bgr_to_rgb(tensor)+registrator = KG.ImageRegistrator('similarity')img1 = K.resize(load_timg('/Users/oldufo/datasets/stewart/MR-CT/CT.png'), (400, 600))diff --git a/docs/source/applications/semantic_segmentation.rst b/docs/source/applications/semantic_segmentation.rstindex eb4fcbc71..9ec6bfdf1 100644--- a/docs/source/applications/semantic_segmentation.rst+++ b/docs/source/applications/semantic_segmentation.rst@@ -26,25 +26,25 @@ Create the dataloaders and transforms:.. literalinclude:: ../../../examples/train/semantic_segmentation/main.py:language: python- :lines: 21-47+ :lines: 20-46Define your model, losses, optimizers and schedulers:.. literalinclude:: ../../../examples/train/semantic_segmentation/main.py:language: python- :lines: 49-61+ :lines: 48-60Create your preprocessing and augmentations pipeline:.. literalinclude:: ../../../examples/train/semantic_segmentation/main.py:language: python- :lines: 63-82+ :lines: 62-81Finally, instantiate the :py:class:`~kornia.x.SemanticSegmentationTrainer` and execute your training pipeline... literalinclude:: ../../../examples/train/semantic_segmentation/main.py:language: python- :lines: 101-111+ :lines: 83-91.. seealso::Play with the full example `here <https://github.com/kornia/kornia/tree/master/examples/train/semantic_segmentation>`_diff --git a/docs/source/feature.rst b/docs/source/feature.rstindex 4e91e7bd1..98296f05b 100644--- a/docs/source/feature.rst+++ b/docs/source/feature.rst@@ -72,20 +72,11 @@ Local Affine Frames (LAF).. autofunction:: laf_to_three_points.. autofunction:: laf_from_three_points.. autofunction:: raise_error_if_laf_is_not_valid--Non Maxima Suppression-------------------------.. autofunction:: non_maxima_suppression2d-.. autofunction:: non_maxima_suppression3d-.. autofunction:: nms2d-.. autofunction:: nms3d+.. autofunction:: perspective_transform_lafsModule-------.. autoclass:: NonMaximaSuppression2d-.. autoclass:: NonMaximaSuppression3d.. autoclass:: BlobHessian.. autoclass:: CornerGFTT.. autoclass:: CornerHarrisdiff --git a/docs/source/geometry.calibration.rst b/docs/source/geometry.calibration.rstindex 2d4fa5dea..ad6866aae 100644--- a/docs/source/geometry.calibration.rst+++ b/docs/source/geometry.calibration.rst@@ -19,6 +19,7 @@ The pinhole model is an ideal projection model that not considers lens distortio1\end{bmatrix} \enspace,\end{align}+which is equivalent to directly using the internal parameters: focals :math:`f_u, f_v` and principal point :math:`(u_0, v_0)` to estimated the normalized coordinates.. math::diff --git a/docs/source/geometry.epipolar.rst b/docs/source/geometry.epipolar.rstindex 096f05f1e..5eeafbb45 100644--- a/docs/source/geometry.epipolar.rst+++ b/docs/source/geometry.epipolar.rst@@ -47,8 +47,6 @@ Numeric-------.. autofunction:: cross_product_matrix-.. autofunction:: eye_like-.. autofunction:: vec_likeTriangulation-------------diff --git a/docs/source/geometry.linalg.rst b/docs/source/geometry.linalg.rstindex 950ea6022..2e24e51e6 100644--- a/docs/source/geometry.linalg.rst+++ b/docs/source/geometry.linalg.rst@@ -8,4 +8,3 @@ kornia.geometry.linalg.. autofunction:: compose_transformations.. autofunction:: inverse_transformation.. autofunction:: transform_points-.. autofunction:: perspective_transform_lafsdiff --git a/docs/source/geometry.rst b/docs/source/geometry.rstindex 63d6d48b6..ec41c73c6 100644--- a/docs/source/geometry.rst+++ b/docs/source/geometry.rst@@ -54,5 +54,4 @@ transforms, camera, conversions, linalg and depth. We next describe each of themgeometry.linalggeometry.subpixgeometry.transform- geometry.warpgeometry.ransacdiff --git a/docs/source/geometry.subpix.rst b/docs/source/geometry.subpix.rstindex 0327f0bbd..1c4c68bbb 100644--- a/docs/source/geometry.subpix.rst+++ b/docs/source/geometry.subpix.rst@@ -20,6 +20,12 @@ Spatial.. autofunction:: spatial_soft_argmax2d.. autofunction:: render_gaussian2d+Non Maxima Suppression+----------------------++.. autofunction:: nms2d+.. autofunction:: nms3d+Module------@@ -27,3 +33,5 @@ Module.. autoclass:: ConvSoftArgmax2d.. autoclass:: ConvSoftArgmax3d.. autoclass:: ConvQuadInterp3d+.. autoclass:: NonMaximaSuppression2d+.. autoclass:: NonMaximaSuppression3ddiff --git a/docs/source/geometry.warp.rst b/docs/source/geometry.warp.rstdeleted file mode 100644index 5eba6282e..000000000--- a/docs/source/geometry.warp.rst+++ /dev/null@@ -1,17 +0,0 @@-kornia.geometry.warp-===========================--.. currentmodule:: kornia.geometry.warp--.. autoclass:: HomographyWarper- :members:--.. autoclass:: DepthWarper- :members:--.. autofunction:: homography_warp-.. autofunction:: depth_warp-.. autofunction:: warp_grid-.. autofunction:: normalize_homography3d-.. autofunction:: normal_transform_pixel-.. autofunction:: normal_transform_pixel3ddiff --git a/kornia/__init__.py b/kornia/__init__.pyindex 4eeee8472..2317157f5 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -1,116 +1,31 @@-# Make sure that kornia is running on Python 3.6.0 or later-# (to avoid running into this bug: https://bugs.python.org/issue29246)-import sys+# import the version variable+from ._version import __version__-if sys.version_info < (3, 6, 0):- raise RuntimeError("Kornia requires Python 3.6.0 or later")+# NOTE: kornia filters and geometry must go first since are the core of the library+# and by changing the import order you might get into a circular dependencies issue.+from . import filters+from . import geometry-try:- from .version import __version__-except ImportError:- pass--from kornia import (+# import the other modules for convenience+from . import (augmentation,color,contrib,enhance,feature,- filters,- geometry,- jit,losses,metrics,morphology,utils,x,)-from kornia.color import (- bgr_to_grayscale,- bgr_to_rgb,- bgr_to_rgba,- grayscale_to_rgb,- hls_to_rgb,- hsv_to_rgb,- lab_to_rgb,- luv_to_rgb,- rgb_to_bgr,- rgb_to_grayscale,- rgb_to_hls,- rgb_to_hsv,- rgb_to_lab,- rgb_to_luv,- rgb_to_rgba,- rgb_to_xyz,- rgb_to_ycbcr,- rgb_to_yuv,- rgba_to_bgr,- rgba_to_rgb,- xyz_to_rgb,- ycbcr_to_rgb,- yuv_to_rgb,-)-from kornia.constants import *-from kornia.contrib import extract_tensor_patches-from kornia.enhance import (- adjust_brightness,- adjust_contrast,- adjust_gamma,- adjust_hue,- adjust_saturation,- denormalize,- linear_transform,- normalize,- normalize_min_max,- zca_mean,- zca_whiten,-)-from kornia.feature import DeFMO, gftt_response, harris_response, hessian_response, MKDDescriptor, nms2d, SIFTDescriptor-from kornia.filters import (- box_blur,- canny,- filter2d,- filter3d,- gaussian_blur2d,- get_gaussian_discrete_kernel1d,- get_gaussian_erf_kernel1d,- get_gaussian_kernel1d,- get_gaussian_kernel2d,- get_laplacian_kernel1d,- get_laplacian_kernel2d,- get_motion_kernel2d,- get_motion_kernel3d,- laplacian,- median_blur,- motion_blur,- motion_blur3d,- sobel,- spatial_gradient,- unsharp_mask,-)-from kornia.geometry import *-from kornia.losses import (- dice_loss,- inverse_depth_smoothness_loss,- js_div_loss_2d,- kl_div_loss_2d,- psnr_loss,- ssim,- total_variation,- tversky_loss,-)+# NOTE: we are going to expose to top level very few things+from kornia.constants import pifrom kornia.testing import xla_is_availablefrom kornia.utils import (+ eye_like,+ vec_like,create_meshgrid,- image_list_to_tensor,image_to_tensor,- load_pointcloud_ply,- one_hot,- save_pointcloud_ply,tensor_to_image,)--# Exposes package functional to top level---# Exposes package functional to top leveldiff --git a/kornia/_version.py b/kornia/_version.pynew file mode 100644index 000000000..29c83aa3d--- /dev/null+++ b/kornia/_version.py@@ -0,0 +1 @@+__version__ = "0.6.0-rc1"diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 5d48bced5..36b7f81eb 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -49,6 +49,7 @@ __all__ = ["ColorJitter","Normalize","Denormalize",+ "PadTo","RandomAffine","RandomBoxBlur","RandomCrop",diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex 99af3a99b..445611787 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -12,18 +12,20 @@ from kornia.enhance import (adjust_contrast,adjust_hue,adjust_saturation,+ denormalize,equalize,invert,+ normalize,posterize,sharpness,solarize,)-from kornia.enhance.normalize import denormalize, normalizefrom kornia.filters import box_blur, gaussian_blur2d, motion_blur-from kornia.geometry import (+from kornia.geometry.bbox import bbox_generator, bbox_to_mask+from kornia.geometry.conversions import deg2rad+from kornia.geometry.transform import (affine,crop_by_transform_mat,- deg2rad,elastic_transform2d,get_affine_matrix2d,get_perspective_transform,@@ -36,7 +38,6 @@ from kornia.geometry import (warp_image_tps,warp_perspective,)-from kornia.geometry.bbox import bbox_generator, bbox_to_maskfrom kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_centerfrom kornia.utils import _extract_device_dtype, create_meshgriddiff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 8088df054..ba1a9c028 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -3,7 +3,6 @@ from itertools import zip_longestfrom typing import cast, List, Optional, Tuple, Unionimport torch-import torch.nn as nnfrom kornia.augmentation.base import (_AugmentationBase,diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.pyindex 4fa05c770..8c5c9e32d 100644--- a/kornia/augmentation/container/base.py+++ b/kornia/augmentation/container/base.py@@ -1,5 +1,5 @@from collections import OrderedDict-from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Tuple, Union+from typing import Any, Iterator, List, NamedTuple, Optional, Tuple, Unionimport torchimport torch.nn as nndiff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 24f1ef7c6..97b42a277 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -1,5 +1,5 @@from itertools import zip_longest-from typing import Any, Iterator, List, Optional, Tuple, Type, Union+from typing import Iterator, List, Optional, Tuple, Type, Unionimport torchimport torch.nn as nndiff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex 3e689e034..84dfaa6df 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -96,7 +96,7 @@ class VideoSequential(ImageSequential):def __infer_channel_exclusive_batch_shape__(self, batch_shape: torch.Size, chennel_index: int) -> torch.Size:# Fix mypy complains: error: Incompatible return value type (got "Tuple[int, ...]", expected "Size")- return cast(torch.Size, batch_shape[:chennel_index] + batch_shape[chennel_index + 1 :])+ return cast(torch.Size, batch_shape[:chennel_index] + batch_shape[chennel_index + 1:])def __repeat_param_across_channels__(self, param: torch.Tensor, frame_num: int) -> torch.Tensor:"""Repeat parameters across channels.diff --git a/kornia/color/__init__.py b/kornia/color/__init__.pyindex 202bb13ff..c3a2543fd 100644--- a/kornia/color/__init__.py+++ b/kornia/color/__init__.py@@ -90,4 +90,17 @@ __all__ = ["raw_to_rgb","rgb_to_raw","CFA",+ "GrayscaleToRgb",+ "luv_to_rgb",+ "rgb_to_luv",+ "bgr_to_rgba",+ "BgrToRgba",+ "linear_rgb_to_rgb",+ "LinearRgbToRgb",+ "rgb_to_linear_rgb",+ "rgba_to_rgb",+ "rgba_to_bgr",+ "RgbaToRgb",+ "RgbaToBgr",+ "RgbToLinearRgb",]diff --git a/kornia/color/hls.py b/kornia/color/hls.pyindex 109177500..b7b99a8a8 100644--- a/kornia/color/hls.py+++ b/kornia/color/hls.py@@ -49,29 +49,29 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:# s: torch.Tensor # not supported by JIT# image_hls: torch.Tensor # not supported by JITif image.requires_grad:- l = maxc + minc+ l_ = maxc + mincs = maxc - minc# weird behaviour with undefined vars in JIT...# scripting requires image_hls be defined even if it is not used :S- h = l # assign to any tensor...- image_hls = l # assign to any tensor...+ h = l_ # assign to any tensor...+ image_hls = l_ # assign to any tensor...else:# define the resulting image to avoid the torch.stack([h, l, s])# so, h, l and s require inplace operations# NOTE: stack() increases in a 10% the cost in colabimage_hls = torch.empty_like(image)h = torch.select(image_hls, -3, 0)- l = torch.select(image_hls, -3, 1)+ l_ = torch.select(image_hls, -3, 1)s = torch.select(image_hls, -3, 2)- torch.add(maxc, minc, out=l) # l = max + min+ torch.add(maxc, minc, out=l_) # l = max + mintorch.sub(maxc, minc, out=s) # s = max - min# precompute image / (max - min)im: torch.Tensor = image / (s + eps).unsqueeze(-3)# epsilon cannot be inside the torch.where to avoid precision issues- s /= torch.where(l < 1.0, l, 2.0 - l) + eps # saturation- l /= 2 # luminance+ s /= torch.where(l_ < 1.0, l_, 2.0 - l_) + eps # saturation+ l_ /= 2 # luminance# note that r,g and b were previously div by (max - min)r: torch.Tensor = torch.select(im, -3, 0)@@ -91,7 +91,7 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:h *= math.pi / 3.0 # hue [0, 2*pi]if image.requires_grad:- return torch.stack([h, l, s], dim=-3)+ return torch.stack([h, l_, s], dim=-3)return image_hlsdiff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.pyindex dff4055e3..66245b314 100644--- a/kornia/contrib/__init__.py+++ b/kornia/contrib/__init__.py@@ -1,15 +1,10 @@-from kornia.contrib.classification import ClassificationHead-from kornia.contrib.connected_components import connected_components-from kornia.contrib.extract_patches import (- combine_tensor_patches,- CombineTensorPatches,- extract_tensor_patches,- ExtractTensorPatches,-)-from kornia.contrib.image_stitching import ImageStitcher-from kornia.contrib.lambda_module import Lambda-from kornia.contrib.vit import VisionTransformer-from kornia.contrib.vit_mobile import MobileViT+from .classification import ClassificationHead+from .connected_components import connected_components+from .extract_patches import combine_tensor_patches, CombineTensorPatches, extract_tensor_patches, ExtractTensorPatches+from .image_stitching import ImageStitcher+from .lambda_module import Lambda+from .vit import VisionTransformer+from .vit_mobile import MobileViT__all__ = ["connected_components",diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.pyindex b3614f222..d2ba28370 100644--- a/kornia/contrib/image_stitching.py+++ b/kornia/contrib/image_stitching.py@@ -3,9 +3,11 @@ from typing import Dict, List, Optional, Tupleimport torchimport torch.nn as nn-import kornia as K--__all__ = ["ImageStitcher"]+from kornia.color import rgb_to_grayscale+from kornia.feature import LoFTR+from kornia.geometry.homography import find_homography_dlt_iterated+from kornia.geometry.ransac import RANSAC+from kornia.geometry.transform import warp_perspectiveclass ImageStitcher(nn.Module):@@ -41,7 +43,7 @@ class ImageStitcher(nn.Module):if estimator not in ['ransac', 'vanilla']:raise NotImplementedError(f"Unsupported estimator {estimator}. Use โransacโ or โvanillaโ instead.")if estimator == "ransac":- self.ransac = K.geometry.RANSAC('homography')+ self.ransac = RANSAC('homography')def _estimate_homography(self, keypoints1: torch.Tensor, keypoints2: torch.Tensor) -> torch.Tensor:"""Estimate homography by the matched keypoints.@@ -52,7 +54,7 @@ class ImageStitcher(nn.Module):"""homo: torch.Tensorif self.estimator == "vanilla":- homo = K.find_homography_dlt_iterated(+ homo = find_homography_dlt_iterated(keypoints2[None],keypoints1[None],torch.ones_like(keypoints1[None, :, 0])@@ -86,10 +88,10 @@ class ImageStitcher(nn.Module):def preprocess(self, image_1: torch.Tensor, image_2: torch.Tensor) -> Dict[str, torch.Tensor]:"""Preprocess input to the required format."""# TODO: probably perform histogram matching here.- if isinstance(self.matcher, K.feature.LoFTR):+ if isinstance(self.matcher, LoFTR):input_dict: Dict[str, torch.Tensor] = { # LofTR works on grayscale images only- "image0": K.color.rgb_to_grayscale(image_1),- "image1": K.color.rgb_to_grayscale(image_2)+ "image0": rgb_to_grayscale(image_1),+ "image1": rgb_to_grayscale(image_2)}else:raise NotImplementedError(f"The preprocessor for {self.matcher} has not been implemented.")@@ -115,7 +117,7 @@ class ImageStitcher(nn.Module):out_shape: Tuple[int, int] = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1])correspondences: dict = self.on_matcher(input_dict)homo: torch.Tensor = self.estimate_transform(**correspondences)- src_img = K.geometry.warp_perspective(images_right, homo, out_shape)+ src_img = warp_perspective(images_right, homo, out_shape)dst_img = torch.cat([images_left, torch.zeros_like(images_right)], dim=-1)# Compute the transformed masks@@ -124,7 +126,7 @@ class ImageStitcher(nn.Module):if mask_right is None:mask_right = torch.ones_like(images_right)# 'nearest' to ensure no floating points in the mask- src_mask = K.geometry.warp_perspective(mask_right, homo, out_shape, mode='nearest')+ src_mask = warp_perspective(mask_right, homo, out_shape, mode='nearest')dst_mask = torch.cat([mask_left, torch.zeros_like(mask_right)], dim=-1)return self.blend_image(src_img, dst_img, src_mask), (dst_mask + src_mask).bool().to(src_mask.dtype)diff --git a/kornia/contrib/vit_mobile.py b/kornia/contrib/vit_mobile.pyindex b7d1df86b..b6dc80b79 100644--- a/kornia/contrib/vit_mobile.py+++ b/kornia/contrib/vit_mobile.py@@ -3,8 +3,6 @@ from typing import Tupleimport torchfrom torch import nn-__all__ = ["MobileViT"]-class SiLU(nn.Module):"""Module SiLU (Sigmoid Linear Units)diff --git a/kornia/enhance/__init__.py b/kornia/enhance/__init__.pyindex 7791372cf..e20b29196 100644--- a/kornia/enhance/__init__.py+++ b/kornia/enhance/__init__.py@@ -1,6 +1,57 @@-from kornia.enhance.adjust import *-from kornia.enhance.core import *-from kornia.enhance.equalization import *-from kornia.enhance.histogram import *-from kornia.enhance.normalize import *-from kornia.enhance.zca import *+from .adjust import (+ adjust_brightness,+ adjust_contrast,+ adjust_gamma,+ adjust_hue,+ adjust_hue_raw,+ adjust_saturation,+ adjust_saturation_raw,+ AdjustBrightness,+ AdjustContrast,+ AdjustGamma,+ AdjustHue,+ AdjustSaturation,+ equalize,+ equalize3d,+ invert,+ Invert,+ posterize,+ sharpness,+ solarize,+)+from .core import add_weighted, AddWeighted+from .equalization import equalize_clahe+from .histogram import histogram, histogram2d, image_histogram2d+from .normalize import denormalize, Denormalize, normalize, Normalize, normalize_min_max+from .zca import linear_transform, zca_mean, zca_whiten, ZCAWhitening++__all__ = [+ "adjust_brightness",+ "adjust_contrast",+ "adjust_gamma",+ "adjust_hue",+ "adjust_saturation",+ "adjust_hue_raw",+ "adjust_saturation_raw",+ "solarize",+ "equalize",+ "equalize3d",+ "posterize",+ "sharpness",+ "invert",+ "AdjustBrightness",+ "AdjustContrast",+ "AdjustGamma",+ "AdjustHue",+ "AdjustSaturation",+ "Invert",+ "add_weighted",+ "AddWeighted",+ "equalize_clahe",+ "histogram",+ "histogram2d",+ "image_histogram2d",+ "normalize", "normalize_min_max", "denormalize", "Normalize",+ "Denormalize",+ "zca_mean", "zca_whiten", "linear_transform", "ZCAWhitening",+]diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 97d2464ce..18f566b47 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -3,34 +3,11 @@ from typing import Optional, Unionimport torchimport torch.nn as nn-import torch.nn.functional as Ffrom kornia.color.hsv import hsv_to_rgb, rgb_to_hsvfrom kornia.utils.helpers import _torch_histc_castfrom kornia.utils.image import perform_keep_shape_image, perform_keep_shape_video-__all__ = [- "adjust_brightness",- "adjust_contrast",- "adjust_gamma",- "adjust_hue",- "adjust_saturation",- "adjust_hue_raw",- "adjust_saturation_raw",- "solarize",- "equalize",- "equalize3d",- "posterize",- "sharpness",- "invert",- "AdjustBrightness",- "AdjustContrast",- "AdjustGamma",- "AdjustHue",- "AdjustSaturation",- "Invert",-]-def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Adjust color saturation of an image. Expecting input to be in hsv format already."""@@ -559,7 +536,7 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens"Batch and channel must be equal between bits and input. "f"Got {bits.shape}, {input.shape[:len(bits.shape)]}.")- _input = input.view(-1, *input.shape[len(bits.shape) :])+ _input = input.view(-1, *input.shape[len(bits.shape):])_bits = bits.flatten()for i in range(input.shape[0]):res.append(_posterize_one(_input[i], _bits[i]))diff --git a/kornia/enhance/core.py b/kornia/enhance/core.pyindex e7c2af61d..8400a0b92 100644--- a/kornia/enhance/core.py+++ b/kornia/enhance/core.py@@ -1,8 +1,6 @@import torchimport torch.nn as nn-__all__ = ["add_weighted", "AddWeighted"]-def add_weighted(src1: torch.Tensor, alpha: float, src2: torch.Tensor, beta: float, gamma: float) -> torch.Tensor:r"""Calculate the weighted sum of two Tensors.diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 81cc3a6bc..5287d8ee6 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -6,11 +6,10 @@ from typing import Tupleimport torchimport torch.nn.functional as F-from kornia.enhance.histogram import histogramfrom kornia.utils.helpers import _torch_histc_castfrom kornia.utils.image import perform_keep_shape_image-__all__ = ["equalize_clahe"]+from .histogram import histogramdef _compute_tiles(@@ -217,13 +216,13 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:(num_imgs, gh, gw, 4, c, luts.shape[-1]), -1, dtype=interp_tiles.dtype, device=interp_tiles.device)# corner regions- luts_x_interp_tiles[:, 0 :: gh - 1, 0 :: gw - 1, 0] = luts[:, 0 :: max(gh // 2 - 1, 1), 0 :: max(gw // 2 - 1, 1)]+ luts_x_interp_tiles[:, 0:: gh - 1, 0:: gw - 1, 0] = luts[:, 0:: max(gh // 2 - 1, 1), 0:: max(gw // 2 - 1, 1)]# border region (h)- luts_x_interp_tiles[:, 1:-1, 0 :: gw - 1, 0] = luts[:, j_idxs[:, 0], 0 :: max(gw // 2 - 1, 1)]- luts_x_interp_tiles[:, 1:-1, 0 :: gw - 1, 1] = luts[:, j_idxs[:, 2], 0 :: max(gw // 2 - 1, 1)]+ luts_x_interp_tiles[:, 1:-1, 0:: gw - 1, 0] = luts[:, j_idxs[:, 0], 0:: max(gw // 2 - 1, 1)]+ luts_x_interp_tiles[:, 1:-1, 0:: gw - 1, 1] = luts[:, j_idxs[:, 2], 0:: max(gw // 2 - 1, 1)]# border region (w)- luts_x_interp_tiles[:, 0 :: gh - 1, 1:-1, 0] = luts[:, 0 :: max(gh // 2 - 1, 1), i_idxs[:, 0]]- luts_x_interp_tiles[:, 0 :: gh - 1, 1:-1, 1] = luts[:, 0 :: max(gh // 2 - 1, 1), i_idxs[:, 1]]+ luts_x_interp_tiles[:, 0:: gh - 1, 1:-1, 0] = luts[:, 0:: max(gh // 2 - 1, 1), i_idxs[:, 0]]+ luts_x_interp_tiles[:, 0:: gh - 1, 1:-1, 1] = luts[:, 0:: max(gh // 2 - 1, 1), i_idxs[:, 1]]# internal regionluts_x_interp_tiles[:, 1:-1, 1:-1, :] = luts[:, j_idxs.repeat(max(gh - 2, 1), 1, 1).permute(1, 0, 2), i_idxs.repeat(max(gw - 2, 1), 1, 1)@@ -294,7 +293,7 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->tiles_equalized[:, 1:-1, 1:-1] = torch.addcmul(b, tih, torch.sub(t, b))# corner regions- tiles_equalized[:, 0 :: gh - 1, 0 :: gw - 1] = preinterp_tiles_equalized[:, 0 :: gh - 1, 0 :: gw - 1, 0]+ tiles_equalized[:, 0:: gh - 1, 0:: gw - 1] = preinterp_tiles_equalized[:, 0:: gh - 1, 0:: gw - 1, 0]# border region (h)t, b, _, _ = preinterp_tiles_equalized[:, 1:-1, 0].unbind(2)diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.pyindex cfafe3904..4088b37e5 100644--- a/kornia/enhance/histogram.py+++ b/kornia/enhance/histogram.py@@ -1,10 +1,7 @@-import mathfrom typing import Optional, Tupleimport torch-__all__ = ["histogram", "histogram2d", "image_histogram2d"]-def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float = 1e-10diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.pyindex e7961b68c..1a425278a 100644--- a/kornia/enhance/zca.py+++ b/kornia/enhance/zca.py@@ -228,7 +228,7 @@ def zca_mean(inp_permute = inp.permute(new_order)N = inp_size[dim]- feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1 : :])+ feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1::])num_features: int = int(torch.prod(feature_sizes).item())mean: torch.Tensor = torch.mean(inp_permute, dim=0, keepdim=True)@@ -368,7 +368,7 @@ def linear_transform(new_order: List[int] = perm.tolist()inv_order: List[int] = perm_inv.tolist()- feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1 : :])+ feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1::])num_features: int = int(torch.prod(feature_sizes).item())inp_permute = inp.permute(new_order)diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex 16b4df144..364621b03 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -1,24 +1,14 @@-from .loftr import LoFTR-from .nms import nms2d, nms3d, NonMaximaSuppression2d, NonMaximaSuppression3d-from .responses import (- BlobDoG,- BlobHessian,- CornerGFTT,- CornerHarris,- dog_response,- gftt_response,- harris_response,- hessian_response,-)--# Backward compatibility-non_maxima_suppression2d = nms2d-non_maxima_suppression3d = nms3d-from .affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, PatchAffineShapeEstimatorfrom .defmo import DeFMOfrom .hardnet import HardNet, HardNet8-from .integrated import *+from .integrated import (+ get_laf_descriptors,+ GFTTAffNetHardNet,+ LAFDescriptor,+ LocalFeature,+ LocalFeatureMatcher,+ SIFTFeature,+)from .laf import (denormalize_laf,ellipse_to_laf,@@ -34,29 +24,47 @@ from .laf import (laf_to_three_points,make_upright,normalize_laf,+ perspective_transform_lafs,raise_error_if_laf_is_not_valid,scale_laf,set_laf_orientation,)-from .matching import *+from .loftr import LoFTR+from .matching import DescriptorMatcher, match_mnn, match_nn, match_smnn, match_snnfrom .mkd import MKDDescriptorfrom .orientation import LAFOrienter, OriNet, PatchDominantGradientOrientation+from .responses import (+ BlobDoG,+ BlobHessian,+ CornerGFTT,+ CornerHarris,+ dog_response,+ gftt_response,+ harris_response,+ hessian_response,+)from .scale_space_detector import PassLAF, ScaleSpaceDetectorfrom .siftdesc import SIFTDescriptorfrom .sosnet import SOSNetfrom .tfeat import TFeat__all__ = [- "nms2d",- "nms3d",- "non_maxima_suppression2d",- "non_maxima_suppression3d",+ "match_nn",+ "match_mnn",+ "match_snn",+ "match_smnn",+ "DescriptorMatcher",+ "get_laf_descriptors",+ "LAFDescriptor",+ "LocalFeature",+ "SIFTFeature",+ "GFTTAffNetHardNet",+ "LocalFeatureMatcher",+ "SOSNet","harris_response","gftt_response","hessian_response","dog_response",- "NonMaximaSuppression2d",- "NonMaximaSuppression3d","CornerHarris","CornerGFTT","BlobHessian",@@ -104,4 +112,5 @@ __all__ = ["LAFDescriptor","DescriptorMatcher","LoFTR",+ "perspective_transform_lafs",]diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 31f3da3cd..6bd562c1e 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -4,7 +4,10 @@ from typing import Dict, Optionalimport torchimport torch.nn as nn-from kornia.feature.laf import (+from kornia.filters.kernels import get_gaussian_kernel2d+from kornia.filters.sobel import SpatialGradient++from .laf import (ellipse_to_laf,extract_patches_from_pyramid,get_laf_scale,@@ -12,7 +15,6 @@ from kornia.feature.laf import (raise_error_if_laf_is_not_valid,scale_laf,)-from kornia.filters import get_gaussian_kernel2d, SpatialGradienturls: Dict[str, str] = {}urls["affnet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/AffNet.pth"diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex d97a48a64..d71352b4a 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -4,14 +4,16 @@ import torchimport torch.nn as nnfrom kornia.color import rgb_to_grayscale-from kornia.feature.affine_shape import LAFAffNetShapeEstimator-from kornia.feature.hardnet import HardNet-from kornia.feature.laf import extract_patches_from_pyramid, get_laf_center, raise_error_if_laf_is_not_valid-from kornia.feature.orientation import LAFOrienter, PassLAF-from kornia.feature.responses import BlobDoG, CornerGFTT-from kornia.feature.scale_space_detector import ScaleSpaceDetector-from kornia.feature.siftdesc import SIFTDescriptor-from kornia.geometry import ConvQuadInterp3d, ScalePyramid+from kornia.geometry.subpix import ConvQuadInterp3d+from kornia.geometry.transform import ScalePyramid++from .affine_shape import LAFAffNetShapeEstimator+from .hardnet import HardNet+from .laf import extract_patches_from_pyramid, get_laf_center, raise_error_if_laf_is_not_valid+from .orientation import LAFOrienter, PassLAF+from .responses import BlobDoG, CornerGFTT+from .scale_space_detector import ScaleSpaceDetector+from .siftdesc import SIFTDescriptordef get_laf_descriptors(img: torch.Tensor,diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex cbe4a008a..8ce63b7c3 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -4,8 +4,9 @@ from typing import Unionimport torchimport torch.nn.functional as F-import kornia-from kornia.geometry import angle_to_rotation_matrix+from kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous, rad2deg+from kornia.geometry.linalg import transform_points+from kornia.geometry.transform import pyrdowndef raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:@@ -88,7 +89,7 @@ def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:"""raise_error_if_laf_is_not_valid(LAF)angle_rad: torch.Tensor = torch.atan2(LAF[..., 0, 1], LAF[..., 0, 0])- return kornia.rad2deg(angle_rad).unsqueeze(-1)+ return rad2deg(angle_rad).unsqueeze(-1)def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:@@ -138,7 +139,7 @@ def laf_from_center_scale_ori(xy: torch.Tensor, scale: torch.Tensor, ori: torch.raise TypeError("{} shape should be must be [{}]. " "Got {}".format(var_name, str(req_shape), var.size()))- unscaled_laf: torch.Tensor = torch.cat([kornia.angle_to_rotation_matrix(ori.squeeze(-1)), xy.unsqueeze(-1)], dim=-1)+ unscaled_laf: torch.Tensor = torch.cat([angle_to_rotation_matrix(ori.squeeze(-1)), xy.unsqueeze(-1)], dim=-1)laf: torch.Tensor = scale_laf(unscaled_laf, scale)return laf@@ -289,7 +290,7 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:aux = torch.tensor([0.0, 0.0, 1.0]).view(1, 1, 3).expand(B * N, 1, 3)HLAF = torch.cat([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)pts_h = torch.bmm(HLAF, pts.permute(0, 2, 1)).permute(0, 2, 1)- return kornia.convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))+ return convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0):@@ -315,7 +316,7 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0):"""# TODO: Refactor doctestraise_error_if_laf_is_not_valid(LAF)- pts = laf_to_boundary_points(LAF[img_idx : img_idx + 1])[0]+ pts = laf_to_boundary_points(LAF[img_idx: img_idx + 1])[0]pts_np = pts.detach().permute(1, 0, 2).cpu().numpy()return (pts_np[..., 0], pts_np[..., 1])@@ -436,10 +437,10 @@ def extract_patches_simple(out = []# for loop temporarily, to be refactoredfor i in range(B):- grid = generate_patch_grid_from_normalized_LAF(img[i : i + 1], nlaf[i : i + 1], PS).to(img.device)+ grid = generate_patch_grid_from_normalized_LAF(img[i: i + 1], nlaf[i: i + 1], PS).to(img.device)out.append(F.grid_sample(- img[i : i + 1].expand(grid.size(0), ch, h, w),+ img[i: i + 1].expand(grid.size(0), ch, h, w),grid, # type: ignorepadding_mode="border",align_corners=False,@@ -485,15 +486,15 @@ def extract_patches_from_pyramid(if (scale_mask.float().sum()) == 0:continuescale_mask = (scale_mask > 0).view(-1)- grid = generate_patch_grid_from_normalized_LAF(cur_img[i : i + 1], nlaf[i : i + 1, scale_mask, :, :], PS)+ grid = generate_patch_grid_from_normalized_LAF(cur_img[i: i + 1], nlaf[i: i + 1, scale_mask, :, :], PS)patches = F.grid_sample(- cur_img[i : i + 1].expand(grid.size(0), ch, h, w),+ cur_img[i: i + 1].expand(grid.size(0), ch, h, w),grid, # type: ignorepadding_mode="border",align_corners=False,)out[i].masked_scatter_(scale_mask.view(-1, 1, 1, 1), patches)- cur_img = kornia.pyrdown(cur_img)+ cur_img = pyrdown(cur_img)cur_pyr_level += 1return out@@ -551,3 +552,72 @@ def laf_from_three_points(threepts: torch.Tensor):[threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1)return laf+++def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) -> torch.Tensor:+ r"""Function that applies perspective transformations to a set of local affine frames (LAFs).++ Args:+ trans_01: tensor for perspective transformations of shape :math:`(B, 3, 3)`.+ lafs_1: tensor of lafs of shape :math:`(B, N, 2, 3)`.++ Returns:+ tensor of N-dimensional points of shape :math:`(B, N, 2, 3)`.++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> lafs_1 = torch.rand(2, 4, 2, 3) # BxNx2x3+ >>> lafs_1+ tensor([[[[0.4963, 0.7682, 0.0885],+ [0.1320, 0.3074, 0.6341]],+ <BLANKLINE>+ [[0.4901, 0.8964, 0.4556],+ [0.6323, 0.3489, 0.4017]],+ <BLANKLINE>+ [[0.0223, 0.1689, 0.2939],+ [0.5185, 0.6977, 0.8000]],+ <BLANKLINE>+ [[0.1610, 0.2823, 0.6816],+ [0.9152, 0.3971, 0.8742]]],+ <BLANKLINE>+ <BLANKLINE>+ [[[0.4194, 0.5529, 0.9527],+ [0.0362, 0.1852, 0.3734]],+ <BLANKLINE>+ [[0.3051, 0.9320, 0.1759],+ [0.2698, 0.1507, 0.0317]],+ <BLANKLINE>+ [[0.2081, 0.9298, 0.7231],+ [0.7423, 0.5263, 0.2437]],+ <BLANKLINE>+ [[0.5846, 0.0332, 0.1387],+ [0.2422, 0.8155, 0.7932]]]])+ >>> trans_01 = torch.eye(3).repeat(2, 1, 1) # Bx3x3+ >>> trans_01.shape+ torch.Size([2, 3, 3])+ >>> lafs_0 = perspective_transform_lafs(trans_01, lafs_1) # BxNx2x3+ """+ raise_error_if_laf_is_not_valid(lafs_1)+ if not torch.is_tensor(trans_01):+ raise TypeError("Input type is not a torch.Tensor")++ if not trans_01.device == lafs_1.device:+ raise TypeError("Tensor must be in the same device")++ if not trans_01.shape[0] == lafs_1.shape[0]:+ raise ValueError("Input batch size must be the same for both tensors")++ if (not (trans_01.shape[-1] == 3)) or (not (trans_01.shape[-2] == 3)):+ raise ValueError("Transformation should be homography")++ bs, n, _, _ = lafs_1.size()+ # First, we convert LAF to points+ threepts_1 = laf_to_three_points(lafs_1)+ points_1 = threepts_1.permute(0, 1, 3, 2).reshape(bs, n * 3, 2)++ # First, transform the points+ points_0 = transform_points(trans_01, points_1)++ # Back to LAF format+ threepts_0 = points_0.view(bs, n, 3, 2).permute(0, 1, 3, 2)+ return laf_from_three_points(threepts_0)diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.pyindex 4aa11224d..622cebcd1 100644--- a/kornia/feature/loftr/utils/coarse_matching.py+++ b/kornia/feature/loftr/utils/coarse_matching.py@@ -103,7 +103,7 @@ class CoarseMatching(nn.Module):'mconf' (torch.Tensor): [M]}NOTE: M' != M during training."""- N, L, S, C = feat_c0.size(0), feat_c0.size(1), feat_c1.size(1), feat_c0.size(2)+ _, L, S, _ = feat_c0.size(0), feat_c0.size(1), feat_c1.size(1), feat_c0.size(2)# normalizefeat_c0, feat_c1 = map(lambda feat: feat / feat.shape[-1]**.5,diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.pyindex 711d39a19..9b97bd6b7 100644--- a/kornia/feature/loftr/utils/fine_matching.py+++ b/kornia/feature/loftr/utils/fine_matching.py@@ -65,7 +65,7 @@ class FineMatching(nn.Module):@torch.no_grad()def get_fine_match(self, coords_normed, data):- W, WW, C, scale = self.W, self.WW, self.C, self.scale+ W, _, _, scale = self.W, self.WW, self.C, self.scale# mkpts0_f and mkpts1_fmkpts0_f = data['mkpts0_c']diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.pyindex 7b8cdd34f..30242a252 100644--- a/kornia/feature/loftr/utils/supervision.py+++ b/kornia/feature/loftr/utils/supervision.py@@ -1,5 +1,3 @@-from math import log-import torchfrom kornia.utils import create_meshgriddiff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex cee95f33b..750ec327a 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -1,10 +1,8 @@-from typing import Dict, List, Optional, Tuple+from typing import Optional, Tupleimport torchimport torch.nn as nn-from kornia.feature import extract_patches_from_pyramid, get_laf_center-def match_nn(desc1: torch.Tensor, desc2: torch.Tensor, dm: Optional[torch.Tensor] = Nonediff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex 5ff9eb8cd..a921b5bd3 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -128,7 +128,7 @@ class VonMisesKernel(nn.Module):frange = frange.reshape(-1, 1, 1)weights = torch.zeros([2 * n + 1])weights[: n + 1] = torch.sqrt(b_coeffs)- weights[n + 1 :] = torch.sqrt(b_coeffs[1:])+ weights[n + 1:] = torch.sqrt(b_coeffs[1:])weights = weights.reshape(-1, 1, 1)self.register_buffer('emb0', emb0)self.register_buffer('frange', frange)diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex 9efa6e1a3..a9c767f3f 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -6,15 +6,11 @@ import torch.nn as nnimport torch.nn.functional as Ffrom kornia.constants import pi-from kornia.feature.laf import (- extract_patches_from_pyramid,- get_laf_orientation,- raise_error_if_laf_is_not_valid,- set_laf_orientation,-)from kornia.filters import get_gaussian_kernel2d, SpatialGradientfrom kornia.geometry import rad2deg+from .laf import extract_patches_from_pyramid, get_laf_orientation, raise_error_if_laf_is_not_valid, set_laf_orientation+urls: Dict[str, str] = {}urls["orinet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/OriNet.pth"diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex a68d6c458..0441a3a5c 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -4,12 +4,13 @@ import torchimport torch.nn as nnimport torch.nn.functional as F-from kornia.feature.laf import denormalize_laf, laf_is_inside_image, normalize_laf-from kornia.feature.orientation import PassLAF-from kornia.feature.responses import BlobHessian-from kornia.geometry import ConvSoftArgmax3d+from kornia.geometry.subpix import ConvSoftArgmax3dfrom kornia.geometry.transform import ScalePyramid+from .laf import denormalize_laf, laf_is_inside_image, normalize_laf+from .orientation import PassLAF+from .responses import BlobHessian+def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_levels: int) -> torch.Tensor:r"""Auxiliary function for ScaleSpaceDetector. Converts scale level index from ConvSoftArgmax3ddiff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.pyindex cea39ede2..2e7fcb870 100644--- a/kornia/filters/__init__.py+++ b/kornia/filters/__init__.py@@ -27,18 +27,24 @@ from .sobel import Sobel, sobel, spatial_gradient, spatial_gradient3d, SpatialGrfrom .unsharp import unsharp_mask, UnsharpMask__all__ = [+ "gaussian",+ "get_binary_kernel2d",+ "get_box_kernel2d","get_gaussian_kernel1d","get_gaussian_discrete_kernel1d","get_gaussian_erf_kernel1d","get_gaussian_kernel2d","get_laplacian_kernel1d","get_laplacian_kernel2d",+ "get_motion_kernel2d",+ "get_motion_kernel3d","get_spatial_gradient_kernel2d","get_spatial_gradient_kernel3d","get_sobel_kernel2d","get_diff_kernel2d","gaussian_blur2d","laplacian",+ "laplacian_1d","unsharp_mask","sobel","spatial_gradient",diff --git a/kornia/filters/blur.py b/kornia/filters/blur.pyindex d8651eec8..1e397090e 100644--- a/kornia/filters/blur.py+++ b/kornia/filters/blur.py@@ -3,8 +3,8 @@ from typing import Tupleimport torchimport torch.nn as nn-import kornia-from kornia.filters.kernels import get_box_kernel2d, normalize_kernel2d+from .filter import filter2d+from .kernels import get_box_kernel2d, normalize_kernel2ddef box_blur(@@ -48,7 +48,7 @@ def box_blur(kernel: torch.Tensor = get_box_kernel2d(kernel_size)if normalized:kernel = normalize_kernel2d(kernel)- return kornia.filter2d(input, kernel, border_type)+ return filter2d(input, kernel, border_type)class BoxBlur(nn.Module):diff --git a/kornia/filters/canny.py b/kornia/filters/canny.pyindex dd1046f5b..2f11f4b73 100644--- a/kornia/filters/canny.py+++ b/kornia/filters/canny.py@@ -1,3 +1,4 @@+import mathfrom typing import Tupleimport torch@@ -5,11 +6,10 @@ import torch.nn as nnimport torch.nn.functional as Ffrom kornia.color import rgb_to_grayscale-from kornia.filters.gaussian import gaussian_blur2d-from kornia.filters.sobel import spatial_gradient-from kornia.geometry.conversions import rad2deg+from .gaussian import gaussian_blur2dfrom .kernels import get_canny_nms_kernel, get_hysteresis_kernel+from .sobel import spatial_gradientdef canny(@@ -92,7 +92,7 @@ def canny(angle: torch.Tensor = torch.atan2(gy, gx)# Radians to Degrees- angle = rad2deg(angle)+ angle = 180. * angle / math.pi# Round angle to the nearest 45 degreeangle = torch.round(angle / 45) * 45diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex 030773413..67194297b 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -3,8 +3,8 @@ from typing import Listimport torchimport torch.nn.functional as F-from kornia.filters.__tmp__ import _deprecation_wrapper-from kornia.filters.kernels import normalize_kernel2d+from .__tmp__ import _deprecation_wrapper+from .kernels import normalize_kernel2ddef _compute_padding(kernel_size: List[int]) -> List[int]:diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex 74e104f44..6fe2b1d6a 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -3,8 +3,8 @@ from typing import Tupleimport torchimport torch.nn as nn-import kornia-from kornia.filters.kernels import get_gaussian_kernel1d, get_gaussian_kernel2d+from .filter import filter2d, filter2d_separable+from .kernels import get_gaussian_kernel1d, get_gaussian_kernel2ddef gaussian_blur2d(input: torch.Tensor,@@ -44,10 +44,10 @@ def gaussian_blur2d(input: torch.Tensor,if separable:kernel_x: torch.Tensor = get_gaussian_kernel1d(kernel_size[1], sigma[1])kernel_y: torch.Tensor = get_gaussian_kernel1d(kernel_size[0], sigma[0])- out = kornia.filters.filter2d_separable(input, kernel_x[None], kernel_y[None], border_type)+ out = filter2d_separable(input, kernel_x[None], kernel_y[None], border_type)else:kernel: torch.Tensor = get_gaussian_kernel2d(kernel_size, sigma)- out = kornia.filters.filter2d(input, kernel[None], border_type)+ out = filter2d(input, kernel[None], border_type)return outdiff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.pyindex 6e0c0cd3d..6bca901d9 100644--- a/kornia/filters/kernels_geometry.py+++ b/kornia/filters/kernels_geometry.py@@ -2,7 +2,7 @@ from typing import cast, Tuple, Unionimport torch-from kornia.geometry.transform.affwarp import rotate, rotate3d+from kornia.geometry.transform import rotate, rotate3dfrom kornia.utils import _extract_device_dtype@@ -15,28 +15,25 @@ def get_motion_kernel2d(r"""Return 2D motion blur filter.Args:- kernel_size (int): motion kernel width and height. It should be odd and positive.- angle (torch.Tensor, float): angle of the motion blur in degrees (anti-clockwise rotation).- direction (float): forward/backward direction of the motion blur.+ kernel_size: motion kernel width and height. It should be odd and positive.+ angle: angle of the motion blur in degrees (anti-clockwise rotation).+ direction: forward/backward direction of the motion blur.Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to auniformly (but still angled) motion blur.- mode (str): interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.- Default: ``'nearest'``+ mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.Returns:- torch.Tensor: the motion blur kernel.+ The motion blur kernel of shape :math:`(B, k_\text{size}, k_\text{size})`.- Shape:- - Output: :math:`(B, ksize, ksize)`-- Examples::+ Examples:>>> get_motion_kernel2d(5, 0., 0.)tensor([[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],[0.2000, 0.2000, 0.2000, 0.2000, 0.2000],[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],[0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]])+>>> get_motion_kernel2d(3, 215., -0.5)tensor([[[0.0000, 0.0000, 0.1667],[0.0000, 0.3333, 0.0000],@@ -53,8 +50,10 @@ def get_motion_kernel2d(angle = torch.tensor([angle], device=device, dtype=dtype)angle = cast(torch.Tensor, angle)+if angle.dim() == 0:angle = angle.unsqueeze(0)+if angle.dim() != 1:raise AssertionError(f"angle must be a 1-dim tensor. Got {angle}.")@@ -62,8 +61,10 @@ def get_motion_kernel2d(direction = torch.tensor([direction], device=device, dtype=dtype)direction = cast(torch.Tensor, direction)+if direction.dim() == 0:direction = direction.unsqueeze(0)+if direction.dim() != 1:raise AssertionError(f"direction must be a 1-dim tensor. Got {direction}.")@@ -71,6 +72,7 @@ def get_motion_kernel2d(raise AssertionError(f"direction and angle must have the same length. Got {direction} and {angle}.")kernel_tuple: Tuple[int, int] = (kernel_size, kernel_size)+# direction from [-1, 1] to [0, 1] rangedirection = (torch.clamp(direction, -1.0, 1.0) + 1.0) / 2.0# kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)@@ -83,9 +85,11 @@ def get_motion_kernel2d(# kernel[:, kernel_size // 2, :] = direction[:, None].repeat(1, kernel_size) + m * torch.arange(0, kernel_size)k = torch.stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)kernel = torch.nn.functional.pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2, 0, 0])+if kernel.shape != torch.Size([direction.size(0), *kernel_tuple]):raise AssertionErrorkernel = kernel.unsqueeze(1)+# rotate (counterclockwise) kernel by given anglekernel = rotate(kernel, angle, mode=mode, align_corners=True)kernel = kernel[:, 0]@@ -102,22 +106,18 @@ def get_motion_kernel3d(r"""Return 3D motion blur filter.Args:- kernel_size (int): motion kernel width, height and depth. It should be odd and positive.- angle (tensor or tuple): Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ kernel_size: motion kernel width, height and depth. It should be odd and positive.+ angle: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.If tensor, it must be :math:`(B, 3)`.If tuple, it must be (yaw, pitch, raw).- direction (float): forward/backward direction of the motion blur.+ direction: forward/backward direction of the motion blur.Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to auniformly (but still angled) motion blur.- mode (str): interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.- Default: ``'nearest'``.+ mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.Returns:- torch.Tensor: the motion blur kernel.-- Shape:- - Output: :math:`(B, kernel_size, kernel_size, kernel_size)`+ The motion blur kernel with shape :math:`(B, k_\text{size}, k_\text{size}, k_\text{size})`.Examples:>>> get_motion_kernel3d(3, (0., 0., 0.), 0.)@@ -132,6 +132,7 @@ def get_motion_kernel3d([[0.0000, 0.0000, 0.0000],[0.0000, 0.0000, 0.0000],[0.0000, 0.0000, 0.0000]]]])+>>> get_motion_kernel3d(3, (90., 90., 0.), -0.5)tensor([[[[0.0000, 0.0000, 0.0000],[0.0000, 0.0000, 0.0000],@@ -156,8 +157,10 @@ def get_motion_kernel3d(angle = torch.tensor([angle], device=device, dtype=dtype)angle = cast(torch.Tensor, angle)+if angle.dim() == 1:angle = angle.unsqueeze(0)+if not (len(angle.shape) == 2 and angle.size(1) == 3):raise AssertionError(f"angle must be (B, 3). Got {angle}.")@@ -165,8 +168,10 @@ def get_motion_kernel3d(direction = torch.tensor([direction], device=device, dtype=dtype)direction = cast(torch.Tensor, direction)+if direction.dim() == 0:direction = direction.unsqueeze(0)+if direction.dim() != 1:raise AssertionError(f"direction must be a 1-dim tensor. Got {direction}.")@@ -174,6 +179,7 @@ def get_motion_kernel3d(raise AssertionError(f"direction and angle must have the same length. Got {direction} and {angle}.")kernel_tuple: Tuple[int, int, int] = (kernel_size, kernel_size, kernel_size)+# direction from [-1, 1] to [0, 1] rangedirection = (torch.clamp(direction, -1.0, 1.0) + 1.0) / 2.0kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)@@ -185,9 +191,11 @@ def get_motion_kernel3d(kernel = torch.nn.functional.pad(k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0])+if kernel.shape != torch.Size([direction.size(0), *kernel_tuple]):raise AssertionErrorkernel = kernel.unsqueeze(1)+# rotate (counterclockwise) kernel by given anglekernel = rotate3d(kernel, angle[:, 0], angle[:, 1], angle[:, 2], mode=mode, align_corners=True)kernel = kernel[:, 0]diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.pyindex 76566156e..6b62292a5 100644--- a/kornia/filters/laplacian.py+++ b/kornia/filters/laplacian.py@@ -1,8 +1,8 @@import torchimport torch.nn as nn-import kornia-from kornia.filters.kernels import get_laplacian_kernel2d, normalize_kernel2d+from .filter import filter2d+from .kernels import get_laplacian_kernel2d, normalize_kernel2ddef laplacian(@@ -41,7 +41,7 @@ def laplacian(if normalized:kernel = normalize_kernel2d(kernel)- return kornia.filter2d(input, kernel, border_type)+ return filter2d(input, kernel, border_type)class Laplacian(nn.Module):diff --git a/kornia/filters/median.py b/kornia/filters/median.pyindex ea532c419..3d9e26910 100644--- a/kornia/filters/median.py+++ b/kornia/filters/median.py@@ -4,7 +4,7 @@ import torchimport torch.nn as nnimport torch.nn.functional as F-from kornia.filters.kernels import get_binary_kernel2d+from .kernels import get_binary_kernel2ddef _compute_zero_padding(kernel_size: Tuple[int, int]) -> Tuple[int, int]:diff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 774b983ed..3a0ac7414 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -3,8 +3,8 @@ from typing import Tuple, Unionimport torchimport torch.nn as nn-import kornia-from kornia.filters.kernels_geometry import get_motion_kernel2d, get_motion_kernel3d+from .filter import filter2d, filter3d+from .kernels_geometry import get_motion_kernel2d, get_motion_kernel3dclass MotionBlur(nn.Module):@@ -148,7 +148,7 @@ def motion_blur(if border_type not in ["constant", "reflect", "replicate", "circular"]:raise AssertionErrorkernel: torch.Tensor = get_motion_kernel2d(kernel_size, angle, direction, mode)- return kornia.filter2d(input, kernel, border_type)+ return filter2d(input, kernel, border_type)def motion_blur3d(@@ -192,4 +192,4 @@ def motion_blur3d(if border_type not in ["constant", "reflect", "replicate", "circular"]:raise AssertionErrorkernel: torch.Tensor = get_motion_kernel3d(kernel_size, angle, direction, mode)- return kornia.filter3d(input, kernel, border_type)+ return filter3d(input, kernel, border_type)diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex 3b5fd9a51..8c9edc2a9 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -2,7 +2,7 @@ import torchimport torch.nn as nnimport torch.nn.functional as F-from kornia.filters.kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d+from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2ddef spatial_gradient(input: torch.Tensor, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> torch.Tensor:diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.pyindex ee5daeaa4..809101bce 100644--- a/kornia/filters/unsharp.py+++ b/kornia/filters/unsharp.py@@ -3,7 +3,7 @@ from typing import Tupleimport torchimport torch.nn as nn-from kornia.filters import gaussian_blur2d+from .gaussian import gaussian_blur2ddef unsharp_mask(diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.pyindex 6054209f6..47068a259 100644--- a/kornia/geometry/__init__.py+++ b/kornia/geometry/__init__.py@@ -1,11 +1,11 @@-from kornia.geometry.bbox import *-from kornia.geometry.calibration import *-from kornia.geometry.camera import *-from kornia.geometry.conversions import *-from kornia.geometry.depth import *-from kornia.geometry.epipolar import *-from kornia.geometry.homography import *-from kornia.geometry.linalg import *-from kornia.geometry.ransac import *-from kornia.geometry.subpix import *-from kornia.geometry.transform import *+from .bbox import *+from .calibration import *+from .camera import *+from .conversions import *+from .depth import *+from .epipolar import *+from .homography import *+from .linalg import *+from .ransac import *+from .subpix import *+from .transform import *diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.pyindex 28555d2ff..74249bd4d 100644--- a/kornia/geometry/bbox.py+++ b/kornia/geometry/bbox.py@@ -2,7 +2,19 @@ from typing import Tupleimport torch-import kornia+from .linalg import transform_points++__all__ = [+ "validate_bbox",+ "validate_bbox3d",+ "infer_bbox_shape",+ "infer_bbox_shape3d",+ "bbox_to_mask",+ "bbox_to_mask3d",+ "bbox_generator",+ "bbox_generator3d",+ "transform_bbox",+]@torch.jit.ignore@@ -445,7 +457,7 @@ def transform_bbox(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyboxes[..., -2] = boxes[..., 0] + boxes[..., -2] # x + wboxes[..., -1] = boxes[..., 1] + boxes[..., -1] # y + h- transformed_boxes: torch.Tensor = kornia.transform_points(trans_mat, boxes.view(boxes.shape[0], -1, 2))+ transformed_boxes: torch.Tensor = transform_points(trans_mat, boxes.view(boxes.shape[0], -1, 2))transformed_boxes = transformed_boxes.view_as(boxes)if mode == 'xywh':diff --git a/kornia/geometry/calibration/__init__.py b/kornia/geometry/calibration/__init__.pyindex 3d0403027..d62ef7e52 100644--- a/kornia/geometry/calibration/__init__.py+++ b/kornia/geometry/calibration/__init__.py@@ -1,3 +1,11 @@-from kornia.geometry.calibration.distort import *-from kornia.geometry.calibration.pnp import *-from kornia.geometry.calibration.undistort import *+from .distort import distort_points, tilt_projection+from .pnp import solve_pnp_dlt+from .undistort import undistort_image, undistort_points++__all__ = [+ "undistort_points",+ "undistort_image",+ "tilt_projection",+ "distort_points",+ "solve_pnp_dlt",+]diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.pyindex c1388fd41..4b01933bc 100644--- a/kornia/geometry/calibration/distort.py+++ b/kornia/geometry/calibration/distort.py@@ -1,10 +1,5 @@import torch-__all__ = [- "tilt_projection",- "distort_points",-]-# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/distortion_model.hpp#L75def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool = False) -> torch.Tensor:@@ -80,8 +75,7 @@ def distort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->>>> points = torch.rand(1, 1, 2)>>> K = torch.eye(3)[None]>>> dist_coeff = torch.rand(1, 4)- >>> distort_points(points, K, dist_coeff)- tensor([[[3.6138, 5.4226]]])+ >>> points_dist = distort_points(points, K, dist_coeff)"""if points.dim() < 2 and points.shape[-1] != 2:diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.pyindex f739443d6..3ff27ea68 100644--- a/kornia/geometry/calibration/pnp.py+++ b/kornia/geometry/calibration/pnp.py@@ -2,15 +2,11 @@ from typing import Optional, Tupleimport torch-import korniafrom kornia.geometry.conversions import convert_points_to_homogeneousfrom kornia.geometry.linalg import transform_points+from kornia.utils import eye_likefrom kornia.utils._compat import linalg_qr-__all__ = [- "solve_pnp_dlt",-]-def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8@@ -38,7 +34,7 @@ def _mean_isotropic_scale_normalize(D_int = points.shape[-1]D_float = torch.tensor(points.shape[-1], dtype=torch.float64, device=points.device)scale = torch.sqrt(D_float) / (scale + eps) # B- transform = kornia.eye_like(D_int + 1, points) # (B, D+1, D+1)+ transform = eye_like(D_int + 1, points) # (B, D+1, D+1)idxs = torch.arange(D_int, dtype=torch.int64, device=points.device)transform[:, idxs, idxs] = transform[:, idxs, idxs] * scale[:, None]@@ -245,7 +241,7 @@ def solve_pnp_dlt(solution = solution.reshape(B, 3, 4)# Creating solution_4x4- solution_4x4 = kornia.eye_like(4, solution)+ solution_4x4 = eye_like(4, solution)solution_4x4[:, :3, :] = solution# De-normalizing the solution@@ -282,7 +278,7 @@ def solve_pnp_dlt(# If right[i, j, j] is negative, then we need to flip the signs of# the column ortho[i, :, j]. The below code performs the necessary# operations in an better way.- mask = kornia.eye_like(3, ortho)+ mask = eye_like(3, ortho)col_sign_fix = torch.sign(mask * right)rot_mat = torch.bmm(ortho, col_sign_fix)diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.pyindex 9a0685d52..88063bddd 100644--- a/kornia/geometry/calibration/undistort.py+++ b/kornia/geometry/calibration/undistort.py@@ -1,14 +1,10 @@import torch-from kornia.geometry.calibration.distort import distort_points, tilt_projectionfrom kornia.geometry.linalg import transform_points-from kornia.geometry.transform.imgwarp import remap+from kornia.geometry.transform import remapfrom kornia.utils import create_meshgrid-__all__ = [- "undistort_points",- "undistort_image",-]+from .distort import distort_points, tilt_projection# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384diff --git a/kornia/geometry/camera/__init__.py b/kornia/geometry/camera/__init__.pyindex 0630c94d3..5bc6495d5 100644--- a/kornia/geometry/camera/__init__.py+++ b/kornia/geometry/camera/__init__.py@@ -2,4 +2,11 @@ from .perspective import project_points, unproject_pointsfrom .pinhole import cam2pixel, PinholeCamera, pixel2camfrom .stereo import StereoCamera-__all__ = ["PinholeCamera", "StereoCamera", "pixel2cam", "cam2pixel", "unproject_points", "project_points"]+__all__ = [+ "PinholeCamera",+ "StereoCamera",+ "pixel2cam",+ "cam2pixel",+ "unproject_points",+ "project_points"+]diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex fbdb2dc62..1913cbb2e 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -498,7 +498,6 @@ def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:"""if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):raise AssertionError(pinholes.shape)- optical_pose_parent = pinholes[..., 6:]# TODO: where is rtvec_to_pose?raise NotImplementedError# TODO: We have rtvec_to_pose in torchgeometrydiff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.pyindex e3287bbba..0a4776b8e 100644--- a/kornia/geometry/camera/stereo.py+++ b/kornia/geometry/camera/stereo.py@@ -1,6 +1,5 @@import torch-from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.linalg import transform_pointsfrom kornia.utils.grid import create_meshgriddiff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 7f6133420..820d1ac04 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -8,7 +8,6 @@ import torch.nn.functional as Ffrom kornia.constants import pi__all__ = [- # functional api"rad2deg","deg2rad","pol2cart",@@ -30,6 +29,7 @@ __all__ = ["normalize_quaternion","denormalize_pixel_coordinates3d","normalize_pixel_coordinates3d",+ "angle_to_rotation_matrix",]@@ -977,3 +977,26 @@ def denormalize_pixel_coordinates3d(factor: torch.Tensor = torch.tensor(2.0) / (dhw - 1).clamp(eps)return torch.tensor(1.0) / factor * (pixel_coordinates + 1)+++def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:+ r"""Create a rotation matrix out of angles in degrees.++ Args:+ angle: tensor of angles in degrees, any shape.++ Returns:+ tensor of *x2x2 rotation matrices.++ Shape:+ - Input: :math:`(*)`+ - Output: :math:`(*, 2, 2)`++ Example:+ >>> input = torch.rand(1, 3) # Nx3+ >>> output = angle_to_rotation_matrix(input) # Nx3x2x2+ """+ ang_rad = deg2rad(angle)+ cos_a: torch.Tensor = torch.cos(ang_rad)+ sin_a: torch.Tensor = torch.sin(ang_rad)+ return torch.stack([cos_a, sin_a, -sin_a, cos_a], dim=-1).view(*angle.shape, 2, 2)diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex cf8e064a2..da4d49fa1 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -6,17 +6,19 @@ import torch.nn as nnimport torch.nn.functional as Ffrom kornia.filters.sobel import spatial_gradient-from kornia.geometry.camera import cam2pixel, PinholeCamera, pixel2cam, project_points, unproject_points-from kornia.geometry.conversions import normalize_pixel_coordinates-from kornia.geometry.linalg import (- compose_transformations,- convert_points_to_homogeneous,- inverse_transformation,- transform_points,-)from kornia.utils import create_meshgrid-__all__ = ["depth_to_3d", "depth_to_normals", "warp_frame_depth", "depth_warp", "DepthWarper"]+from .camera import cam2pixel, PinholeCamera, pixel2cam, project_points, unproject_points+from .conversions import normalize_pixel_coordinates+from .linalg import compose_transformations, convert_points_to_homogeneous, inverse_transformation, transform_points++__all__ = [+ "depth_to_3d",+ "depth_to_normals",+ "warp_frame_depth",+ "depth_warp",+ "DepthWarper"+]def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:diff --git a/kornia/geometry/epipolar/__init__.py b/kornia/geometry/epipolar/__init__.pyindex 14c7be7ab..515e39ef0 100644--- a/kornia/geometry/epipolar/__init__.py+++ b/kornia/geometry/epipolar/__init__.py@@ -1,7 +1,56 @@-from ._metrics import *-from .essential import *-from .fundamental import *-from .numeric import *-from .projection import *-from .scene import *-from .triangulation import *+from ._metrics import sampson_epipolar_distance, symmetrical_epipolar_distance+from .essential import (+ decompose_essential_matrix,+ essential_from_fundamental,+ essential_from_Rt,+ motion_from_essential,+ motion_from_essential_choose_solution,+ relative_camera_motion,+)+from .fundamental import (+ compute_correspond_epilines,+ find_fundamental,+ fundamental_from_essential,+ fundamental_from_projections,+ normalize_points,+ normalize_transformation,+)+from .numeric import cross_product_matrix+from .projection import (+ depth_from_point,+ intrinsics_like,+ KRt_from_projection,+ projection_from_KRt,+ projections_from_fundamental,+ random_intrinsics,+ scale_intrinsics,+)+from .scene import generate_scene+from .triangulation import triangulate_points++__all__ = [+ "cross_product_matrix",+ "sampson_epipolar_distance",+ "symmetrical_epipolar_distance",+ "essential_from_fundamental",+ "decompose_essential_matrix",+ "essential_from_Rt",+ "motion_from_essential",+ "motion_from_essential_choose_solution",+ "relative_camera_motion",+ "normalize_points",+ "normalize_transformation",+ "find_fundamental",+ "compute_correspond_epilines",+ "fundamental_from_essential",+ "fundamental_from_projections",+ "intrinsics_like",+ "random_intrinsics",+ "scale_intrinsics",+ "projection_from_KRt",+ "KRt_from_projection",+ "depth_from_point",+ "projections_from_fundamental",+ "generate_scene",+ "triangulate_points",+]diff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.pyindex a1088603e..6077e1bac 100644--- a/kornia/geometry/epipolar/_metrics.py+++ b/kornia/geometry/epipolar/_metrics.py@@ -2,7 +2,7 @@import torch-import kornia+from kornia.geometry.conversions import convert_points_to_homogeneousdef sampson_epipolar_distance(@@ -31,10 +31,10 @@ def sampson_epipolar_distance(raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")if pts1.size(-1) == 2:- pts1 = kornia.convert_points_to_homogeneous(pts1)+ pts1 = convert_points_to_homogeneous(pts1)if pts2.size(-1) == 2:- pts2 = kornia.convert_points_to_homogeneous(pts2)+ pts2 = convert_points_to_homogeneous(pts2)# From Hartley and Zisserman, Sampson error (11.9)# sam = (x'^T F x) ** 2 / ( (((Fx)_1**2) + (Fx)_2**2)) + (((F^Tx')_1**2) + (F^Tx')_2**2)) )@@ -83,10 +83,10 @@ def symmetrical_epipolar_distance(raise ValueError(f"Fm must be a (*, 3, 3) tensor. Got {Fm.shape}")if pts1.size(-1) == 2:- pts1 = kornia.convert_points_to_homogeneous(pts1)+ pts1 = convert_points_to_homogeneous(pts1)if pts2.size(-1) == 2:- pts2 = kornia.convert_points_to_homogeneous(pts2)+ pts2 = convert_points_to_homogeneous(pts2)# From Hartley and Zisserman, symmetric epipolar distance (11.10)# sed = (x'^T F x) ** 2 / (((Fx)_1**2) + (Fx)_2**2)) + 1/ (((F^Tx')_1**2) + (F^Tx')_2**2))diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex 7e3d01c84..9ec155b69 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -3,7 +3,20 @@ from typing import Optional, Tupleimport torch-from kornia.geometry.epipolar import numeric, projection, triangulation+from kornia.utils import eye_like, vec_like++from .numeric import cross_product_matrix+from .projection import depth_from_point, projection_from_KRt+from .triangulation import triangulate_points++__all__ = [+ "essential_from_fundamental",+ "decompose_essential_matrix",+ "essential_from_Rt",+ "motion_from_essential",+ "motion_from_essential_choose_solution",+ "relative_camera_motion",+]def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Tensor) -> torch.Tensor:@@ -62,7 +75,7 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torchU = torch.where((torch.det(U) < 0.0)[..., None, None], U * mask, U)Vt = torch.where((torch.det(Vt) < 0.0)[..., None, None], Vt * maskt, Vt)- W = numeric.cross_product_matrix(torch.tensor([[0.0, 0.0, 1.0]]).type_as(E_mat))+ W = cross_product_matrix(torch.tensor([[0.0, 0.0, 1.0]]).type_as(E_mat))W[..., 2, 2] += 1.0# reconstruct rotations and retrieve translation vector@@ -104,7 +117,7 @@ def essential_from_Rt(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2:R, t = relative_camera_motion(R1, t1, R2, t2)# get the cross product from relative translation vector- Tx = numeric.cross_product_matrix(t[..., 0])+ Tx = cross_product_matrix(t[..., 0])return Tx @ R@@ -204,29 +217,29 @@ def motion_from_essential_choose_solution(Rs, ts = motion_from_essential(E_mat)# set reference view pose and compute projection matrix- R1 = numeric.eye_like(3, E_mat) # Bx3x3- t1 = numeric.vec_like(3, E_mat) # Bx3x1+ R1 = eye_like(3, E_mat) # Bx3x3+ t1 = vec_like(3, E_mat) # Bx3x1# compute the projection matrices for first cameraR1 = R1[:, None].expand(-1, 4, -1, -1)t1 = t1[:, None].expand(-1, 4, -1, -1)K1 = K1[:, None].expand(-1, 4, -1, -1)- P1 = projection.projection_from_KRt(K1, R1, t1) # 1x4x4x4+ P1 = projection_from_KRt(K1, R1, t1) # 1x4x4x4# compute the projection matrices for second cameraR2 = Rst2 = tsK2 = K2[:, None].expand(-1, 4, -1, -1)- P2 = projection.projection_from_KRt(K2, R2, t2) # Bx4x4x4+ P2 = projection_from_KRt(K2, R2, t2) # Bx4x4x4# triangulate the pointsx1 = x1[:, None].expand(-1, 4, -1, -1)x2 = x2[:, None].expand(-1, 4, -1, -1)- X = triangulation.triangulate_points(P1, P2, x1, x2) # Bx4xNx3+ X = triangulate_points(P1, P2, x1, x2) # Bx4xNx3# project points and compute their depth values- d1 = projection.depth(R1, t1, X)- d2 = projection.depth(R2, t2, X)+ d1 = depth_from_point(R1, t1, X)+ d2 = depth_from_point(R2, t2, X)# verify the point values that have a positive depth valuedepth_mask = (d1 > 0.0) & (d2 > 0.0)diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex b9a734ad8..a797487d5 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -4,7 +4,8 @@ from typing import Tupleimport torch-import kornia+from kornia.geometry.conversions import convert_points_to_homogeneous+from kornia.geometry.linalg import transform_pointsdef normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:@@ -43,7 +44,7 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Ten) # Bx9transform = transform.view(-1, 3, 3) # Bx3x3- points_norm = kornia.transform_points(transform, points) # BxNx2+ points_norm = transform_points(transform, points) # BxNx2return (points_norm, transform)@@ -139,7 +140,7 @@ def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> toif not (len(F_mat.shape) == 3 and F_mat.shape[-2:] == (3, 3)):raise AssertionError(F_mat.shape)- points_h: torch.Tensor = kornia.convert_points_to_homogeneous(points)+ points_h: torch.Tensor = convert_points_to_homogeneous(points)# project points and retrieve lines componentsa, b, c = torch.chunk(F_mat @ points_h.permute(0, 2, 1), dim=1, chunks=3)diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.pyindex 4b5482e8f..487419111 100644--- a/kornia/geometry/epipolar/numeric.py+++ b/kornia/geometry/epipolar/numeric.py@@ -2,8 +2,6 @@import torch-# TODO: this should go to `kornia.geometry.linalg`-def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:r"""Return the cross_product_matrix symmetric matrix of a vector.@@ -26,45 +24,3 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:zeros = torch.zeros_like(x0)cross_product_matrix_flat = torch.stack([zeros, -x2, x1, x2, zeros, -x0, -x1, x0, zeros], dim=-1)return cross_product_matrix_flat.view(-1, 3, 3)---def eye_like(n: int, input: torch.Tensor) -> torch.Tensor:- r"""Return a 2-D tensor with ones on the diagonal and zeros elsewhere with the same batch size as the input.-- Args:- n: the number of rows :math:`(N)`.- input: image tensor that will determine the batch size of the output matrix.- The expected shape is :math:`(B, *)`.-- Returns:- The identity matrix with the same batch size as the input :math:`(B, N, N)`.-- """- if n <= 0:- raise AssertionError(type(n), n)- if len(input.shape) < 1:- raise AssertionError(input.shape)-- identity = torch.eye(n, device=input.device, dtype=input.dtype)- return identity[None].repeat(input.shape[0], 1, 1)---def vec_like(n, tensor):- r"""Return a 2-D tensor with a vector containing zeros with the same batch size as the input.-- Args:- n: the number of rows :math:`(N)`.- tensor: image tensor that will determine the batch size of the output matrix.- The expected shape is :math:`(B, *)`.-- Returns:- The vector with the same batch size as the input :math:`(B, N, 1)`.-- """- if n <= 0:- raise AssertionError(type(n), n)- if len(tensor.shape) < 1:- raise AssertionError(tensor.shape)-- vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)- return vec[None].repeat(tensor.shape[0], 1, 1)diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.pyindex a4706d238..8e862979f 100644--- a/kornia/geometry/epipolar/projection.py+++ b/kornia/geometry/epipolar/projection.py@@ -3,9 +3,11 @@ from typing import Tuple, Unionimport torch-from kornia.geometry.epipolar import numeric+from kornia.utils import eye_like, vec_likefrom kornia.utils._compat import linalg_qr+from .numeric import cross_product_matrix+def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:r"""Return a 3x3 instrinsics matrix, with same size as the input.@@ -28,7 +30,7 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:_, _, H, W = input.shape- intrinsics = numeric.eye_like(3, input)+ intrinsics = eye_like(3, input)intrinsics[..., 0, 0] *= focalintrinsics[..., 1, 1] *= focalintrinsics[..., 0, 2] += 1.0 * W / 2@@ -148,7 +150,7 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tensoreturn K, R, t-def depth(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch.Tensor:+def depth_from_point(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch.Tensor:r"""Return the depth of a point transformed by a rigid transform.Args:@@ -194,14 +196,14 @@ def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:if F_mat.shape[-2:] != (3, 3):raise AssertionError(F_mat.shape)- R1 = numeric.eye_like(3, F_mat) # Bx3x3- t1 = numeric.vec_like(3, F_mat) # Bx3+ R1 = eye_like(3, F_mat) # Bx3x3+ t1 = vec_like(3, F_mat) # Bx3Ft_mat = F_mat.transpose(-2, -1)_, e2 = _nullspace(Ft_mat)- R2 = numeric.cross_product_matrix(e2) @ F_mat # Bx3x3+ R2 = cross_product_matrix(e2) @ F_mat # Bx3x3t2 = e2[..., :, None] # Bx3x1P1 = torch.cat([R1, t1], dim=-1) # Bx3x4diff --git a/kornia/geometry/epipolar/scene.py b/kornia/geometry/epipolar/scene.pyindex ed435a50b..5cc506c4a 100644--- a/kornia/geometry/epipolar/scene.py+++ b/kornia/geometry/epipolar/scene.py@@ -1,10 +1,13 @@"""Module to generate synthetic 3d scenes."""+import mathfrom typing import Dictimport torch-import kornia-from kornia.geometry import epipolar+from kornia.geometry.conversions import angle_axis_to_rotation_matrix+from kornia.geometry.linalg import transform_points++from .projection import projection_from_KRt, random_intrinsicsdef generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:@@ -12,14 +15,14 @@ def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:points3d = torch.rand(1, num_points, 3) # NxMx3# Create random camera matrix- K = epipolar.random_intrinsics(0.0, 100.0) # 1x3x3+ K = random_intrinsics(0.0, 100.0) # 1x3x3# Create random rotation per view- ang = torch.rand(num_views, 1) * kornia.pi * 2.0+ ang = torch.rand(num_views, 1) * math.pi * 2.0rvec = torch.rand(num_views, 3)rvec = ang * rvec / torch.norm(rvec, dim=1, keepdim=True) # Nx3- rot_mat = kornia.angle_axis_to_rotation_matrix(rvec) # Nx3x3+ rot_mat = angle_axis_to_rotation_matrix(rvec) # Nx3x3# matches with cv2.Rodrigues -> yay !# Create random translation per view@@ -34,9 +37,9 @@ def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:tvec[:, 2, 0] = torch.where(min_dist < 0, tz - min_dist + 1.0, tz)# compute projection matrices- P = epipolar.projection_from_KRt(K, rot_mat, tvec)+ P = projection_from_KRt(K, rot_mat, tvec)# project points3d and backproject to image plane- points2d = kornia.transform_points(P, points3d.expand(num_views, -1, -1))+ points2d = transform_points(P, points3d.expand(num_views, -1, -1))return dict(K=K, R=rot_mat, t=tvec, P=P, points3d=points3d, points2d=points2d)diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.pyindex 7e55352c5..567459339 100644--- a/kornia/geometry/epipolar/triangulation.py+++ b/kornia/geometry/epipolar/triangulation.py@@ -2,7 +2,7 @@import torch-import kornia+from kornia.geometry.conversions import convert_points_from_homogeneous# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/triangulation.cpp#L68@@ -61,5 +61,5 @@ def triangulate_points(_, _, V = torch.svd(X)points3d_h = V[..., -1]- points3d: torch.Tensor = kornia.convert_points_from_homogeneous(points3d_h)+ points3d: torch.Tensor = convert_points_from_homogeneous(points3d_h)return points3ddiff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex b146a852e..b7b25ac01 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -3,10 +3,12 @@ from typing import Optional, Tupleimport torch-import kornia-from kornia.geometry.epipolar import normalize_pointsfrom kornia.utils import _extract_device_dtype, safe_inverse_with_mask+from .conversions import convert_points_from_homogeneous+from .epipolar import normalize_points+from .linalg import transform_points+TupleTensor = Tuple[torch.Tensor, torch.Tensor]@@ -35,14 +37,14 @@ def oneway_transfer_error(raise ValueError(f"H must be a (*, 3, 3) tensor. Got {H.shape}")if pts1.size(-1) == 3:- pts1 = kornia.convert_points_from_homogeneous(pts1)+ pts1 = convert_points_from_homogeneous(pts1)if pts2.size(-1) == 3:- pts2 = kornia.convert_points_from_homogeneous(pts2)+ pts2 = convert_points_from_homogeneous(pts2)# From Hartley and Zisserman, Error in one image (4.6)# dist = \sum_{i} ( d(x', Hx)**2)- pts1_in_2: torch.Tensor = kornia.transform_points(H, pts1)+ pts1_in_2: torch.Tensor = transform_points(H, pts1)error_squared: torch.Tensor = (pts1_in_2 - pts2).pow(2).sum(dim=-1)if squared:return error_squared@@ -74,10 +76,11 @@ def symmetric_transfer_error(raise ValueError(f"H must be a (*, 3, 3) tensor. Got {H.shape}")if pts1.size(-1) == 3:- pts1 = kornia.convert_points_from_homogeneous(pts1)+ pts1 = convert_points_from_homogeneous(pts1)if pts2.size(-1) == 3:- pts2 = kornia.convert_points_from_homogeneous(pts2)+ pts2 = convert_points_from_homogeneous(pts2)+max_num = torch.finfo(pts1.dtype).max# From Hartley and Zisserman, Symmetric transfer error (4.7)# dist = \sum_{i} (d(x, H^-1 x')**2 + d(x', Hx)**2)@@ -141,7 +144,7 @@ def find_homography_dlt(try:_, _, V = torch.svd(A)- except:+ except ValueError:warnings.warn('SVD did not converge', RuntimeWarning)return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 9a1d9bee4..1ccb643d6 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -1,15 +1,14 @@import torch-import kornia-from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.testing import check_is_tensor+from .conversions import convert_points_from_homogeneous, convert_points_to_homogeneous+__all__ = ["compose_transformations","relative_transformation","inverse_transformation","transform_points",- "perspective_transform_lafs",]@@ -201,131 +200,5 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tepoints_0 = points_0.reshape(shape_inp)return points_0--def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) -> torch.Tensor:- r"""Function that applies perspective transformations to a set of local affine frames (LAFs).-- Args:- trans_01: tensor for perspective transformations of shape :math:`(B, 3, 3)`.- lafs_1: tensor of lafs of shape :math:`(B, N, 2, 3)`.-- Returns:- tensor of N-dimensional points of shape :math:`(B, N, 2, 3)`.-- Examples:- >>> rng = torch.manual_seed(0)- >>> lafs_1 = torch.rand(2, 4, 2, 3) # BxNx2x3- >>> lafs_1- tensor([[[[0.4963, 0.7682, 0.0885],- [0.1320, 0.3074, 0.6341]],- <BLANKLINE>- [[0.4901, 0.8964, 0.4556],- [0.6323, 0.3489, 0.4017]],- <BLANKLINE>- [[0.0223, 0.1689, 0.2939],- [0.5185, 0.6977, 0.8000]],- <BLANKLINE>- [[0.1610, 0.2823, 0.6816],- [0.9152, 0.3971, 0.8742]]],- <BLANKLINE>- <BLANKLINE>- [[[0.4194, 0.5529, 0.9527],- [0.0362, 0.1852, 0.3734]],- <BLANKLINE>- [[0.3051, 0.9320, 0.1759],- [0.2698, 0.1507, 0.0317]],- <BLANKLINE>- [[0.2081, 0.9298, 0.7231],- [0.7423, 0.5263, 0.2437]],- <BLANKLINE>- [[0.5846, 0.0332, 0.1387],- [0.2422, 0.8155, 0.7932]]]])- >>> trans_01 = torch.eye(3).repeat(2, 1, 1) # Bx3x3- >>> trans_01.shape- torch.Size([2, 3, 3])- >>> lafs_0 = perspective_transform_lafs(trans_01, lafs_1) # BxNx2x3- """- kornia.feature.laf.raise_error_if_laf_is_not_valid(lafs_1)- if not torch.is_tensor(trans_01):- raise TypeError("Input type is not a torch.Tensor")-- if not trans_01.device == lafs_1.device:- raise TypeError("Tensor must be in the same device")-- if not trans_01.shape[0] == lafs_1.shape[0]:- raise ValueError("Input batch size must be the same for both tensors")-- if (not (trans_01.shape[-1] == 3)) or (not (trans_01.shape[-2] == 3)):- raise ValueError("Transformation should be homography")-- bs, n, _, _ = lafs_1.size()- # First, we convert LAF to points- threepts_1 = kornia.feature.laf.laf_to_three_points(lafs_1)- points_1 = threepts_1.permute(0, 1, 3, 2).reshape(bs, n * 3, 2)-- # First, transform the points- points_0 = transform_points(trans_01, points_1)- # Back to LAF format- threepts_0 = points_0.view(bs, n, 3, 2).permute(0, 1, 3, 2)- return kornia.feature.laf.laf_from_three_points(threepts_0)--# TODO:# - project_points: from opencv--# layer api--# NOTE: is it needed ?-'''class TransformPoints(nn.Module):- r"""Create an object to transform a set of points.-- Args:- dst_pose_src (torhc.Tensor): tensor for transformations of- shape :math:`(B, D+1, D+1)`.-- Returns:- torch.Tensor: tensor of N-dimensional points.-- Shape:- - Input: :math:`(B, D, N)`- - Output: :math:`(B, N, D)`-- Examples:- >>> input = torch.rand(2, 4, 3) # BxNx3- >>> transform = torch.eye(4).view(1, 4, 4) # Bx4x4- >>> transform_op = kornia.TransformPoints(transform)- >>> output = transform_op(input) # BxNx3- """-- def __init__(self, dst_homo_src: torch.Tensor) -> None:- super(TransformPoints, self).__init__()- self.dst_homo_src: torch.Tensor = dst_homo_src-- def forward(self, points_src: torch.Tensor) -> torch.Tensor: # type: ignore- return transform_points(self.dst_homo_src, points_src)---class InversePose(nn.Module):- r"""Create a transformation that inverts a 4x4 pose.-- Args:- points (Tensor): tensor with poses.-- Returns:- Tensor: tensor with inverted poses.-- Shape:- - Input: :math:`(N, 4, 4)`- - Output: :math:`(N, 4, 4)`-- Example:- >>> pose = torch.rand(1, 4, 4) # Nx4x4- >>> transform = kornia.InversePose()- >>> pose_inv = transform(pose) # Nx4x4- """-- def __init__(self):- super(InversePose, self).__init__()-- def forward(self, input):- return inverse_pose(input)'''diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 931d70aa1..5fb3c67b1 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -4,7 +4,6 @@ from typing import Optional, Tupleimport torchimport torch.nn as nn-import torch.nn.functional as Ffrom kornia.geometry import (find_fundamental,diff --git a/kornia/geometry/subpix/__init__.py b/kornia/geometry/subpix/__init__.pyindex a963a37e5..62ea4cdd9 100644--- a/kornia/geometry/subpix/__init__.py+++ b/kornia/geometry/subpix/__init__.py@@ -1,2 +1,30 @@-from .dsnt import *-from .spatial_soft_argmax import *+from .dsnt import render_gaussian2d, spatial_expectation2d, spatial_softmax2d+from .nms import nms2d, nms3d, NonMaximaSuppression2d, NonMaximaSuppression3d+from .spatial_soft_argmax import (+ conv_quad_interp3d,+ conv_soft_argmax2d,+ conv_soft_argmax3d,+ ConvQuadInterp3d,+ ConvSoftArgmax2d,+ ConvSoftArgmax3d,+ spatial_soft_argmax2d,+ SpatialSoftArgmax2d,+)++__all__ = [+ "conv_soft_argmax2d",+ "conv_soft_argmax3d",+ "ConvSoftArgmax2d",+ "ConvSoftArgmax3d",+ "spatial_soft_argmax2d",+ "SpatialSoftArgmax2d",+ "conv_quad_interp3d",+ "ConvQuadInterp3d",+ "NonMaximaSuppression2d",+ "NonMaximaSuppression3d",+ "nms2d",+ "nms3d",+ "spatial_softmax2d",+ "spatial_expectation2d",+ "render_gaussian2d",+]diff --git a/kornia/feature/nms.py b/kornia/geometry/subpix/nms.pysimilarity index 98%rename from kornia/feature/nms.pyrename to kornia/geometry/subpix/nms.pyindex 06a3cef8a..bbd3056fd 100644--- a/kornia/feature/nms.py+++ b/kornia/geometry/subpix/nms.py@@ -142,13 +142,13 @@ class NonMaximaSuppression3d(nn.Module):return x * (mask.to(x.dtype))-# functiona api+# functional apidef nms2d(input: torch.Tensor, kernel_size: Tuple[int, int], mask_only: bool = False) -> torch.Tensor:r"""Apply non maxima suppression to filter.- See :class:`~kornia.feature.NonMaximaSuppression2d` for details.+ See :class:`~kornia.geometry.subpix.NonMaximaSuppression2d` for details."""return NonMaximaSuppression2d(kernel_size)(input, mask_only)diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex b2ce30ea9..13efd60e8 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -4,11 +4,14 @@ import torchimport torch.nn as nnimport torch.nn.functional as F-import kornia+from kornia.filters.sobel import spatial_gradient3dfrom kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3d-from kornia.geometry.subpix import dsntfrom kornia.utils import create_meshgrid, create_meshgrid3d-from kornia.utils.helpers import _pytorch_version_geq, safe_solve_with_mask+from kornia.utils._compat import torch_version_geq+from kornia.utils.helpers import safe_solve_with_mask++from .dsnt import spatial_expectation2d, spatial_softmax2d+from .nms import nms3ddef _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:@@ -492,8 +495,8 @@ def conv_soft_argmax3d(in_levels: int = input.size(2)out_levels: int = x_softmaxpool.size(2)skip_levels: int = (in_levels - out_levels) // 2- strict_maxima: torch.Tensor = F.avg_pool3d(kornia.feature.nms3d(input, kernel_size), 1, stride, 0)- strict_maxima = strict_maxima[:, :, skip_levels : out_levels - skip_levels]+ strict_maxima: torch.Tensor = F.avg_pool3d(nms3d(input, kernel_size), 1, stride, 0)+ strict_maxima = strict_maxima[:, :, skip_levels: out_levels - skip_levels]x_softmaxpool *= 1.0 + strict_maxima_bonus * strict_maximax_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3), x_softmaxpool.size(4))return coords_max, x_softmaxpool@@ -524,8 +527,8 @@ def spatial_soft_argmax2d(>>> spatial_soft_argmax2d(input, normalized_coordinates=False)tensor([[[1.0000, 1.0000]]])"""- input_soft: torch.Tensor = dsnt.spatial_softmax2d(input, temperature)- output: torch.Tensor = dsnt.spatial_expectation2d(input_soft, normalized_coordinates)+ input_soft: torch.Tensor = spatial_softmax2d(input, temperature)+ output: torch.Tensor = spatial_expectation2d(input_soft, normalized_coordinates)return output@@ -602,9 +605,9 @@ def conv_quad_interp3d(# to determine the location we are solving system of linear equations Ax = b, where b is 1st order gradient# and A is Hessian matrix- b: torch.Tensor = kornia.filters.spatial_gradient3d(input, order=1, mode='diff') #+ b: torch.Tensor = spatial_gradient3d(input, order=1, mode='diff') #b = b.permute(0, 1, 3, 4, 5, 2).reshape(-1, 3, 1)- A: torch.Tensor = kornia.filters.spatial_gradient3d(input, order=2, mode='diff')+ A: torch.Tensor = spatial_gradient3d(input, order=2, mode='diff')A = A.permute(0, 1, 3, 4, 5, 2).reshape(-1, 6)dxx = A[..., 0]dyy = A[..., 1]@@ -614,11 +617,11 @@ def conv_quad_interp3d(dxs = 0.25 * A[..., 5] # normalization to match OpenCV implementationHes = torch.stack([dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss], dim=-1).view(-1, 3, 3)- if not _pytorch_version_geq(1, 10):+ if not torch_version_geq(1, 10):# The following is needed to avoid singular casesHes += torch.rand(Hes[0].size(), device=Hes.device).abs()[None] * eps- nms_mask: torch.Tensor = kornia.feature.nms3d(input, (3, 3, 3), True)+ nms_mask: torch.Tensor = nms3d(input, (3, 3, 3), True)x_solved: torch.Tensor = torch.zeros_like(b)x_solved_masked, _, solved_correctly = safe_solve_with_mask(b[nms_mask.view(-1)], Hes[nms_mask.view(-1)])diff --git a/kornia/geometry/transform/__init__.py b/kornia/geometry/transform/__init__.pyindex 6db3f6cc5..f853e1842 100644--- a/kornia/geometry/transform/__init__.py+++ b/kornia/geometry/transform/__init__.py@@ -1,12 +1,11 @@-from kornia.geometry.transform import crop-from kornia.geometry.transform.affwarp import *-from kornia.geometry.transform.crop.crop2d import *-from kornia.geometry.transform.crop.crop3d import *-from kornia.geometry.transform.elastic_transform import *-from kornia.geometry.transform.flips import *-from kornia.geometry.transform.homography_warper import *-from kornia.geometry.transform.image_registrator import *-from kornia.geometry.transform.imgwarp import *-from kornia.geometry.transform.projwarp import *-from kornia.geometry.transform.pyramid import *-from kornia.geometry.transform.thin_plate_spline import *+from .affwarp import *+from .crop2d import *+from .crop3d import *+from .elastic_transform import *+from .flips import *+from .homography_warper import *+from .image_registrator import *+from .imgwarp import *+from .projwarp import *+from .pyramid import *+from .thin_plate_spline import *diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex e8e66d4db..7390b438b 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -3,12 +3,13 @@ from typing import Optional, Tuple, Unionimport torchimport torch.nn as nn-import kornia-from kornia.geometry.transform.imgwarp import get_affine_matrix2d, get_rotation_matrix2d, warp_affine-from kornia.geometry.transform.projwarp import get_projective_transform, warp_affine3d+from kornia.filters import gaussian_blur2dfrom kornia.utils import _extract_device_dtypefrom kornia.utils.image import perform_keep_shape_image+from .imgwarp import get_affine_matrix2d, get_rotation_matrix2d, warp_affine+from .projwarp import get_projective_transform, warp_affine3d+__all__ = ["affine","affine3d",@@ -595,7 +596,7 @@ def resize(if (ks[1] % 2) == 0:ks = ks[0], ks[1] + 1- input = kornia.filters.gaussian_blur2d(input, ks, sigmas)+ input = gaussian_blur2d(input, ks, sigmas)output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)return outputdiff --git a/kornia/geometry/transform/crop/__init__.py b/kornia/geometry/transform/crop/__init__.pydeleted file mode 100644index 697d9de4a..000000000--- a/kornia/geometry/transform/crop/__init__.py+++ /dev/null@@ -1,2 +0,0 @@-from .crop2d import *-from .crop3d import *diff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop2d.pysimilarity index 98%rename from kornia/geometry/transform/crop/crop2d.pyrename to kornia/geometry/transform/crop2d.pyindex ddfe0c6d2..d91b045e8 100644--- a/kornia/geometry/transform/crop/crop2d.py+++ b/kornia/geometry/transform/crop2d.py@@ -1,10 +1,10 @@-import warnings-from typing import Optional, Tuple+from typing import Tupleimport torchfrom kornia.geometry.bbox import infer_bbox_shape, validate_bbox-from kornia.geometry.transform.imgwarp import get_perspective_transform, warp_affine++from .imgwarp import get_perspective_transform, warp_affine__all__ = ["crop_and_resize",diff --git a/kornia/geometry/transform/crop/crop3d.py b/kornia/geometry/transform/crop3d.pysimilarity index 99%rename from kornia/geometry/transform/crop/crop3d.pyrename to kornia/geometry/transform/crop3d.pyindex 6187cacb8..1a3ff7e32 100644--- a/kornia/geometry/transform/crop/crop3d.py+++ b/kornia/geometry/transform/crop3d.py@@ -1,9 +1,10 @@-from typing import Optional, Tuple+from typing import Tupleimport torchfrom kornia.geometry.bbox import infer_bbox_shape3d, validate_bbox3d-from kornia.geometry.transform.projwarp import get_perspective_transform3d, warp_affine3d++from .projwarp import get_perspective_transform3d, warp_affine3d__all__ = ["crop_and_resize3d",diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.pyindex d6a43a4d5..5997d266e 100644--- a/kornia/geometry/transform/elastic_transform.py+++ b/kornia/geometry/transform/elastic_transform.py@@ -3,8 +3,8 @@ from typing import Tupleimport torchimport torch.nn.functional as F-import kornia-from kornia.filters.kernels import get_gaussian_kernel2d+from kornia.filters import filter2d, get_gaussian_kernel2d+from kornia.utils import create_meshgrid__all__ = ["elastic_transform2d"]@@ -80,15 +80,15 @@ def elastic_transform2d(disp_x: torch.Tensor = noise[:, :1]disp_y: torch.Tensor = noise[:, 1:]- disp_x = kornia.filters.filter2d(disp_x, kernel=kernel_y, border_type='constant') * alpha[0]- disp_y = kornia.filters.filter2d(disp_y, kernel=kernel_x, border_type='constant') * alpha[1]+ disp_x = filter2d(disp_x, kernel=kernel_y, border_type='constant') * alpha[0]+ disp_y = filter2d(disp_y, kernel=kernel_x, border_type='constant') * alpha[1]# stack and normalize displacementdisp = torch.cat([disp_x, disp_y], dim=1).permute(0, 2, 3, 1)# Warp image based on displacement matrix_, _, h, w = image.shape- grid = kornia.utils.create_meshgrid(h, w, device=image.device).to(image.dtype)+ grid = create_meshgrid(h, w, device=image.device).to(image.dtype)warped = F.grid_sample(image, (grid + disp).clamp(-1, 1), align_corners=align_corners, mode=mode)return warpeddiff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.pyindex 75b7f93da..2804644bb 100644--- a/kornia/geometry/transform/flips.py+++ b/kornia/geometry/transform/flips.py@@ -1,6 +1,15 @@import torchimport torch.nn as nn+__all__ = [+ "Vflip",+ "Hflip",+ "Rot180",+ "rot180",+ "hflip",+ "vflip",+]+class Vflip(nn.Module):r"""Vertically flip a tensor image or a batch of tensor images.diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.pyindex 9973d2ef8..c1628ea45 100644--- a/kornia/geometry/transform/image_registrator.py+++ b/kornia/geometry/transform/image_registrator.py@@ -1,15 +1,14 @@-from typing import Callable, List, Optional, Tuple, Type, Union+from typing import Callable, List, Tuple, Unionimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.optim as optim-from kornia.geometry.conversions import convert_affinematrix_to_homography-from kornia.geometry.transform.homography_warper import HomographyWarper-from kornia.geometry.transform.imgwarp import angle_to_rotation_matrix-from kornia.geometry.transform.pyramid import build_pyramid-from kornia.testing import check_is_tensor+from kornia.geometry.conversions import angle_to_rotation_matrix, convert_affinematrix_to_homography++from .homography_warper import HomographyWarper+from .pyramid import build_pyramid__all__ = ["ImageRegistrator",diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex fbf783147..e46eff20b 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -4,18 +4,18 @@ import torchimport torch.nn.functional as Ffrom kornia.geometry.conversions import (+ angle_to_rotation_matrix,convert_affinematrix_to_homography,convert_affinematrix_to_homography3d,- deg2rad,normalize_pixel_coordinates,)-from kornia.geometry.epipolar import eye_likefrom kornia.geometry.linalg import transform_points-from kornia.geometry.transform.homography_warper import normalize_homography-from kornia.geometry.transform.projwarp import get_projective_transform-from kornia.utils import create_meshgrid+from kornia.utils import create_meshgrid, eye_likefrom kornia.utils.helpers import _torch_inverse_cast, _torch_solve_cast+from .homography_warper import normalize_homography+from .projwarp import get_projective_transform+__all__ = ["warp_perspective","warp_affine",@@ -23,7 +23,6 @@ __all__ = ["get_rotation_matrix2d","remap","invert_affine_transform",- "angle_to_rotation_matrix","get_affine_matrix2d","get_affine_matrix3d","get_shear_matrix2d",@@ -282,29 +281,6 @@ def _build_perspective_param(p: torch.Tensor, q: torch.Tensor, axis: str) -> torraise NotImplementedError(f"perspective params for axis `{axis}` is not implemented.")-def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:- r"""Create a rotation matrix out of angles in degrees.-- Args:- angle: tensor of angles in degrees, any shape.-- Returns:- tensor of *x2x2 rotation matrices.-- Shape:- - Input: :math:`(*)`- - Output: :math:`(*, 2, 2)`-- Example:- >>> input = torch.rand(1, 3) # Nx3- >>> output = angle_to_rotation_matrix(input) # Nx3x2x2- """- ang_rad = deg2rad(angle)- cos_a: torch.Tensor = torch.cos(ang_rad)- sin_a: torch.Tensor = torch.sin(ang_rad)- return torch.stack([cos_a, sin_a, -sin_a, cos_a], dim=-1).view(*angle.shape, 2, 2)--def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:r"""Calculate an affine matrix of 2D rotation.diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.pyindex 7158d3a6d..cc51c1a51 100644--- a/kornia/geometry/transform/projwarp.py+++ b/kornia/geometry/transform/projwarp.py@@ -1,15 +1,15 @@"""Module to perform projective transformations to tensors."""-import warnings-from typing import List, Optional, Tuple+from typing import List, Tupleimport torch-import kornia as K-from kornia.geometry.conversions import convert_affinematrix_to_homography3d-from kornia.geometry.transform.homography_warper import homography_warp3d, normalize_homography3d+from kornia.geometry.conversions import angle_axis_to_rotation_matrix, convert_affinematrix_to_homography3d, deg2radfrom kornia.testing import check_is_tensor+from kornia.utils import eye_likefrom kornia.utils.helpers import _torch_inverse_cast, _torch_solve_cast+from .homography_warper import homography_warp3d, normalize_homography3d+__all__ = ["warp_affine3d","get_projective_transform",@@ -130,9 +130,9 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:raise AssertionError(center.dtype, angles.dtype)# create rotation matrix- angle_axis_rad: torch.Tensor = K.deg2rad(angles)- rmat: torch.Tensor = K.angle_axis_to_rotation_matrix(angle_axis_rad) # Bx3x3- scaling_matrix: torch.Tensor = K.eye_like(3, rmat)+ angle_axis_rad: torch.Tensor = deg2rad(angles)+ rmat: torch.Tensor = angle_axis_to_rotation_matrix(angle_axis_rad) # Bx3x3+ scaling_matrix: torch.Tensor = eye_like(3, rmat)scaling_matrix = scaling_matrix * scales.unsqueeze(dim=1)rmat = rmat @ scaling_matrix.to(rmat)diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.pyindex 1d437fd2a..3a3453722 100644--- a/kornia/geometry/transform/pyramid.py+++ b/kornia/geometry/transform/pyramid.py@@ -5,10 +5,16 @@ import torchimport torch.nn as nnimport torch.nn.functional as F-from kornia.filters.filter import filter2d-from kornia.filters.gaussian import gaussian_blur2d--__all__ = ["PyrDown", "PyrUp", "ScalePyramid", "pyrdown", "pyrup", "build_pyramid"]+from kornia.filters import filter2d, gaussian_blur2d++__all__ = [+ "PyrDown",+ "PyrUp",+ "ScalePyramid",+ "pyrdown",+ "pyrup",+ "build_pyramid"+]def _get_pyramid_gaussian_kernel() -> torch.Tensor:diff --git a/kornia/geometry/warp/__init__.py b/kornia/geometry/warp/__init__.pydeleted file mode 100644index 0a6deb8cf..000000000--- a/kornia/geometry/warp/__init__.py+++ /dev/null@@ -1,2 +0,0 @@-from kornia.geometry.warp.depth_warper import *-from kornia.geometry.warp.homography_warper import *diff --git a/kornia/geometry/warp/depth_warper.py b/kornia/geometry/warp/depth_warper.pydeleted file mode 100644index cd1efbf17..000000000--- a/kornia/geometry/warp/depth_warper.py+++ /dev/null@@ -1,55 +0,0 @@-import warnings--import torch--from kornia.geometry.camera import PinholeCamera-from kornia.geometry.depth import depth_warp as _depth_warp-from kornia.geometry.depth import DepthWarper as _DepthWarper--__all__ = ["depth_warp", "DepthWarper"]---class DepthWarper(_DepthWarper):- __doc__ = _DepthWarper.__doc__ # skipcq: PYL-W0612-- def __init__(- self,- pinhole_dst: PinholeCamera,- height: int,- width: int,- mode: str = 'bilinear',- padding_mode: str = 'zeros',- align_corners: bool = True,- ):- super().__init__(- pinhole_dst=pinhole_dst,- height=height,- width=width,- mode=mode,- padding_mode=padding_mode,- align_corners=align_corners,- )- warnings.warn(- "`DepthWarper` is deprecated and will be removed > 0.6.0. "- "Please use `kornia.geometry.DepthWarper instead.`",- DeprecationWarning,- stacklevel=2,- )---def depth_warp(- pinhole_dst: PinholeCamera,- pinhole_src: PinholeCamera,- depth_src: torch.Tensor,- patch_dst: torch.Tensor,- height: int,- width: int,- align_corners: bool = True,-):- __doc__ = _depth_warp.__doc__ # skipcq: PYL-W0612- warnings.warn(- "`depth_warp` is deprecated and will be removed > 0.6.0. Please use `kornia.geometry.depth_warp instead.`",- DeprecationWarning,- stacklevel=2,- )- return _depth_warp(pinhole_dst, pinhole_src, depth_src, patch_dst, height, width, align_corners)diff --git a/kornia/geometry/warp/homography_warper.py b/kornia/geometry/warp/homography_warper.pydeleted file mode 100644index 46936211c..000000000--- a/kornia/geometry/warp/homography_warper.py+++ /dev/null@@ -1,164 +0,0 @@-import warnings-from typing import Optional, Tuple--import torch--import kornia.geometry.transform.homography_warper as HMW--__all__ = [- "HomographyWarper",- "homography_warp",- "homography_warp3d",- "warp_grid",- "warp_grid3d",- "normalize_homography",- "normalize_homography3d",- "normal_transform_pixel",- "normal_transform_pixel3d",-]---def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:- __doc__ = HMW.warp_grid.__doc__ # skipcq: PYL-W0612- warnings.warn(- "`warp_grid` is deprecated and will be removed > 0.6.0. "- "Please use `kornia.geometry.transform.warp_grid instead.`",- DeprecationWarning,- stacklevel=2,- )- return HMW.warp_grid(grid, src_homo_dst)---def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:- __doc__ = HMW.warp_grid3d.__doc__ # skipcq: PYL-W0612- warnings.warn(- "`warp_grid3d` is deprecated. Please use `kornia.geometry.transform.warp_grid3d instead.`",- DeprecationWarning,- stacklevel=2,- )- return HMW.warp_grid3d(grid, src_homo_dst)---# functional api-def homography_warp(- patch_src: torch.Tensor,- src_homo_dst: torch.Tensor,- dsize: Tuple[int, int],- mode: str = 'bilinear',- padding_mode: str = 'zeros',- align_corners: bool = False,- normalized_coordinates: bool = True,-) -> torch.Tensor:- __doc__ = HMW.homography_warp.__doc__ # skipcq: PYL-W0612- warnings.warn(- "`homography_warp` is deprecated and will be removed > 0.6.0."- "Please use `kornia.geometry.transform.homography_warp instead.`",- DeprecationWarning,- stacklevel=2,- )- return HMW.homography_warp(- patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates- )---def homography_warp3d(- patch_src: torch.Tensor,- src_homo_dst: torch.Tensor,- dsize: Tuple[int, int, int],- mode: str = 'bilinear',- padding_mode: str = 'zeros',- align_corners: bool = False,- normalized_coordinates: bool = True,-) -> torch.Tensor:- __doc__ = HMW.homography_warp3d.__doc__ # skipcq: PYL-W0612- warnings.warn(- "`homography_warp3d` is deprecated and will be removed > 0.6.0. "- "Please use `kornia.geometry.transform.homography_warp3d instead.`",- DeprecationWarning,- stacklevel=2,- )- return HMW.homography_warp3d(- patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates- )---class HomographyWarper(HMW.HomographyWarper):- __doc__ = HMW.HomographyWarper.__doc__ # skipcq: PYL-W0612-- def __init__(- self,- height: int,- width: int,- mode: str = 'bilinear',- padding_mode: str = 'zeros',- normalized_coordinates: bool = True,- align_corners: bool = False,- ) -> None:- super().__init__(height, width, mode, padding_mode, normalized_coordinates, align_corners)- warnings.warn(- "`HomographyWarper` is deprecated and will be removed > 0.6.0. "- "Please use `kornia.geometry.transform.HomographyWarper instead.`",- DeprecationWarning,- stacklevel=2,- )---def normal_transform_pixel(- height: int,- width: int,- eps: float = 1e-14,- device: Optional[torch.device] = None,- dtype: Optional[torch.dtype] = None,-) -> torch.Tensor:- __doc__ = HMW.normal_transform_pixel.__doc__ # skipcq: PYL-W0612- warnings.warn(- "`normal_transform_pixel` is deprecated and will be removed > 0.6.0."- "Please use `kornia.geometry.transform.normal_transform_pixel instead.`",- DeprecationWarning,- stacklevel=2,- )- return HMW.normal_transform_pixel(height, width, eps, device, dtype)---def normal_transform_pixel3d(- depth: int,- height: int,- width: int,- eps: float = 1e-14,- device: Optional[torch.device] = None,- dtype: Optional[torch.dtype] = None,-) -> torch.Tensor:- __doc__ = HMW.normal_transform_pixel3d.__doc__ # skipcq: PYL-W0612- warnings.warn(- "`normal_transform_pixel3d` is deprecated and will be removed > 0.6.0. "- "Please use `kornia.geometry.transform.normal_transform_pixel3d instead.`",- DeprecationWarning,- stacklevel=2,- )- return HMW.normal_transform_pixel3d(depth, height, width, eps, device=device, dtype=dtype)---def normalize_homography(- dst_pix_trans_src_pix: torch.Tensor, dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int]-) -> torch.Tensor:- __doc__ = HMW.normalize_homography.__doc__ # skipcq: PYL-W0612- warnings.warn(- "`normalize_homography` is deprecated and will be removed > 0.6.0. "- "Please use `kornia.geometry.transform.normalize_homography instead.`",- DeprecationWarning,- stacklevel=2,- )- return HMW.normalize_homography(dst_pix_trans_src_pix, dsize_src, dsize_dst)---def normalize_homography3d(- dst_pix_trans_src_pix: torch.Tensor, dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int]-) -> torch.Tensor:- __doc__ = HMW.normalize_homography3d.__doc__ # skipcq: PYL-W0612- warnings.warn(- "`normalize_homography3d` is deprecated and will be removed > 0.6.0. "- "Please use `kornia.geometry.transform.normalize_homography3d instead.`",- DeprecationWarning,- stacklevel=2,- )- return HMW.normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)diff --git a/kornia/jit/__init__.py b/kornia/jit/__init__.pydeleted file mode 100644index 52e992732..000000000--- a/kornia/jit/__init__.py+++ /dev/null@@ -1,15 +0,0 @@-import torch--import kornia as K--# expose functions to torch.jit-# TODO: find an automatic way to do this-grayscale_to_rgb = torch.jit.script(K.color.grayscale_to_rgb)-rgb_to_grayscale = torch.jit.script(K.color.rgb_to_grayscale)-bgr_to_grayscale = torch.jit.script(K.color.bgr_to_grayscale)--spatial_soft_argmax2d = torch.jit.script(K.geometry.spatial_soft_argmax2d)-spatial_softmax2d = torch.jit.script(K.geometry.dsnt.spatial_softmax2d)-spatial_expectation2d = torch.jit.script(K.geometry.dsnt.spatial_expectation2d)-render_gaussian2d = torch.jit.script(K.geometry.dsnt.render_gaussian2d)-warp_perspective = torch.jit.script(K.geometry.warp_perspective)diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.pyindex c7b2335a2..7da3980e2 100644--- a/kornia/losses/__init__.py+++ b/kornia/losses/__init__.py@@ -7,3 +7,26 @@ from .psnr import psnr_loss, PSNRLossfrom .ssim import ssim_loss, SSIMLossfrom .total_variation import total_variation, TotalVariationfrom .tversky import tversky_loss, TverskyLoss++__all__ = [+ "inverse_depth_smoothness_loss",+ "InverseDepthSmoothnessLoss",+ "dice_loss",+ "DiceLoss",+ "js_div_loss_2d",+ "kl_div_loss_2d",+ "binary_focal_loss_with_logits",+ "BinaryFocalLossWithLogits",+ "focal_loss",+ "FocalLoss",+ "HausdorffERLoss",+ "HausdorffERLoss3D",+ "psnr_loss",+ "PSNRLoss",+ "ssim_loss",+ "SSIMLoss",+ "total_variation",+ "TotalVariation",+ "tversky_loss",+ "TverskyLoss"+]diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.pyindex b56f8a7b8..895b44b05 100644--- a/kornia/losses/psnr.py+++ b/kornia/losses/psnr.py@@ -1,6 +1,5 @@import torchimport torch.nn as nn-from torch.nn.functional import mse_loss as mseimport kornia.metrics as metricsdiff --git a/kornia/metrics/__init__.py b/kornia/metrics/__init__.pyindex ba7c0775d..40dada0af 100644--- a/kornia/metrics/__init__.py+++ b/kornia/metrics/__init__.py@@ -4,3 +4,13 @@ from .confusion_matrix import confusion_matrixfrom .mean_iou import mean_ioufrom .psnr import psnrfrom .ssim import ssim, SSIM++__all__ = [+ "accuracy",+ "AverageMeter",+ "confusion_matrix",+ "mean_iou",+ "psnr",+ "ssim",+ "SSIM",+]diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.pyindex 996e9c101..0e3aa01ac 100644--- a/kornia/metrics/confusion_matrix.py+++ b/kornia/metrics/confusion_matrix.py@@ -1,5 +1,3 @@-from typing import Optional-import torch# Inspired by:diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.pyindex c39a7ab79..2db61c93c 100644--- a/kornia/morphology/morphology.py+++ b/kornia/morphology/morphology.py@@ -3,6 +3,16 @@ from typing import List, Optionalimport torchimport torch.nn.functional as F+__all__ = [+ "dilation",+ "erosion",+ "opening",+ "closing",+ "gradient",+ "top_hat",+ "bottom_hat"+]+def _neight2channels_like_kernel(kernel: torch.Tensor) -> torch.Tensor:h, w = kernel.size()diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex d75af0fbc..e79807edd 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -50,7 +50,7 @@ def dict_to(data: dict, device: torch.device, dtype: torch.dtype) -> dict:def compute_patch_error(x, y, h, w):"""Compute the absolute error between patches."""- return torch.abs(x - y)[..., h // 4 : -h // 4, w // 4 : -w // 4].mean()+ return torch.abs(x - y)[..., h // 4: -h // 4, w // 4: -w // 4].mean()def check_is_tensor(obj):@@ -143,7 +143,7 @@ def _get_precision_by_name(try:# torch.testing.assert_close is only available for torch>=1.9from torch.testing import assert_close as _assert_close # type: ignore- from torch.testing._core import _get_default_tolerance+ from torch.testing._core import _get_default_tolerance # type: ignoredef assert_close(actual: torch.Tensor,diff --git a/kornia/tracking/__init__.py b/kornia/tracking/__init__.pyindex d9140dc93..3d2a98bba 100644--- a/kornia/tracking/__init__.py+++ b/kornia/tracking/__init__.py@@ -1 +1,5 @@-from .planar_tracker import *+from .planar_tracker import HomographyTracker++__all__ = [+ "HomographyTracker",+]diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.pyindex a6fe0ffd3..e1f221312 100644--- a/kornia/tracking/planar_tracker.py+++ b/kornia/tracking/planar_tracker.py@@ -1,4 +1,4 @@-from typing import Dict, Optional, Tuple, Union+from typing import Dict, Optional, Tupleimport torchimport torch.nn as nn@@ -6,11 +6,7 @@ import torch.nn as nnfrom kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, LoFTRfrom kornia.geometry.linalg import transform_pointsfrom kornia.geometry.ransac import RANSAC-from kornia.geometry.transform.imgwarp import warp_perspective--__all__ = [- "HomographyTracker",-]+from kornia.geometry.transform import warp_perspectiveclass HomographyTracker(nn.Module):diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.pyindex 60f620702..aae146d52 100644--- a/kornia/utils/__init__.py+++ b/kornia/utils/__init__.py@@ -3,6 +3,7 @@ from .grid import create_meshgrid, create_meshgrid3dfrom .helpers import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_maskfrom .image import image_list_to_tensor, image_to_tensor, ImageToTensor, tensor_to_imagefrom .memory import batched_forward+from .misc import eye_like, vec_likefrom .one_hot import one_hotfrom .pointcloud_io import load_pointcloud_ply, save_pointcloud_ply@@ -21,4 +22,6 @@ __all__ = ["safe_inverse_with_mask","safe_solve_with_mask","ImageToTensor",+ "eye_like",+ "vec_like",]diff --git a/kornia/utils/_compat.py b/kornia/utils/_compat.pyindex 1c6a860a3..4bd3beca1 100644--- a/kornia/utils/_compat.py+++ b/kornia/utils/_compat.py@@ -8,6 +8,11 @@ def torch_version() -> str:return torch.__version__.split('+')[0]+def torch_version_geq(major, minor) -> bool:+ _version = version.parse(torch_version())+ return _version >= version.parse(f"{major}.{minor}")++if version.parse(torch_version()) > version.parse("1.7.1"):# TODO: remove the type: ignore once Python 3.6 is deprecated.# It turns out that Pytorch has no attribute `torch.linalg` for@@ -27,4 +32,4 @@ if version.parse(torch_version()) > version.parse("1.7.1"):# Python 3.6 / PyTorch 1.7.0, 1.7.1from torch.linalg import qr as linalg_qr # type: ignoreelse:- from torch import qr as linalg_qr # type: ignore+ from torch import qr as linalg_qr # type: ignore # noqa: F401diff --git a/kornia/utils/draw.py b/kornia/utils/draw.pyindex e95bfb5f8..e296dc8c2 100644--- a/kornia/utils/draw.py+++ b/kornia/utils/draw.py@@ -66,20 +66,20 @@ def draw_rectangle(image[b,:,- int(rectangle[b, n, 1]) : int(rectangle[b, n, 3] + 1),- int(rectangle[b, n, 0]) : int(rectangle[b, n, 2] + 1),+ int(rectangle[b, n, 1]): int(rectangle[b, n, 3] + 1),+ int(rectangle[b, n, 0]): int(rectangle[b, n, 2] + 1),] = color[b, n, :, None, None]else:- image[b, :, int(rectangle[b, n, 1]) : int(rectangle[b, n, 3] + 1), rectangle[b, n, 0]] = color[+ image[b, :, int(rectangle[b, n, 1]): int(rectangle[b, n, 3] + 1), rectangle[b, n, 0]] = color[b, n, :, None]- image[b, :, int(rectangle[b, n, 1]) : int(rectangle[b, n, 3] + 1), rectangle[b, n, 2]] = color[+ image[b, :, int(rectangle[b, n, 1]): int(rectangle[b, n, 3] + 1), rectangle[b, n, 2]] = color[b, n, :, None]- image[b, :, rectangle[b, n, 1], int(rectangle[b, n, 0]) : int(rectangle[b, n, 2] + 1)] = color[+ image[b, :, rectangle[b, n, 1], int(rectangle[b, n, 0]): int(rectangle[b, n, 2] + 1)] = color[b, n, :, None]- image[b, :, rectangle[b, n, 3], int(rectangle[b, n, 0]) : int(rectangle[b, n, 2] + 1)] = color[+ image[b, :, rectangle[b, n, 3], int(rectangle[b, n, 0]): int(rectangle[b, n, 2] + 1)] = color[b, n, :, None]diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex 3e3d5fef4..8236e6ed5 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -3,12 +3,7 @@ from typing import Any, List, Optional, Tupleimport torch-from kornia.utils._compat import solve---def _pytorch_version_geq(major, minor):- version = torch.__version__.split('.')- return (int(version[0]) >= major) and (int(version[1]) >= minor)+from kornia.utils._compat import solve, torch_version_geqdef _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:@@ -111,7 +106,7 @@ def _torch_solve_cast(input: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensodef safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:r"""Helper function, which avoids crashing because of singular matrix input and outputs themask of valid solution"""- if not (_pytorch_version_geq(1, 10)):+ if not torch_version_geq(1, 10):sol, lu = _torch_solve_cast(B, A)warnings.warn('PyTorch version < 1.10, solve validness mask maybe not correct', RuntimeWarning)return sol, lu, torch.ones(len(A), dtype=torch.bool, device=A.device)@@ -123,9 +118,7 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensordtype = torch.float32A_LU, pivots, info = torch.lu(A.to(dtype), get_infos=True)valid_mask: torch.Tensor = info == 0- A_LU_solvable = A_LU[valid_mask]X = torch.lu_solve(B.to(dtype), A_LU, pivots)- A_LU_out = A_LUreturn X.to(B.dtype), A_LU.to(A.dtype), valid_mask@@ -133,7 +126,7 @@ def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]r"""Helper function, which avoids crashing because of non-invertable matrix input and outputs themask of valid solution"""# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622- if not (_pytorch_version_geq(1, 9)):+ if not torch_version_geq(1, 9):inv = _torch_inverse_cast(A)warnings.warn('PyTorch version < 1.9, inverse validness mask maybe not correct', RuntimeWarning)return inv, torch.ones(len(A), dtype=torch.bool, device=A.device)@@ -144,7 +137,7 @@ def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]dtype = torch.float32else:dtype = dtype_original- from torch.linalg import inv_ex+ from torch.linalg import inv_ex # type: ignore # (not available in 1.8.1)inverse, info = inv_ex(A.to(dtype))mask = info == 0return inverse.to(dtype_original), maskdiff --git a/kornia/utils/memory.py b/kornia/utils/memory.pyindex 47230abf1..71a47fe8e 100644--- a/kornia/utils/memory.py+++ b/kornia/utils/memory.py@@ -1,7 +1,5 @@import torch-import kornia-def batched_forward(model: torch.nn.Module, data: torch.Tensor, device: torch.device, batch_size: int = 128, **kwargsdiff --git a/kornia/utils/misc.py b/kornia/utils/misc.pynew file mode 100644index 000000000..4a1f5bbc5--- /dev/null+++ b/kornia/utils/misc.py@@ -0,0 +1,43 @@+import torch+++def eye_like(n: int, input: torch.Tensor) -> torch.Tensor:+ r"""Return a 2-D tensor with ones on the diagonal and zeros elsewhere with the same batch size as the input.++ Args:+ n: the number of rows :math:`(N)`.+ input: image tensor that will determine the batch size of the output matrix.+ The expected shape is :math:`(B, *)`.++ Returns:+ The identity matrix with the same batch size as the input :math:`(B, N, N)`.++ """+ if n <= 0:+ raise AssertionError(type(n), n)+ if len(input.shape) < 1:+ raise AssertionError(input.shape)++ identity = torch.eye(n, device=input.device, dtype=input.dtype)+ return identity[None].repeat(input.shape[0], 1, 1)+++def vec_like(n, tensor):+ r"""Return a 2-D tensor with a vector containing zeros with the same batch size as the input.++ Args:+ n: the number of rows :math:`(N)`.+ tensor: image tensor that will determine the batch size of the output matrix.+ The expected shape is :math:`(B, *)`.++ Returns:+ The vector with the same batch size as the input :math:`(B, N, 1)`.++ """+ if n <= 0:+ raise AssertionError(type(n), n)+ if len(tensor.shape) < 1:+ raise AssertionError(tensor.shape)++ vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)+ return vec[None].repeat(tensor.shape[0], 1, 1)diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.pyindex 1875ab8e3..88d63e2b8 100644--- a/kornia/utils/pointcloud_io.py+++ b/kornia/utils/pointcloud_io.py@@ -1,5 +1,4 @@import os-from typing import Optionalimport torchdiff --git a/requirements/dev.txt b/requirements/dev.txtindex c8ce73cda..da1a38bc6 100644--- a/requirements/dev.txt+++ b/requirements/dev.txt@@ -11,3 +11,4 @@ isortnumpyscipy-r ../docs/requirements.txt+-r ./x.txt # kornia[x]diff --git a/setup.cfg b/setup.cfgindex 61961a7d2..8eee8b016 100644--- a/setup.cfg+++ b/setup.cfg@@ -19,20 +19,16 @@ license_file = LICENSE[flake8]max-line-length = 120+exclude =+ docs+ versioneer.py+ kornia/_version.py+per-file-ignores =+ __init__.py: F401, F403+verbose = 2ignore =- E203- E305- E402- E721- E722- E741- F401- F403- F405- F811- F841- W503-exclude = docs/src+ W503 # Ignore "Line break occurred before a binary operator"+ E203 # Ignore "whitespace before ':'"[mypy]files = kornia, test@@ -53,7 +49,6 @@ exclude_lines =if 0:if __name__ == .__main__.:-[isort]line_length = 120known_first_party =@@ -64,3 +59,4 @@ order_by_type = False# 3 - Vertical Hanging Indentmulti_line_output = 3include_trailing_comma = True+skip=kornia/__init__.pydiff --git a/setup.py b/setup.pyindex cbd410fbe..746fa45ad 100644--- a/setup.py+++ b/setup.py@@ -1,124 +1,39 @@# Welcome to the Kornia setup.py.#-import distutils.command.clean-import glob-import io-import os-import shutil-import subprocess+import reimport sys-from setuptools import find_packages, setup--################-# The variables below define the current version under-# development and the current pytorch supported versions.-# WARNING: Becareful and do not touch those variables,-# unless you are a maintainer. Otherwise, could brake-# the package backward compatibility.--# NOTE(maintainers): modify this variable each time you do a release--version = '0.5.11' # this a tag for the current development version---# NOTE(maintainers): update this dictionary each time you do a release-# When multiple pytorch versions are associated with a single version of kornia,-# the oldest one is the requirement. The versions should be inequalities.-# Once a pytorch version (in the future) breaks a kornia version, we could just-# add a maximal version.-kornia_pt_dependencies = {- '0.5.11': '>=1.6.0',- '0.5.10': '>=1.6.0',- '0.5.9': '>=1.6.0',- '0.5.8': '>=1.6.0',- '0.5.7': '>=1.6.0',- '0.5.6': '>=1.6.0',- '0.5.5': '>=1.6.0',- '0.5.4': '>=1.6.0',- '0.5.3': '>=1.6.0',- '0.5.2': '>=1.6.0',- '0.5.1': '>=1.6.0',- '0.5.0': '>=1.6.0',- '0.4.2': '>=1.5.1',- '0.4.1': '>=1.6.0',- '0.4.0': '>=1.6.0,<1.7.0',- '0.3.2': '>=1.5.0,<1.6.0',- '0.3.1': '>=1.5.0',- '0.2.2': '>=1.4.0',- '0.1.4': '>=1.2.0',-}---# version can be overridden eg with KORNIA_BUILD_VERSION so we map each possible kornia version to the dictionary keys-def dep_version(version):- compatible_versions = [v for v in kornia_pt_dependencies if v >= version]- compatible_versions += [sorted(kornia_pt_dependencies)[-1]]- return min(compatible_versions)+# Make sure that kornia is running on Python 3.6.0 or later+# (to avoid running into this bug: https://bugs.python.org/issue29246)+if sys.version_info < (3, 6, 0):+ raise RuntimeError("Kornia requires Python 3.6.0 or later.")-#################################-sha = 'Unknown'-package_name = 'kornia'--cwd = os.path.dirname(os.path.abspath(__file__))--try:- sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=cwd).decode('ascii').strip()-except subprocess.CalledProcessError:- pass+from setuptools import find_packages, setup-if os.getenv('KORNIA_BUILD_VERSION'):- version = os.getenv('KORNIA_BUILD_VERSION')-elif os.getenv('KORNIA_RELEASE'):- pass-elif sha != 'Unknown':- version += '+' + sha[:7]-print(f"Building wheel {package_name}-{version}")+def find_version(file_path: str) -> str:+ version_file = open(file_path).read()+ version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)+ if not version_match:+ raise RuntimeError(f"Unable to find version string in {file_path}")+ return version_match.group(1)-def write_version_file():- version_path = os.path.join(cwd, 'kornia', 'version.py')- with open(version_path, 'w') as f:- f.write(f"__version__ = '{version}'\n")- f.write(f"git_version = {repr(sha)}\n")+VERSION = find_version("kornia/_version.py")-def read(*names, **kwargs):- with open(os.path.join(os.path.dirname(__file__), *names), encoding=kwargs.get("encoding", "utf8")) as fp:- return fp.read()+# NOTE: kornia MUST only require PyTorch+requirements = [+ 'torch>=1.8.1', 'packaging',+]# open readme file and set long descriptionwith open("README.md", encoding="utf-8") as fh:long_description = fh.read()-class clean(distutils.command.clean.clean):- def run(self):- with open('.gitignore') as f:- ignores = f.read()- for wildcard in filter(None, ignores.split('\n')):- for filename in glob.glob(wildcard):- try:- os.remove(filename)- except OSError:- shutil.rmtree(filename, ignore_errors=True)-- # It's an old-style class in Python 2.7...- super().run()-- # remove compiled and temporary files- subprocess.call(['rm -rf dist/ build/ kornia.egg*'], shell=True)---requirements = [- 'torch' + kornia_pt_dependencies[dep_version(version)],- 'packaging' # REMOVE once we deprecate pytorch > 1.7.1. See: issue #1264-]--def load_requirements(filename: str):with open(filename) as f:return [x.strip() for x in f.readlines() if "-r" != x[0:2]]@@ -126,19 +41,17 @@ def load_requirements(filename: str):requirements_extras = {"x": load_requirements("requirements/x.txt"),- "dev": load_requirements("requirements/dev.txt"),+ "dev": load_requirements("requirements/dev.txt")}requirements_extras["all"] = requirements_extras["x"] + requirements_extras["dev"]if __name__ == '__main__':- write_version_file()setup(- # Metadata- name=package_name,- version=version,+ name='kornia',+ version=VERSION,author='Edgar Riba',- author_email='[email protected]',+ author_email='[email protected]',url='https://www.kornia.org',download_url='https://github.com/kornia/kornia',license='Apache License 2.0',@@ -151,7 +64,7 @@ if __name__ == '__main__':packages=find_packages(exclude=('docs', 'test', 'examples')),package_data={"kornia": ["py.typed"]},zip_safe=True,- install_require=requirements,+ install_requires=requirements,extras_require=requirements_extras,keywords=['computer vision', 'deep learning', 'pytorch'],project_urls={diff --git a/setup_dev_env.sh b/setup_dev_env.shindex 6e2d8729c..5ac6691ba 100755--- a/setup_dev_env.sh+++ b/setup_dev_env.sh@@ -36,7 +36,7 @@ fi# define a python version to initialise the conda environment.# by default we assume python 3.7.python_version=${PYTHON_VERSION:-"3.7"}-pytorch_version=${PYTORCH_VERSION:-"1.9.0"}+pytorch_version=${PYTORCH_VERSION:-"1.9.1"}pytorch_mode=${PYTORCH_MODE:-""} # use `cpuonly` for CPU or leave it in blank for GPUcuda_version=${CUDA_VERSION:-"10.2"}diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex a74b37244..a3faca343 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -1,4 +1,4 @@-from typing import Any, Dict, Optional, Tuple, Type, Union+from typing import Any, Dict, Optional, Tuple, Typeimport pytestimport torch@@ -32,7 +32,9 @@ from kornia.augmentation import ()from kornia.augmentation.base import AugmentationBase2Dfrom kornia.constants import pi, Resample+from kornia.geometry import transform_pointsfrom kornia.testing import assert_close, BaseTester, default_with_one_parameter_changed+from kornia.utils import create_meshgridfrom kornia.utils.helpers import _torch_inverse_cast# TODO same_on_batch tests?@@ -283,11 +285,11 @@ class CommonTests(BaseTester):if (transform == kornia.eye_like(3, transform)).all():pytest.skip("Test not relevant for intensity augmentations.")- indices = kornia.create_meshgrid(+ indices = create_meshgrid(height=output.shape[-2], width=output.shape[-1], normalized_coordinates=False, device=self.device)output_indices = indices.reshape((1, -1, 2)).to(dtype=self.dtype)- input_indices = kornia.geometry.transform_points(_torch_inverse_cast(transform.to(self.dtype)), output_indices)+ input_indices = transform_points(_torch_inverse_cast(transform.to(self.dtype)), output_indices)output_indices = output_indices.round().long().squeeze(0)input_indices = input_indices.round().long().squeeze(0)@@ -568,14 +570,10 @@ class TestRandomHorizontalFlipAlternative(CommonTests):).repeat((2, 1, 1, 1))expected_output = torch.tensor([[[[0.3, 0.2, 0.1], [0.6, 0.5, 0.4], [0.9, 0.8, 0.7]]]], device=self.device, dtype=self.dtype- ).repeat(- (2, 1, 1, 1)- )+ ).repeat((2, 1, 1, 1))expected_transformation = torch.tensor([[[-1.0, 0.0, 2.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype- ).repeat(- (2, 1, 1)- )+ ).repeat((2, 1, 1))parameters = {}self._test_random_p_1_return_transform_implementation(input_tensor=input_tensor,@@ -641,14 +639,10 @@ class TestRandomVerticalFlipAlternative(CommonTests):).repeat((2, 1, 1, 1))expected_output = torch.tensor([[[[0.7, 0.8, 0.9], [0.4, 0.5, 0.6], [0.1, 0.2, 0.3]]]], device=self.device, dtype=self.dtype- ).repeat(- (2, 1, 1, 1)- )+ ).repeat((2, 1, 1, 1))expected_transformation = torch.tensor([[[1.0, 0.0, 0.0], [0.0, -1.0, 2.0], [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype- ).repeat(- (2, 1, 1)- )+ ).repeat((2, 1, 1))parameters = {}self._test_random_p_1_return_transform_implementation(input_tensor=input_tensor,@@ -1480,7 +1474,7 @@ class TestColorJitter:def test_gradcheck(self, device, dtype):input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.augmentation.ColorJitter(p=1.0), (input,), raise_exception=True)+ assert gradcheck(ColorJitter(p=1.0), (input,), raise_exception=True)class TestRectangleRandomErasing:@@ -1523,18 +1517,6 @@ class TestRectangleRandomErasing:input = utils.tensor_to_gradcheck_var(input) # to varassert gradcheck(rand_rec, (input, rect_params), raise_exception=True)- @pytest.mark.skip(reason="turn off all jit for a while")- def test_jit(self, device, dtype):- @torch.jit.script- def op_script(img):- return kornia.augmentation.random_rectangle_erase(img, (0.2, 0.4), (0.3, 0.5))-- batch_size, channels, height, width = 2, 3, 64, 64- img = torch.ones(batch_size, channels, height, width)- expected = RandomErasing(1.0, (0.2, 0.4), (0.3, 0.5))(img)- actual = op_script(img)- assert_close(actual, expected, atol=1e-4, rtol=1e-4)-class TestRandomGrayscale:@@ -1624,7 +1606,7 @@ class TestRandomGrayscale:dtype=dtype,)- img_gray = kornia.augmentation.RandomGrayscale(p=1.0)(data)+ img_gray = RandomGrayscale(p=1.0)(data)assert_close(img_gray, expected, atol=1e-4, rtol=1e-4)def test_opencv_false(self, device, dtype):@@ -1660,7 +1642,7 @@ class TestRandomGrayscale:expected = data- img_gray = kornia.augmentation.RandomGrayscale(p=0.0)(data)+ img_gray = RandomGrayscale(p=0.0)(data)assert_close(img_gray, expected, atol=1e-4, rtol=1e-4)def test_opencv_true_batch(self, device, dtype):@@ -1723,7 +1705,7 @@ class TestRandomGrayscale:)expected = expected.unsqueeze(0).repeat(4, 1, 1, 1)- img_gray = kornia.augmentation.RandomGrayscale(p=1.0)(data)+ img_gray = RandomGrayscale(p=1.0)(data)assert_close(img_gray, expected, atol=1e-4, rtol=1e-4)def test_opencv_false_batch(self, device, dtype):@@ -1758,7 +1740,7 @@ class TestRandomGrayscale:expected = data- img_gray = kornia.augmentation.RandomGrayscale(p=0.0)(data)+ img_gray = RandomGrayscale(p=0.0)(data)assert_close(img_gray, expected, atol=1e-4, rtol=1e-4)def test_random_grayscale_sequential_batch(self, device, dtype):@@ -1776,27 +1758,27 @@ class TestRandomGrayscale:def test_gradcheck(self, device, dtype):input = torch.rand((3, 5, 5), device=device, dtype=dtype) # 3 x 3input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.augmentation.RandomGrayscale(p=1.0), (input,), raise_exception=True)- assert gradcheck(kornia.augmentation.RandomGrayscale(p=0.0), (input,), raise_exception=True)+ assert gradcheck(RandomGrayscale(p=1.0), (input,), raise_exception=True)+ assert gradcheck(RandomGrayscale(p=0.0), (input,), raise_exception=True)class TestCenterCrop:def test_no_transform(self, device, dtype):inp = torch.rand(1, 2, 4, 4, device=device, dtype=dtype)- out = kornia.augmentation.CenterCrop(2)(inp)+ out = CenterCrop(2)(inp)assert out.shape == (1, 2, 2, 2)- aug = kornia.augmentation.CenterCrop(2, cropping_mode="resample")+ aug = CenterCrop(2, cropping_mode="resample")out = aug(inp)assert out.shape == (1, 2, 2, 2)assert aug.inverse(out).shape == (1, 2, 4, 4)def test_transform(self, device, dtype):inp = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)- out = kornia.augmentation.CenterCrop(2, return_transform=True)(inp)+ out = CenterCrop(2, return_transform=True)(inp)assert len(out) == 2assert out[0].shape == (1, 2, 2, 2)assert out[1].shape == (1, 3, 3)- aug = kornia.augmentation.CenterCrop(2, cropping_mode="resample", return_transform=True)+ aug = CenterCrop(2, cropping_mode="resample", return_transform=True)out = aug(inp)assert out[0].shape == (1, 2, 2, 2)assert out[1].shape == (1, 3, 3)@@ -1804,9 +1786,9 @@ class TestCenterCrop:def test_no_transform_tuple(self, device, dtype):inp = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)- out = kornia.augmentation.CenterCrop((3, 4))(inp)+ out = CenterCrop((3, 4))(inp)assert out.shape == (1, 2, 3, 4)- aug = kornia.augmentation.CenterCrop((3, 4), cropping_mode="resample")+ aug = CenterCrop((3, 4), cropping_mode="resample")out = aug(inp)assert out.shape == (1, 2, 3, 4)assert aug.inverse(out).shape == (1, 2, 5, 4)@@ -1825,7 +1807,7 @@ class TestCenterCrop: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(kornia.augmentation.CenterCrop(3), (input,), raise_exception=True)+ assert gradcheck(CenterCrop(3), (input,), raise_exception=True)class TestRandomRotation:@@ -2248,7 +2230,7 @@ class TestRandomCrop:img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)actual = op_script(img)- expected = kornia.center_crop3d(img)+ expected = kornia.geometry.transform.center_crop3d(img)assert_close(actual, expected, atol=1e-4, rtol=1e-4)@pytest.mark.skip("Need to fix Union type")diff --git a/test/augmentation/test_augmentation_3d.py b/test/augmentation/test_augmentation_3d.pyindex 1ef701789..dea64c87a 100644--- a/test/augmentation/test_augmentation_3d.py+++ b/test/augmentation/test_augmentation_3d.py@@ -1,5 +1,3 @@-from typing import Tuple, Union-import pytestimport torchimport torch.nn as nn@@ -8,6 +6,7 @@ from torch.autograd import gradcheckimport korniaimport kornia.testing as utils # test utilsfrom kornia.augmentation import (+ CenterCrop3D,RandomAffine3D,RandomCrop,RandomCrop3D,@@ -18,6 +17,7 @@ from kornia.augmentation import (RandomVerticalFlip3D,)from kornia.testing import assert_close+from kornia.utils._compat import torch_version_geqclass TestRandomHorizontalFlip3D:@@ -833,7 +833,7 @@ class TestRandomCrop3D:img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)actual = op_script(img)- expected = kornia.center_crop3d(img)+ expected = kornia.geometry.transform.center_crop3d(img)assert_close(actual, expected)@pytest.mark.skip("Need to fix Union type")@@ -858,25 +858,25 @@ class TestRandomCrop3D:class TestCenterCrop3D:def test_no_transform(self, device, dtype):inp = torch.rand(1, 2, 4, 4, 4, device=device, dtype=dtype)- out = kornia.augmentation.CenterCrop3D(2)(inp)+ out = CenterCrop3D(2)(inp)assert out.shape == (1, 2, 2, 2, 2)def test_transform(self, device, dtype):inp = torch.rand(1, 2, 5, 4, 8, device=device, dtype=dtype)- out = kornia.augmentation.CenterCrop3D(2, return_transform=True)(inp)+ out = CenterCrop3D(2, return_transform=True)(inp)assert len(out) == 2assert out[0].shape == (1, 2, 2, 2, 2)assert out[1].shape == (1, 4, 4)def test_no_transform_tuple(self, device, dtype):inp = torch.rand(1, 2, 5, 4, 8, device=device, dtype=dtype)- out = kornia.augmentation.CenterCrop3D((3, 4, 5))(inp)+ out = CenterCrop3D((3, 4, 5))(inp)assert out.shape == (1, 2, 3, 4, 5)def test_gradcheck(self, device, dtype):input = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.augmentation.CenterCrop3D(3), (input,), raise_exception=True)+ assert gradcheck(CenterCrop3D(3), (input,), raise_exception=True)class TestRandomEqualize3D:@@ -964,19 +964,25 @@ class TestRandomEqualize3D:class TestRandomAffine3D:-def test_batch_random_affine_3d(self, device, dtype):+ # TODO(jian): crashes with pytorch 1.10, cuda and fp64+ if torch_version_geq(1, 10) and "cuda" in str(device) and dtype == torch.float64:+ pytest.skip("AssertionError: assert tensor(False, device='cuda:0')")- f = RandomAffine3D((0, 0, 0), p=1., return_transform=True) # No rotation- tensor = torch.tensor([[[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]]],- device=device, dtype=dtype) # 1 x 1 x 1 x 3 x 3+ f = RandomAffine3D((0, 0, 0), p=1.0, return_transform=True) # No rotation+ tensor = torch.tensor(+ [[[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]]], device=device, dtype=dtype+ ) # 1 x 1 x 1 x 3 x 3- expected = torch.tensor([[[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]]],- device=device, dtype=dtype) # 1 x 1 x 1 x 3 x 3+ expected = torch.tensor(+ [[[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]]], device=device, dtype=dtype+ ) # 1 x 1 x 1 x 3 x 3expected_transform = 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], [0.0, 0.0, 0.0, 1.0]]],- device=device, dtype=dtype) # 1 x 4 x 4+ device=device,+ dtype=dtype,+ ) # 1 x 4 x 4tensor = tensor.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3expected = expected.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pyindex a6b1134b7..8cdee66ff 100644--- a/test/augmentation/test_container.py+++ b/test/augmentation/test_container.py@@ -191,12 +191,8 @@ class TestSequential:K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),kornia.filters.MedianBlur((3, 3)),K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),- K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)- ),- K.ImageSequential(- K.RandomAffine(360, p=1.0)- ),+ K.ImageSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)),+ K.ImageSequential(K.RandomAffine(360, p=1.0)),K.RandomAffine(360, p=1.0),K.RandomMixUp(p=1.0),return_transform=return_transform,@@ -230,8 +226,7 @@ class TestAugmentationSequential:inp = torch.as_tensor(inp, device=device, dtype=dtype)aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),- K.RandomAffine(360, p=1.0, return_transform=True),+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0, return_transform=True)),K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, p=1.0),@@ -251,19 +246,15 @@ class TestAugmentationSequential:def test_video(self, device, dtype):input = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)[None]- bbox = torch.tensor([[- [1., 1.],- [2., 1.],- [2., 2.],- [1., 2.],- ]], device=device, dtype=dtype).expand(2, -1, -1)[None]- points = torch.tensor([[[1., 1.]]], device=device, dtype=dtype).expand(2, -1, -1)[None]+ bbox = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype).expand(+ 2, -1, -1+ )[None]+ points = torch.tensor([[[1.0, 1.0]]], device=device, dtype=dtype).expand(2, -1, -1)[None]aug_list = K.AugmentationSequential(K.VideoSequential(- kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),- kornia.augmentation.RandomAffine(360, p=1.0),+ kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), kornia.augmentation.RandomAffine(360, p=1.0)),- data_keys=["input", "mask", "bbox", "keypoints"]+ data_keys=["input", "mask", "bbox", "keypoints"],)out = aug_list(input, input, bbox, points)assert out[0].shape == input.shape@@ -313,8 +304,7 @@ class TestAugmentationSequential:)[:, None].float()aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),- K.RandomAffine(360, p=1.0, return_transform=True),+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0, return_transform=True)),K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, p=1.0),@@ -348,11 +338,10 @@ class TestAugmentationSequential:aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),- K.RandomAffine(360, p=1.0, return_transform=True),+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0, return_transform=True)),K.RandomAffine(360, p=1.0, return_transform=False),- data_keys=['input', 'mask', 'bbox', 'keypoints']+ data_keys=['input', 'mask', 'bbox', 'keypoints'],)reproducibility_test((inp, mask, bbox, keypoints), aug)@@ -377,8 +366,7 @@ class TestAugmentationSequential:)[:, None].float()aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),- K.RandomAffine(360, p=1.0, return_transform=True),+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0, return_transform=True)),K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),K.RandomAffine(360, p=1.0, return_transform=True),@@ -409,8 +397,7 @@ class TestAugmentationSequential:)[:, None].float()aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),- K.RandomAffine(360, p=1.0, return_transform=True),+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0, return_transform=True)),K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),K.RandomAffine(360, p=1.0, return_transform=True),@@ -477,7 +464,7 @@ class TestPatchSequential:torch.manual_seed(11)try: # skip wrong param settings.seq = K.PatchSequential(- kornia.color.RgbToBgr(),+ K.color.RgbToBgr(),K.ColorJitter(0.1, 0.1, 0.1, 0.1),K.ImageSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),@@ -492,7 +479,8 @@ class TestPatchSequential:keepdim=keepdim,random_apply=random_apply,)- except:+ # TODO: improve me and remove the exception.+ except Exception:returninput = torch.randn(*shape, device=device, dtype=dtype)diff --git a/test/augmentation/test_perspective.py b/test/augmentation/test_perspective_rand.pysimilarity index 100%rename from test/augmentation/test_perspective.pyrename to test/augmentation/test_perspective_rand.pydiff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.pyindex 6fafd25a0..622cf4867 100644--- a/test/augmentation/test_random_generator.py+++ b/test/augmentation/test_random_generator.py@@ -19,6 +19,7 @@ from kornia.augmentation.random_generator import (random_solarize_generator,)from kornia.testing import assert_close+from kornia.utils._compat import torch_version_geqclass RandomGeneratorBaseTests:@@ -126,6 +127,9 @@ class TestColorJitterGen(RandomGeneratorBaseTests):)def test_random_gen(self, device, dtype):+ # TODO(jian): crashes with pytorch 1.10, cuda and fp64+ if torch_version_geq(1, 10) and "cuda" in str(device):+ pytest.skip("AssertionError: Tensor-likes are not close!")torch.manual_seed(42)batch_size = 8jitter_params = random_color_jitter_generator(diff --git a/test/color/test_gray.py b/test/color/test_gray.pyindex a4eef7ee6..a42313061 100644--- a/test/color/test_gray.py+++ b/test/color/test_gray.py@@ -11,12 +11,12 @@ class TestGrayscaleToRgb(BaseTester):def test_smoke(self, device, dtype):C, H, W = 1, 4, 5img = torch.rand(C, H, W, device=device, dtype=dtype)- assert isinstance(kornia.grayscale_to_rgb(img), torch.Tensor)+ assert isinstance(kornia.color.grayscale_to_rgb(img), torch.Tensor)@pytest.mark.parametrize("batch_size, height, width", [(1, 3, 4), (2, 2, 4), (3, 4, 1)])def test_cardinality(self, device, dtype, batch_size, height, width):img = torch.ones(batch_size, 1, height, width, device=device, dtype=dtype)- assert kornia.grayscale_to_rgb(img).shape == (batch_size, 3, height, width)+ assert kornia.color.grayscale_to_rgb(img).shape == (batch_size, 3, height, width)def test_exception(self, device, dtype):with pytest.raises(TypeError):@@ -78,21 +78,21 @@ class TestGrayscaleToRgb(BaseTester):dtype=dtype,)- img_rgb = kornia.grayscale_to_rgb(data)+ img_rgb = kornia.color.grayscale_to_rgb(data)assert_close(img_rgb, expected)@pytest.mark.graddef test_gradcheck(self, device, dtype):B, C, H, W = 2, 1, 4, 4img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)- assert gradcheck(kornia.grayscale_to_rgb, (img,), raise_exception=True)+ assert gradcheck(kornia.color.grayscale_to_rgb, (img,), raise_exception=True)@pytest.mark.jitdef test_jit(self, device, dtype):B, C, H, W = 2, 1, 4, 4img = torch.ones(B, C, H, W, device=device, dtype=dtype)- op = kornia.grayscale_to_rgb- op_jit = kornia.jit.grayscale_to_rgb+ op = kornia.color.grayscale_to_rgb+ op_jit = torch.jit.script(op)assert_close(op(img), op_jit(img))@pytest.mark.nn@@ -108,12 +108,12 @@ class TestRgbToGrayscale(BaseTester):def test_smoke(self, device, dtype):C, H, W = 3, 4, 5img = torch.rand(C, H, W, device=device, dtype=dtype)- assert isinstance(kornia.rgb_to_grayscale(img), torch.Tensor)+ assert isinstance(kornia.color.rgb_to_grayscale(img), torch.Tensor)@pytest.mark.parametrize("batch_size, height, width", [(1, 3, 4), (2, 2, 4), (3, 4, 1)])def test_cardinality(self, device, dtype, batch_size, height, width):img = torch.ones(batch_size, 3, height, width, device=device, dtype=dtype)- assert kornia.rgb_to_grayscale(img).shape == (batch_size, 1, height, width)+ assert kornia.color.rgb_to_grayscale(img).shape == (batch_size, 1, height, width)def test_exception(self, device, dtype):with pytest.raises(TypeError):@@ -180,7 +180,7 @@ class TestRgbToGrayscale(BaseTester):dtype=dtype,)- img_gray = kornia.rgb_to_grayscale(data)+ img_gray = kornia.color.rgb_to_grayscale(data)assert_close(img_gray, expected)def test_custom_rgb_weights(self, device, dtype):@@ -188,7 +188,7 @@ class TestRgbToGrayscale(BaseTester):img = torch.ones(B, C, H, W, device=device, dtype=dtype)rgb_weights = torch.tensor([0.5, 0.25, 0.25])- img_gray = kornia.rgb_to_grayscale(img, rgb_weights=rgb_weights)+ img_gray = kornia.color.rgb_to_grayscale(img, rgb_weights=rgb_weights)assert img_gray.device == deviceassert img_gray.dtype == dtype@@ -196,14 +196,14 @@ class TestRgbToGrayscale(BaseTester):def test_gradcheck(self, device, dtype):B, C, H, W = 2, 3, 4, 4img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)- assert gradcheck(kornia.rgb_to_grayscale, (img,), raise_exception=True)+ assert gradcheck(kornia.color.rgb_to_grayscale, (img,), raise_exception=True)@pytest.mark.jitdef test_jit(self, device, dtype):B, C, H, W = 2, 3, 4, 4img = torch.ones(B, C, H, W, device=device, dtype=dtype)- op = kornia.rgb_to_grayscale- op_jit = kornia.jit.rgb_to_grayscale+ op = kornia.color.rgb_to_grayscale+ op_jit = torch.jit.script(op)assert_close(op(img), op_jit(img))@pytest.mark.nn@@ -219,12 +219,12 @@ class TestBgrToGrayscale(BaseTester):def test_smoke(self, device, dtype):C, H, W = 3, 4, 5img = torch.rand(C, H, W, device=device, dtype=dtype)- assert kornia.bgr_to_grayscale(img) is not None+ assert kornia.color.bgr_to_grayscale(img) is not None@pytest.mark.parametrize("batch_size, height, width", [(1, 3, 4), (2, 2, 4), (3, 4, 1)])def test_cardinality(self, device, dtype, batch_size, height, width):img = torch.ones(batch_size, 3, height, width, device=device, dtype=dtype)- assert kornia.bgr_to_grayscale(img).shape == (batch_size, 1, height, width)+ assert kornia.color.bgr_to_grayscale(img).shape == (batch_size, 1, height, width)def test_exception(self, device, dtype):with pytest.raises(TypeError):@@ -282,21 +282,21 @@ class TestBgrToGrayscale(BaseTester):dtype=dtype,)- img_gray = kornia.bgr_to_grayscale(data)+ img_gray = kornia.color.bgr_to_grayscale(data)assert_close(img_gray, expected)@pytest.mark.graddef test_gradcheck(self, device, dtype):B, C, H, W = 2, 3, 4, 4img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)- assert gradcheck(kornia.bgr_to_grayscale, (img,), raise_exception=True)+ assert gradcheck(kornia.color.bgr_to_grayscale, (img,), raise_exception=True)@pytest.mark.jitdef test_jit(self, device, dtype):B, C, H, W = 2, 3, 4, 4img = torch.ones(B, C, H, W, device=device, dtype=dtype)- op = kornia.rgb_to_grayscale- op_jit = kornia.jit.bgr_to_grayscale+ op = kornia.color.rgb_to_grayscale+ op_jit = torch.jit.script(op)assert_close(op(img), op_jit(img))@pytest.mark.nndiff --git a/test/color/test_hsv.py b/test/color/test_hsv.pyindex 8b45a3df6..533e4b5c5 100644--- a/test/color/test_hsv.py+++ b/test/color/test_hsv.py@@ -115,19 +115,6 @@ class TestRgbToHsv(BaseTester):fcn = kornia.color.rgb_to_hsvassert_close(ops(img), fcn(img))- @pytest.mark.skip(reason="working but causes some warnings tdue to boolean conversion.")- def test_onnx(self, device, dtype):- B, C, H, W = 1, 3, 4, 4- img = torch.ones(B, C, H, W, device=device, dtype=dtype)- torch.onnx.export(- kornia.color.RgbToHsv(),- (img), # Dummy input for shape- "model.onnx",- opset_version=12,- do_constant_folding=True,- verbose=True,- )-class TestHsvToRgb(BaseTester):def test_smoke(self, device, dtype):diff --git a/test/color/test_lab.py b/test/color/test_lab.pyindex b9254497d..28d190252 100644--- a/test/color/test_lab.py+++ b/test/color/test_lab.py@@ -240,7 +240,7 @@ class TestLabToRgb(BaseTester):def test_gradcheck(self, device, dtype):B, C, H, W = 2, 3, 4, 4img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)- img = kornia.rgb_to_lab(img)+ img = kornia.color.rgb_to_lab(img)assert gradcheck(kornia.color.lab_to_rgb, (img,), raise_exception=True)@pytest.mark.jitdiff --git a/test/color/test_luv.py b/test/color/test_luv.pyindex 70372898b..76b761a51 100644--- a/test/color/test_luv.py+++ b/test/color/test_luv.py@@ -209,7 +209,7 @@ class TestLuvToRgb(BaseTester):def test_gradcheck(self, device, dtype):B, C, H, W = 2, 3, 4, 4img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)- img = kornia.rgb_to_luv(img)+ img = kornia.color.rgb_to_luv(img)assert gradcheck(kornia.color.luv_to_rgb, (img,), raise_exception=True)@pytest.mark.jitdiff --git a/test/color/test_raw.py b/test/color/test_raw.pyindex c57a9341d..7b13c56b7 100644--- a/test/color/test_raw.py+++ b/test/color/test_raw.py@@ -61,41 +61,47 @@ class TestRawToRgb(BaseTester):# make sure different cfas are actually differentdef test_cfas_not_the_same(self, device, dtype): # skipcq: PYL-R0201data = torch.rand(1, 16, 16, device=device, dtype=dtype)- assert torch.max(kornia.color.raw_to_rgb(data, kornia.color.CFA.BG)- - kornia.color.raw_to_rgb(data, kornia.color.CFA.RG)) > 0.0+ assert (+ torch.max(+ kornia.color.raw_to_rgb(data, kornia.color.CFA.BG) - kornia.color.raw_to_rgb(data, kornia.color.CFA.RG)+ )+ > 0.0+ )# The outcome will be very different for different implementations# Here we compare against a current baseline, it is safe to update this if the underlying algorithm changesdef test_functional(self, device, dtype): # skipcq: PYL-R0201data = torch.tensor(+ [[[1, 0.5, 0.2, 0.4], [0.75, 0.25, 0.8, 0.3], [0.65, 0.15, 0.7, 0.2], [0.55, 0.5, 0.6, 0.1]]],+ device=device,+ dtype=dtype,+ )+ # checked by hand as correct interpolation. Note the ugly replication that happens for Red on the last column+ # and row. We shall accept to live with that+ expected = torch.tensor([[- [1, 0.5, 0.2, 0.4],- [0.75, 0.25, 0.8, 0.3],- [0.65, 0.15, 0.7, 0.2],- [0.55, 0.5, 0.6, 0.1],- ]+ [1.0000, 0.6000, 0.2000, 0.2000],+ [0.8250, 0.6375, 0.4500, 0.4500],+ [0.6500, 0.6750, 0.7000, 0.7000],+ [0.6500, 0.6750, 0.7000, 0.7000],+ ],+ [+ [0.6250, 0.5000, 0.6250, 0.4000],+ [0.7500, 0.5500, 0.8000, 0.5500],+ [0.4000, 0.1500, 0.4375, 0.2000],+ [0.5500, 0.3625, 0.6000, 0.4000],+ ],+ [+ [0.2500, 0.2500, 0.2750, 0.3000],+ [0.2500, 0.2500, 0.2750, 0.3000],+ [0.3750, 0.3750, 0.2875, 0.2000],+ [0.5000, 0.5000, 0.3000, 0.1000],+ ],],device=device,dtype=dtype,)- # checked by hand as correct interpolation. Note the ugly replication that happens for Red on the last column- # and row. We shall accept to live with that- expected = torch.tensor([[[1.0000, 0.6000, 0.2000, 0.2000],- [0.8250, 0.6375, 0.4500, 0.4500],- [0.6500, 0.6750, 0.7000, 0.7000],- [0.6500, 0.6750, 0.7000, 0.7000]],- [[0.6250, 0.5000, 0.6250, 0.4000],- [0.7500, 0.5500, 0.8000, 0.5500],- [0.4000, 0.1500, 0.4375, 0.2000],- [0.5500, 0.3625, 0.6000, 0.4000]],- [[0.2500, 0.2500, 0.2750, 0.3000],- [0.2500, 0.2500, 0.2750, 0.3000],- [0.3750, 0.3750, 0.2875, 0.2000],- [0.5000, 0.5000, 0.3000, 0.1000]]],- device=device,- dtype=dtype,- )img_rgb = kornia.color.raw_to_rgb(data, kornia.color.raw.CFA.BG)assert_close(img_rgb, expected)diff --git a/test/color/test_rgb.py b/test/color/test_rgb.pyindex d88d8dcbe..b4440c820 100644--- a/test/color/test_rgb.py+++ b/test/color/test_rgb.py@@ -168,7 +168,7 @@ class TestRgbToRgba(BaseTester):dtype=dtype,) # Bx4x2x2- assert_close(kornia.rgb_to_rgba(data, aval), expected)+ assert_close(kornia.color.rgb_to_rgba(data, aval), expected)@pytest.mark.parametrize("aval", [0.4, 45.0])def test_unit_aval_th(self, device, dtype, aval):@@ -190,7 +190,7 @@ class TestRgbToRgba(BaseTester):) # Bx4x2x2aval = torch.full_like(data[:, :1], aval) # Bx1xHxW- assert_close(kornia.rgb_to_rgba(data, aval), expected)+ assert_close(kornia.color.rgb_to_rgba(data, aval), expected)@pytest.mark.graddef test_gradcheck(self, device, dtype):diff --git a/test/color/test_yuv.py b/test/color/test_yuv.pyindex 8a51180d8..8f0a87d90 100644--- a/test/color/test_yuv.py+++ b/test/color/test_yuv.py@@ -110,8 +110,14 @@ class TestRgbToYuv420(BaseTester):# Test max/min values. This is essentially testing the transform rather than the subsampling# ref values manually checked vs rec 601def test_unit_white(self, device, dtype): # skipcq: PYL-R0201- rgb = torch.tensor([[[255, 255], [255, 255]], [[255, 255], [255, 255]], [[255, 255], [255, 255]]],- device=device, dtype=torch.uint8).type(dtype) / 255.0+ rgb = (+ torch.tensor(+ [[[255, 255], [255, 255]], [[255, 255], [255, 255]], [[255, 255], [255, 255]]],+ device=device,+ dtype=torch.uint8,+ ).type(dtype)+ / 255.0+ )refy = torch.tensor([[[255, 255], [255, 255]]], device=device, dtype=torch.uint8)refuv = torch.tensor([[[0]], [[0]]], device=device, dtype=torch.int8)@@ -121,8 +127,12 @@ class TestRgbToYuv420(BaseTester):assert_close(refuv, resuv)def test_unit_black(self, device, dtype): # skipcq: PYL-R0201- rgb = torch.tensor([[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]],- device=device, dtype=torch.uint8).type(dtype) / 255.0+ rgb = (+ torch.tensor([[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], device=device, dtype=torch.uint8).type(+ dtype+ )+ / 255.0+ )refy = torch.tensor([[[0, 0], [0, 0]]], device=device, dtype=torch.uint8)refuv = torch.tensor([[[0]], [[0]]], device=device, dtype=torch.int8)@@ -132,8 +142,14 @@ class TestRgbToYuv420(BaseTester):assert_close(refuv, resuv)def test_unit_gray(self, device, dtype): # skipcq: PYL-R0201- rgb = torch.tensor([[[127, 127], [127, 127]], [[127, 127], [127, 127]], [[127, 127], [127, 127]]],- device=device, dtype=torch.uint8).type(dtype) / 255.0+ rgb = (+ torch.tensor(+ [[[127, 127], [127, 127]], [[127, 127], [127, 127]], [[127, 127], [127, 127]]],+ device=device,+ dtype=torch.uint8,+ ).type(dtype)+ / 255.0+ )refy = torch.tensor([[[127, 127], [127, 127]]], device=device, dtype=torch.uint8)refuv = torch.tensor([[[0]], [[0]]], device=device, dtype=torch.int8)@@ -143,8 +159,12 @@ class TestRgbToYuv420(BaseTester):assert_close(refuv, resuv)def test_unit_red(self, device, dtype): # skipcq: PYL-R0201- rgb = torch.tensor([[[255, 255], [255, 255]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]],- device=device, dtype=torch.uint8).type(dtype) / 255.0+ rgb = (+ torch.tensor(+ [[[255, 255], [255, 255]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], device=device, dtype=torch.uint8+ ).type(dtype)+ / 255.0+ )refy = torch.tensor([[[76, 76], [76, 76]]], device=device, dtype=torch.uint8)refuv = torch.tensor([[[-37]], [[127]]], device=device, dtype=torch.int8)@@ -154,8 +174,12 @@ class TestRgbToYuv420(BaseTester):assert_close(refuv, resuv)def test_unit_blue(self, device, dtype): # skipcq: PYL-R0201- rgb = torch.tensor([[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[255, 255], [255, 255]]],- device=device, dtype=torch.uint8).type(dtype) / 255.0+ rgb = (+ torch.tensor(+ [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[255, 255], [255, 255]]], device=device, dtype=torch.uint8+ ).type(dtype)+ / 255.0+ )refy = torch.tensor([[[29, 29], [29, 29]]], device=device, dtype=torch.uint8)refuv = torch.tensor([[[111]], [[-25]]], device=device, dtype=torch.int8)@@ -379,8 +403,11 @@ class TestYuv420ToRgb(BaseTester):# Test max/min values. This is essentially testing the transform rather than the subsampling# ref values manually checked vs rec 601def test_unit_white(self, device, dtype): # skipcq: PYL-R0201- refrgb = torch.tensor([[[255, 255], [255, 255]], [[255, 255], [255, 255]], [[255, 255], [255, 255]]],- device=device, dtype=torch.uint8)+ refrgb = torch.tensor(+ [[[255, 255], [255, 255]], [[255, 255], [255, 255]], [[255, 255], [255, 255]]],+ device=device,+ dtype=torch.uint8,+ )y = torch.tensor([[[255, 255], [255, 255]]], device=device, dtype=torch.uint8).type(dtype) / 255.0uv = torch.tensor([[[0]], [[0]]], device=device, dtype=torch.int8).type(torch.float) / 255.0@@ -388,8 +415,9 @@ class TestYuv420ToRgb(BaseTester):assert_close(refrgb, resrgb)def test_unit_red(self, device, dtype): # skipcq: PYL-R0201- refrgb = torch.tensor([[[221, 221], [221, 221]], [[17, 17], [17, 17]], [[1, 1], [1, 1]]],- device=device, dtype=torch.uint8)+ refrgb = torch.tensor(+ [[[221, 221], [221, 221]], [[17, 17], [17, 17]], [[1, 1], [1, 1]]], device=device, dtype=torch.uint8+ )y = torch.tensor([[[76, 76], [76, 76]]], device=device, dtype=torch.uint8).type(dtype) / 255.0uv = torch.tensor([[[-37]], [[127]]], device=device, dtype=torch.int8).type(torch.float) / 255.0diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.pyindex b269c253c..2d4d850f6 100644--- a/test/enhance/test_adjust.py+++ b/test/enhance/test_adjust.py@@ -90,7 +90,7 @@ class TestAdjustSaturation:batch_size, channels, height, width = 2, 3, 4, 5img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = tensor_to_gradcheck_var(img) # to var- assert gradcheck(kornia.adjust_saturation, (img, 2.0), raise_exception=True)+ assert gradcheck(kornia.enhance.adjust_saturation, (img, 2.0), raise_exception=True)class TestAdjustHue:@@ -146,7 +146,7 @@ class TestAdjustHue:batch_size, channels, height, width = 2, 3, 4, 5img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = tensor_to_gradcheck_var(img) # to var- assert gradcheck(kornia.adjust_hue, (img, 2.0), raise_exception=True)+ assert gradcheck(kornia.enhance.adjust_hue, (img, 2.0), raise_exception=True)class TestAdjustGamma:@@ -239,7 +239,7 @@ class TestAdjustGamma:batch_size, channels, height, width = 2, 3, 4, 5img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)img = tensor_to_gradcheck_var(img) # to var- assert gradcheck(kornia.adjust_gamma, (img, 1.0, 2.0), raise_exception=True)+ assert gradcheck(kornia.enhance.adjust_gamma, (img, 1.0, 2.0), raise_exception=True)class TestAdjustContrast:@@ -389,7 +389,7 @@ class TestAdjustContrast:batch_size, channels, height, width = 2, 3, 4, 5img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)img = tensor_to_gradcheck_var(img) # to var- assert gradcheck(kornia.adjust_contrast, (img, 2.0), raise_exception=True)+ assert gradcheck(kornia.enhance.adjust_contrast, (img, 2.0), raise_exception=True)class TestAdjustBrightness:@@ -491,7 +491,7 @@ class TestAdjustBrightness:batch_size, channels, height, width = 2, 3, 4, 5img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)img = tensor_to_gradcheck_var(img) # to var- assert gradcheck(kornia.adjust_brightness, (img, 2.0), raise_exception=True)+ assert gradcheck(kornia.enhance.adjust_brightness, (img, 2.0), raise_exception=True)class TestEqualize:diff --git a/test/enhance/test_equalization.py b/test/enhance/test_equalization.pyindex aaf9253d6..00291f984 100644--- a/test/enhance/test_equalization.py+++ b/test/enhance/test_equalization.py@@ -4,7 +4,8 @@ import pytestimport torchfrom torch.autograd import gradcheck-from kornia import enhance, rotate+from kornia import enhance+from kornia.geometry import rotatefrom kornia.testing import assert_close, BaseTester, tensor_to_gradcheck_var@@ -75,14 +76,10 @@ class TestEqualization(BaseTester):inputs = tensor_to_gradcheck_var(inputs)def grad_rot(input, a, b, c):- rot = rotate(input, torch.tensor(30.,- dtype=input.dtype,- device=device))+ rot = rotate(input, torch.tensor(30.0, dtype=input.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)++ assert gradcheck(grad_rot, (inputs, 40.0, (2, 2), True), nondet_tol=1e-4, raise_exception=True)@pytest.mark.skip(reason="args and kwargs in decorator")def test_jit(self, device, dtype):@@ -192,61 +189,68 @@ class TestEqualization(BaseTester):clip_limit: float = 2.0grid_size: Tuple = (8, 8)res = enhance.equalize_clahe(img, clip_limit=clip_limit, grid_size=grid_size)- res_diff = enhance.equalize_clahe(img,- clip_limit=clip_limit,- grid_size=grid_size,- slow_and_differentiable=True)+ res_diff = enhance.equalize_clahe(img, clip_limit=clip_limit, grid_size=grid_size, slow_and_differentiable=True)# NOTE: for next versions we need to improve the computation of the LUT# and test with a better image- expected = torch.tensor([[[0.1216,- 0.8745,- 0.9373,- 0.9163,- 0.8745,- 0.8745,- 0.9373,- 0.8745,- 0.8745,- 0.8118,- 0.9373,- 0.8745,- 0.8745,- 0.8118,- 0.8745,- 0.8745,- 0.8327,- 0.8118,- 0.8745,- 1.0000]]], dtype=res.dtype, device=res.device)- exp_diff = torch.tensor([[[0.1250,- 0.8752,- 0.9042,- 0.9167,- 0.8401,- 0.8852,- 0.9302,- 0.9120,- 0.8750,- 0.8370,- 0.9620,- 0.9077,- 0.8750,- 0.8754,- 0.9204,- 0.9167,- 0.8370,- 0.8806,- 0.9096,- 1.0000]]], dtype=res.dtype, device=res.device)- assert torch.allclose(- res[..., 0, :],- expected,- atol=1e-04,- rtol=1e-04,+ expected = torch.tensor(+ [+ [+ [+ 0.1216,+ 0.8745,+ 0.9373,+ 0.9163,+ 0.8745,+ 0.8745,+ 0.9373,+ 0.8745,+ 0.8745,+ 0.8118,+ 0.9373,+ 0.8745,+ 0.8745,+ 0.8118,+ 0.8745,+ 0.8745,+ 0.8327,+ 0.8118,+ 0.8745,+ 1.0000,+ ]+ ]+ ],+ dtype=res.dtype,+ device=res.device,)- assert torch.allclose(- res_diff[..., 0, :],- exp_diff,- atol=1e-04,- rtol=1e-04,+ exp_diff = torch.tensor(+ [+ [+ [+ 0.1250,+ 0.8752,+ 0.9042,+ 0.9167,+ 0.8401,+ 0.8852,+ 0.9302,+ 0.9120,+ 0.8750,+ 0.8370,+ 0.9620,+ 0.9077,+ 0.8750,+ 0.8754,+ 0.9204,+ 0.9167,+ 0.8370,+ 0.8806,+ 0.9096,+ 1.0000,+ ]+ ]+ ],+ dtype=res.dtype,+ device=res.device,)+ assert torch.allclose(res[..., 0, :], expected, atol=1e-04, rtol=1e-04)+ assert torch.allclose(res_diff[..., 0, :], exp_diff, atol=1e-04, rtol=1e-04)diff --git a/test/enhance/test_normalize.py b/test/enhance/test_normalize.pyindex 3fc1a9a00..ed3a80bad 100644--- a/test/enhance/test_normalize.py+++ b/test/enhance/test_normalize.py@@ -104,7 +104,7 @@ class TestNormalize:# expected outputexpected = (data - mean) / std- assert_close(kornia.normalize(data, mean, std), expected)+ assert_close(kornia.enhance.normalize(data, mean, std), expected)def test_module(self, device, dtype):data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)@@ -239,7 +239,7 @@ class TestDenormalize:# expected outputexpected = (data * std) + mean- assert_close(kornia.denormalize(data, mean, std), expected)+ assert_close(kornia.enhance.denormalize(data, mean, std), expected)def test_module(self, device, dtype):data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)@@ -256,29 +256,29 @@ class TestDenormalize:class TestNormalizeMinMax(BaseTester):def test_smoke(self, device, dtype):x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)- assert kornia.normalize_min_max(x) is not None+ assert kornia.enhance.normalize_min_max(x) is not Noneassert kornia.enhance.normalize_min_max(x) is not Nonedef test_exception(self, device, dtype):x = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)with pytest.raises(TypeError):- assert kornia.normalize_min_max(0.0)+ assert kornia.enhance.normalize_min_max(0.0)with pytest.raises(TypeError):- assert kornia.normalize_min_max(x, '', '')+ assert kornia.enhance.normalize_min_max(x, '', '')with pytest.raises(TypeError):- assert kornia.normalize_min_max(x, 2.0, '')+ assert kornia.enhance.normalize_min_max(x, 2.0, '')@pytest.mark.parametrize("input_shape", [(1, 2, 3, 4), (2, 1, 4, 3), (1, 3, 2, 1)])def test_cardinality(self, device, dtype, input_shape):x = torch.rand(input_shape, device=device, dtype=dtype)- assert kornia.normalize_min_max(x).shape == input_shape+ assert kornia.enhance.normalize_min_max(x).shape == input_shape@pytest.mark.parametrize("min_val, max_val", [(1.0, 2.0), (2.0, 3.0), (5.0, 20.0), (40.0, 1000.0)])def test_range(self, device, dtype, min_val, max_val):x = torch.rand(1, 2, 4, 5, device=device, dtype=dtype)- out = kornia.normalize_min_max(x, min_val=min_val, max_val=max_val)+ out = kornia.enhance.normalize_min_max(x, min_val=min_val, max_val=max_val)assert_close(out.min().item(), min_val)assert_close(out.max().item(), max_val)@@ -289,20 +289,20 @@ class TestNormalizeMinMax(BaseTester):[[[[-0.8, -0.6, -0.2], [-1.0, 0.0, -0.2], [1.0, 0.2, -0.4]]]], device=device, dtype=dtype)- actual = kornia.normalize_min_max(x, min_val=-1.0, max_val=1.0)+ actual = kornia.enhance.normalize_min_max(x, min_val=-1.0, max_val=1.0)assert_close(actual, expected, atol=1e-6, rtol=1e-6)@pytest.mark.jitdef test_jit(self, device, dtype):x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)- op = kornia.normalize_min_max+ op = kornia.enhance.normalize_min_maxop_jit = torch.jit.script(op)assert_close(op(x), op_jit(x))@pytest.mark.graddef test_gradcheck(self, device, dtype):x = torch.ones(1, 1, 1, 1, device=device, dtype=torch.float64, requires_grad=True)- assert gradcheck(kornia.normalize_min_max, (x,), raise_exception=True)+ assert gradcheck(kornia.enhance.normalize_min_max, (x,), raise_exception=True)@pytest.mark.skip(reason="not implemented yet")@pytest.mark.nndiff --git a/test/enhance/test_zca.py b/test/enhance/test_zca.pyindex 8e62d794d..3ab014a3c 100644--- a/test/enhance/test_zca.py+++ b/test/enhance/test_zca.py@@ -150,7 +150,7 @@ class TestZCA:expected = torch.sqrt(unbiased_val * torch.abs(data)) * torch.sign(data)- actual = kornia.zca_whiten(data, unbiased=unbiased)+ actual = kornia.enhance.zca_whiten(data, unbiased=unbiased)tol_val: float = utils._get_precision(device, dtype)assert_close(actual, expected, atol=tol_val, rtol=tol_val)diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.pyindex 9e97d95ce..306e72822 100644--- a/test/feature/test_affine_shape_estimator.py+++ b/test/feature/test_affine_shape_estimator.py@@ -1,8 +1,9 @@import pytest+import torchfrom torch.autograd import gradcheckimport kornia.testing as utils # test utils-from kornia.feature.affine_shape import *+from kornia.feature.affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, PatchAffineShapeEstimatorfrom kornia.testing import assert_close@@ -38,7 +39,6 @@ class TestPatchAffineShapeEstimator:patches = utils.tensor_to_gradcheck_var(patches) # to varassert gradcheck(ori, (patches,), raise_exception=True, nondet_tol=1e-4)- @pytest.mark.jitdef test_jit(self, device, dtype):B, C, H, W = 2, 1, 13, 13patches = torch.ones(B, C, H, W, device=device, dtype=dtype)diff --git a/test/feature/test_integrated.py b/test/feature/test_integrated.pyindex 9d4adfc06..aea63d281 100644--- a/test/feature/test_integrated.py+++ b/test/feature/test_integrated.py@@ -1,3 +1,5 @@+import sys+import pytestimport torchimport torch.nn as nn@@ -27,21 +29,13 @@ class TestGetLAFDescriptors:PS = 16img = torch.rand(B, C, H, W, device=device, dtype=dtype)img_gray = kornia.color.rgb_to_grayscale(img)- centers = torch.tensor([[H / 3.0, W / 3.],- [2.0 * H / 3.0, W / 2.]],- device=device,- dtype=dtype).view(1, 2, 2)- scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.0],- device=device,- dtype=dtype).view(1, 2, 1, 1)- ori = torch.tensor([0.0, 30.],- device=device,- dtype=dtype).view(1, 2, 1)+ centers = torch.tensor([[H / 3.0, W / 3.0], [2.0 * H / 3.0, W / 2.0]], device=device, dtype=dtype).view(1, 2, 2)+ scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.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)sift = SIFTDescriptor(PS).to(device, dtype)descs_test_from_rgb = get_laf_descriptors(img, lafs, sift, PS, True)- descs_test_from_gray = get_laf_descriptors(img_gray,- lafs, sift, PS, True)+ descs_test_from_gray = get_laf_descriptors(img_gray, lafs, sift, PS, True)patches = extract_patches_from_pyramid(img_gray, lafs, PS)B1, N1, CH1, H1, W1 = patches.size()@@ -51,20 +45,15 @@ class TestGetLAFDescriptors:assert_close(descs_test_from_rgb, descs_reference)assert_close(descs_test_from_gray, descs_reference)- def test_gradcheck(self, device):+ def test_gradcheck(self, device, dtype=torch.float64):B, C, H, W = 1, 1, 32, 32- dtype = torch.doublePS = 16img = torch.rand(B, C, H, W, device=device)- centers = torch.tensor([[H / 3.0, W / 3.],- [2.0 * H / 3.0, W / 2.]],- device=device,- dtype=torch.double).view(1, 2, 2)- scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.0],- device=device, dtype=torch.double).view(1, 2, 1, 1)- ori = torch.tensor([0.0, 30.],- device=device,- dtype=dtype).view(1, 2, 1)+ centers = torch.tensor([[H / 3.0, W / 3.0], [2.0 * H / 3.0, W / 2.0]], device=device, dtype=dtype).view(+ 1, 2, 2+ )+ scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.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 varlafs = utils.tensor_to_gradcheck_var(lafs) # to var@@ -75,9 +64,8 @@ class TestGetLAFDescriptors:desc = _MeanPatch()img = utils.tensor_to_gradcheck_var(img) # to var- assert gradcheck(get_laf_descriptors,- (img, lafs, desc, PS, True),- eps=1e-3, atol=1e-3, raise_exception=True)+ assert gradcheck(get_laf_descriptors, (img, lafs, desc, PS, True),+ eps=1e-3, atol=1e-3, raise_exception=True, nondet_tol=1e-3)class TestLAFDescriptor:@@ -86,16 +74,9 @@ class TestLAFDescriptor:PS = 16img = torch.rand(B, C, H, W, device=device, dtype=dtype)img_gray = kornia.color.rgb_to_grayscale(img)- centers = torch.tensor([[H / 3.0, W / 3.],- [2.0 * H / 3.0, W / 2.]],- device=device,- dtype=dtype).view(1, 2, 2)- scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.0],- device=device,- dtype=dtype).view(1, 2, 1, 1)- ori = torch.tensor([0.0, 30.],- device=device,- dtype=dtype).view(1, 2, 1)+ centers = torch.tensor([[H / 3.0, W / 3.0], [2.0 * H / 3.0, W / 2.0]], device=device, dtype=dtype).view(1, 2, 2)+ scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.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)sift = SIFTDescriptor(PS).to(device, dtype)lafsift = LAFDescriptor(sift, PS)@@ -107,21 +88,13 @@ class TestLAFDescriptor:descs_reference = sift(patches.view(B1 * N1, CH1, H1, W1)).view(B1, N1, -1)assert_close(descs_test, descs_reference)- def test_gradcheck(self, device):- dtype = torch.double+ def test_gradcheck(self, device, dtype=torch.float64):B, C, H, W = 1, 1, 32, 32PS = 16img = torch.rand(B, C, H, W, device=device)- centers = torch.tensor([[H / 3.0, W / 3.],- [2.0 * H / 3.0, W / 2.]],- device=device,- dtype=dtype).view(1, 2, 2)- scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.0],- device=device,- dtype=dtype).view(1, 2, 1, 1)- ori = torch.tensor([0.0, 30.],- device=device,- dtype=dtype).view(1, 2, 1)+ centers = torch.tensor([[H / 3.0, W / 3.0], [2.0 * H / 3.0, W / 2.0]], device=device, dtype=dtype).view(1, 2, 2)+ scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.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 varlafs = utils.tensor_to_gradcheck_var(lafs) # to var@@ -132,9 +105,7 @@ class TestLAFDescriptor:lafdesc = LAFDescriptor(_MeanPatch(), PS)img = utils.tensor_to_gradcheck_var(img) # to var- assert gradcheck(lafdesc,- (img, lafs),- eps=1e-3, atol=1e-3, raise_exception=True)+ assert gradcheck(lafdesc, (img, lafs), eps=1e-3, atol=1e-3, raise_exception=True, nondet_tol=1e-3)class TestLocalFeature:@@ -167,9 +138,8 @@ class TestLocalFeature:B, C, H, W = 1, 1, 32, 32PS = 16img = torch.rand(B, C, H, W, device=device)- local_feature = LocalFeature(ScaleSpaceDetector(2),- LAFDescriptor(SIFTDescriptor(PS), PS)).to(device)img = utils.tensor_to_gradcheck_var(img) # to var+ local_feature = LocalFeature(ScaleSpaceDetector(2), LAFDescriptor(SIFTDescriptor(PS), PS)).to(device, img.dtype)assert gradcheck(local_feature, img, eps=1e-4, atol=1e-4, raise_exception=True)@@ -198,31 +168,27 @@ class TestGFTTAffNetHardNet:def test_gradcheck(self, device):B, C, H, W = 1, 1, 32, 32img = torch.rand(B, C, H, W, device=device)- local_feature = GFTTAffNetHardNet(2, True).to(device, torch.double)img = utils.tensor_to_gradcheck_var(img) # to var+ local_feature = GFTTAffNetHardNet(2, True).to(device, img.dtype)assert gradcheck(local_feature, img, eps=1e-4, atol=1e-4, raise_exception=True)class TestLocalFeatureMatcher:def test_smoke(self, device):- matcher = LocalFeatureMatcher(SIFTFeature(5),- DescriptorMatcher('snn', 0.8)).to(device)+ matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher('snn', 0.8)).to(device)assert matcher is not None@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)+ matcher = LocalFeatureMatcher(GFTTAffNetHardNet(100), DescriptorMatcher('snn', 0.8)).to(device, dtype)data_dev = utils.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)+ out = matcher({"image0": data_dev["image0"], "image1": 0 * data_dev["image0"]})+ assert len(out['keypoints0']) == 0@pytest.mark.skip("Takes too long time (but works)")def test_gradcheck(self, device):- matcher = LocalFeatureMatcher(SIFTFeature(5),- DescriptorMatcher('nn', 1.0)).to(device)+ matcher = LocalFeatureMatcher(SIFTFeature(5), DescriptorMatcher('nn', 1.0)).to(device)patches = torch.rand(1, 1, 32, 32, device=device)patches05 = resize(patches, (48, 48))patches = utils.tensor_to_gradcheck_var(patches) # to var@@ -230,14 +196,14 @@ class TestLocalFeatureMatcher: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)@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)def test_real_sift(self, device, dtype, data):torch.random.manual_seed(0)# This is not unit test, but that is quite good integration test- matcher = LocalFeatureMatcher(SIFTFeature(2000),- DescriptorMatcher('snn', 0.8)).to(device, dtype)+ matcher = LocalFeatureMatcher(SIFTFeature(2000), DescriptorMatcher('snn', 0.8)).to(device, dtype)ransac = RANSAC('homography', 1.0, 2048, 10).to(device, dtype)data_dev = utils.dict_to(data, device, dtype)pts_src = data_dev['pts0']@@ -245,21 +211,16 @@ class TestLocalFeatureMatcher:with torch.no_grad():out = matcher(data_dev)homography, inliers = ransac(out['keypoints0'], out['keypoints1'])- assert (inliers.sum().item() > 50) # we have enough inliers+ 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)+ assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)def test_real_sift_preextract(self, device, dtype, data):torch.random.manual_seed(0)# This is not unit test, but that is quite good integration testfeat = SIFTFeature(2000)- matcher = LocalFeatureMatcher(feat,- DescriptorMatcher('snn', 0.8)).to(device)+ matcher = LocalFeatureMatcher(feat, DescriptorMatcher('snn', 0.8)).to(device)ransac = RANSAC('homography', 1.0, 2048, 10).to(device, dtype)data_dev = utils.dict_to(data, device, dtype)pts_src = data_dev['pts0']@@ -276,20 +237,17 @@ class TestLocalFeatureMatcher:with torch.no_grad():out = matcher(data_dev)homography, inliers = ransac(out['keypoints0'], out['keypoints1'])- assert (inliers.sum().item() > 50) # we have enough inliers+ 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)+ assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)+ @pytest.mark.skipif(sys.platform == "win32",+ reason="this test takes so much memory in the CI with Windows")@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)def test_real_gftt(self, device, dtype, data):torch.random.manual_seed(0)# This is not unit test, but that is quite good integration test- matcher = LocalFeatureMatcher(GFTTAffNetHardNet(2000),- DescriptorMatcher('snn', 0.8)).to(device, dtype)+ matcher = LocalFeatureMatcher(GFTTAffNetHardNet(2000), DescriptorMatcher('snn', 0.8)).to(device, dtype)ransac = RANSAC('homography', 1.0, 2048, 10).to(device, dtype)data_dev = utils.dict_to(data, device, dtype)pts_src = data_dev['pts0']@@ -297,13 +255,9 @@ class TestLocalFeatureMatcher:with torch.no_grad():out = matcher(data_dev)homography, inliers = ransac(out['keypoints0'], out['keypoints1'])- assert (inliers.sum().item() > 50) # we have enough inliers+ 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)+ 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):@@ -311,8 +265,7 @@ class TestLocalFeatureMatcher:patches = torch.rand(B, C, H, W, device=device, dtype=dtype)patches2x = resize(patches, (48, 48))inputs = {"image0": patches, "image1": patches2x}- model = LocalFeatureMatcher(SIFTDescriptor(32),- DescriptorMatcher('snn', 0.8)).to(device).eval()+ model = LocalFeatureMatcher(SIFTDescriptor(32), DescriptorMatcher('snn', 0.8)).to(device).eval()model_jit = torch.jit.script(model)out = model(inputs)diff --git a/test/feature/test_laf.py b/test/feature/test_laf.pyindex d0f598cf1..b813988df 100644--- a/test/feature/test_laf.py+++ b/test/feature/test_laf.py@@ -569,3 +569,35 @@ class TestGetLAFFrom3pts:model = kornia.feature.laf_from_three_pointsmodel_jit = torch.jit.script(kornia.feature.laf_from_three_points)assert_close(model(inp), model_jit(inp))+++class TestTransformLAFs:+ @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):+ # generate input data+ 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)++ # transform the points from dst to ref+ lafs_dst = kornia.feature.perspective_transform_lafs(dst_homo_src, lafs_src)++ # transform the points from ref to dst+ src_homo_dst = torch.inverse(dst_homo_src)+ 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)++ def test_gradcheck(self, device, dtype):+ # 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)+ # 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)diff --git a/test/feature/test_local_features_orientation.py b/test/feature/test_local_features_orientation.pyindex f22b99704..eb0efd6d7 100644--- a/test/feature/test_local_features_orientation.py+++ b/test/feature/test_local_features_orientation.py@@ -1,9 +1,10 @@import pytest+import torchfrom torch.autograd import gradcheck-import korniaimport kornia.testing as utils # test utils-from kornia.feature.orientation import *+from kornia.feature.orientation import LAFOrienter, OriNet, PassLAF, PatchDominantGradientOrientation+from kornia.geometry.conversions import rad2degfrom kornia.testing import assert_close@@ -64,7 +65,7 @@ class TestPatchDominantGradientOrientation:inp[:, :, :10, :] = 1ang = ori(inp)expected = torch.tensor([90.0], device=device)- assert_close(kornia.rad2deg(ang), expected)+ assert_close(rad2deg(ang), expected)def test_gradcheck(self, device):batch_size, channels, height, width = 1, 1, 13, 13@@ -112,7 +113,7 @@ class TestOriNet:ori = OriNet(True).to(device=device, dtype=inp.dtype).eval()ang = ori(inp)expected = torch.tensor([70.58], device=device)- assert_close(kornia.rad2deg(ang), expected, atol=1e-2, rtol=1e-3)+ assert_close(rad2deg(ang), expected, atol=1e-2, rtol=1e-3)@pytest.mark.skip("jacobian not well computed")def test_gradcheck(self, device):diff --git a/test/feature/test_loftr.py b/test/feature/test_loftr.pyindex 4a4782f47..8470a16ac 100644--- a/test/feature/test_loftr.py+++ b/test/feature/test_loftr.py@@ -1,3 +1,5 @@+import sys+import pytestimport torchfrom torch.autograd import gradcheck@@ -6,6 +8,7 @@ import kornia.testing as utils # test utilsfrom kornia.feature import LoFTRfrom kornia.geometry import resizefrom kornia.testing import assert_close+from kornia.utils._compat import torch_version_geqclass TestLoFTR:@@ -17,6 +20,9 @@ class TestLoFTR:loftr = LoFTR('indoor').to(device, dtype)assert loftr is not None+ @pytest.mark.skipif(torch_version_geq(1, 10), reason="RuntimeError: CUDA out of memory with pytorch>=1.10")+ @pytest.mark.skipif(sys.platform == "win32",+ reason="this test takes so much memory in the CI with Windows")@pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)def test_pretrained_indoor(self, device, dtype, data):loftr = LoFTR('indoor').to(device, dtype)@@ -26,6 +32,9 @@ class TestLoFTR:assert_close(out['keypoints0'], data_dev["loftr_indoor_tentatives0"])assert_close(out['keypoints1'], data_dev["loftr_indoor_tentatives1"])+ @pytest.mark.skipif(torch_version_geq(1, 10), reason="RuntimeError: CUDA out of memory with pytorch>=1.10")+ @pytest.mark.skipif(sys.platform == "win32",+ reason="this test takes so much memory in the CI with Windows")@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)def test_pretrained_outdoor(self, device, dtype, data):loftr = LoFTR('outdoor').to(device, dtype)diff --git a/test/feature/test_matching.py b/test/feature/test_matching.pyindex 3223af235..4912461ef 100644--- a/test/feature/test_matching.py+++ b/test/feature/test_matching.py@@ -4,7 +4,6 @@ from torch.autograd import gradcheckimport kornia.testing as utils # test utilsfrom kornia.feature.matching import DescriptorMatcher, match_mnn, match_nn, match_smnn, match_snn-from kornia.geometry import resizefrom kornia.testing import assert_closediff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.pyindex 8d11b1109..9b0cac8b2 100644--- a/test/feature/test_mkd.py+++ b/test/feature/test_mkd.py@@ -1,8 +1,23 @@+from math import pi+import pytest+import torchfrom torch.autograd import gradcheckimport kornia.testing as utils # test utils-from kornia.feature.mkd import *+from kornia.feature.mkd import (+ COEFFS,+ EmbedGradients,+ ExplicitSpacialEncoding,+ get_grid_dict,+ get_kron_order,+ MKDDescriptor,+ MKDGradients,+ SimpleKD,+ spatial_kernel_embedding,+ VonMisesKernel,+ Whitening,+)from kornia.testing import assert_close@@ -131,9 +146,7 @@ class TestVonMisesKernel:def test_jit(self, device, dtype):B, C, H, W = 2, 1, 13, 13patches = torch.rand(B, C, H, W, device=device, dtype=dtype)- model = (- VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval()- )+ model = VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval()model_jit = torch.jit.script(VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval())@@ -442,9 +455,7 @@ class TestSimpleKD:def test_jit(self, device, dtype):batch_size, channels, ps = 1, 1, 19patches = torch.rand(batch_size, channels, ps, ps).to(device)- model = (- SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()- )+ model = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()model_jit = torch.jit.script(SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval())diff --git a/test/feature/test_scale_space_detector.py b/test/feature/test_scale_space_detector.pyindex d1ab3e273..12c05d9ec 100644--- a/test/feature/test_scale_space_detector.py+++ b/test/feature/test_scale_space_detector.py@@ -1,64 +1,57 @@-import pytest+import torchfrom torch.autograd import gradcheckimport korniaimport kornia.testing as utils # test utils-from kornia.feature.scale_space_detector import *+from kornia.feature.scale_space_detector import ScaleSpaceDetectorfrom kornia.testing import assert_closeclass TestScaleSpaceDetector:- def test_shape(self, device):- inp = torch.rand(1, 1, 32, 32, device=device)+ def test_shape(self, device, dtype):+ inp = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)n_feats = 10- det = ScaleSpaceDetector(n_feats).to(device)+ det = ScaleSpaceDetector(n_feats).to(device, dtype)lafs, resps = det(inp)assert lafs.shape == torch.Size([1, n_feats, 2, 3])assert resps.shape == torch.Size([1, n_feats])- def test_shape_batch(self, device):- inp = torch.rand(7, 1, 32, 32, device=device)+ def test_shape_batch(self, device, dtype):+ inp = torch.rand(7, 1, 32, 32, device=device, dtype=dtype)n_feats = 10- det = ScaleSpaceDetector(n_feats).to(device)+ det = ScaleSpaceDetector(n_feats).to(device, dtype)lafs, resps = det(inp)assert lafs.shape == torch.Size([7, n_feats, 2, 3])assert resps.shape == torch.Size([7, n_feats])- def test_print(self, device):- sift = ScaleSpaceDetector()- sift.__repr__()-- def test_toy(self, device):- inp = torch.zeros(1, 1, 33, 33, device=device)+ def test_toy(self, device, dtype):+ inp = torch.zeros(1, 1, 33, 33, device=device, dtype=dtype)inp[:, :, 13:-13, 13:-13] = 1.0n_feats = 1- det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device)+ det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device, dtype)lafs, resps = det(inp)- expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device)- expected_resp = torch.tensor([[0.0857]], device=device)+ 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)- def test_toy_mask(self, device):- if "cuda" in str(device):- pytest.skip("this cuda test is broken")-- inp = torch.zeros(1, 1, 33, 33, device=device)+ def test_toy_mask(self, device, dtype):+ inp = torch.zeros(1, 1, 33, 33, device=device, dtype=dtype)inp[:, :, 13:-13, 13:-13] = 1.0- mask = torch.zeros(1, 1, 33, 33, device=device)+ mask = torch.zeros(1, 1, 33, 33, device=device, dtype=dtype)mask[:, :, 1:-1, 3:-3] = 1.0n_feats = 1- det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device)+ det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device, dtype)lafs, resps = det(inp, mask)- expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device)- expected_resp = torch.tensor([[0.0857]], device=device)+ 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)def test_gradcheck(self, device):- batch_size, channels, height, width = 1, 1, 31, 21+ batch_size, channels, height, width = 1, 1, 7, 7patches = torch.rand(batch_size, channels, height, width, device=device)patches = utils.tensor_to_gradcheck_var(patches) # to varassert gradcheck(ScaleSpaceDetector(2).to(device), patches, raise_exception=True, nondet_tol=1e-4)diff --git a/test/feature/test_siftdesc.py b/test/feature/test_siftdesc.pyindex 604a504e8..cd43d61fa 100644--- a/test/feature/test_siftdesc.py+++ b/test/feature/test_siftdesc.py@@ -1,8 +1,9 @@import pytest+import torchfrom torch.autograd import gradcheckimport kornia.testing as utils # test utils-from kornia.feature.siftdesc import *+from kornia.feature.siftdesc import get_sift_bin_ksize_stride_pad, get_sift_pooling_kernel, SIFTDescriptorfrom kornia.testing import assert_close@@ -19,48 +20,44 @@ def test_get_sift_bin_ksize_stride_pad(ps, n_bins, ksize, stride, pad):class TestSIFTDescriptor:- def test_shape(self, device):- inp = torch.ones(1, 1, 32, 32, device=device)- sift = SIFTDescriptor(32).to(device)+ def test_shape(self, device, dtype):+ inp = torch.ones(1, 1, 32, 32, device=device, dtype=dtype)+ sift = SIFTDescriptor(32).to(device, dtype)out = sift(inp)assert out.shape == (1, 128)- def test_batch_shape(self, device):- inp = torch.ones(2, 1, 15, 15, device=device)- sift = SIFTDescriptor(15).to(device)+ def test_batch_shape(self, device, dtype):+ inp = torch.ones(2, 1, 15, 15, device=device, dtype=dtype)+ sift = SIFTDescriptor(15).to(device, dtype)out = sift(inp)assert out.shape == (2, 128)- def test_batch_shape_non_std(self, device):- inp = torch.ones(3, 1, 19, 19, device=device)- sift = SIFTDescriptor(19, 5, 3).to(device)+ def test_batch_shape_non_std(self, device, dtype):+ inp = torch.ones(3, 1, 19, 19, device=device, dtype=dtype)+ sift = SIFTDescriptor(19, 5, 3).to(device, dtype)out = sift(inp)assert out.shape == (3, (3 ** 2) * 5)- def test_print(self, device):- sift = SIFTDescriptor(41)- sift.__repr__()-- def test_toy(self, device):- patch = torch.ones(1, 1, 6, 6, device=device).float()+ def test_toy(self, device, dtype):+ patch = torch.ones(1, 1, 6, 6, device=device, dtype=dtype)patch[0, 0, :, 3:] = 0- sift = SIFTDescriptor(6, num_ang_bins=4, num_spatial_bins=1, clipval=0.2, rootsift=False).to(device)+ 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)+ expected = torch.tensor([[0, 0, 1.0, 0]], device=device, dtype=dtype)assert_close(out, expected, atol=1e-3, rtol=1e-3)- @pytest.mark.xfail(reason='May raise checkIfNumericalAnalyticAreClose.')def test_gradcheck(self, device):- batch_size, channels, height, width = 1, 1, 13, 13- patches = torch.rand(batch_size, channels, height, width, device=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- assert gradcheck(sift_describe, (patches, 13), raise_exception=True, nondet_tol=1e-4)+ sift = SIFTDescriptor(15).to(device, dtype)+ assert gradcheck(sift, (patches,), raise_exception=True, nondet_tol=1e-4)- @pytest.mark.jit@pytest.mark.skip("Compiled functions can't take variable number")def test_jit(self, device, dtype):- B, C, H, W = 2, 1, 41, 41+ B, C, H, W = 1, 1, 32, 32patches = 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())+ model = SIFTDescriptor(32).to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(model)assert_close(model(patches), model_jit(patches))diff --git a/test/filters/test_filters.py b/test/filters/test_filters.pyindex 6af3e6314..acc231935 100644--- a/test/filters/test_filters.py+++ b/test/filters/test_filters.py@@ -15,10 +15,10 @@ class TestFilter2D:input = torch.ones(1, 1, 7, 8, device=device, dtype=dtype)b, c, h, w = input.shapeif padding == 'same':- out = kornia.filter2d(input, kernel, padding=padding)+ out = kornia.filters.filter2d(input, kernel, padding=padding)assert out.shape == (b, c, h, w)else:- out = kornia.filter2d(input, kernel, padding=padding)+ out = kornia.filters.filter2d(input, kernel, padding=padding)assert out.shape == (b, c, h - height + 1, w - width + 1)@pytest.mark.parametrize("batch_size", [2, 3, 6, 8])@@ -30,10 +30,10 @@ class TestFilter2D:input = torch.ones(B, 3, 7, 8, device=device, dtype=dtype)b, c, h, w = input.shapeif padding == 'same':- out = kornia.filter2d(input, kernel, padding=padding)+ out = kornia.filters.filter2d(input, kernel, padding=padding)assert out.shape == (b, c, h, w)else:- out = kornia.filter2d(input, kernel, padding=padding)+ out = kornia.filters.filter2d(input, kernel, padding=padding)assert out.shape == (b, c, h - height + 1, w - width + 1)@pytest.mark.parametrize("padding", ["same", "valid"])@@ -71,20 +71,10 @@ class TestFilter2D:)expected_valid = torch.tensor(- [- [- [- [5.0, 5.0, 5.0],- [5.0, 5.0, 5.0],- [5.0, 5.0, 5.0],- ]- ]- ],- device=device,- dtype=dtype,+ [[[[5.0, 5.0, 5.0], [5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]]], device=device, dtype=dtype)- actual = kornia.filter2d(input, kernel, padding=padding)+ actual = kornia.filters.filter2d(input, kernel, padding=padding)if padding == 'same':assert_close(actual, expected_same)else:@@ -126,20 +116,10 @@ class TestFilter2D:).expand(2, 2, -1, -1)expected_valid = torch.tensor(- [- [- [- [5.0, 5.0, 5.0],- [5.0, 5.0, 5.0],- [5.0, 5.0, 5.0],- ]- ]- ],- device=device,- dtype=dtype,+ [[[[5.0, 5.0, 5.0], [5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]]], device=device, dtype=dtype).expand(2, 2, -1, -1)- actual = kornia.filter2d(input, kernel, padding=padding)+ actual = kornia.filters.filter2d(input, kernel, padding=padding)if padding == 'same':assert_close(actual, expected_same)else:@@ -182,20 +162,10 @@ class TestFilter2D:).expand(2, 2, -1, -1)expected_valid = torch.tensor(- [- [- [- [nv, nv, nv],- [nv, nv, nv],- [nv, nv, nv],- ]- ]- ],- device=device,- dtype=dtype,+ [[[[nv, nv, nv], [nv, nv, nv], [nv, nv, nv]]]], device=device, dtype=dtype).expand(2, 2, -1, -1)- actual = kornia.filter2d(input, kernel, normalized=True, padding=padding)+ actual = kornia.filters.filter2d(input, kernel, normalized=True, padding=padding)tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)if padding == 'same':@@ -239,21 +209,12 @@ class TestFilter2D:)expected_valid = torch.tensor(- [- [- [- [0.0, 0.0, 0.0, 0.0],- [0.0, 5.0, 5.0, 0.0],- [0.0, 5.0, 5.0, 0.0],- [0.0, 0.0, 0.0, 0.0],- ]- ]- ],+ [[[[0.0, 0.0, 0.0, 0.0], [0.0, 5.0, 5.0, 0.0], [0.0, 5.0, 5.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]],device=device,dtype=dtype,)- actual = kornia.filter2d(input, kernel, padding=padding)+ actual = kornia.filters.filter2d(input, kernel, padding=padding)if padding == 'same':assert_close(actual, expected_same)else:@@ -265,7 +226,7 @@ class TestFilter2D:inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)kernel = torch.ones(1, 2, 2, device=device, dtype=dtype)- actual = kornia.filter2d(inp, kernel, padding=padding)+ actual = kornia.filters.filter2d(inp, kernel, padding=padding)assert_close(actual, actual)@pytest.mark.parametrize("padding", ["same", "valid"])@@ -275,7 +236,7 @@ class TestFilter2D:kernel_x = torch.ones(1, 3, device=device, dtype=dtype)kernel_y = torch.ones(1, 3, device=device, dtype=dtype)kernel = kernel_y.t() @ kernel_x- out = kornia.filter2d(inp, kernel[None], padding=padding)+ out = kornia.filters.filter2d(inp, kernel[None], padding=padding)out_sep = kornia.filters.filter2d_separable(inp, kernel_x, kernel_y, padding=padding)assert_close(out, out_sep)@@ -286,11 +247,11 @@ class TestFilter2D:# evaluate function gradientinput = utils.tensor_to_gradcheck_var(input) # to varkernel = utils.tensor_to_gradcheck_var(kernel) # to var- assert gradcheck(kornia.filter2d, (input, kernel), raise_exception=True)+ assert gradcheck(kornia.filters.filter2d, (input, kernel), raise_exception=True)@pytest.mark.parametrize("padding", ["same", "valid"])def test_jit(self, padding, device, dtype):- op = kornia.filter2d+ op = kornia.filters.filter2dop_script = torch.jit.script(op)kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)@@ -304,14 +265,14 @@ class TestFilter3D:def test_smoke(self, device, dtype):kernel = torch.rand(1, 3, 3, 3).to(device)input = torch.ones(1, 1, 6, 7, 8).to(device)- assert kornia.filter3d(input, kernel).shape == input.shape+ assert kornia.filters.filter3d(input, kernel).shape == input.shape@pytest.mark.parametrize("batch_size", [2, 3, 6, 8])def test_batch(self, batch_size, device, dtype):B: int = batch_sizekernel = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)input = torch.ones(B, 3, 6, 7, 8, device=device, dtype=dtype)- assert kornia.filter3d(input, kernel).shape == input.shape+ assert kornia.filters.filter3d(input, kernel).shape == input.shapedef test_mean_filter(self, device, dtype):kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)@@ -379,7 +340,7 @@ class TestFilter3D:dtype=dtype,)- actual = kornia.filter3d(input, kernel)+ actual = kornia.filters.filter3d(input, kernel)assert_close(actual, expected)def test_mean_filter_2batch_2ch(self, device, dtype):@@ -450,7 +411,7 @@ class TestFilter3D:)expected = expected.expand(2, 2, -1, -1, -1)- actual = kornia.filter3d(input, kernel)+ actual = kornia.filters.filter3d(input, kernel)assert_close(actual, expected)def test_normalized_mean_filter(self, device, dtype):@@ -522,7 +483,7 @@ class TestFilter3D:)expected = expected.expand(2, 2, -1, -1, -1)- actual = kornia.filter3d(input, kernel, normalized=True)+ actual = kornia.filters.filter3d(input, kernel, normalized=True)tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)assert_close(actual, expected, rtol=tol_val, atol=tol_val)@@ -593,7 +554,7 @@ class TestFilter3D:dtype=dtype,)- actual = kornia.filter3d(input, kernel)+ actual = kornia.filters.filter3d(input, kernel)assert_close(actual, expected)def test_noncontiguous(self, device, dtype):@@ -601,7 +562,7 @@ class TestFilter3D:inp = torch.rand(3, 5, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1, -1)kernel = torch.ones(1, 2, 2, 2, device=device, dtype=dtype)- actual = kornia.filter3d(inp, kernel)+ actual = kornia.filters.filter3d(inp, kernel)expected = actualassert_close(actual, expected)@@ -612,10 +573,10 @@ class TestFilter3D:# evaluate function gradientinput = utils.tensor_to_gradcheck_var(input) # to varkernel = utils.tensor_to_gradcheck_var(kernel) # to var- assert gradcheck(kornia.filter3d, (input, kernel), raise_exception=True)+ assert gradcheck(kornia.filters.filter3d, (input, kernel), raise_exception=True)def test_jit(self, device, dtype):- op = kornia.filter3d+ op = kornia.filters.filter3dop_script = torch.jit.script(op)kernel = torch.rand(1, 1, 3, 3, device=device, dtype=dtype)diff --git a/test/filters/test_gaussian.py b/test/filters/test_gaussian.pyindex fcdf8f8c1..80136928a 100644--- a/test/filters/test_gaussian.py+++ b/test/filters/test_gaussian.py@@ -10,7 +10,7 @@ from kornia.testing import assert_close@pytest.mark.parametrize("window_size", [5, 11])@pytest.mark.parametrize("sigma", [1.5, 5.0])def test_get_gaussian_kernel(window_size, sigma):- kernel = kornia.get_gaussian_kernel1d(window_size, sigma)+ kernel = kornia.filters.get_gaussian_kernel1d(window_size, sigma)assert kernel.shape == (window_size,)assert kernel.sum().item() == pytest.approx(1.0)@@ -18,7 +18,7 @@ def test_get_gaussian_kernel(window_size, sigma):@pytest.mark.parametrize("window_size", [5, 11])@pytest.mark.parametrize("sigma", [1.5, 5.0])def test_get_gaussian_discrete_kernel(window_size, sigma):- kernel = kornia.get_gaussian_discrete_kernel1d(window_size, sigma)+ kernel = kornia.filters.get_gaussian_discrete_kernel1d(window_size, sigma)assert kernel.shape == (window_size,)assert kernel.sum().item() == pytest.approx(1.0)@@ -26,7 +26,7 @@ def test_get_gaussian_discrete_kernel(window_size, sigma):@pytest.mark.parametrize("window_size", [5, 11])@pytest.mark.parametrize("sigma", [1.5, 5.0])def test_get_gaussian_erf_kernel(window_size, sigma):- kernel = kornia.get_gaussian_erf_kernel1d(window_size, sigma)+ kernel = kornia.filters.get_gaussian_erf_kernel1d(window_size, sigma)assert kernel.shape == (window_size,)assert kernel.sum().item() == pytest.approx(1.0)@@ -35,7 +35,7 @@ def test_get_gaussian_erf_kernel(window_size, sigma):@pytest.mark.parametrize("ksize_y", [3, 7])@pytest.mark.parametrize("sigma", [1.5, 2.1])def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):- kernel = kornia.get_gaussian_kernel2d((ksize_x, ksize_y), (sigma, sigma))+ kernel = kornia.filters.get_gaussian_kernel2d((ksize_x, ksize_y), (sigma, sigma))assert kernel.shape == (ksize_x, ksize_y)assert kernel.sum().item() == pytest.approx(1.0)@@ -45,16 +45,8 @@ def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):@pytest.mark.parametrize("sigma", [1.5, 2.1])def test_separable(ksize_x, ksize_y, sigma, device, dtype):input = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)- out = kornia.filters.gaussian_blur2d(input,- (ksize_x, ksize_y),- (sigma, sigma),- "replicate",- separable=False)- out_sep = kornia.filters.gaussian_blur2d(input,- (ksize_x, ksize_y),- (sigma, sigma),- "replicate",- separable=True)+ out = kornia.filters.gaussian_blur2d(input, (ksize_x, ksize_y), (sigma, sigma), "replicate", separable=False)+ out_sep = kornia.filters.gaussian_blur2d(input, (ksize_x, ksize_y), (sigma, sigma), "replicate", separable=True)assert_close(out, out_sep)@@ -86,7 +78,7 @@ class TestGaussianBlur2d:# evaluate function gradientinput = torch.rand(batch_shape, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.gaussian_blur2d, (input, kernel_size, sigma, "replicate"), raise_exception=True)+ assert gradcheck(kornia.filters.gaussian_blur2d, (input, kernel_size, sigma, "replicate"), raise_exception=True)def test_jit(self, device, dtype):op = kornia.filters.gaussian_blur2ddiff --git a/test/filters/test_laplacian.py b/test/filters/test_laplacian.pyindex 89801ef1d..a59fb36f9 100644--- a/test/filters/test_laplacian.py+++ b/test/filters/test_laplacian.py@@ -9,14 +9,14 @@ from kornia.testing import assert_close@pytest.mark.parametrize("window_size", [5])def test_get_laplacian_kernel(window_size):- kernel = kornia.get_laplacian_kernel1d(window_size)+ kernel = kornia.filters.get_laplacian_kernel1d(window_size)assert kernel.shape == (window_size,)assert kernel.sum().item() == pytest.approx(0.0)@pytest.mark.parametrize("window_size", [7])def test_get_laplacian_kernel2d(window_size):- kernel = kornia.get_laplacian_kernel2d(window_size)+ kernel = kornia.filters.get_laplacian_kernel2d(window_size)assert kernel.shape == (window_size, window_size)assert kernel.sum().item() == pytest.approx(0.0)expected = torch.tensor(@@ -58,7 +58,7 @@ class TestLaplacian:# evaluate function gradientinput = torch.rand(batch_shape, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input)- assert gradcheck(kornia.laplacian, (input, kernel_size), raise_exception=True)+ assert gradcheck(kornia.filters.laplacian, (input, kernel_size), raise_exception=True)def test_jit(self, device, dtype):op = kornia.filters.laplaciandiff --git a/test/filters/test_motion.py b/test/filters/test_motion.pyindex 30ba78a40..459059ff8 100644--- a/test/filters/test_motion.py+++ b/test/filters/test_motion.py@@ -3,7 +3,6 @@ import torchfrom torch.autograd import gradcheckimport kornia-import kornia.filters.kernels_geometryimport kornia.testing as utils # test utilsfrom kornia.testing import assert_close@@ -52,7 +51,9 @@ class TestMotionBlur:input = torch.rand(batch_shape, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input)- assert gradcheck(kornia.motion_blur, (input, ksize, angle, direction, "replicate"), raise_exception=True)+ assert gradcheck(+ kornia.filters.motion_blur, (input, ksize, angle, direction, "replicate"), raise_exception=True+ )@pytest.mark.skip("angle can be Union")def test_jit(self, device, dtype):diff --git a/test/geometry/calibration/test_pnp.py b/test/geometry/calibration/test_pnp.pyindex 0c0a2348f..df5815011 100644--- a/test/geometry/calibration/test_pnp.py+++ b/test/geometry/calibration/test_pnp.py@@ -8,7 +8,6 @@ from kornia.testing import assert_close, tensor_to_gradcheck_varclass TestSolvePnpDlt:-@staticmethoddef _get_samples(shape, low, high, device, dtype):"""Return a tensor having the given shape and whose values are in the range [low, high)"""@@ -48,21 +47,13 @@ class TestSolvePnpDlt:torch.manual_seed(84)tau = 2 * 3.141592653589793- angle_axis_1 = self._get_samples(- shape=(1, 3), low=-tau, high=tau, dtype=dtype, device=device,- )- angle_axis_2 = self._get_samples(- shape=(1, 3), low=-tau, high=tau, dtype=dtype, device=device,- )+ angle_axis_1 = self._get_samples(shape=(1, 3), low=-tau, high=tau, dtype=dtype, device=device)+ angle_axis_2 = self._get_samples(shape=(1, 3), low=-tau, high=tau, dtype=dtype, device=device)rotation_1 = kornia.geometry.angle_axis_to_rotation_matrix(angle_axis_1)rotation_2 = kornia.geometry.angle_axis_to_rotation_matrix(angle_axis_2)- translation_1 = self._get_samples(- shape=(3,), low=-100, high=100, dtype=dtype, device=device,- )- translation_2 = self._get_samples(- shape=(3,), low=-100, high=100, dtype=dtype, device=device,- )+ translation_1 = self._get_samples(shape=(3,), low=-100, high=100, dtype=dtype, device=device)+ translation_2 = self._get_samples(shape=(3,), low=-100, high=100, dtype=dtype, device=device)temp = torch.eye(4, dtype=dtype, device=device)world_to_cam_mats = temp.unsqueeze(0).repeat(batch_size, 1, 1)@@ -71,27 +62,21 @@ class TestSolvePnpDlt:world_to_cam_mats[1, :3, :3] = torch.squeeze(rotation_2)world_to_cam_mats[1, :3, 3] = translation_2- intrinsic_1 = torch.tensor([- [500.0, 0.0, 250.0],- [0.0, 500.0, 250.0],- [0.0, 0.0, 1.0],- ], dtype=dtype, device=device)+ intrinsic_1 = torch.tensor(+ [[500.0, 0.0, 250.0], [0.0, 500.0, 250.0], [0.0, 0.0, 1.0]], dtype=dtype, device=device+ )- intrinsic_2 = torch.tensor([- [1000.0, 0.0, 550.0],- [0.0, 750.0, 200.0],- [0.0, 0.0, 1.0],- ], dtype=dtype, device=device)+ intrinsic_2 = torch.tensor(+ [[1000.0, 0.0, 550.0], [0.0, 750.0, 200.0], [0.0, 0.0, 1.0]], dtype=dtype, device=device+ )intrinsics = torch.stack([intrinsic_1, intrinsic_2], dim=0)cam_points_xy = self._get_samples(- shape=(batch_size, num_points, 2),- low=-100, high=100, dtype=dtype, device=device,+ shape=(batch_size, num_points, 2), low=-100, high=100, dtype=dtype, device=device)cam_points_z = self._get_samples(- shape=(batch_size, num_points, 1),- low=0.5, high=100, dtype=dtype, device=device,+ shape=(batch_size, num_points, 1), low=0.5, high=100, dtype=dtype, device=device)cam_points = torch.cat([cam_points_xy, cam_points_z], dim=-1)@@ -103,45 +88,38 @@ class TestSolvePnpDlt:return intrinsics, world_to_cam_3x4, world_points, img_points- @pytest.mark.parametrize("num_points", (6, 20, 1000))+ @pytest.mark.parametrize("num_points", (6, 20,))def test_smoke(self, num_points, device, dtype):- intrinsics, _, world_points, img_points = \- self._get_test_data(num_points, device, dtype)+ intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, dtype)batch_size = world_points.shape[0]pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)assert pred_world_to_cam.shape == (batch_size, 3, 4)- @pytest.mark.parametrize("num_points", (6, 10, 20))+ @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)+ intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, dtype)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,- )+ assert gradcheck(kornia.geometry.solve_pnp_dlt, (world_points, img_points, intrinsics), raise_exception=True)- @pytest.mark.parametrize("num_points", (6, 20, 1000))+ @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)+ 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)- @pytest.mark.parametrize("num_points", (6, 20, 1000))+ @pytest.mark.parametrize("num_points", (6, 20,))def test_project(self, num_points, device, dtype):- intrinsics, _, world_points, img_points = \- self._get_test_data(num_points, device, dtype)+ intrinsics, _, 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)@@ -149,15 +127,12 @@ class TestSolvePnpDlt:pred_world_to_cam_4x4[:, :3, :] = pred_world_to_camrepeated_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- )+ 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)class TestNormalization:-@pytest.mark.parametrize("dimension", (2, 3, 5))def test_smoke(self, dimension, device, dtype):@@ -177,7 +152,4 @@ class TestNormalization:points = torch.rand((batch_size, num_points, dimension), device=device, dtype=dtype)points = tensor_to_gradcheck_var(points)- assert gradcheck(- _mean_isotropic_scale_normalize,- (points,), raise_exception=True,- )+ assert gradcheck(_mean_isotropic_scale_normalize, (points,), raise_exception=True)diff --git a/test/geometry/calibration/test_undistort.py b/test/geometry/calibration/test_undistort.pyindex 8797319d2..7eb910845 100644--- a/test/geometry/calibration/test_undistort.py+++ b/test/geometry/calibration/test_undistort.py@@ -221,41 +221,29 @@ class TestUndistortImage:[9, 182, 97, 213, 3],[91, 10, 33, 141, 230],[229, 63, 221, 244, 61],- [19, 137, 23, 59, 227]+ [19, 137, 23, 59, 227],]]],- device=device, dtype=dtype- )-- K = torch.tensor(- [[2, 0, 2], [0, 2, 2], [0, 0, 1]],device=device,- dtype=dtype+ dtype=dtype,)+ K = torch.tensor([[2, 0, 2], [0, 2, 2], [0, 0, 1]], device=device, dtype=dtype)+dist = torch.tensor([0.2290, 0.9565, 0.0083, 0.0475], device=device, dtype=dtype)# Expected output generated with OpenCV:# import cv2# imu_expected = cv2.undistort(np.uint8(im[0,0].numpy()), K.numpy(), dist.numpy())imu_expected = torch.tensor(- [- [- [- [0, 0, 0, 0, 0],- [0, 124, 112, 82, 0],- [0, 13, 33, 158, 0],- [0, 108, 197, 150, 0],- [0, 0, 0, 0, 0]- ]- ]- ],- device=device, dtype=dtype+ [[[[0, 0, 0, 0, 0], [0, 124, 112, 82, 0], [0, 13, 33, 158, 0], [0, 108, 197, 150, 0], [0, 0, 0, 0, 0]]]],+ device=device,+ dtype=dtype,)- imu = undistort_image(im / 255., K, dist)- assert_close(imu, imu_expected / 255., rtol=1e-2, atol=1e-2)+ imu = undistort_image(im / 255.0, K, dist)+ 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)diff --git a/test/geometry/test_perspective.py b/test/geometry/camera/test_perspective.pysimilarity index 100%rename from test/geometry/test_perspective.pyrename to test/geometry/camera/test_perspective.pydiff --git a/test/geometry/test_pinhole.py b/test/geometry/camera/test_pinhole.pysimilarity index 71%rename from test/geometry/test_pinhole.pyrename to test/geometry/camera/test_pinhole.pyindex a09c6dc6e..8412095d8 100644--- a/test/geometry/test_pinhole.py+++ b/test/geometry/camera/test_pinhole.py@@ -25,7 +25,7 @@ class TestCam2Pixel:"""Return a tensor having the given shape and whose values are in the range [low, high)"""return ((high - low) * torch.rand(shape, device=device, dtype=dtype)) + low- @pytest.mark.parametrize("batch_size", (1, 2, 5))+ @pytest.mark.parametrize("batch_size", (1,))def test_smoke(self, batch_size, device, dtype):H, W = 250, 500fx, fy = W, H@@ -43,7 +43,9 @@ class TestCam2Pixel:torch.manual_seed(seed)cam_coords_src = self._get_samples((batch_size, H, W, 3), low, high, device, dtype)- pixel_coords_dst = kornia.cam2pixel(cam_coords_src=cam_coords_src, dst_proj_src=proj_mat, eps=eps)+ pixel_coords_dst = kornia.geometry.camera.cam2pixel(+ cam_coords_src=cam_coords_src, dst_proj_src=proj_mat, eps=eps+ )assert pixel_coords_dst.shape == (batch_size, H, W, 2)@pytest.mark.parametrize("batch_size", (1, 2, 5))@@ -65,19 +67,21 @@ class TestCam2Pixel:torch.manual_seed(seed)cam_coords_input = self._get_samples((batch_size, H, W, 3), low, high, device, dtype)- pixel_coords_output = kornia.cam2pixel(cam_coords_src=cam_coords_input, dst_proj_src=proj_mat, eps=eps)+ pixel_coords_output = kornia.geometry.camera.cam2pixel(+ cam_coords_src=cam_coords_input, dst_proj_src=proj_mat, eps=eps+ )last_ch = torch.ones((batch_size, H, W, 1), device=device, dtype=dtype)pixel_coords_concat = torch.cat([pixel_coords_output, last_ch], axis=-1)depth = cam_coords_input[..., 2:3].permute(0, 3, 1, 2).contiguous()- cam_coords_output = kornia.pixel2cam(+ cam_coords_output = kornia.geometry.camera.pixel2cam(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)- @pytest.mark.parametrize("batch_size", (1, 2, 5))+ @pytest.mark.parametrize("batch_size", (1,))def test_gradcheck(self, batch_size, device, dtype):H, W = 10, 20fx, fy = W, H@@ -105,7 +109,11 @@ class TestCam2Pixel:proj_mat = tensor_to_gradcheck_var(proj_mat)assert gradcheck(- kornia.geometry.cam2pixel, (cam_coords_src, proj_mat, eps), raise_exception=True, atol=atol, rtol=rtol+ kornia.geometry.camera.cam2pixel,+ (cam_coords_src, proj_mat, eps),+ raise_exception=True,+ atol=atol,+ rtol=rtol,)@@ -146,7 +154,9 @@ class TestPixel2Cam:intrinsics_inv = self._create_intrinsics_inv(batch_size, fx, fy, cx, cy, device=device, dtype=dtype)- output = kornia.pixel2cam(depth=depth, intrinsics_inv=intrinsics_inv, pixel_coords=pixel_coords_input)+ output = kornia.geometry.camera.pixel2cam(+ depth=depth, intrinsics_inv=intrinsics_inv, pixel_coords=pixel_coords_input+ )assert output.shape == (batch_size, H, W, 3)@@ -170,17 +180,21 @@ class TestPixel2Cam:intrinsics = self._create_intrinsics(batch_size, fx, fy, cx, cy, device=device, dtype=dtype)intrinsics_inv = self._create_intrinsics_inv(batch_size, fx, fy, cx, cy, device=device, dtype=dtype)- cam_coords = kornia.pixel2cam(depth=depth, intrinsics_inv=intrinsics_inv, pixel_coords=pixel_coords_input)+ cam_coords = kornia.geometry.camera.pixel2cam(+ depth=depth, intrinsics_inv=intrinsics_inv, pixel_coords=pixel_coords_input+ )# Setting the projection matrix to the intrinsic matrix for# simplicity (i.e. assuming that the RT matrix is an identity matrix)proj_mat = intrinsics- pixel_coords_output = kornia.cam2pixel(cam_coords_src=cam_coords, dst_proj_src=proj_mat, eps=eps)+ pixel_coords_output = kornia.geometry.camera.cam2pixel(+ cam_coords_src=cam_coords, dst_proj_src=proj_mat, eps=eps+ )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)- @pytest.mark.parametrize("batch_size", (1, 2, 5))+ @pytest.mark.parametrize("batch_size", (1,))def test_gradcheck(self, batch_size, device, dtype):H, W = 10, 20fx, fy = W, H@@ -205,7 +219,9 @@ class TestPixel2Cam:intrinsics_inv = tensor_to_gradcheck_var(intrinsics_inv)pixel_coords_input = tensor_to_gradcheck_var(pixel_coords_input)- assert gradcheck(kornia.geometry.pixel2cam, (depth, intrinsics_inv, pixel_coords_input), raise_exception=True)+ assert gradcheck(+ kornia.geometry.camera.pixel2cam, (depth, intrinsics_inv, pixel_coords_input), raise_exception=True+ )class TestPinholeCamera:@@ -229,8 +245,8 @@ class TestPinholeCamera:extrinsics = torch.eye(4, device=device, dtype=dtype)[None]height = torch.ones(1, device=device, dtype=dtype)width = torch.ones(1, device=device, dtype=dtype)- pinhole = kornia.PinholeCamera(intrinsics, extrinsics, height, width)- assert isinstance(pinhole, kornia.PinholeCamera)+ pinhole = kornia.geometry.camera.PinholeCamera(intrinsics, extrinsics, height, width)+ assert isinstance(pinhole, kornia.geometry.camera.PinholeCamera)def test_pinhole_camera_attributes(self, device, dtype):batch_size = 1@@ -243,7 +259,7 @@ class TestPinholeCamera:height = torch.ones(batch_size, device=device, dtype=dtype) * heightwidth = torch.ones(batch_size, device=device, dtype=dtype) * width- pinhole = kornia.PinholeCamera(intrinsics, extrinsics, height, width)+ pinhole = kornia.geometry.camera.PinholeCamera(intrinsics, extrinsics, height, width)assert pinhole.batch_size == batch_sizeassert pinhole.fx.item() == fx@@ -271,7 +287,7 @@ class TestPinholeCamera:height = torch.ones(batch_size, device=device, dtype=dtype) * heightwidth = torch.ones(batch_size, device=device, dtype=dtype) * width- pinhole = kornia.PinholeCamera(intrinsics, extrinsics, height, width)+ pinhole = kornia.geometry.camera.PinholeCamera(intrinsics, extrinsics, height, width)assert pinhole.tx.item() == txassert pinhole.ty.item() == ty@@ -306,7 +322,7 @@ class TestPinholeCamera:height = torch.ones(batch_size, device=device, dtype=dtype) * heightwidth = torch.ones(batch_size, device=device, dtype=dtype) * width- pinhole = kornia.PinholeCamera(intrinsics, extrinsics, height, width)+ pinhole = kornia.geometry.camera.PinholeCamera(intrinsics, extrinsics, height, width)assert pinhole.batch_size == batch_sizeassert pinhole.fx.shape[0] == batch_size@@ -336,7 +352,7 @@ class TestPinholeCamera:width = torch.ones(batch_size, device=device, dtype=dtype) * widthscale_factor = torch.ones(batch_size, device=device, dtype=dtype) * scale_val- pinhole = kornia.PinholeCamera(intrinsics, extrinsics, height, width)+ pinhole = kornia.geometry.camera.PinholeCamera(intrinsics, extrinsics, height, width)pinhole_scale = pinhole.scale(scale_factor)assert_close(@@ -367,7 +383,7 @@ class TestPinholeCamera:width = torch.ones(batch_size, device=device, dtype=dtype) * widthscale_factor = torch.ones(batch_size, device=device, dtype=dtype) * scale_val- pinhole = kornia.PinholeCamera(intrinsics, extrinsics, height, width)+ pinhole = kornia.geometry.camera.PinholeCamera(intrinsics, extrinsics, height, width)pinhole_scale = pinhole.clone()pinhole_scale.scale_(scale_factor)@@ -385,133 +401,3 @@ class TestPinholeCamera:) # cyassert_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)---'''@pytest.mark.parametrize("batch_size", [1, 2, 5, 6])-def test_scale_pinhole(batch_size, device_type):- # generate input data- device = torch.device(device_type)- pinholes = torch.rand(batch_size, 12, device=device, dtype=dtype)- scales = torch.rand(batch_size, device=device, dtype=dtype)-- pinholes_scale = kornia.scale_pinhole(pinholes, scales)- assert_close(- pinholes_scale[..., :6] / scales.unsqueeze(-1), pinholes[..., :6])-- # evaluate function gradient- pinholes = utils.tensor_to_gradcheck_var(pinholes) # to var- scales = utils.tensor_to_gradcheck_var(scales) # to var- assert gradcheck(kornia.scale_pinhole, (pinholes, scales,),- raise_exception=True)--[email protected]("batch_size", [1, 2, 5, 6])-def test_pinhole_matrix(batch_size, device_type):- # generate input data- image_height, image_width = 32., 32.- cx, cy = image_width / 2, image_height / 2- fx, fy = 1., 1.- rx, ry, rz = 0., 0., 0.- tx, ty, tz = 0., 0., 0.- offset_x = 10. # we will apply a 10units offset to `i` camera- eps = 1e-6-- pinhole = utils.create_pinhole(- fx, fy, cx, cy, image_height, image_width, rx, ry, rx, tx, ty, tz)- pinhole = pinhole.repeat(batch_size, 1).to(torch.device(device_type))-- pinhole_matrix = kornia.pinhole_matrix(pinhole)-- ones = torch.ones(batch_size)- assert bool((pinhole_matrix[:, 0, 0] == fx * ones).all())- assert bool((pinhole_matrix[:, 1, 1] == fy * ones).all())- assert bool((pinhole_matrix[:, 0, 2] == cx * ones).all())- assert bool((pinhole_matrix[:, 1, 2] == cy * ones).all())-- # functional- assert kornia.PinholeMatrix()(pinhole).shape == (batch_size, 4, 4)-- # evaluate function gradient- pinhole = utils.tensor_to_gradcheck_var(pinhole) # to var- assert gradcheck(kornia.pinhole_matrix, (pinhole,),- raise_exception=True)--[email protected]("batch_size", [1, 2, 5, 6])-def test_inverse_pinhole_matrix(batch_size, device_type):- # generate input data- image_height, image_width = 32., 32.- cx, cy = image_width / 2, image_height / 2- fx, fy = 1., 1.- rx, ry, rz = 0., 0., 0.- tx, ty, tz = 0., 0., 0.- offset_x = 10. # we will apply a 10units offset to `i` camera- eps = 1e-6-- pinhole = utils.create_pinhole(- fx, fy, cx, cy, image_height, image_width, rx, ry, rx, tx, ty, tz)- pinhole = pinhole.repeat(batch_size, 1).to(torch.device(device_type))-- pinhole_matrix = kornia.inverse_pinhole_matrix(pinhole)-- ones = torch.ones(batch_size)- assert_close(pinhole_matrix[:, 0, 0], (1. / fx) * ones)- assert_close(pinhole_matrix[:, 1, 1], (1. / fy) * ones)- assert_close(- pinhole_matrix[:, 0, 2], (-1. * cx / fx) * ones)- assert_close(- pinhole_matrix[:, 1, 2], (-1. * cy / fx) * ones)-- # functional- assert kornia.InversePinholeMatrix()(pinhole).shape == (batch_size, 4, 4)-- # evaluate function gradient- pinhole = utils.tensor_to_gradcheck_var(pinhole) # to var- assert gradcheck(kornia.pinhole_matrix, (pinhole,),- raise_exception=True)--[email protected]("batch_size", [1, 2, 5, 6])-def test_homography_i_H_ref(batch_size, device_type):- # generate input data- device = torch.device(device_type)- image_height, image_width = 32., 32.- cx, cy = image_width / 2, image_height / 2- fx, fy = 1., 1.- rx, ry, rz = 0., 0., 0.- tx, ty, tz = 0., 0., 0.- offset_x = 10. # we will apply a 10units offset to `i` camera- eps = 1e-6-- pinhole_ref = utils.create_pinhole(- fx, fy, cx, cy, image_height, image_width, rx, ry, rx, tx, ty, tz)- pinhole_ref = pinhole_ref.repeat(batch_size, 1, device=device, dtype=dtype)-- pinhole_i = utils.create_pinhole(- fx,- fy,- cx,- cy,- image_height,- image_width,- rx,- ry,- rx,- tx + offset_x,- ty,- tz)- pinhole_i = pinhole_i.repeat(batch_size, 1, device=device, dtype=dtype)-- # compute homography from ref to i- i_H_ref = kornia.homography_i_H_ref(pinhole_i, pinhole_ref) + eps- i_H_ref_inv = torch.inverse(i_H_ref)-- # compute homography from i to ref- ref_H_i = kornia.homography_i_H_ref(pinhole_ref, pinhole_i) + eps- assert_close(i_H_ref_inv, ref_H_i)-- # evaluate function gradient- assert gradcheck(kornia.homography_i_H_ref,- (utils.tensor_to_gradcheck_var(pinhole_ref) + eps,- utils.tensor_to_gradcheck_var(pinhole_i) + eps,),- raise_exception=True)'''diff --git a/test/geometry/test_stereo.py b/test/geometry/camera/test_stereo.pysimilarity index 99%rename from test/geometry/test_stereo.pyrename to test/geometry/camera/test_stereo.pyindex 702c8fc8b..38a7e8345 100644--- a/test/geometry/test_stereo.py+++ b/test/geometry/camera/test_stereo.py@@ -4,7 +4,7 @@ import pytestimport torchfrom torch.testing import assert_allclose-from kornia.geometry.camera.stereo import StereoCamera+from kornia.geometry.camera import StereoCamera@pytest.fixture(params=[1, 2, 4])diff --git a/test/geometry/epipolar/test_essential.py b/test/geometry/epipolar/test_essential.pyindex 61a0651e8..59a52b4c2 100644--- a/test/geometry/epipolar/test_essential.py+++ b/test/geometry/epipolar/test_essential.py@@ -3,6 +3,7 @@ import test_common as utilsimport torchfrom torch.autograd import gradcheck+import korniaimport kornia.geometry.epipolar as epifrom kornia.testing import assert_close@@ -89,8 +90,8 @@ class TestRelativeCameraMotion:t1 = torch.tensor([[[10.0], [0.0], [0.0]]]).type_as(R1)- R2 = epi.eye_like(3, R1)- t2 = epi.vec_like(3, t1)+ R2 = kornia.eye_like(3, R1)+ t2 = kornia.vec_like(3, t1)R_expected = R1.clone()t_expected = -t1@@ -104,8 +105,8 @@ class TestRelativeCameraMotion:R2 = torch.tensor([[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)- t1 = epi.vec_like(3, R1)- t2 = epi.vec_like(3, R2)+ t1 = kornia.vec_like(3, R1)+ t2 = kornia.vec_like(3, R2)R_expected = R2.clone()t_expected = t1diff --git a/test/geometry/epipolar/test_numeric.py b/test/geometry/epipolar/test_numeric.pyindex 678849f93..ed02d8dc6 100644--- a/test/geometry/epipolar/test_numeric.py+++ b/test/geometry/epipolar/test_numeric.py@@ -2,6 +2,7 @@ import pytestimport torchfrom torch.autograd import gradcheck+import korniaimport kornia.geometry.epipolar as epifrom kornia.testing import assert_close@@ -34,7 +35,7 @@ class TestSkewSymmetric:class TestEyeLike:def test_smoke(self, device, dtype):image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)- identity = epi.eye_like(3, image)+ identity = kornia.eye_like(3, image)assert identity.shape == (1, 3, 3)assert identity.device == image.deviceassert identity.dtype == image.dtype@@ -43,7 +44,7 @@ class TestEyeLike:def test_shape(self, batch_size, eye_size, device, dtype):B, N = batch_size, eye_sizeimage = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)- identity = epi.eye_like(N, image)+ identity = kornia.eye_like(N, image)assert identity.shape == (B, N, N)assert identity.device == image.deviceassert identity.dtype == image.dtype@@ -52,7 +53,7 @@ class TestEyeLike:class TestVecLike:def test_smoke(self, device, dtype):image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)- vec = epi.vec_like(3, image)+ vec = kornia.vec_like(3, image)assert vec.shape == (1, 3, 1)assert vec.device == image.deviceassert vec.dtype == image.dtype@@ -61,7 +62,7 @@ class TestVecLike:def test_shape(self, batch_size, eye_size, device, dtype):B, N = batch_size, eye_sizeimage = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)- vec = epi.vec_like(N, image)+ vec = kornia.vec_like(N, image)assert vec.shape == (B, N, 1)assert vec.device == image.deviceassert vec.dtype == image.dtypediff --git a/test/geometry/epipolar/test_triangulation.py b/test/geometry/epipolar/test_triangulation.pyindex 1ae568051..ddba50196 100644--- a/test/geometry/epipolar/test_triangulation.py+++ b/test/geometry/epipolar/test_triangulation.py@@ -40,7 +40,7 @@ class TestTriangulation:x2 = scene['points2d'][1:2]X = epi.triangulate_points(P1, P2, x1, x2)- x_reprojected = kornia.transform_points(scene['P'], X.expand(num_views, -1, -1))+ x_reprojected = kornia.geometry.transform_points(scene['P'], X.expand(num_views, -1, -1))assert_close(scene['points3d'], X, rtol=1e-4, atol=1e-4)assert_close(scene['points2d'], x_reprojected, rtol=1e-4, atol=1e-4)@@ -48,8 +48,8 @@ class TestTriangulation:def test_gradcheck(self, device):points1 = torch.rand(1, 8, 2, device=device, dtype=torch.float64, requires_grad=True)points2 = torch.rand(1, 8, 2, device=device, dtype=torch.float64)- P1 = epi.eye_like(3, points1)+ P1 = kornia.eye_like(3, points1)P1 = torch.nn.functional.pad(P1, [0, 1])- P2 = epi.eye_like(3, points2)+ P2 = kornia.eye_like(3, points2)P2 = torch.nn.functional.pad(P2, [0, 1])assert gradcheck(epi.triangulate_points, (P1, P2, points1, points2), raise_exception=True)diff --git a/test/geometry/subpix/test_dsnt.py b/test/geometry/subpix/test_dsnt.pyindex fb459511b..c57068241 100644--- a/test/geometry/subpix/test_dsnt.py+++ b/test/geometry/subpix/test_dsnt.py@@ -23,27 +23,27 @@ class TestRenderGaussian2d:def test_pixel_coordinates(self, gaussian, device, dtype):mean = torch.tensor([2.0, 2.0], dtype=dtype, device=device)std = torch.tensor([1.0, 1.0], dtype=dtype, device=device)- actual = kornia.geometry.dsnt.render_gaussian2d(mean, std, (5, 5), False)+ actual = kornia.geometry.subpix.render_gaussian2d(mean, std, (5, 5), False)assert_close(actual, gaussian, rtol=0, atol=1e-4)def test_normalized_coordinates(self, gaussian, device, dtype):mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)std = torch.tensor([0.25, 0.25], dtype=dtype, device=device)- actual = kornia.geometry.dsnt.render_gaussian2d(mean, std, (5, 5), True)+ actual = kornia.geometry.subpix.render_gaussian2d(mean, std, (5, 5), True)assert_close(actual, gaussian, rtol=0, atol=1e-4)def test_jit(self, device, dtype):mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)std = torch.tensor([0.25, 0.25], dtype=dtype, device=device)args = (mean, std, (5, 5), True)- op = kornia.geometry.dsnt.render_gaussian2d- op_jit = kornia.jit.render_gaussian2d+ op = kornia.geometry.subpix.render_gaussian2d+ op_jit = torch.jit.script(op)assert_close(op(*args), op_jit(*args), rtol=0, atol=1e-5)@pytest.mark.skip(reason="it works but raises some warnings.")def test_jit_trace(self, device, dtype):def op(mean, std):- return kornia.geometry.dsnt.render_gaussian2d(mean, std, (5, 5), True)+ return kornia.geometry.subpix.render_gaussian2d(mean, std, (5, 5), True)mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)std = torch.tensor([0.25, 0.25], dtype=dtype, device=device)@@ -58,19 +58,19 @@ class TestSpatialSoftmax2d:return request.param.to(device, dtype)def test_forward(self, input):- actual = kornia.geometry.dsnt.spatial_softmax2d(input)+ actual = kornia.geometry.subpix.spatial_softmax2d(input)assert actual.lt(0).sum().item() == 0, 'expected no negative values'sums = actual.sum(-1).sum(-1)assert_close(sums, torch.ones_like(sums))def test_jit(self, input):- op = kornia.geometry.dsnt.spatial_softmax2d- op_jit = kornia.jit.spatial_softmax2d+ op = kornia.geometry.subpix.spatial_softmax2d+ op_jit = torch.jit.script(op)assert_close(op(input), op_jit(input), rtol=0, atol=1e-5)@pytest.mark.skip(reason="it works but raises some warnings.")def test_jit_trace(self, input):- op = kornia.geometry.dsnt.spatial_softmax2d+ op = kornia.geometry.subpix.spatial_softmax2dop_jit = torch.jit.trace(op, (input,))assert_close(op(input), op_jit(input), rtol=0, atol=1e-5)@@ -91,20 +91,20 @@ class TestSpatialExpectation2d:def test_forward(self, example):input, expected_norm, expected_px = example- actual_norm = kornia.geometry.dsnt.spatial_expectation2d(input, True)+ actual_norm = kornia.geometry.subpix.spatial_expectation2d(input, True)assert_close(actual_norm, expected_norm)- actual_px = kornia.geometry.dsnt.spatial_expectation2d(input, False)+ actual_px = kornia.geometry.subpix.spatial_expectation2d(input, False)assert_close(actual_px, expected_px)def test_jit(self, example):input = example[0]- op = kornia.geometry.dsnt.spatial_expectation2d- op_jit = kornia.jit.spatial_expectation2d+ op = kornia.geometry.subpix.spatial_expectation2d+ op_jit = torch.jit.script(op)assert_close(op(input), op_jit(input), rtol=0, atol=1e-5)@pytest.mark.skip(reason="it works but raises some warnings.")def test_jit_trace(self, example):input = example[0]- op = kornia.geometry.dsnt.spatial_expectation2d+ op = kornia.geometry.subpix.spatial_expectation2dop_jit = torch.jit.trace(op, (input,))assert_close(op(input), op_jit(input), rtol=0, atol=1e-5)diff --git a/test/feature/test_nms.py b/test/geometry/subpix/test_nms.pysimilarity index 86%rename from test/feature/test_nms.pyrename to test/geometry/subpix/test_nms.pyindex ae331739d..12cf90baa 100644--- a/test/feature/test_nms.py+++ b/test/geometry/subpix/test_nms.py@@ -9,12 +9,12 @@ from kornia.testing import assert_closeclass TestNMS2d:def test_shape(self, device):inp = torch.ones(1, 3, 4, 4, device=device)- nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((3, 3)).to(device)assert nms(inp).shape == inp.shapedef test_shape_batch(self, device):inp = torch.ones(4, 3, 4, 4, device=device)- nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((3, 3)).to(device)assert nms(inp).shape == inp.shapedef test_nms(self, device):@@ -45,7 +45,7 @@ class TestNMS2d:],device=device,).float()- nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((3, 3)).to(device)scores = nms(inp)assert_close(scores, expected, atol=1e-4, rtol=1e-3)@@ -53,18 +53,18 @@ class TestNMS2d:batch_size, channels, height, width = 1, 2, 5, 4img = torch.rand(batch_size, channels, height, width, device=device)img = utils.tensor_to_gradcheck_var(img) # to var- assert gradcheck(kornia.feature.nms2d, (img, (3, 3)), raise_exception=True, nondet_tol=1e-4)+ assert gradcheck(kornia.geometry.subpix.nms2d, (img, (3, 3)), raise_exception=True, nondet_tol=1e-4)class TestNMS3d:def test_shape(self, device):inp = torch.ones(1, 1, 3, 4, 4, device=device)- nms = kornia.feature.NonMaximaSuppression3d((3, 3, 3)).to(device)+ nms = kornia.geometry.subpix.NonMaximaSuppression3d((3, 3, 3)).to(device)assert nms(inp).shape == inp.shapedef test_shape_batch(self, device):inp = torch.ones(4, 1, 3, 4, 4, device=device)- nms = kornia.feature.NonMaximaSuppression3d((3, 3, 3)).to(device)+ nms = kornia.geometry.subpix.NonMaximaSuppression3d((3, 3, 3)).to(device)assert nms(inp).shape == inp.shapedef test_nms(self, device):@@ -127,7 +127,7 @@ class TestNMS3d:]]).to(device)- nms = kornia.feature.NonMaximaSuppression3d((3, 3, 3)).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)@@ -135,4 +135,4 @@ class TestNMS3d:batch_size, channels, depth, height, width = 1, 1, 4, 5, 4img = torch.rand(batch_size, channels, depth, height, width, device=device)img = utils.tensor_to_gradcheck_var(img) # to var- assert gradcheck(kornia.feature.nms3d, (img, (3, 3, 3)), raise_exception=True, nondet_tol=1e-4)+ assert gradcheck(kornia.geometry.subpix.nms3d, (img, (3, 3, 3)), raise_exception=True, nondet_tol=1e-4)diff --git a/test/geometry/subpix/test_spatial_softargmax.py b/test/geometry/subpix/test_spatial_softargmax.pyindex 3772d9ef2..6948fb482 100644--- a/test/geometry/subpix/test_spatial_softargmax.py+++ b/test/geometry/subpix/test_spatial_softargmax.py@@ -65,19 +65,19 @@ class TestCenterKernel3d:class TestSpatialSoftArgmax2d:def test_smoke(self, device, dtype):input = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)- m = kornia.SpatialSoftArgmax2d()+ m = kornia.geometry.subpix.SpatialSoftArgmax2d()assert m(input).shape == (1, 1, 2)def test_smoke_batch(self, device, dtype):input = torch.zeros(2, 1, 2, 3, device=device, dtype=dtype)- m = kornia.SpatialSoftArgmax2d()+ m = kornia.geometry.subpix.SpatialSoftArgmax2d()assert m(input).shape == (2, 1, 2)def test_top_left_normalized(self, device, dtype):input = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)input[..., 0, 0] = 1e16- coord = kornia.spatial_soft_argmax2d(input, normalized_coordinates=True)+ coord = kornia.geometry.subpix.spatial_soft_argmax2d(input, 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)@@ -85,7 +85,7 @@ class TestSpatialSoftArgmax2d:input = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)input[..., 0, 0] = 1e16- coord = kornia.spatial_soft_argmax2d(input, normalized_coordinates=False)+ coord = kornia.geometry.subpix.spatial_soft_argmax2d(input, 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)@@ -93,7 +93,7 @@ class TestSpatialSoftArgmax2d:input = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)input[..., -1, -1] = 1e16- coord = kornia.spatial_soft_argmax2d(input, normalized_coordinates=True)+ coord = kornia.geometry.subpix.spatial_soft_argmax2d(input, 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)@@ -101,7 +101,7 @@ class TestSpatialSoftArgmax2d:input = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)input[..., -1, -1] = 1e16- coord = kornia.spatial_soft_argmax2d(input, normalized_coordinates=False)+ coord = kornia.geometry.subpix.spatial_soft_argmax2d(input, 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)@@ -112,7 +112,7 @@ class TestSpatialSoftArgmax2d:input[1, 0, -1, 0] = 1e16 # bottom-leftinput[1, 1, -1, -1] = 1e16 # bottom-right- coord = kornia.spatial_soft_argmax2d(input)+ coord = kornia.geometry.subpix.spatial_soft_argmax2d(input)assert_close(coord[0, 0, 0].item(), -1.0, atol=1e-4, rtol=1e-4) # top-leftassert_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@@ -125,17 +125,17 @@ class TestSpatialSoftArgmax2d:def test_gradcheck(self, device, dtype):input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.spatial_soft_argmax2d, (input), raise_exception=True)+ assert gradcheck(kornia.geometry.subpix.spatial_soft_argmax2d, (input), raise_exception=True)def test_end_to_end(self, device, dtype):input = torch.full((1, 2, 7, 7), 1.0, requires_grad=True, device=device, dtype=dtype)target = torch.as_tensor([[[0.0, 0.0], [1.0, 1.0]]], device=device, dtype=dtype)std = torch.tensor([1.0, 1.0], device=device, dtype=dtype)- hm = kornia.geometry.dsnt.spatial_softmax2d(input)+ hm = kornia.geometry.subpix.spatial_softmax2d(input)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.dsnt.spatial_expectation2d(hm)+ pred = kornia.geometry.subpix.spatial_expectation2d(hm)assert_close(pred, torch.as_tensor([[[0.0, 0.0], [0.0, 0.0]]], device=device, dtype=dtype), atol=1e-4, rtol=1e-4)@@ -144,7 +144,7 @@ class TestSpatialSoftArgmax2d:expected_loss1 = torch.as_tensor([[0.0, 1.0]], device=device, dtype=dtype)assert_close(loss1, expected_loss1, atol=1e-4, rtol=1e-4)- target_hm = kornia.geometry.dsnt.render_gaussian2d(target, std, input.shape[-2:]).contiguous()+ target_hm = kornia.geometry.subpix.render_gaussian2d(target, std, input.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)@@ -155,14 +155,14 @@ class TestSpatialSoftArgmax2d:def test_jit(self, device, dtype):input = torch.rand((2, 3, 7, 7), dtype=dtype, device=device)- op = kornia.spatial_soft_argmax2d- op_jit = kornia.jit.spatial_soft_argmax2d+ op = kornia.geometry.subpix.spatial_soft_argmax2d+ op_jit = torch.jit.script(op)assert_close(op(input), op_jit(input), rtol=0, atol=1e-5)@pytest.mark.skip(reason="it works but raises some warnings.")def test_jit_trace(self, device, dtype):input = torch.rand((2, 3, 7, 7), dtype=dtype, device=device)- op = kornia.spatial_soft_argmax2d+ op = kornia.geometry.subpix.spatial_soft_argmax2dop_jit = torch.jit.trace(op, (input,))assert_close(op(input), op_jit(input), rtol=0, atol=1e-5)@@ -170,24 +170,24 @@ class TestSpatialSoftArgmax2d:class TestConvSoftArgmax2d:def test_smoke(self, device, dtype):input = torch.zeros(1, 1, 3, 3, device=device, dtype=dtype)- m = kornia.ConvSoftArgmax2d((3, 3))+ m = kornia.geometry.subpix.ConvSoftArgmax2d((3, 3))assert m(input).shape == (1, 1, 2, 3, 3)def test_smoke_batch(self, device, dtype):input = torch.zeros(2, 5, 3, 3, device=device, dtype=dtype)- m = kornia.ConvSoftArgmax2d()+ m = kornia.geometry.subpix.ConvSoftArgmax2d()assert m(input).shape == (2, 5, 2, 3, 3)def test_smoke_with_val(self, device, dtype):input = torch.zeros(1, 1, 3, 3, device=device, dtype=dtype)- m = kornia.ConvSoftArgmax2d((3, 3), output_value=True)+ m = kornia.geometry.subpix.ConvSoftArgmax2d((3, 3), output_value=True)coords, val = m(input)assert coords.shape == (1, 1, 2, 3, 3)assert val.shape == (1, 1, 3, 3)def test_smoke_batch_with_val(self, device, dtype):input = torch.zeros(2, 5, 3, 3, device=device, dtype=dtype)- m = kornia.ConvSoftArgmax2d((3, 3), output_value=True)+ m = kornia.geometry.subpix.ConvSoftArgmax2d((3, 3), output_value=True)coords, val = m(input)assert coords.shape == (2, 5, 2, 3, 3)assert val.shape == (2, 5, 3, 3)@@ -195,7 +195,7 @@ class TestConvSoftArgmax2d:def test_gradcheck(self, device, dtype):input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.conv_soft_argmax2d, (input), raise_exception=True)+ assert gradcheck(kornia.geometry.subpix.conv_soft_argmax2d, (input), raise_exception=True)def test_cold_diag(self, device, dtype):input = torch.tensor(@@ -213,7 +213,7 @@ class TestConvSoftArgmax2d:device=device,dtype=dtype,)- softargmax = kornia.ConvSoftArgmax2d(+ softargmax = kornia.geometry.subpix.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0), temperature=0.05, normalized_coordinates=False, output_value=True)expected_val = torch.tensor([[[[1.0, 0.0], [0.0, 1.0]]]], device=device, dtype=dtype)@@ -240,7 +240,7 @@ class TestConvSoftArgmax2d:device=device,dtype=dtype,)- softargmax = kornia.ConvSoftArgmax2d(+ softargmax = kornia.geometry.subpix.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0), temperature=10.0, normalized_coordinates=False, output_value=True)expected_val = torch.tensor([[[[0.1214, 0.0], [0.0, 0.1214]]]], device=device, dtype=dtype)@@ -267,7 +267,7 @@ class TestConvSoftArgmax2d:device=device,dtype=dtype,)- softargmax = kornia.ConvSoftArgmax2d(+ softargmax = kornia.geometry.subpix.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0), temperature=0.05, normalized_coordinates=True, output_value=True)expected_val = torch.tensor([[[[1.0, 0.0], [0.0, 1.0]]]], device=device, dtype=dtype)@@ -294,7 +294,7 @@ class TestConvSoftArgmax2d:device=device,dtype=dtype,)- softargmax = kornia.ConvSoftArgmax2d(+ softargmax = kornia.geometry.subpix.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0), temperature=10.0, normalized_coordinates=True, output_value=True)expected_val = torch.tensor([[[[0.1214, 0.0], [0.0, 0.1214]]]], device=device, dtype=dtype)@@ -309,12 +309,12 @@ class TestConvSoftArgmax2d:class TestConvSoftArgmax3d:def test_smoke(self, device, dtype):input = torch.zeros(1, 1, 3, 3, 3, device=device, dtype=dtype)- m = kornia.ConvSoftArgmax3d((3, 3, 3), output_value=False)+ m = kornia.geometry.subpix.ConvSoftArgmax3d((3, 3, 3), output_value=False)assert m(input).shape == (1, 1, 3, 3, 3, 3)def test_smoke_with_val(self, device, dtype):input = torch.zeros(1, 1, 3, 3, 3, device=device, dtype=dtype)- m = kornia.ConvSoftArgmax3d((3, 3, 3), output_value=True)+ m = kornia.geometry.subpix.ConvSoftArgmax3d((3, 3, 3), output_value=True)coords, val = m(input)assert coords.shape == (1, 1, 3, 3, 3, 3)assert val.shape == (1, 1, 3, 3, 3)@@ -322,7 +322,7 @@ class TestConvSoftArgmax3d:def test_gradcheck(self, device, dtype):input = torch.rand(1, 2, 3, 5, 5, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.conv_soft_argmax3d, (input), raise_exception=True)+ assert gradcheck(kornia.geometry.subpix.conv_soft_argmax3d, (input), raise_exception=True)def test_cold_diag(self, device, dtype):input = torch.tensor(@@ -342,7 +342,7 @@ class TestConvSoftArgmax3d:device=device,dtype=dtype,)- softargmax = kornia.ConvSoftArgmax3d(+ softargmax = kornia.geometry.subpix.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=0.05, normalized_coordinates=False, output_value=True)expected_val = torch.tensor([[[[[1.0, 0.0], [0.0, 1.0]]]]], device=device, dtype=dtype)@@ -373,7 +373,7 @@ class TestConvSoftArgmax3d:device=device,dtype=dtype,)- softargmax = kornia.ConvSoftArgmax3d(+ softargmax = kornia.geometry.subpix.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=10.0, normalized_coordinates=False, output_value=True)expected_val = torch.tensor([[[[[0.1214, 0.0], [0.0, 0.1214]]]]], device=device, dtype=dtype)@@ -404,7 +404,7 @@ class TestConvSoftArgmax3d:device=device,dtype=dtype,)- softargmax = kornia.ConvSoftArgmax3d(+ softargmax = kornia.geometry.subpix.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=0.05, normalized_coordinates=True, output_value=True)expected_val = torch.tensor([[[[[1.0, 0.0], [0.0, 1.0]]]]], device=device, dtype=dtype)@@ -435,7 +435,7 @@ class TestConvSoftArgmax3d:device=device,dtype=dtype,)- softargmax = kornia.ConvSoftArgmax3d(+ softargmax = kornia.geometry.subpix.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=10.0, normalized_coordinates=True, output_value=True)expected_val = torch.tensor([[[[[0.1214, 0.0], [0.0, 0.1214]]]]], device=device, dtype=dtype)@@ -450,8 +450,10 @@ class TestConvSoftArgmax3d:class TestConvQuadInterp3d:- @pytest.mark.skipif((int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 9),- reason='<1.9.0 not supporting')+ @pytest.mark.skipif(+ (int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 9),+ reason='<1.9.0 not supporting',+ )def test_smoke(self, device, dtype):input = torch.randn(2, 3, 3, 4, 4, device=device, dtype=dtype)nms = kornia.geometry.ConvQuadInterp3d(1)@@ -459,8 +461,10 @@ class TestConvQuadInterp3d:assert coord.shape == (2, 3, 3, 3, 4, 4)assert val.shape == (2, 3, 3, 4, 4)- @pytest.mark.skipif((int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 9),- reason='<1.9.0 not supporting')+ @pytest.mark.skipif(+ (int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 9),+ reason='<1.9.0 not supporting',+ )def test_gradcheck(self, device, dtype):input = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)input[0, 0, 1, 2, 2] += 20.0@@ -499,7 +503,7 @@ class TestConvQuadInterp3d:device=device,dtype=dtype,)- input = kornia.gaussian_blur2d(input, (5, 5), (0.5, 0.5)).unsqueeze(0)+ input = kornia.filters.gaussian_blur2d(input, (5, 5), (0.5, 0.5)).unsqueeze(0)softargmax = kornia.geometry.ConvQuadInterp3d(10)expected_val = torch.tensor([diff --git a/test/geometry/test_bbox.py b/test/geometry/test_bbox.pyindex 411897f13..c0e0319ea 100644--- a/test/geometry/test_bbox.py+++ b/test/geometry/test_bbox.py@@ -1,4 +1,3 @@-import pytestimport torchfrom torch.autograd import gradcheckfrom torch.testing import assert_allclosediff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.pyindex d1f3a9ee9..27913c7b3 100644--- a/test/geometry/test_conversions.py+++ b/test/geometry/test_conversions.py@@ -34,38 +34,44 @@ class TestAngleAxisToQuaternion:def test_smoke_xyzw(self, device, dtype):angle_axis = torch.zeros(3, dtype=dtype, device=device)with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert quaternion.shape == (4,)def test_smoke(self, device, dtype):angle_axis = torch.zeros(3, dtype=dtype, device=device)- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert quaternion.shape == (4,)@pytest.mark.parametrize("batch_size", (1, 3, 8))def test_smoke_batch_xyzw(self, batch_size, device, dtype):angle_axis = torch.zeros(batch_size, 3, device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert quaternion.shape == (batch_size, 4)@pytest.mark.parametrize("batch_size", (1, 3, 8))def test_smoke_batch(self, batch_size, device, dtype):angle_axis = torch.zeros(batch_size, 3, device=device, dtype=dtype)- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert quaternion.shape == (batch_size, 4)def test_zero_angle_xyzw(self, device, dtype, atol, rtol):angle_axis = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_zero_angle(self, device, dtype, atol, rtol):angle_axis = 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.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_small_angle_x_xyzw(self, device, dtype, atol, rtol):@@ -73,14 +79,16 @@ class TestAngleAxisToQuaternion:angle_axis = torch.tensor((theta, 0.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((np.sin(theta / 2.0), 0.0, 0.0, np.cos(theta / 2.0)), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_small_angle_x(self, device, dtype, atol, rtol):theta = 1.0e-2angle_axis = 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.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_small_angle_y_xyzw(self, device, dtype, atol, rtol):@@ -88,14 +96,16 @@ class TestAngleAxisToQuaternion:angle_axis = torch.tensor((0.0, theta, 0.0), device=device, dtype=dtype)expected = torch.tensor((0.0, np.sin(theta / 2.0), 0.0, np.cos(theta / 2.0)), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_small_angle_y(self, device, dtype, atol, rtol):theta = 1.0e-2angle_axis = 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.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_small_angle_z_xyzw(self, device, dtype, atol, rtol):@@ -103,14 +113,16 @@ class TestAngleAxisToQuaternion:angle_axis = torch.tensor((0.0, 0.0, theta), device=device, dtype=dtype)expected = torch.tensor((0.0, 0.0, np.sin(theta / 2.0), np.cos(theta / 2.0)), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_small_angle_z(self, device, dtype, atol, rtol):theta = 1.0e-2angle_axis = 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.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_x_rotation_xyzw(self, device, dtype, atol, rtol):@@ -118,14 +130,16 @@ class TestAngleAxisToQuaternion:angle_axis = torch.tensor((kornia.pi / 2.0, 0.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((half_sqrt2, 0.0, 0.0, half_sqrt2), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )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)angle_axis = 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.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_y_rotation_xyzw(self, device, dtype, atol, rtol):@@ -133,14 +147,16 @@ class TestAngleAxisToQuaternion:angle_axis = torch.tensor((0.0, kornia.pi / 2.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((0.0, half_sqrt2, 0.0, half_sqrt2), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )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)angle_axis = 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.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_z_rotation_xyzw(self, device, dtype, atol, rtol):@@ -148,14 +164,16 @@ class TestAngleAxisToQuaternion:angle_axis = torch.tensor((0.0, 0.0, kornia.pi / 2.0), device=device, dtype=dtype)expected = torch.tensor((0.0, 0.0, half_sqrt2, half_sqrt2), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )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)angle_axis = 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.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_gradcheck_xyzw(self, device, dtype):@@ -165,7 +183,7 @@ class TestAngleAxisToQuaternion:# evaluate function gradientwith pytest.warns(UserWarning):assert gradcheck(- partial(kornia.angle_axis_to_quaternion, order=QuaternionCoeffOrder.XYZW),+ partial(kornia.geometry.conversions.angle_axis_to_quaternion, order=QuaternionCoeffOrder.XYZW),(angle_axis,),raise_exception=True,)@@ -176,7 +194,7 @@ class TestAngleAxisToQuaternion:angle_axis = tensor_to_gradcheck_var(angle_axis)# evaluate function gradientassert gradcheck(- partial(kornia.angle_axis_to_quaternion, order=QuaternionCoeffOrder.WXYZ),+ partial(kornia.geometry.conversions.angle_axis_to_quaternion, order=QuaternionCoeffOrder.WXYZ),(angle_axis,),raise_exception=True,)@@ -186,77 +204,89 @@ class TestQuaternionToAngleAxis:def test_smoke_xyzw(self, device, dtype):quaternion = torch.zeros(4, device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert angle_axis.shape == (3,)def test_smoke(self, device, dtype):quaternion = torch.zeros(4, device=device, dtype=dtype)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert angle_axis.shape == (3,)@pytest.mark.parametrize("batch_size", (1, 3, 8))def test_smoke_batch_xyzw(self, batch_size, device, dtype):quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert angle_axis.shape == (batch_size, 3)@pytest.mark.parametrize("batch_size", (1, 3, 8))def test_smoke_batch(self, batch_size, device, dtype):quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert angle_axis.shape == (batch_size, 3)def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)expected = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_unit_quaternion(self, device, dtype, atol, rtol):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)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_x_rotation_xyzw(self, device, dtype, atol, rtol):quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((kornia.pi, 0.0, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(angle_axis, 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)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_y_rotation_xyzw(self, device, dtype, atol, rtol):quaternion = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((0.0, kornia.pi, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(angle_axis, 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)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_z_rotation_xyzw(self, device, dtype, atol, rtol):quaternion = torch.tensor((0.0, 0.0, 0.5, np.sqrt(3.0) / 2.0), device=device, dtype=dtype)expected = torch.tensor((0.0, 0.0, kornia.pi / 3.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(angle_axis, 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)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_small_angle_x_xyzw(self, device, dtype, atol, rtol):@@ -264,14 +294,16 @@ class TestQuaternionToAngleAxis:quaternion = torch.tensor((np.sin(theta / 2.0), 0.0, 0.0, np.cos(theta / 2.0)), device=device, dtype=dtype)expected = torch.tensor((theta, 0.0, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_small_angle_x(self, device, dtype, atol, rtol):theta = 1.0e-2quaternion = 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)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_small_angle_y_xyzw(self, device, dtype, atol, rtol):@@ -279,14 +311,16 @@ class TestQuaternionToAngleAxis:quaternion = torch.tensor((0.0, np.sin(theta / 2), 0.0, np.cos(theta / 2)), device=device, dtype=dtype)expected = torch.tensor((0.0, theta, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_small_angle_y(self, device, dtype, atol, rtol):theta = 1.0e-2quaternion = 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)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_small_angle_z_xyzw(self, device, dtype, atol, rtol):@@ -294,14 +328,16 @@ class TestQuaternionToAngleAxis:quaternion = torch.tensor((0.0, 0.0, np.sin(theta / 2), np.cos(theta / 2)), device=device, dtype=dtype)expected = torch.tensor((0.0, 0.0, theta), device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_small_angle_z(self, device, dtype, atol, rtol):theta = 1.0e-2quaternion = 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)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(angle_axis, expected, atol=atol, rtol=rtol)def test_gradcheck_xyzw(self, device, dtype):@@ -311,7 +347,7 @@ class TestQuaternionToAngleAxis:# evaluate function gradientwith pytest.warns(UserWarning):assert gradcheck(- partial(kornia.quaternion_to_angle_axis, order=QuaternionCoeffOrder.XYZW),+ partial(kornia.geometry.conversions.quaternion_to_angle_axis, order=QuaternionCoeffOrder.XYZW),(quaternion,),raise_exception=True,)@@ -322,7 +358,7 @@ class TestQuaternionToAngleAxis:quaternion = tensor_to_gradcheck_var(quaternion)# evaluate function gradientassert gradcheck(- partial(kornia.quaternion_to_angle_axis, order=QuaternionCoeffOrder.WXYZ),+ partial(kornia.geometry.conversions.quaternion_to_angle_axis, order=QuaternionCoeffOrder.WXYZ),(quaternion,),raise_exception=True,)@@ -333,26 +369,30 @@ class TestRotationMatrixToQuaternion:def test_smoke_batch_xyzw(self, batch_size, device, dtype):matrix = torch.zeros(batch_size, 3, 3, device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ matrix, order=QuaternionCoeffOrder.XYZW+ )assert quaternion.shape == (batch_size, 4)@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)- quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)assert quaternion.shape == (batch_size, 4)def test_identity_xyzw(self, device, dtype, atol, rtol):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, 0.0, 1.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ matrix, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_identity(self, device, dtype, atol, rtol):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.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_rot_x_45_xyzw(self, device, dtype, atol, rtol):@@ -360,29 +400,39 @@ class TestRotationMatrixToQuaternion:pi_half2 = torch.cos(kornia.pi / 4.0).to(device=device, dtype=dtype)expected = torch.tensor((pi_half2, 0.0, 0.0, pi_half2), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ matrix, order=QuaternionCoeffOrder.XYZW+ )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.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)assert_close(quaternion, expected, atol=atol, rtol=rtol)def test_back_and_forth_xyzw(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsmatrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.0)), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps, order=QuaternionCoeffOrder.XYZW)- matrix_hat = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ matrix, eps=eps, order=QuaternionCoeffOrder.XYZW+ )+ matrix_hat = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(matrix, matrix_hat, atol=atol, rtol=rtol)def test_back_and_forth(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsmatrix = 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.rotation_matrix_to_quaternion(matrix, eps=eps, order=QuaternionCoeffOrder.WXYZ)- matrix_hat = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ matrix, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )+ matrix_hat = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ quaternion, order=QuaternionCoeffOrder.WXYZ+ )assert_close(matrix, matrix_hat, atol=atol, rtol=rtol)def test_corner_case_xyzw(self, device, dtype, atol, rtol):@@ -400,7 +450,9 @@ class TestRotationMatrixToQuaternion:(0.280136495828629, -0.440902262926102, 0.834015488624573, 0.177614107728004), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ matrix, eps=eps, order=QuaternionCoeffOrder.XYZW+ )torch.set_printoptions(precision=10)assert_close(quaternion_true, quaternion, atol=atol, rtol=rtol)@@ -418,7 +470,9 @@ class TestRotationMatrixToQuaternion:quaternion_true = torch.tensor((0.177614107728004, 0.280136495828629, -0.440902262926102, 0.834015488624573), device=device, dtype=dtype)- quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ matrix, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )torch.set_printoptions(precision=10)assert_close(quaternion_true, quaternion, atol=atol, rtol=rtol)@@ -429,7 +483,9 @@ class TestRotationMatrixToQuaternion:# evaluate function gradientwith pytest.warns(UserWarning):assert gradcheck(- partial(kornia.rotation_matrix_to_quaternion, eps=eps, order=QuaternionCoeffOrder.XYZW),+ partial(+ kornia.geometry.conversions.rotation_matrix_to_quaternion, eps=eps, order=QuaternionCoeffOrder.XYZW+ ),(matrix,),raise_exception=True,)@@ -440,14 +496,16 @@ class TestRotationMatrixToQuaternion:matrix = tensor_to_gradcheck_var(matrix)# evaluate function gradientassert gradcheck(- partial(kornia.rotation_matrix_to_quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ),+ partial(+ kornia.geometry.conversions.rotation_matrix_to_quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ+ ),(matrix,),raise_exception=True,)@pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')def test_jit_xyzw(self, device, dtype):- op = kornia.quaternion_log_to_exp+ op = kornia.geometry.conversions.quaternion_log_to_expop_script = torch.jit.script(op)quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)with pytest.warns(UserWarning):@@ -459,7 +517,7 @@ class TestRotationMatrixToQuaternion:@pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')def test_jit(self, device, dtype):eps = torch.finfo(dtype).eps- op = kornia.quaternion_log_to_exp+ op = kornia.geometry.conversions.quaternion_log_to_expop_script = torch.jit.script(op)quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)actual = op_script(quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ)@@ -472,39 +530,45 @@ class TestQuaternionToRotationMatrix:def test_smoke_batch_xyzw(self, batch_size, device, dtype):quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)with pytest.warns(UserWarning):- matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert matrix.shape == (batch_size, 3, 3)@pytest.mark.parametrize("batch_size", (1, 3, 8))def test_smoke_batch(self, batch_size, device, dtype):quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)- matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)assert matrix.shape == (batch_size, 3, 3)def test_unit_quaternion_xyzw(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)with pytest.warns(UserWarning):- matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(matrix, expected, atol=atol, rtol=rtol)def test_unit_quaternion(self, device, dtype, atol, rtol):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.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(matrix, expected, atol=atol, rtol=rtol)def test_x_rotation_xyzw(self, device, dtype, atol, rtol):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)with pytest.warns(UserWarning):- matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )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.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(matrix, expected, atol=atol, rtol=rtol)def test_y_rotation_xyzw(self, device, dtype, atol, rtol):@@ -512,26 +576,30 @@ class TestQuaternionToRotationMatrix: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)with pytest.warns(UserWarning):- matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )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.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(matrix, expected, atol=atol, rtol=rtol)def test_z_rotation_xyzw(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)with pytest.warns(UserWarning):- matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )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.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)+ matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)assert_close(matrix, expected, atol=atol, rtol=rtol)def test_gradcheck_xyzw(self, device, dtype):@@ -540,7 +608,7 @@ class TestQuaternionToRotationMatrix:# evaluate function gradientwith pytest.warns(UserWarning):assert gradcheck(- partial(kornia.quaternion_to_rotation_matrix, order=QuaternionCoeffOrder.XYZW),+ partial(kornia.geometry.conversions.quaternion_to_rotation_matrix, order=QuaternionCoeffOrder.XYZW),(quaternion,),raise_exception=True,)@@ -550,7 +618,7 @@ class TestQuaternionToRotationMatrix:quaternion = tensor_to_gradcheck_var(quaternion)# evaluate function gradientassert gradcheck(- partial(kornia.quaternion_to_rotation_matrix, order=QuaternionCoeffOrder.WXYZ),+ partial(kornia.geometry.conversions.quaternion_to_rotation_matrix, order=QuaternionCoeffOrder.WXYZ),(quaternion,),raise_exception=True,)@@ -578,13 +646,17 @@ class TestQuaternionLogToExp:def test_smoke_batch_xyzw(self, batch_size, device, dtype):quaternion_log = torch.zeros(batch_size, 3, device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, order=QuaternionCoeffOrder.XYZW)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, order=QuaternionCoeffOrder.XYZW+ )assert quaternion_exp.shape == (batch_size, 4)@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)- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, order=QuaternionCoeffOrder.WXYZ)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, order=QuaternionCoeffOrder.WXYZ+ )assert quaternion_exp.shape == (batch_size, 4)def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):@@ -592,14 +664,18 @@ class TestQuaternionLogToExp:quaternion_log = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)def test_unit_quaternion(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsquaternion_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.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)def test_pi_quaternion_x_xyzw(self, device, dtype, atol, rtol):@@ -608,7 +684,9 @@ class TestQuaternionLogToExp:quaternion_log = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((torch.sin(one), 0.0, 0.0, torch.cos(one)), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)def test_pi_quaternion_x(self, device, dtype, atol, rtol):@@ -616,7 +694,9 @@ class TestQuaternionLogToExp:one = torch.tensor(1.0, device=device, dtype=dtype)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.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)def test_pi_quaternion_y_xyzw(self, device, dtype, atol, rtol):@@ -625,7 +705,9 @@ class TestQuaternionLogToExp:quaternion_log = torch.tensor((0.0, 1.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((0.0, torch.sin(one), 0.0, torch.cos(one)), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)def test_pi_quaternion_y(self, device, dtype, atol, rtol):@@ -633,7 +715,9 @@ class TestQuaternionLogToExp:one = torch.tensor(1.0, device=device, dtype=dtype)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.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)def test_pi_quaternion_z_xyzw(self, device, dtype, atol, rtol):@@ -643,7 +727,9 @@ class TestQuaternionLogToExp:expected = torch.tensor((0.0, 0.0, torch.sin(one), torch.cos(one)), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)def test_pi_quaternion_z(self, device, dtype, atol, rtol):@@ -651,7 +737,9 @@ class TestQuaternionLogToExp:one = torch.tensor(1.0, device=device, dtype=dtype)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.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_exp, expected, atol=atol, rtol=rtol)def test_back_and_forth_xyzw(self, device, dtype, atol, rtol):@@ -659,17 +747,25 @@ class TestQuaternionLogToExp:quaternion_log = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW+ )with pytest.warns(UserWarning):- quaternion_log_hat = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_log_hat = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_log, quaternion_log_hat, atol=atol, rtol=rtol)def test_back_and_forth(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsquaternion_log = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=dtype)- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)- quaternion_log_hat = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_exp = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )+ quaternion_log_hat = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_log, quaternion_log_hat, atol=atol, rtol=rtol)def test_gradcheck_xyzw(self, device, dtype):@@ -679,7 +775,7 @@ class TestQuaternionLogToExp:# evaluate function gradientwith pytest.warns(UserWarning):assert gradcheck(- partial(kornia.quaternion_log_to_exp, eps=eps, order=QuaternionCoeffOrder.XYZW),+ partial(kornia.geometry.conversions.quaternion_log_to_exp, eps=eps, order=QuaternionCoeffOrder.XYZW),(quaternion,),raise_exception=True,)@@ -690,7 +786,7 @@ class TestQuaternionLogToExp:quaternion = tensor_to_gradcheck_var(quaternion)# evaluate function gradientassert gradcheck(- partial(kornia.quaternion_log_to_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ),+ partial(kornia.geometry.conversions.quaternion_log_to_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ),(quaternion,),raise_exception=True,)@@ -721,14 +817,18 @@ class TestQuaternionExpToLog:eps = torch.finfo(dtype).epsquaternion_exp = torch.zeros(batch_size, 4, device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert quaternion_log.shape == (batch_size, 3)@pytest.mark.parametrize("batch_size", (1, 3, 8))def test_smoke_batch(self, batch_size, device, dtype):eps = torch.finfo(dtype).epsquaternion_exp = torch.zeros(batch_size, 4, device=device, dtype=dtype)- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert quaternion_log.shape == (batch_size, 3)def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):@@ -736,14 +836,18 @@ class TestQuaternionExpToLog:quaternion_exp = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)expected = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_log, expected, atol=atol, rtol=rtol)def test_unit_quaternion(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsquaternion_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.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_log, expected, atol=atol, rtol=rtol)def test_pi_quaternion_x_xyzw(self, device, dtype, atol, rtol):@@ -751,14 +855,18 @@ class TestQuaternionExpToLog:quaternion_exp = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((kornia.pi / 2.0, 0.0, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_log, expected, atol=atol, rtol=rtol)def test_pi_quaternion_x(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsquaternion_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.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_log, expected, atol=atol, rtol=rtol)def test_pi_quaternion_y_xyzw(self, device, dtype, atol, rtol):@@ -766,14 +874,18 @@ class TestQuaternionExpToLog:quaternion_exp = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((0.0, kornia.pi / 2.0, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_log, expected, atol=atol, rtol=rtol)def test_pi_quaternion_y(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsquaternion_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.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_log, expected, atol=atol, rtol=rtol)def test_pi_quaternion_z_xyzw(self, device, dtype, atol, rtol):@@ -781,14 +893,18 @@ class TestQuaternionExpToLog:quaternion_exp = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)expected = torch.tensor((0.0, 0.0, kornia.pi / 2.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_log, expected, atol=atol, rtol=rtol)def test_pi_quaternion_z(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsquaternion_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.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_log, expected, atol=atol, rtol=rtol)def test_back_and_forth_xyzw(self, device, dtype, atol, rtol):@@ -796,16 +912,24 @@ class TestQuaternionExpToLog:quaternion_exp = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW+ )with pytest.warns(UserWarning):- quaternion_exp_hat = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion_exp_hat = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_exp, quaternion_exp_hat, atol=atol, rtol=rtol)def test_back_and_forth(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsquaternion_exp = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)- quaternion_exp_hat = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion_log = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )+ quaternion_exp_hat = kornia.geometry.conversions.quaternion_log_to_exp(+ quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_exp, quaternion_exp_hat, atol=atol, rtol=rtol)def test_gradcheck_xyzw(self, device, dtype):@@ -815,7 +939,7 @@ class TestQuaternionExpToLog:# evaluate function gradientwith pytest.warns(UserWarning):assert gradcheck(- partial(kornia.quaternion_exp_to_log, eps=eps, order=QuaternionCoeffOrder.XYZW),+ partial(kornia.geometry.conversions.quaternion_exp_to_log, eps=eps, order=QuaternionCoeffOrder.XYZW),(quaternion,),raise_exception=True,)@@ -826,7 +950,7 @@ class TestQuaternionExpToLog:quaternion = tensor_to_gradcheck_var(quaternion)# evaluate function gradientassert gradcheck(- partial(kornia.quaternion_exp_to_log, eps=eps, order=QuaternionCoeffOrder.WXYZ),+ partial(kornia.geometry.conversions.quaternion_exp_to_log, eps=eps, order=QuaternionCoeffOrder.WXYZ),(quaternion,),raise_exception=True,)@@ -841,7 +965,7 @@ class TestQuaternionExpToLog:@pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')def test_jit(self, device, dtype, atol, rtol):- op = kornia.quaternion_exp_to_log+ op = kornia.geometry.conversions.quaternion_exp_to_logop_script = torch.jit.script(op)quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)@@ -858,14 +982,14 @@ class TestAngleAxisToRotationMatrix:eye_batch = create_eye_batch(batch_size, 3, device=device, dtype=dtype)# apply transform- rotation_matrix = kornia.angle_axis_to_rotation_matrix(angle_axis)+ rotation_matrix = kornia.geometry.conversions.angle_axis_to_rotation_matrix(angle_axis)rotation_matrix_eye = torch.matmul(rotation_matrix, rotation_matrix.transpose(-2, -1))assert_close(rotation_matrix_eye, eye_batch, atol=atol, rtol=rtol)# evaluate function gradientangle_axis = tensor_to_gradcheck_var(angle_axis) # to var- assert gradcheck(kornia.angle_axis_to_rotation_matrix, (angle_axis,), raise_exception=True)+ assert gradcheck(kornia.geometry.conversions.angle_axis_to_rotation_matrix, (angle_axis,), raise_exception=True)def test_angle_axis_to_rotation_matrix(self, device, dtype, atol, rtol):rmat_1 = torch.tensor(@@ -892,7 +1016,7 @@ class TestAngleAxisToRotationMatrix:rmat = torch.stack((rmat_2, rmat_1), dim=0)rvec = torch.stack((rvec_2, rvec_1), dim=0)- assert_close(kornia.angle_axis_to_rotation_matrix(rvec), rmat, atol=atol, rtol=rtol)+ assert_close(kornia.geometry.conversions.angle_axis_to_rotation_matrix(rvec), rmat, atol=atol, rtol=rtol)class TestRotationMatrixToAngleAxis:@@ -900,8 +1024,10 @@ class TestRotationMatrixToAngleAxis:def test_rand_quaternion_gradcheck(self, batch_size, device, dtype, atol, rtol):# generate input dataquaternion = torch.rand(batch_size, 4, device=device, dtype=dtype)- quaternion = kornia.normalize_quaternion(quaternion)- rotation_matrix = kornia.quaternion_to_rotation_matrix(quaternion=quaternion, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.normalize_quaternion(quaternion + 1e-6)+ rotation_matrix = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ quaternion=quaternion, order=QuaternionCoeffOrder.WXYZ+ )eye_batch = create_eye_batch(batch_size, 3, device=device, dtype=dtype)rotation_matrix_eye = torch.matmul(rotation_matrix, rotation_matrix.transpose(-2, -1))@@ -910,7 +1036,9 @@ class TestRotationMatrixToAngleAxis:# evaluate function gradientrotation_matrix = tensor_to_gradcheck_var(rotation_matrix) # to var- assert gradcheck(kornia.rotation_matrix_to_angle_axis, (rotation_matrix,), raise_exception=True)+ assert gradcheck(+ kornia.geometry.conversions.rotation_matrix_to_angle_axis, (rotation_matrix,), raise_exception=True+ )def test_rotation_matrix_to_angle_axis(self, device, dtype, atol, rtol):rmat_1 = torch.tensor(@@ -937,27 +1065,27 @@ class TestRotationMatrixToAngleAxis:rmat = torch.stack((rmat_2, rmat_1), dim=0)rvec = torch.stack((rvec_2, rvec_1), dim=0)- assert_close(kornia.rotation_matrix_to_angle_axis(rmat), rvec, atol=atol, rtol=rtol)+ assert_close(kornia.geometry.conversions.rotation_matrix_to_angle_axis(rmat), rvec, atol=atol, rtol=rtol)def test_pi():- assert_close(kornia.pi.item(), 3.141592)+ 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(batch_shape, device, dtype):# generate input data- x_rad = kornia.pi * torch.rand(batch_shape, device=device, dtype=dtype)+ x_rad = kornia.constants.pi * torch.rand(batch_shape, device=device, dtype=dtype)# convert radians/degrees- x_deg = kornia.rad2deg(x_rad)- x_deg_to_rad = kornia.deg2rad(x_deg)+ x_deg = kornia.geometry.conversions.rad2deg(x_rad)+ x_deg_to_rad = kornia.geometry.conversions.deg2rad(x_deg)# compute errorassert_close(x_rad, x_deg_to_rad)# evaluate function gradient- assert gradcheck(kornia.rad2deg, (tensor_to_gradcheck_var(x_rad),), raise_exception=True)+ assert gradcheck(kornia.geometry.conversions.rad2deg, (tensor_to_gradcheck_var(x_rad),), raise_exception=True)@pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])@@ -966,37 +1094,39 @@ def test_deg2rad(batch_shape, device, dtype, atol, rtol):x_deg = 180.0 * torch.rand(batch_shape, device=device, dtype=dtype)# convert radians/degrees- x_rad = kornia.deg2rad(x_deg)- x_rad_to_deg = kornia.rad2deg(x_rad)+ x_rad = kornia.geometry.conversions.deg2rad(x_deg)+ x_rad_to_deg = kornia.geometry.conversions.rad2deg(x_rad)assert_close(x_deg, x_rad_to_deg, atol=atol, rtol=rtol)- assert gradcheck(kornia.deg2rad, (tensor_to_gradcheck_var(x_deg),), raise_exception=True)+ assert gradcheck(kornia.geometry.conversions.deg2rad, (tensor_to_gradcheck_var(x_deg),), raise_exception=True)class TestPolCartConversions:def test_smoke(self, device, dtype):x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)- assert kornia.pol2cart(x, x) is not None- assert kornia.cart2pol(x, x) is not None+ assert kornia.geometry.conversions.pol2cart(x, x) is not None+ assert kornia.geometry.conversions.cart2pol(x, x) is not None@pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])def test_pol2cart(self, batch_shape, device, dtype):# generate input datarho = torch.rand(batch_shape, dtype=dtype)- phi = kornia.pi * torch.rand(batch_shape, dtype=dtype)+ phi = kornia.constants.pi * torch.rand(batch_shape, dtype=dtype)rho = rho.to(device)phi = phi.to(device)# convert pol/cart- x_pol2cart, y_pol2cart = kornia.pol2cart(rho, phi)- rho_pol2cart, phi_pol2cart = kornia.cart2pol(x_pol2cart, y_pol2cart, 0)+ 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)assert gradcheck(- kornia.pol2cart, (tensor_to_gradcheck_var(rho), tensor_to_gradcheck_var(phi)), raise_exception=True+ kornia.geometry.conversions.pol2cart,+ (tensor_to_gradcheck_var(rho), tensor_to_gradcheck_var(phi)),+ raise_exception=True,)@pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])@@ -1008,14 +1138,16 @@ class TestPolCartConversions:y = y.to(device)# convert cart/pol- rho_cart2pol, phi_cart2pol = kornia.cart2pol(x, y, 0)- x_cart2pol, y_cart2pol = kornia.pol2cart(rho_cart2pol, phi_cart2pol)+ 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)assert gradcheck(- kornia.cart2pol, (tensor_to_gradcheck_var(x), tensor_to_gradcheck_var(y)), raise_exception=True+ kornia.geometry.conversions.cart2pol,+ (tensor_to_gradcheck_var(x), tensor_to_gradcheck_var(y)),+ raise_exception=True,)@@ -1041,7 +1173,7 @@ class TestConvertPointsToHomogeneous:)# to euclidean- points = kornia.convert_points_to_homogeneous(points_h)+ points = kornia.geometry.conversions.convert_points_to_homogeneous(points_h)assert_close(points, expected, atol=1e-4, rtol=1e-4)def test_convert_points_batch(self, device, dtype):@@ -1053,7 +1185,7 @@ class TestConvertPointsToHomogeneous:)# to euclidean- points = kornia.convert_points_to_homogeneous(points_h)+ points = kornia.geometry.conversions.convert_points_to_homogeneous(points_h)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)])@@ -1062,7 +1194,7 @@ class TestConvertPointsToHomogeneous:# evaluate function gradientpoints_h = tensor_to_gradcheck_var(points_h) # to var- assert gradcheck(kornia.convert_points_to_homogeneous, (points_h,), raise_exception=True)+ assert gradcheck(kornia.geometry.conversions.convert_points_to_homogeneous, (points_h,), raise_exception=True)def test_jit(self, device, dtype):op = kornia.geometry.conversions.convert_points_to_homogeneous@@ -1090,7 +1222,9 @@ class TestConvertAtoH:# evaluate function gradientpoints_h = tensor_to_gradcheck_var(points_h) # to var- assert gradcheck(kornia.convert_affinematrix_to_homography, (points_h,), raise_exception=True)+ assert gradcheck(+ kornia.geometry.conversions.convert_affinematrix_to_homography, (points_h,), raise_exception=True+ )def test_jit(self, device, dtype):op = kornia.geometry.conversions.convert_affinematrix_to_homography@@ -1103,7 +1237,7 @@ class TestConvertPointsFromHomogeneous:@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)- points = kornia.convert_points_from_homogeneous(points_h)+ points = kornia.geometry.conversions.convert_points_from_homogeneous(points_h)assert points.shape == points.shape[:-1] + (2,)def test_points(self, device, dtype):@@ -1119,7 +1253,7 @@ class TestConvertPointsFromHomogeneous:)# to euclidean- points = kornia.convert_points_from_homogeneous(points_h)+ points = kornia.geometry.conversions.convert_points_from_homogeneous(points_h)assert_close(points, expected, atol=1e-4, rtol=1e-4)def test_points_batch(self, device, dtype):@@ -1129,7 +1263,7 @@ class TestConvertPointsFromHomogeneous:expected = torch.tensor([[[2.0, 1.0]], [[0.0, 0.5]], [[0.0, -0.5]]], device=device, dtype=dtype)# to euclidean- points = kornia.convert_points_from_homogeneous(points_h)+ points = kornia.geometry.conversions.convert_points_from_homogeneous(points_h)assert_close(points, expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self, device, dtype):@@ -1137,7 +1271,7 @@ class TestConvertPointsFromHomogeneous:# evaluate function gradientpoints_h = tensor_to_gradcheck_var(points_h) # to var- assert gradcheck(kornia.convert_points_from_homogeneous, (points_h,), raise_exception=True)+ assert gradcheck(kornia.geometry.conversions.convert_points_from_homogeneous, (points_h,), raise_exception=True)@pytest.mark.skip("RuntimeError: Jacobian mismatch for output 0 with respect to input 0,")def test_gradcheck_zvec_zeros(self, device, dtype):@@ -1146,7 +1280,7 @@ class TestConvertPointsFromHomogeneous:# evaluate function gradientpoints_h = tensor_to_gradcheck_var(points_h) # to var- assert gradcheck(kornia.convert_points_from_homogeneous, (points_h,), raise_exception=True)+ assert gradcheck(kornia.geometry.conversions.convert_points_from_homogeneous, (points_h,), raise_exception=True)def test_jit(self, device, dtype):op = kornia.geometry.conversions.convert_points_from_homogeneous@@ -1165,7 +1299,7 @@ class TestNormalizePixelCoordinates:dtype=dtype)- grid_norm = kornia.normalize_pixel_coordinates(grid, height, width, eps=eps)+ grid_norm = kornia.geometry.conversions.normalize_pixel_coordinates(grid, height, width, eps=eps)assert_close(grid_norm, expected, atol=atol, rtol=rtol)@@ -1180,7 +1314,7 @@ class TestNormalizePixelCoordinates:)expected = expected.contiguous().view(-1, 2)- grid_norm = kornia.normalize_pixel_coordinates(grid, height, width, eps=eps)+ grid_norm = kornia.geometry.conversions.normalize_pixel_coordinates(grid, height, width, eps=eps)assert_close(grid_norm, expected, atol=atol, rtol=rtol)@@ -1205,7 +1339,7 @@ class TestDenormalizePixelCoordinates:dtype=dtype)- grid_norm = kornia.denormalize_pixel_coordinates(grid, height, width)+ grid_norm = kornia.geometry.conversions.denormalize_pixel_coordinates(grid, height, width)assert_close(grid_norm, expected, atol=1e-4, rtol=1e-4)@@ -1219,7 +1353,7 @@ class TestDenormalizePixelCoordinates:)expected = expected.contiguous().view(-1, 2)- grid_norm = kornia.denormalize_pixel_coordinates(grid, height, width)+ grid_norm = kornia.geometry.conversions.denormalize_pixel_coordinates(grid, height, width)assert_close(grid_norm, expected, atol=1e-4, rtol=1e-4)diff --git a/test/geometry/test_depth.py b/test/geometry/test_depth.pyindex e5a9e4084..61c6798b6 100644--- a/test/geometry/test_depth.py+++ b/test/geometry/test_depth.py@@ -12,7 +12,7 @@ class TestDepthTo3d:depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)- points3d = kornia.depth_to_3d(depth, camera_matrix)+ points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix)assert points3d.shape == (1, 3, 3, 4)@pytest.mark.parametrize("batch_size", [2, 4, 5])@@ -20,7 +20,7 @@ class TestDepthTo3d:depth = torch.rand(batch_size, 1, 3, 4, device=device, dtype=dtype)camera_matrix = torch.rand(batch_size, 3, 3, device=device, dtype=dtype)- points3d = kornia.depth_to_3d(depth, camera_matrix)+ points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix)assert points3d.shape == (batch_size, 3, 3, 4)@pytest.mark.parametrize("batch_size", [1, 2, 4, 5])@@ -28,7 +28,7 @@ class TestDepthTo3d:depth = torch.rand(batch_size, 1, 3, 4, device=device, dtype=dtype)camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)- points3d = kornia.depth_to_3d(depth, camera_matrix)+ points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix)assert points3d.shape == (batch_size, 3, 3, 4)def test_unproject_denormalized(self, device, dtype):@@ -51,7 +51,7 @@ class TestDepthTo3d:dtype=dtype,)- points3d = kornia.depth_to_3d(depth, camera_matrix) # default is normalize_points=False+ points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix) # default is normalize_points=Falseassert_close(points3d, points3d_expected, atol=1e-4, rtol=1e-4)def test_unproject_normalized(self, device, dtype):@@ -89,7 +89,7 @@ class TestDepthTo3d:dtype=dtype,)- points3d = kornia.depth_to_3d(depth, camera_matrix, normalize_points=True)+ points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix, normalize_points=True)assert_close(points3d, points3d_expected, atol=1e-4, rtol=1e-4)def test_unproject_and_project(self, device, dtype):@@ -99,9 +99,9 @@ class TestDepthTo3d: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)- points3d = kornia.depth_to_3d(depth, camera_matrix)- points2d = kornia.project_points(points3d.permute(0, 2, 3, 1), camera_matrix[:, None, None])- points2d_expected = kornia.create_meshgrid(4, 3, False, device=device).to(dtype=dtype)+ 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)def test_gradcheck(self, device, dtype):@@ -113,7 +113,7 @@ class TestDepthTo3d:camera_matrix = utils.tensor_to_gradcheck_var(camera_matrix) # to var# evaluate function gradient- assert gradcheck(kornia.depth_to_3d, (depth, camera_matrix), raise_exception=True)+ assert gradcheck(kornia.geometry.depth.depth_to_3d, (depth, camera_matrix), raise_exception=True)class TestDepthToNormals:@@ -121,7 +121,7 @@ class TestDepthToNormals:depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)- points3d = kornia.depth_to_normals(depth, camera_matrix)+ points3d = kornia.geometry.depth.depth_to_normals(depth, camera_matrix)assert points3d.shape == (1, 3, 3, 4)@pytest.mark.parametrize("batch_size", [2, 4, 5])@@ -129,7 +129,7 @@ class TestDepthToNormals:depth = torch.rand(batch_size, 1, 3, 4, device=device, dtype=dtype)camera_matrix = torch.rand(batch_size, 3, 3, device=device, dtype=dtype)- points3d = kornia.depth_to_normals(depth, camera_matrix)+ points3d = kornia.geometry.depth.depth_to_normals(depth, camera_matrix)assert points3d.shape == (batch_size, 3, 3, 4)@pytest.mark.parametrize("batch_size", [2, 4, 5])@@ -137,7 +137,7 @@ class TestDepthToNormals:depth = torch.rand(batch_size, 1, 3, 4, device=device, dtype=dtype)camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)- points3d = kornia.depth_to_normals(depth, camera_matrix)+ points3d = kornia.geometry.depth.depth_to_normals(depth, camera_matrix)assert points3d.shape == (batch_size, 3, 3, 4)def test_simple(self, device, dtype):@@ -160,7 +160,7 @@ class TestDepthToNormals:dtype=dtype,)- normals = kornia.depth_to_normals(depth, camera_matrix) # default is normalize_points=False+ normals = kornia.geometry.depth.depth_to_normals(depth, camera_matrix) # default is normalize_points=Falseassert_close(normals, normals_expected, rtol=1e-3, atol=1e-3)def test_simple_normalized(self, device, dtype):@@ -198,7 +198,7 @@ class TestDepthToNormals:dtype=dtype,)- normals = kornia.depth_to_normals(depth, camera_matrix, normalize_points=True)+ normals = kornia.geometry.depth.depth_to_normals(depth, camera_matrix, normalize_points=True)assert_close(normals, normals_expected, rtol=1e-3, atol=1e-3)def test_gradcheck(self, device, dtype):@@ -210,7 +210,7 @@ class TestDepthToNormals:camera_matrix = utils.tensor_to_gradcheck_var(camera_matrix) # to var# evaluate function gradient- assert gradcheck(kornia.depth_to_normals, (depth, camera_matrix), raise_exception=True)+ assert gradcheck(kornia.geometry.depth.depth_to_normals, (depth, camera_matrix), raise_exception=True)class TestWarpFrameDepth:@@ -220,7 +220,7 @@ class TestWarpFrameDepth:src_trans_dst = torch.rand(1, 4, 4, device=device, dtype=dtype)camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)- image_dst = kornia.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix)+ image_dst = kornia.geometry.depth.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix)assert image_dst.shape == (1, 3, 3, 4)@pytest.mark.parametrize("batch_size", [2, 4, 5])@@ -231,7 +231,7 @@ class TestWarpFrameDepth:src_trans_dst = torch.rand(batch_size, 4, 4, device=device, dtype=dtype)camera_matrix = torch.rand(batch_size, 3, 3, device=device, dtype=dtype)- image_dst = kornia.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix)+ image_dst = kornia.geometry.depth.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix)assert image_dst.shape == (batch_size, num_features, 3, 4)def test_translation(self, device, dtype):@@ -259,7 +259,7 @@ class TestWarpFrameDepth:[[[[2.0, 3.0, 0.0], [2.0, 3.0, 0.0], [2.0, 3.0, 0.0], [2.0, 3.0, 0.0]]]], device=device, dtype=dtype)- image_dst = kornia.warp_frame_depth(+ image_dst = kornia.geometry.depth.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix) # default is normalize_points=Falseassert_close(image_dst, image_dst_expected, rtol=1e-3, atol=1e-3)@@ -300,7 +300,9 @@ class TestWarpFrameDepth:dtype=dtype,)- image_dst = kornia.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix, normalize_points=True)+ 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)def test_gradcheck(self, device, dtype):@@ -318,5 +320,7 @@ class TestWarpFrameDepth:# evaluate function gradientassert gradcheck(- kornia.warp_frame_depth, (image_src, depth_dst, src_trans_dst, camera_matrix), raise_exception=True+ kornia.geometry.depth.warp_frame_depth,+ (image_src, depth_dst, src_trans_dst, camera_matrix),+ raise_exception=True,)diff --git a/test/geometry/test_depth_warper.py b/test/geometry/test_depth_warper.pyindex d6b4ff4a0..2a7f9edf8 100644--- a/test/geometry/test_depth_warper.py+++ b/test/geometry/test_depth_warper.py@@ -19,10 +19,10 @@ class TestDepthWarper:tx, ty, tz = 0, 0, 0# create pinhole cameras- pinhole_src = kornia.PinholeCamera.from_parameters(+ pinhole_src = kornia.geometry.camera.PinholeCamera.from_parameters(fx, fy, cx, cy, height, width, tx, ty, tz, batch_size, device=device, dtype=dtype)- pinhole_dst = kornia.PinholeCamera.from_parameters(+ pinhole_dst = kornia.geometry.camera.PinholeCamera.from_parameters(fx, fy, cx, cy, height, width, tx, ty, tz, batch_size, device=device, dtype=dtype)return pinhole_src, pinhole_dst@@ -34,7 +34,7 @@ class TestDepthWarper:pinhole_dst.tx += 1.0 # apply offset to tx# create warper- warper = kornia.DepthWarper(pinhole_dst, height, width)+ warper = kornia.geometry.depth.DepthWarper(pinhole_dst, height, width)assert warper._dst_proj_src is None# initialize projection matrices@@ -59,7 +59,7 @@ class TestDepthWarper:depth_src = torch.ones(batch_size, 1, height, width, device=device, dtype=dtype)# create warper, initialize projection matrices and warp grid- warper = kornia.DepthWarper(pinhole_dst, height, width)+ warper = kornia.geometry.depth.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)grid_warped = warper.warp_grid(depth_src)@@ -85,7 +85,7 @@ class TestDepthWarper:depth_src = torch.ones(batch_size, 1, height, width, device=device, dtype=dtype)# create warper, initialize projection matrices and warp grid- warper = kornia.DepthWarper(pinhole_dst, height, width)+ warper = kornia.geometry.depth.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)grid_warped = warper.warp_grid(depth_src)@@ -111,7 +111,7 @@ class TestDepthWarper:depth_src = torch.ones(batch_size, 1, height, width, device=device, dtype=dtype)# create warper, initialize projection matrices and warp grid- warper = kornia.DepthWarper(pinhole_dst, height, width)+ warper = kornia.geometry.depth.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)# create patch to warp@@ -133,7 +133,7 @@ class TestDepthWarper:pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size, device, dtype)# create warper, initialize projection matrices and warp grid- warper = kornia.DepthWarper(pinhole_dst, height, width)+ warper = kornia.geometry.depth.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)# test compute_projection@@ -146,7 +146,7 @@ class TestDepthWarper:pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size, device, dtype)# create warper, initialize projection matrices and warp grid- warper = kornia.DepthWarper(pinhole_dst, height, width)+ warper = kornia.geometry.depth.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)# test compute_subpixel_step@@ -169,7 +169,9 @@ class TestDepthWarper:# evaluate function gradientassert gradcheck(- kornia.depth_warp, (pinhole_dst, pinhole_src, depth_src, img_dst, height, width), raise_exception=True+ kornia.geometry.depth.depth_warp,+ (pinhole_dst, pinhole_src, depth_src, img_dst, height, width),+ raise_exception=True,)# TODO(edgar): we should include a test showing some kind of occlusiondiff --git a/test/geometry/test_homography.py b/test/geometry/test_homography.pyindex 5edb34758..9281b7615 100644--- a/test/geometry/test_homography.py+++ b/test/geometry/test_homography.py@@ -119,13 +119,13 @@ class TestFindHomographyDLT:H = H * 0.3 * torch.rand_like(H)H = H / H[:, 2:3, 2:3]- points_dst = kornia.transform_points(H, points_src)+ points_dst = kornia.geometry.transform_points(H, points_src)weights = torch.ones(batch_size, 10, device=device, dtype=dtype)# compute transform from source to targetdst_homo_src = find_homography_dlt(points_src, points_dst, weights)- assert_close(kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)+ assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)@pytest.mark.grad@pytest.mark.skipif(torch.__version__ < '1.7', reason="pytorch bug of incopatible types: #33546 fixed in v1.7")@@ -193,13 +193,13 @@ class TestFindHomographyDLTIter:H = H * 0.3 * torch.rand_like(H)H = H / H[:, 2:3, 2:3]- points_dst = kornia.transform_points(H, points_src)+ points_dst = kornia.geometry.transform_points(H, points_src)weights = torch.ones(batch_size, 10, device=device, dtype=dtype)# compute transform from source to targetdst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 10)- assert_close(kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)+ assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)@pytest.mark.grad@pytest.mark.skipif(torch.__version__ < '1.7', reason="pytorch bug of incopatible types: #33546 fixed in v1.7")@@ -256,7 +256,7 @@ class TestFindHomographyDLTIter:H = H / H[:, 2:3, 2:3]points_src = 100.0 * torch.rand(batch_size, 20, 2, device=device, dtype=dtype)- points_dst = kornia.transform_points(H, points_src)+ points_dst = kornia.geometry.transform_points(H, points_src)# making last point an outlierpoints_dst[:, -1, :] += 20@@ -267,5 +267,5 @@ class TestFindHomographyDLTIter:dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 0.5, 10)assert_close(- kornia.transform_points(dst_homo_src, points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3+ kornia.geometry.transform_points(dst_homo_src, points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3)diff --git a/test/geometry/test_linalg.py b/test/geometry/test_linalg.pyindex 89512070d..4892ffc0b 100644--- a/test/geometry/test_linalg.py+++ b/test/geometry/test_linalg.py@@ -93,11 +93,11 @@ class TestTransformPoints:dst_homo_src = dst_homo_src.to(device)# transform the points from dst to ref- points_dst = kornia.transform_points(dst_homo_src, points_src)+ points_dst = kornia.geometry.linalg.transform_points(dst_homo_src, points_src)# transform the points from ref to dstsrc_homo_dst = torch.inverse(dst_homo_src)- points_dst_to_src = kornia.transform_points(src_homo_dst, points_dst)+ points_dst_to_src = kornia.geometry.linalg.transform_points(src_homo_dst, points_dst)# projected should be equal as initialassert_close(points_src, points_dst_to_src, atol=1e-4, rtol=1e-4)@@ -166,7 +166,7 @@ class TestComposeTransforms:trans_12 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]trans_12[..., :3, -1] += offset # add offset to translation vector- trans_02 = kornia.compose_transformations(trans_01, trans_12)+ trans_02 = kornia.geometry.linalg.compose_transformations(trans_01, trans_12)assert_close(trans_02, trans_12, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -176,7 +176,7 @@ class TestComposeTransforms:trans_12 = identity_matrix(batch_size, device=device, dtype=dtype)trans_12[..., :3, -1] += offset # add offset to translation vector- trans_02 = kornia.compose_transformations(trans_01, trans_12)+ trans_02 = kornia.geometry.linalg.compose_transformations(trans_01, trans_12)assert_close(trans_02, trans_12, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -186,7 +186,7 @@ class TestComposeTransforms:trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to vartrans_12 = utils.tensor_to_gradcheck_var(trans_12) # to var- assert gradcheck(kornia.compose_transformations, (trans_01, trans_12), raise_exception=True)+ assert gradcheck(kornia.geometry.linalg.compose_transformations, (trans_01, trans_12), raise_exception=True)class TestInverseTransformation:@@ -222,8 +222,8 @@ class TestInverseTransformation:trans_01 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]trans_01[..., :3, -1] += offset # add offset to translation vector- trans_10 = kornia.inverse_transformation(trans_01)- trans_01_hat = kornia.inverse_transformation(trans_10)+ trans_10 = kornia.geometry.linalg.inverse_transformation(trans_01)+ trans_01_hat = kornia.geometry.linalg.inverse_transformation(trans_10)assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -232,8 +232,8 @@ class TestInverseTransformation:trans_01 = identity_matrix(batch_size, device=device, dtype=dtype)trans_01[..., :3, -1] += offset # add offset to translation vector- trans_10 = kornia.inverse_transformation(trans_01)- trans_01_hat = kornia.inverse_transformation(trans_10)+ trans_10 = kornia.geometry.linalg.inverse_transformation(trans_01)+ trans_01_hat = kornia.geometry.linalg.inverse_transformation(trans_10)assert_close(trans_01, trans_01_hat, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -247,15 +247,15 @@ class TestInverseTransformation:trans_01[..., :3, -1] += offset # add offset to translation vectortrans_01[..., :3, :3] = rmat_01[..., :3, :3]- trans_10 = kornia.inverse_transformation(trans_01)- trans_01_hat = kornia.inverse_transformation(trans_10)+ trans_10 = kornia.geometry.linalg.inverse_transformation(trans_01)+ trans_01_hat = kornia.geometry.linalg.inverse_transformation(trans_10)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(kornia.inverse_transformation, (trans_01,), raise_exception=True)+ assert gradcheck(kornia.geometry.linalg.inverse_transformation, (trans_01,), raise_exception=True)class TestRelativeTransformation:@@ -301,8 +301,8 @@ class TestRelativeTransformation:trans_02 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]trans_02[..., :3, -1] += offset # add offset to translation vector- trans_12 = kornia.relative_transformation(trans_01, trans_02)- trans_02_hat = kornia.compose_transformations(trans_01, trans_12)+ trans_12 = kornia.geometry.linalg.relative_transformation(trans_01, trans_02)+ trans_02_hat = kornia.geometry.linalg.compose_transformations(trans_01, trans_12)assert_close(trans_02_hat, trans_02, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -317,8 +317,8 @@ class TestRelativeTransformation:trans_02[..., :3, -1] += offset # add offset to translation vectortrans_02[..., :3, :3] = rmat_02[..., :3, :3]- trans_12 = kornia.relative_transformation(trans_01, trans_02)- trans_02_hat = kornia.compose_transformations(trans_01, trans_12)+ trans_12 = kornia.geometry.linalg.relative_transformation(trans_01, trans_02)+ trans_02_hat = kornia.geometry.linalg.compose_transformations(trans_01, trans_12)assert_close(trans_02_hat, trans_02, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("batch_size", [1, 2, 5])@@ -328,36 +328,4 @@ class TestRelativeTransformation:trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to vartrans_02 = utils.tensor_to_gradcheck_var(trans_02) # to var- assert gradcheck(kornia.relative_transformation, (trans_01, trans_02), raise_exception=True)---class TestTransformLAFs:- @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):- # generate input data- 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)-- # transform the points from dst to ref- lafs_dst = kornia.perspective_transform_lafs(dst_homo_src, lafs_src)-- # transform the points from ref to dst- src_homo_dst = torch.inverse(dst_homo_src)- lafs_dst_to_src = kornia.perspective_transform_lafs(src_homo_dst, lafs_dst)-- # projected should be equal as initial- assert_close(lafs_src, lafs_dst_to_src)-- def test_gradcheck(self, device, dtype):- # 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)- # 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.perspective_transform_lafs, (dst_homo_src, points_src), raise_exception=True)+ assert gradcheck(kornia.geometry.linalg.relative_transformation, (trans_01, trans_02), raise_exception=True)diff --git a/test/geometry/test_ransac.py b/test/geometry/test_ransac.pyindex 840efef23..bc925a720 100644--- a/test/geometry/test_ransac.py+++ b/test/geometry/test_ransac.py@@ -1,12 +1,9 @@-import random-import pytestimport torchfrom torch.autograd import gradcheck-import kornia-import kornia.testing as utils-from kornia.geometry import RANSAC+import kornia.testing as utils # test utils+from kornia.geometry import RANSAC, transform_pointsfrom kornia.geometry.epipolar import sampson_epipolar_distancefrom kornia.testing import assert_close@@ -30,7 +27,7 @@ class TestRANSACHomography:H[2:, :2] = H[2:, :2] + 0.001 * torch.rand_like(H[2:, :2])points_src = 100.0 * torch.rand(1, 20, 2, device=device, dtype=dtype)- points_dst = kornia.geometry.transform_points(H[None], points_src)+ points_dst = transform_points(H[None], points_src)# making last point an outlierpoints_dst[:, -1, :] += 800@@ -38,11 +35,7 @@ class TestRANSACHomography:# compute transform from source to targetdst_homo_src, _ = ransac(points_src[0], points_dst[0])- assert_close(- kornia.geometry.transform_points(dst_homo_src[None], points_src[:, :-1]),- points_dst[:, :-1],- rtol=1e-3,- atol=1e-3)+ assert_close(transform_points(dst_homo_src[None], points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3)@pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)@@ -58,11 +51,7 @@ class TestRANSACHomography:# compute transform from source to targetdst_homo_src, _ = ransac(pts_src, pts_dst)- assert_close(- kornia.geometry.transform_points(dst_homo_src[None], pts_src[None]),- pts_dst[None],- rtol=1e-3,- atol=1e-3)+ assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=1e-3, atol=1e-3)@pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)@@ -83,11 +72,7 @@ class TestRANSACHomography:dst_homo_src, _ = ransac(kp1, kp2)# Reprojection error of 5px is OK- assert_close(- kornia.geometry.transform_points(dst_homo_src[None], pts_src[None]),- pts_dst[None],- rtol=5,- atol=0.15)+ assert_close(transform_points(dst_homo_src[None], pts_src[None]), pts_dst[None], rtol=5, atol=0.15)@pytest.mark.skip(reason="find_homography_dlt is using try/except block")def test_jit(self, device, dtype):@@ -95,12 +80,8 @@ class TestRANSACHomography:points1 = torch.rand(4, 2, device=device, dtype=dtype)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)+ 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)class TestRANSACFundamental:@@ -121,15 +102,11 @@ class TestRANSACFundamental:pts_src = data_dev['pts0']pts_dst = data_dev['pts1']# compute transform from source to target- ransac = RANSAC('fundamental',- inl_th=0.5,- max_iter=20,- max_lo_iters=10).to(device=device, dtype=dtype)+ ransac = RANSAC('fundamental', inl_th=0.5, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)fundamental_matrix, _ = ransac(pts_src, pts_dst)- gross_errors = sampson_epipolar_distance(pts_src[None],- pts_dst[None],- fundamental_matrix[None],- squared=False) > 1.0+ gross_errors = (+ sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 1.0+ )assert gross_errors.sum().item() == 0@pytest.mark.xfail(reason="might fail, because out F-RANSAC is not yet 7pt")@@ -144,16 +121,12 @@ class TestRANSACFundamental:kp1 = data_dev['loftr_indoor_tentatives0']kp2 = data_dev['loftr_indoor_tentatives1']- ransac = RANSAC('fundamental',- inl_th=1.0,- max_iter=20,- max_lo_iters=10).to(device=device, dtype=dtype)+ ransac = RANSAC('fundamental', inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)# compute transform from source to targetfundamental_matrix, _ = ransac(kp1, kp2)- gross_errors = sampson_epipolar_distance(pts_src[None],- pts_dst[None],- fundamental_matrix[None],- squared=False) > 10.0+ gross_errors = (+ sampson_epipolar_distance(pts_src[None], pts_dst[None], fundamental_matrix[None], squared=False) > 10.0+ )assert gross_errors.sum().item() < 2def test_jit(self, device, dtype):@@ -162,10 +135,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)+ 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):@@ -176,4 +146,5 @@ class TestRANSACFundamental:def gradfun(p1, p2):return model(p1, p2)[0]+assert gradcheck(gradfun, (points1, points2), raise_exception=True)diff --git a/test/geometry/transform/test_affine.py b/test/geometry/transform/test_affine.pyindex b2cd97dbc..ceb0625f9 100644--- a/test/geometry/transform/test_affine.py+++ b/test/geometry/transform/test_affine.py@@ -10,166 +10,166 @@ from kornia.testing import assert_closeclass TestResize:def test_smoke(self, device, dtype):inp = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)- out = kornia.resize(inp, (3, 4), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (3, 4), align_corners=False)assert_close(inp, out, atol=1e-4, rtol=1e-4)# 2Dinp = torch.rand(3, 4, device=device, dtype=dtype)- out = kornia.resize(inp, (3, 4), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (3, 4), align_corners=False)assert_close(inp, out, atol=1e-4, rtol=1e-4)# 3Dinp = torch.rand(3, 3, 4, device=device, dtype=dtype)- out = kornia.resize(inp, (3, 4), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (3, 4), align_corners=False)assert_close(inp, out, atol=1e-4, rtol=1e-4)# arbitrary diminp = torch.rand(1, 2, 3, 2, 1, 3, 3, 4, device=device, dtype=dtype)- out = kornia.resize(inp, (3, 4), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (3, 4), align_corners=False)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)- out = kornia.resize(inp, (6, 8), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (6, 8), align_corners=False)assert out.shape == (1, 3, 6, 8)# 2Dinp = torch.rand(3, 4, device=device, dtype=dtype)- out = kornia.resize(inp, (6, 8), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (6, 8), align_corners=False)assert out.shape == (6, 8)# 3Dinp = torch.rand(3, 3, 4, device=device, dtype=dtype)- out = kornia.resize(inp, (6, 8), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (6, 8), align_corners=False)assert out.shape == (3, 6, 8)# arbitrary diminp = torch.rand(1, 2, 3, 2, 1, 3, 3, 4, device=device, dtype=dtype)- out = kornia.resize(inp, (6, 8), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (6, 8), align_corners=False)assert out.shape == (1, 2, 3, 2, 1, 3, 6, 8)def test_downsize(self, device, dtype):inp = torch.rand(1, 3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, (3, 1), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (3, 1), align_corners=False)assert out.shape == (1, 3, 3, 1)# 2Dinp = torch.rand(5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, (3, 1), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (3, 1), align_corners=False)assert out.shape == (3, 1)# 3Dinp = torch.rand(3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, (3, 1), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (3, 1), align_corners=False)assert out.shape == (3, 3, 1)# arbitrary diminp = torch.rand(1, 2, 3, 2, 1, 3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, (3, 1), align_corners=False)+ out = kornia.geometry.transform.resize(inp, (3, 1), align_corners=False)assert out.shape == (1, 2, 3, 2, 1, 3, 3, 1)def test_downsizeAA(self, device, dtype):inp = torch.rand(1, 3, 10, 8, device=device, dtype=dtype)- out = kornia.resize(inp, (5, 3), align_corners=False, antialias=True)+ out = kornia.geometry.transform.resize(inp, (5, 3), align_corners=False, antialias=True)assert out.shape == (1, 3, 5, 3)inp = torch.rand(1, 1, 20, 10, device=device, dtype=dtype)- out = kornia.resize(inp, (15, 8), align_corners=False, antialias=True)+ out = kornia.geometry.transform.resize(inp, (15, 8), align_corners=False, antialias=True)assert out.shape == (1, 1, 15, 8)# 2Dinp = torch.rand(10, 8, device=device, dtype=dtype)- out = kornia.resize(inp, (5, 3), align_corners=False, antialias=True)+ out = kornia.geometry.transform.resize(inp, (5, 3), align_corners=False, antialias=True)assert out.shape == (5, 3)# 3Dinp = torch.rand(3, 10, 8, device=device, dtype=dtype)- out = kornia.resize(inp, (5, 3), align_corners=False, antialias=True)+ out = kornia.geometry.transform.resize(inp, (5, 3), align_corners=False, antialias=True)assert out.shape == (3, 5, 3)# arbitrary diminp = torch.rand(1, 2, 3, 2, 1, 3, 10, 8, device=device, dtype=dtype)- out = kornia.resize(inp, (5, 3), align_corners=False, antialias=True)+ out = kornia.geometry.transform.resize(inp, (5, 3), align_corners=False, antialias=True)assert out.shape == (1, 2, 3, 2, 1, 3, 5, 3)def test_one_param(self, device, dtype):inp = torch.rand(1, 3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False)+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False)assert out.shape == (1, 3, 25, 10)# 2Dinp = torch.rand(5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False)+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False)assert out.shape == (25, 10)# 3Dinp = torch.rand(3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False)+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False)assert out.shape == (3, 25, 10)# arbitrary diminp = torch.rand(1, 2, 3, 2, 1, 3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False)+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False)assert out.shape == (1, 2, 3, 2, 1, 3, 25, 10)def test_one_param_long(self, device, dtype):inp = torch.rand(1, 3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="long")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="long")assert out.shape == (1, 3, 10, 4)# 2Dinp = torch.rand(5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="long")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="long")assert out.shape == (10, 4)# 3Dinp = torch.rand(3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="long")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="long")assert out.shape == (3, 10, 4)# arbitrary diminp = torch.rand(1, 2, 3, 2, 1, 3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="long")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="long")assert out.shape == (1, 2, 3, 2, 1, 3, 10, 4)def test_one_param_vert(self, device, dtype):inp = torch.rand(1, 3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="vert")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="vert")assert out.shape == (1, 3, 10, 4)# 2Dinp = torch.rand(5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="vert")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="vert")assert out.shape == (10, 4)# 3Dinp = torch.rand(3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="vert")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="vert")assert out.shape == (3, 10, 4)# arbitrary diminp = torch.rand(1, 2, 3, 2, 1, 3, 5, 2, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="vert")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="vert")assert out.shape == (1, 2, 3, 2, 1, 3, 10, 4)def test_one_param_horz(self, device, dtype):inp = torch.rand(1, 3, 2, 5, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="horz")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="horz")assert out.shape == (1, 3, 4, 10)# 2Dinp = torch.rand(1, 3, 2, 5, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="horz")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="horz")assert out.shape == (1, 3, 4, 10)# 3Dinp = torch.rand(1, 3, 2, 5, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="horz")+ out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="horz")assert out.shape == (1, 3, 4, 10)# arbitrary diminp = torch.rand(1, 3, 2, 5, device=device, dtype=dtype)- out = kornia.resize(inp, 10, align_corners=False, side="horz")+ 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):@@ -177,30 +177,32 @@ class TestResize:new_size = 4input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.Resize(new_size, align_corners=False), (input,), raise_exception=True)+ assert gradcheck(+ kornia.geometry.transform.Resize(new_size, align_corners=False), (input,), raise_exception=True+ )class TestRescale:def test_smoke(self, device, dtype):input = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)- output = kornia.rescale(input, (1.0, 1.0), align_corners=False)+ output = kornia.geometry.transform.rescale(input, (1.0, 1.0), align_corners=False)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)- output = kornia.rescale(input, (3.0, 2.0), align_corners=False)+ output = kornia.geometry.transform.rescale(input, (3.0, 2.0), align_corners=False)assert output.shape == (1, 3, 9, 8)def test_downsize(self, device, dtype):input = torch.rand(1, 3, 9, 8, device=device, dtype=dtype)- output = kornia.rescale(input, (1.0 / 3.0, 1.0 / 2.0), align_corners=False)+ output = kornia.geometry.transform.rescale(input, (1.0 / 3.0, 1.0 / 2.0), align_corners=False)assert output.shape == (1, 3, 3, 4)def test_downscale_values(self, device, dtype):inp_x = torch.arange(20, device=device, dtype=dtype) / 20.0inp = inp_x[None].T @ inp_x[None]inp = inp[None, None]- out = kornia.rescale(inp, (0.25, 0.25), antialias=False, align_corners=False)+ out = kornia.geometry.transform.rescale(inp, (0.25, 0.25), antialias=False, align_corners=False)expected = torch.tensor([[@@ -222,7 +224,7 @@ class TestRescale:inp_x = torch.arange(20, device=device, dtype=dtype) / 20.0inp = inp_x[None].T @ inp_x[None]inp = inp[None, None]- out = kornia.rescale(inp, (0.25, 0.25), antialias=True, align_corners=False)+ out = kornia.geometry.transform.rescale(inp, (0.25, 0.25), antialias=True, align_corners=False)expected = torch.tensor([[@@ -242,13 +244,13 @@ class TestRescale:def test_one_param(self, device, dtype):input = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)- output = kornia.rescale(input, 2.0, align_corners=False)+ 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.Rescale(2.0, align_corners=False), (input,), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.Rescale(2.0, align_corners=False), (input,), raise_exception=True)class TestRotate:@@ -258,7 +260,7 @@ class TestRotate:expected = torch.tensor([[[0.0, 0.0], [4.0, 6.0], [3.0, 5.0], [0.0, 0.0]]], device=device, dtype=dtype)# prepare transformationangle = torch.tensor([90.0], device=device, dtype=dtype)- transform = kornia.Rotate(angle, align_corners=True)+ transform = kornia.geometry.transform.Rotate(angle, align_corners=True)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_angle90_batch2(self, device, dtype):@@ -273,7 +275,7 @@ class TestRotate:)# prepare transformationangle = torch.tensor([90.0, -90.0], device=device, dtype=dtype)- transform = kornia.Rotate(angle, align_corners=True)+ transform = kornia.geometry.transform.Rotate(angle, align_corners=True)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_angle90_batch2_broadcast(self, device, dtype):@@ -288,7 +290,7 @@ class TestRotate:)# prepare transformationangle = torch.tensor([90.0], device=device, dtype=dtype)- transform = kornia.Rotate(angle, align_corners=True)+ transform = kornia.geometry.transform.Rotate(angle, align_corners=True)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self, device, dtype):@@ -299,7 +301,7 @@ class TestRotate:# evaluate function gradientinput = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.rotate, (input, angle), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.rotate, (input, angle), raise_exception=True)@pytest.mark.skip('Need deep look into it since crashes everywhere.')@pytest.mark.skip(reason="turn off all jit for a while")@@ -307,8 +309,8 @@ class TestRotate:angle = torch.tensor([90.0], device=device, dtype=dtype)batch_size, channels, height, width = 2, 3, 64, 64img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)- rot = kornia.Rotate(angle)- rot_traced = torch.jit.trace(kornia.Rotate(angle), img)+ rot = kornia.geometry.transform.Rotate(angle)+ rot_traced = torch.jit.trace(kornia.geometry.transform.Rotate(angle), img)assert_close(rot(img), rot_traced(img))@@ -319,7 +321,7 @@ class TestTranslate:expected = torch.tensor([[[0.0, 1.0], [0.0, 3.0], [0.0, 5.0], [0.0, 7.0]]], device=device, dtype=dtype)# prepare transformationtranslation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)- transform = kornia.Translate(translation, align_corners=True)+ transform = kornia.geometry.transform.Translate(translation, align_corners=True)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_dxdy_batch(self, device, dtype):@@ -334,7 +336,7 @@ class TestTranslate:)# prepare transformationtranslation = torch.tensor([[1.0, 0.0], [1.0, 1.0]], device=device, dtype=dtype)- transform = kornia.Translate(translation, align_corners=True)+ transform = kornia.geometry.transform.Translate(translation, align_corners=True)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_dxdy_batch_broadcast(self, device, dtype):@@ -349,7 +351,7 @@ class TestTranslate:)# prepare transformationtranslation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)- transform = kornia.Translate(translation, align_corners=True)+ transform = kornia.geometry.transform.Translate(translation, align_corners=True)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self, device, dtype):@@ -360,7 +362,7 @@ class TestTranslate:# evaluate function gradientinput = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.translate, (input, translation), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.translate, (input, translation), raise_exception=True)@pytest.mark.skip('Need deep look into it since crashes everywhere.')@pytest.mark.skip(reason="turn off all jit for a while")@@ -368,8 +370,8 @@ class TestTranslate:translation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)batch_size, channels, height, width = 2, 3, 64, 64img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)- trans = kornia.Translate(translation)- trans_traced = torch.jit.trace(kornia.Translate(translation), img)+ 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)@@ -383,7 +385,7 @@ class TestScale:)# prepare transformationscale_factor = torch.tensor([[2.0, 2.0]], device=device, dtype=dtype)- transform = kornia.Scale(scale_factor)+ transform = kornia.geometry.transform.Scale(scale_factor)assert_close(transform(inp).sum().item(), 12.25, atol=1e-4, rtol=1e-4)def test_scale_factor_05(self, device, dtype):@@ -400,7 +402,7 @@ class TestScale:)# prepare transformationscale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)- transform = kornia.Scale(scale_factor)+ transform = kornia.geometry.transform.Scale(scale_factor)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_scale_factor_05_batch2(self, device, dtype):@@ -417,7 +419,7 @@ class TestScale:).repeat(2, 1, 1, 1)# prepare transformationscale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)- transform = kornia.Scale(scale_factor)+ transform = kornia.geometry.transform.Scale(scale_factor)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_scale_factor_05_batch2_broadcast(self, device, dtype):@@ -434,7 +436,7 @@ class TestScale:).repeat(2, 1, 1, 1)# prepare transformationscale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)- transform = kornia.Scale(scale_factor)+ transform = kornia.geometry.transform.Scale(scale_factor)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self, device, dtype):@@ -445,7 +447,7 @@ class TestScale:# evaluate function gradientinput = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.scale, (input, scale_factor), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.scale, (input, scale_factor), raise_exception=True)@pytest.mark.skip('Need deep look into it since crashes everywhere.')@pytest.mark.skip(reason="turn off all jit for a while")@@ -453,7 +455,7 @@ class TestScale:scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)batch_size, channels, height, width = 2, 3, 64, 64img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)- trans = kornia.Scale(scale_factor)+ 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)@@ -474,7 +476,7 @@ class TestShear:# prepare transformationshear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)- transform = kornia.Shear(shear, align_corners=False)+ transform = kornia.geometry.transform.Shear(shear, align_corners=False)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_shear_y(self, device, dtype):@@ -492,7 +494,7 @@ class TestShear:# prepare transformationshear = torch.tensor([[0.0, 0.5]], device=device, dtype=dtype)- transform = kornia.Shear(shear, align_corners=False)+ transform = kornia.geometry.transform.Shear(shear, align_corners=False)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_shear_batch2(self, device, dtype):@@ -514,7 +516,7 @@ class TestShear:# prepare transformationshear = torch.tensor([[0.5, 0.0], [0.0, 0.5]], device=device, dtype=dtype)- transform = kornia.Shear(shear, align_corners=False)+ transform = kornia.geometry.transform.Shear(shear, align_corners=False)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_shear_batch2_broadcast(self, device, dtype):@@ -533,7 +535,7 @@ class TestShear:# prepare transformationshear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)- transform = kornia.Shear(shear, align_corners=False)+ transform = kornia.geometry.transform.Shear(shear, align_corners=False)assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self, device, dtype):@@ -544,7 +546,7 @@ class TestShear:# evaluate function gradientinput = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.shear, (input, shear), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.shear, (input, shear), raise_exception=True)@pytest.mark.skip('Need deep look into it since crashes everywhere.')@pytest.mark.skip(reason="turn off all jit for a while")@@ -552,21 +554,21 @@ class TestShear:shear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)batch_size, channels, height, width = 2, 3, 64, 64img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)- trans = kornia.Shear(shear, align_corners=False)- trans_traced = torch.jit.trace(kornia.Shear(shear), img)+ 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)class TestAffine2d:def test_affine_no_args(self):with pytest.raises(RuntimeError):- kornia.Affine()+ kornia.geometry.transform.Affine()def test_affine_batch_size_mismatch(self, device, dtype):with pytest.raises(RuntimeError):angle = torch.rand(1, device=device, dtype=dtype)translation = torch.rand(2, 2, device=device, dtype=dtype)- kornia.Affine(angle, translation)+ kornia.geometry.transform.Affine(angle, translation)def test_affine_rotate(self, device, dtype):# TODO: Remove when #666 is implemented@@ -576,9 +578,9 @@ class TestAffine2d:angle = torch.rand(1, device=device, dtype=dtype) * 90.0input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)- transform = kornia.Affine(angle=angle).to(device=device, dtype=dtype)+ transform = kornia.geometry.transform.Affine(angle=angle).to(device=device, dtype=dtype)actual = transform(input)- expected = kornia.rotate(input, angle)+ expected = kornia.geometry.transform.rotate(input, angle)assert_close(actual, expected, atol=1e-4, rtol=1e-4)def test_affine_translate(self, device, dtype):@@ -589,9 +591,9 @@ class TestAffine2d:translation = torch.rand(1, 2, device=device, dtype=dtype) * 2.0input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)- transform = kornia.Affine(translation=translation).to(device=device, dtype=dtype)+ transform = kornia.geometry.transform.Affine(translation=translation).to(device=device, dtype=dtype)actual = transform(input)- expected = kornia.translate(input, translation)+ expected = kornia.geometry.transform.translate(input, translation)assert_close(actual, expected, atol=1e-4, rtol=1e-4)def test_affine_scale(self, device, dtype):@@ -603,9 +605,9 @@ class TestAffine2d:scale_factor = torch.stack([_scale_factor, _scale_factor], dim=1)input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)- transform = kornia.Affine(scale_factor=scale_factor).to(device=device, dtype=dtype)+ transform = kornia.geometry.transform.Affine(scale_factor=scale_factor).to(device=device, dtype=dtype)actual = transform(input)- expected = kornia.scale(input, scale_factor)+ expected = kornia.geometry.transform.scale(input, scale_factor)assert_close(actual, expected, atol=1e-4, rtol=1e-4)@pytest.mark.skip(@@ -617,9 +619,9 @@ class TestAffine2d:shear = torch.rand(1, 2, device=device, dtype=dtype)input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)- transform = kornia.Affine(shear=shear).to(device, dtype)+ transform = kornia.geometry.transform.Affine(shear=shear).to(device, dtype)actual = transform(input)- expected = kornia.shear(input, shear)+ expected = kornia.geometry.transform.shear(input, shear)assert_close(actual, expected, atol=1e-4, rtol=1e-4)def test_affine_rotate_translate(self, device, dtype):@@ -643,7 +645,7 @@ class TestAffine2d:dtype=dtype,).repeat(batch_size, 1, 1, 1)- transform = kornia.Affine(angle=angle, translation=translation, align_corners=True).to(+ transform = kornia.geometry.transform.Affine(angle=angle, translation=translation, align_corners=True).to(device=device, dtype=dtype)actual = transform(input)@@ -688,7 +690,7 @@ class TestAffine2d:matrix_expected = T([[1.27536969, 4.26828945e-01, -3.2876e01], [2.18297196e-03, 1.29424165e00, -1.1717e01]])center = T([float(width), float(height)]).view(1, 2) / 2.0 + 0.5center = center.expand(batch_size, -1)- matrix_kornia = kornia.get_affine_matrix2d(+ matrix_kornia = kornia.geometry.transform.get_affine_matrix2d(T(translations).view(-1, 2),center,T([scale]).view(-1, 2),@@ -703,7 +705,7 @@ class TestAffine2d:class TestGetAffineMatrix:def test_smoke(self, device, dtype):H, W = 5, 5- translation = torch.tensor([[0., 0.]], device=device, dtype=dtype)+ translation = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)# NOTE: ideally the center should be [W * 0.5, H * 0.5]center = torch.tensor([[W // 2, H // 2]], device=device, dtype=dtype)zoom1 = torch.ones([1, 1], device=device, dtype=dtype) * 0.5@@ -714,7 +716,7 @@ class TestGetAffineMatrix:img = torch.ones(1, 1, H, W, device=device, dtype=dtype)expected = torch.zeros_like(img)- expected[..., 1:4] = 1.+ expected[..., 1:4] = 1.0- out = kornia.geometry.warp_affine(img, affine_mat[:, :2], (H, W))+ out = kornia.geometry.transform.warp_affine(img, affine_mat[:, :2], (H, W))assert_close(out, expected)diff --git a/test/geometry/transform/test_bbox.py b/test/geometry/transform/test_bbox.pydeleted file mode 100644index 9bbf04191..000000000--- a/test/geometry/transform/test_bbox.py+++ /dev/null@@ -1,122 +0,0 @@-import torch-from torch.autograd import gradcheck--import kornia-import kornia.testing as utils # test utils-from kornia.testing import assert_close---class TestTransformBoxes:- def test_transform_bbox(self, device, dtype):-- boxes = torch.tensor([[139.2640, 103.0150, 397.3120, 410.5225]], device=device, dtype=dtype)-- expected = torch.tensor([[372.7360, 103.0150, 114.6880, 410.5225]], device=device, dtype=dtype)-- 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 = kornia.transform_bbox(trans_mat, boxes)- assert_close(out, expected, atol=1e-4, rtol=1e-4)-- def test_transform_multiple_boxes(self, device, dtype):-- boxes = torch.tensor(- [- [139.2640, 103.0150, 397.3120, 410.5225],- [1.0240, 80.5547, 512.0000, 512.0000],- [165.2053, 262.1440, 510.6347, 508.9280],- [119.8080, 144.2067, 257.0240, 410.1292],- ],- device=device,- dtype=dtype,- )-- boxes = boxes.repeat(2, 1, 1) # 2 x 4 x 4 two images 4 boxes each-- expected = torch.tensor(- [- [- [372.7360, 103.0150, 114.6880, 410.5225],- [510.9760, 80.5547, 0.0000, 512.0000],- [346.7947, 262.1440, 1.3653, 508.9280],- [392.1920, 144.2067, 254.9760, 410.1292],- ],- [- [139.2640, 103.0150, 397.3120, 410.5225],- [1.0240, 80.5547, 512.0000, 512.0000],- [165.2053, 262.1440, 510.6347, 508.9280],- [119.8080, 144.2067, 257.0240, 410.1292],- ],- ],- device=device,- dtype=dtype,- )-- trans_mat = torch.tensor(- [- [[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],- [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],- ],- device=device,- dtype=dtype,- )-- out = kornia.transform_bbox(trans_mat, boxes)- assert_close(out, expected, atol=1e-4, rtol=1e-4)-- def test_transform_bbox_wh(self, device, dtype):-- boxes = torch.tensor(- [- [139.2640, 103.0150, 258.0480, 307.5075],- [1.0240, 80.5547, 510.9760, 431.4453],- [165.2053, 262.1440, 345.4293, 246.7840],- [119.8080, 144.2067, 137.2160, 265.9225],- ],- device=device,- dtype=dtype,- )-- expected = torch.tensor(- [- [372.7360, 103.0150, -258.0480, 307.5075],- [510.9760, 80.5547, -510.9760, 431.4453],- [346.7947, 262.1440, -345.4293, 246.7840],- [392.1920, 144.2067, -137.2160, 265.9225],- ],- device=device,- dtype=dtype,- )-- 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 = kornia.transform_bbox(trans_mat, boxes, mode='xywh')- assert_close(out, expected, atol=1e-4, rtol=1e-4)-- def test_gradcheck(self, device, dtype):-- boxes = torch.tensor(- [- [139.2640, 103.0150, 258.0480, 307.5075],- [1.0240, 80.5547, 510.9760, 431.4453],- [165.2053, 262.1440, 345.4293, 246.7840],- [119.8080, 144.2067, 137.2160, 265.9225],- ],- device=device,- dtype=dtype,- )-- 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)-- trans_mat = utils.tensor_to_gradcheck_var(trans_mat)- boxes = utils.tensor_to_gradcheck_var(boxes)-- assert gradcheck(kornia.transform_bbox, (trans_mat, boxes), raise_exception=True)-- def test_jit(self, device, dtype):- boxes = torch.tensor([[139.2640, 103.0150, 258.0480, 307.5075]], device=device, dtype=dtype)- 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)- args = (boxes, trans_mat)- op = kornia.geometry.transform_points- op_jit = torch.jit.script(op)- assert_close(op(*args), op_jit(*args))diff --git a/test/geometry/transform/crop/test_crop2d.py b/test/geometry/transform/test_crop2d.pysimilarity index 87%rename from test/geometry/transform/crop/test_crop2d.pyrename to test/geometry/transform/test_crop2d.pyindex b444f7d57..436a1c90c 100644--- a/test/geometry/transform/crop/test_crop2d.py+++ b/test/geometry/transform/test_crop2d.py@@ -21,7 +21,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# default should use align_coners True- patches = kornia.crop_and_resize(inp, boxes, (height, width))+ patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (height, width))assert_close(patches, expected, rtol=1e-4, atol=1e-4)def test_align_corners_false(self, device, dtype):@@ -36,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.crop_and_resize(inp, boxes, (height, width), align_corners=False)+ patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (height, width), align_corners=False)assert_close(patches, expected, rtol=1e-4, atol=1e-4)def test_crop_batch(self, device, dtype):@@ -59,7 +59,7 @@ class TestCropAndResize:dtype=dtype,) # 2x4x2- patches = kornia.crop_and_resize(inp, boxes, (2, 2))+ patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (2, 2))assert_close(patches, expected, rtol=1e-4, atol=1e-4)def test_crop_batch_broadcast(self, device, dtype):@@ -78,7 +78,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.crop_and_resize(inp, boxes, (2, 2))+ patches = kornia.geometry.transform.crop_and_resize(inp, boxes, (2, 2))assert_close(patches, expected, rtol=1e-4, atol=1e-4)def test_gradcheck(self, device, dtype):@@ -88,11 +88,11 @@ 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) # 1x4x2boxes = utils.tensor_to_gradcheck_var(boxes, requires_grad=False) # to var- assert gradcheck(kornia.crop_and_resize, (img, boxes, (4, 2)), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.crop_and_resize, (img, boxes, (4, 2)), raise_exception=True)def test_jit(self, device, dtype):# Define script- op = kornia.crop_and_resize+ op = kornia.geometry.transform.crop_and_resizeop_script = torch.jit.script(op)# Define inputimg = torch.tensor(@@ -118,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.center_crop(inp, (2, 4))+ out_crop = kornia.geometry.transform.center_crop(inp, (2, 4))assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)def test_center_crop_h4_w2(self, device, dtype):@@ -131,7 +131,7 @@ class TestCenterCrop:height, width = 4, 2expected = 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.center_crop(inp, (height, width))+ out_crop = kornia.geometry.transform.center_crop(inp, (height, width))assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)def test_center_crop_h4_w2_batch(self, device, dtype):@@ -153,18 +153,18 @@ class TestCenterCrop:dtype=dtype,)- out_crop = kornia.center_crop(inp, (4, 2))+ out_crop = kornia.geometry.transform.center_crop(inp, (4, 2))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- assert gradcheck(kornia.center_crop, (img, (4, 2)), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.center_crop, (img, (4, 2)), raise_exception=True)def test_jit(self, device, dtype):# Define script- op = kornia.center_crop+ op = kornia.geometry.transform.center_cropop_script = torch.jit.script(op)# Define inputimg = torch.ones(1, 2, 5, 4, device=device, dtype=dtype)@@ -175,7 +175,7 @@ class TestCenterCrop:def test_jit_trace(self, device, dtype):# Define script- op = kornia.center_crop+ op = kornia.geometry.transform.center_cropop_script = torch.jit.script(op)# Define inputimg = torch.ones(2, 1, 6, 3, device=device, dtype=dtype)@@ -201,7 +201,7 @@ class TestCropByBoxes:expected = torch.tensor([[[[6.0, 7.0], [10.0, 11.0]]]], device=device, dtype=dtype)- patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst)+ patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst)assert_close(patches, expected)def test_crop_by_boxes_resizing(self, device, dtype):@@ -217,7 +217,7 @@ 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.crop_by_boxes(inp, src, dst)+ patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst)assert_close(patches, expected, rtol=1e-4, atol=1e-4)def test_gradcheck(self, device, dtype):@@ -227,7 +227,7 @@ class TestCropByBoxes:inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var- assert gradcheck(kornia.geometry.transform.crop.crop_by_boxes, (inp, src, dst), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.crop_by_boxes, (inp, src, dst), raise_exception=True)class TestCropByTransform:@@ -244,7 +244,7 @@ class TestCropByTransform:expected = torch.tensor([[[[6.0, 7.0], [10.0, 11.0]]]], device=device, dtype=dtype)- patches = kornia.geometry.transform.crop.crop_by_transform_mat(inp, transform, (2, 2))+ patches = kornia.geometry.transform.crop_by_transform_mat(inp, transform, (2, 2))assert_close(patches, expected)def test_crop_by_boxes_resizing(self, device, dtype):@@ -260,7 +260,7 @@ 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.crop_by_transform_mat(inp, transform, (2, 3))+ patches = kornia.geometry.transform.crop_by_transform_mat(inp, transform, (2, 3))assert_close(patches, expected, rtol=1e-4, atol=1e-4)def test_gradcheck(self, device, dtype):@@ -272,5 +272,5 @@ class TestCropByTransform:inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to varassert gradcheck(- kornia.geometry.transform.crop.crop_by_transform_mat, (inp, transform, (2, 2)), raise_exception=True+ kornia.geometry.transform.crop_by_transform_mat, (inp, transform, (2, 2)), raise_exception=True)diff --git a/test/geometry/transform/crop/test_crop3d.py b/test/geometry/transform/test_crop3d.pysimilarity index 89%rename from test/geometry/transform/crop/test_crop3d.pyrename to test/geometry/transform/test_crop3d.pyindex 418205bfc..23dc9f9e7 100644--- a/test/geometry/transform/crop/test_crop3d.py+++ b/test/geometry/transform/test_crop3d.py@@ -24,7 +24,7 @@ class TestCropAndResize3D:dtype=dtype,) # 1x8x3- patches = kornia.crop_and_resize3d(inp, boxes, (depth, height, width))+ patches = kornia.geometry.transform.crop_and_resize3d(inp, boxes, (depth, height, width))assert_close(patches, expected)def test_crop_batch(self, device, dtype):@@ -55,7 +55,7 @@ class TestCropAndResize3D:dtype=dtype,) # 2x8x3- patches = kornia.crop_and_resize3d(inp, boxes, (depth, height, width), align_corners=True)+ patches = kornia.geometry.transform.crop_and_resize3d(inp, boxes, (depth, height, width), align_corners=True)assert_close(patches, expected)def test_gradcheck(self, device, dtype):@@ -69,11 +69,11 @@ class TestCropAndResize3D:) # 1x8x3boxes = utils.tensor_to_gradcheck_var(boxes, requires_grad=False) # to var- assert gradcheck(kornia.crop_and_resize3d, (img, boxes, (4, 3, 2)), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.crop_and_resize3d, (img, boxes, (4, 3, 2)), raise_exception=True)def test_jit(self, device, dtype):# Define script- op = kornia.crop_and_resize3d+ op = kornia.geometry.transform.crop_and_resize3dop_script = torch.jit.script(op)img = torch.arange(0.0, 64.0, device=device, dtype=dtype).view(1, 1, 4, 4, 4)@@ -100,7 +100,7 @@ class TestCenterCrop3D:(inp.size(3) // 2 - crop_size[1] // 2) : (inp.size(3) // 2 + crop_size[1] // 2 + 1),(inp.size(4) // 2 - crop_size[2] // 2) : (inp.size(4) // 2 + crop_size[2] // 2 + 1),]- out_crop = kornia.center_crop3d(inp, crop_size, align_corners=True)+ out_crop = kornia.geometry.transform.center_crop3d(inp, crop_size, align_corners=True)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)])@@ -118,23 +118,23 @@ class TestCenterCrop3D:(inp.size(3) // 2 - crop_size[1] // 2) : (inp.size(3) // 2 + crop_size[1] // 2 + 1),(inp.size(4) // 2 - crop_size[2] // 2) : (inp.size(4) // 2 + crop_size[2] // 2 + 1),]- out_crop = kornia.center_crop3d(inp, crop_size, align_corners=True)+ out_crop = kornia.geometry.transform.center_crop3d(inp, crop_size, align_corners=True)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- assert gradcheck(kornia.center_crop3d, (img, (3, 5, 7)), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.center_crop3d, (img, (3, 5, 7)), raise_exception=True)def test_jit(self, device, dtype):# Define script- op = kornia.center_crop3d+ op = kornia.geometry.transform.center_crop3dop_script = torch.jit.script(op)img = torch.ones(4, 3, 5, 6, 7, device=device, dtype=dtype)actual = op_script(img, (4, 3, 2))- expected = kornia.center_crop3d(img, (4, 3, 2))+ expected = kornia.geometry.transform.center_crop3d(img, (4, 3, 2))assert_close(actual, expected, rtol=1e-4, atol=1e-4)@@ -176,7 +176,7 @@ class TestCropByBoxes3D:expected = inp[:, :, 1:3, 1:4, 1:4]- patches = kornia.geometry.transform.crop.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)+ 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)def test_crop_by_boxes_resizing(self, device, dtype):@@ -220,12 +220,12 @@ class TestCropByBoxes3D:dtype=dtype,)- patches = kornia.geometry.transform.crop.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)+ 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)def test_jit(self, device, dtype):# Define script- op = kornia.geometry.transform.crop.crop_by_boxes3d+ op = kornia.geometry.transform.crop_by_boxes3dop_script = torch.jit.script(op)# Define inputinp = torch.randn((1, 1, 7, 7, 7), device=device, dtype=dtype)@@ -303,4 +303,4 @@ class TestCropByBoxes3D:inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var- assert gradcheck(kornia.geometry.transform.crop.crop_by_boxes3d, (inp, src_box, dst_box), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.crop_by_boxes3d, (inp, src_box, dst_box), raise_exception=True)diff --git a/test/geometry/transform/test_flip.py b/test/geometry/transform/test_flip.pyindex 236293c9d..b6b29733e 100644--- a/test/geometry/transform/test_flip.py+++ b/test/geometry/transform/test_flip.py@@ -9,13 +9,13 @@ from kornia.testing import assert_closeclass TestVflip:def smoke_test(self, device, dtype):- f = kornia.Vflip()+ f = kornia.geometry.transform.Vflip()repr = "Vflip()"assert str(f) == reprdef test_vflip(self, device, dtype):- f = kornia.Vflip()+ f = kornia.geometry.transform.Vflip()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 3expected = torch.tensor(@@ -30,7 +30,7 @@ class TestVflip:input = input.repeat(2, 1, 1) # 2 x 3 x 3- f = kornia.Vflip()+ f = kornia.geometry.transform.Vflip()expected = torch.tensor([[[0.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]], device=device, dtype=dtype) # 1 x 3 x 3@@ -44,7 +44,7 @@ class TestVflip:@torch.jit.scriptdef op_script(data: torch.Tensor) -> torch.Tensor:- return kornia.vflip(data)+ return kornia.geometry.transform.vflip(data)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@@ -72,18 +72,18 @@ class TestVflip:input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.Vflip(), (input,), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.Vflip(), (input,), raise_exception=True)class TestHflip:def smoke_test(self, device, dtype):- f = kornia.Hflip()+ f = kornia.geometry.transform.Hflip()repr = "Hflip()"assert str(f) == reprdef test_hflip(self, device, dtype):- f = kornia.Hflip()+ f = kornia.geometry.transform.Hflip()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 3expected = torch.tensor(@@ -100,7 +100,7 @@ class TestHflip:input = input.repeat(2, 1, 1) # 2 x 3 x 3- f = kornia.Hflip()+ f = kornia.geometry.transform.Hflip()expected = torch.tensor([[[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@@ -114,7 +114,7 @@ class TestHflip:@torch.jit.scriptdef op_script(data: torch.Tensor) -> torch.Tensor:- return kornia.hflip(data)+ return kornia.geometry.transform.hflip(data)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@@ -142,18 +142,18 @@ class TestHflip:input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.Hflip(), (input,), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.Hflip(), (input,), raise_exception=True)class TestRot180:def smoke_test(self, device, dtype):- f = kornia.Rot180()+ f = kornia.geometry.transform.Rot180()repr = "Rot180()"assert str(f) == reprdef test_rot180(self, device, dtype):- f = kornia.Rot180()+ f = kornia.geometry.transform.Rot180()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 3expected = torch.tensor(@@ -168,7 +168,7 @@ class TestRot180:input = input.repeat(2, 1, 1) # 2 x 3 x 3- f = kornia.Rot180()+ f = kornia.geometry.transform.Rot180()expected = torch.tensor([[1.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype) # 1 x 3 x 3@@ -182,7 +182,7 @@ class TestRot180:@torch.jit.scriptdef op_script(data: torch.Tensor) -> torch.Tensor:- return kornia.rot180(data)+ return kornia.geometry.transform.rot180(data)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@@ -210,4 +210,4 @@ class TestRot180:input = utils.tensor_to_gradcheck_var(input) # to var- assert gradcheck(kornia.Rot180(), (input,), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.Rot180(), (input,), raise_exception=True)diff --git a/test/geometry/transform/test_homography_warper.py b/test/geometry/transform/test_homography_warper.pyindex 0eef5b6e2..2e338d715 100644--- a/test/geometry/transform/test_homography_warper.py+++ b/test/geometry/transform/test_homography_warper.py@@ -19,7 +19,7 @@ class TestHomographyWarper:dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=3, device=device, dtype=dtype)# instantiate warper- warper = kornia.HomographyWarper(height, width, align_corners=True)+ warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=True)# warp from source to destinationpatch_dst = warper(patch_src, dst_homo_src)@@ -32,13 +32,17 @@ class TestHomographyWarper: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 (kornia.normal_transform_pixel(height, width, device=device, dtype=dtype) == res).all()+ assert (+ kornia.geometry.transform.normal_transform_pixel(height, width, device=device, dtype=dtype) == res+ ).all()- norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height, width))+ norm_homo = kornia.geometry.transform.normalize_homography(dst_homo_src, (height, width), (height, width))assert (norm_homo == dst_homo_src).all()# change output scale- norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height * 2, width // 2))+ norm_homo = kornia.geometry.transform.normalize_homography(+ dst_homo_src, (height, width), (height * 2, width // 2)+ )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)@@ -51,13 +55,17 @@ class TestHomographyWarper: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 (kornia.normal_transform_pixel(height, width, device=device, dtype=dtype) == res).all()+ assert (+ kornia.geometry.transform.normal_transform_pixel(height, width, device=device, dtype=dtype) == res+ ).all()- denorm_homo = kornia.denormalize_homography(dst_homo_src, (height, width), (height, width))+ denorm_homo = kornia.geometry.transform.denormalize_homography(dst_homo_src, (height, width), (height, width))assert (denorm_homo == dst_homo_src).all()# change output scale- denorm_homo = kornia.denormalize_homography(dst_homo_src, (height, width), (height * 2, width // 2))+ denorm_homo = kornia.geometry.transform.denormalize_homography(+ dst_homo_src, (height, width), (height * 2, width // 2)+ )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)@@ -74,7 +82,7 @@ class TestHomographyWarper:dst_homo_src[..., 1, 2] = 2.0dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)- norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height, width))+ norm_homo = kornia.geometry.transform.normalize_homography(dst_homo_src, (height, width), (height, width))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)assert (norm_homo == res).all()@@ -89,7 +97,7 @@ class TestHomographyWarper:dst_homo_src[..., 1, 2] = 2.0dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)- denorm_homo = kornia.denormalize_homography(dst_homo_src, (height, width), (height, width))+ denorm_homo = kornia.geometry.transform.denormalize_homography(dst_homo_src, (height, width), (height, width))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)assert (denorm_homo == res).all()@@ -104,11 +112,11 @@ class TestHomographyWarper:dst_homo_src[..., 1, 2] = 2.0dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)- denorm_homo = kornia.denormalize_homography(dst_homo_src, (height, width), (height, width))- norm_denorm_homo = kornia.normalize_homography(denorm_homo, (height, width), (height, width))+ denorm_homo = kornia.geometry.transform.denormalize_homography(dst_homo_src, (height, width), (height, width))+ norm_denorm_homo = kornia.geometry.transform.normalize_homography(denorm_homo, (height, width), (height, width))assert (dst_homo_src == norm_denorm_homo).all()- norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height, width))- denorm_norm_homo = kornia.denormalize_homography(norm_homo, (height, width), (height, width))+ norm_homo = kornia.geometry.transform.normalize_homography(dst_homo_src, (height, width), (height, width))+ denorm_norm_homo = kornia.geometry.transform.denormalize_homography(norm_homo, (height, width), (height, width))assert (dst_homo_src == denorm_norm_homo).all()@pytest.mark.parametrize("offset", [1, 3, 7])@@ -118,8 +126,8 @@ class TestHomographyWarper:height, width = shapedst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=3, device=device, dtype=dtype)dst_homo_src[..., 0, 2] = offset # apply offset in x- grid = kornia.create_meshgrid(height, width, normalized_coordinates=False)- flow = kornia.warp_grid(grid, dst_homo_src)+ 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.@@ -134,7 +142,7 @@ class TestHomographyWarper:dst_homo_src = utils.create_eye_batch(batch_size, eye_size=3, device=device, dtype=dtype)# instantiate warper warp from source to destination- warper = kornia.HomographyWarper(height // 2, width // 2, align_corners=True)+ warper = kornia.geometry.transform.HomographyWarper(height // 2, width // 2, align_corners=True)patch_dst = warper(patch_src, dst_homo_src)# check the corners@@ -153,7 +161,7 @@ class TestHomographyWarper:dst_homo_src[..., 0, 2] = offset / (width - 1) # apply offset in x# instantiate warper and from source to destination- warper = kornia.HomographyWarper(height, width, align_corners=True)+ 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)@@ -171,7 +179,7 @@ class TestHomographyWarper:dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)# instantiate warper and warp from source to destination- warper = kornia.HomographyWarper(height, width, align_corners=True)+ warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=True)patch_dst = warper(patch_src, dst_homo_src)# check the corners@@ -192,7 +200,7 @@ class TestHomographyWarper:dst_homo_src = utils.create_eye_batch(batch_size, eye_size, device=device, dtype=dtype)# instantiate warper- warper = kornia.HomographyWarper(height, width, align_corners=True)+ warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=True)for _ in range(self.num_tests):# generate homography noise@@ -215,7 +223,7 @@ class TestHomographyWarper:assert error.item() < self.threshold# check functional api- patch_dst_to_src_functional = kornia.homography_warp(+ patch_dst_to_src_functional = kornia.geometry.transform.homography_warp(patch_dst, _torch_inverse_cast(dst_homo_src_i), (height, width), align_corners=True)@@ -236,7 +244,7 @@ class TestHomographyWarper:dst_homo_src = utils.tensor_to_gradcheck_var(dst_homo_src, requires_grad=False) # to var# instantiate warper- warper = kornia.HomographyWarper(height, width, align_corners=True)+ warper = kornia.geometry.transform.HomographyWarper(height, width, align_corners=True)# evaluate function gradientassert gradcheck(warper, (patch_src, dst_homo_src), raise_exception=True)@@ -261,14 +269,14 @@ class TestHomographyWarper:dst_homo_src_i = dst_homo_src + homo_delta# transform the points with and without jit- patch_dst = kornia.homography_warp(+ patch_dst = kornia.geometry.transform.homography_warp(patch_src,dst_homo_src_i,(height, width),align_corners=align_corners,normalized_coordinates=normalized_coordinates,)- patch_dst_jit = torch.jit.script(kornia.homography_warp)(+ patch_dst_jit = torch.jit.script(kornia.geometry.transform.homography_warp)(patch_src,dst_homo_src_i,(height, width),@@ -294,42 +302,42 @@ class TestHomographyNormalTransform:@pytest.mark.parametrize("height,width,expected", [(2, 5, expected_2d_0), (1, 5, expected_2d_1)])def test_transform2d(self, height, width, expected, device, dtype):- output = kornia.normal_transform_pixel(height, width, device=device, dtype=dtype)+ output = kornia.geometry.transform.normal_transform_pixel(height, width, device=device, dtype=dtype)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])def test_divide_by_zero2d(self, height, width, device, dtype):- output = kornia.normal_transform_pixel(height, width, device=device, dtype=dtype)+ output = kornia.geometry.transform.normal_transform_pixel(height, width, device=device, dtype=dtype)assert torch.isinf(output).sum().item() == 0def test_transform2d_apply(self, device, dtype):height, width = 2, 5input = torch.tensor([[0.0, 0.0], [width - 1, height - 1]], device=device, dtype=dtype)expected = torch.tensor([[-1.0, -1.0], [1.0, 1.0]], device=device, dtype=dtype)- transform = kornia.normal_transform_pixel(height, width, device=device, dtype=dtype)- output = kornia.transform_points(transform, input)+ transform = kornia.geometry.transform.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)@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.normal_transform_pixel3d(depth, height, width, device=device, dtype=dtype)+ output = kornia.geometry.transform.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)@pytest.mark.parametrize("height", [1, 2, 5])@pytest.mark.parametrize("width", [1, 2, 5])@pytest.mark.parametrize("depth", [1, 2, 5])def test_divide_by_zero3d(self, height, width, depth, device, dtype):- output = kornia.normal_transform_pixel3d(depth, height, width, device=device, dtype=dtype)+ output = kornia.geometry.transform.normal_transform_pixel3d(depth, height, width, device=device, dtype=dtype)assert torch.isinf(output).sum().item() == 0def test_transform3d_apply(self, device, dtype):depth, height, width = 3, 2, 5input = torch.tensor([[0.0, 0.0, 0.0], [width - 1, height - 1, depth - 1]], device=device, dtype=dtype)expected = torch.tensor([[-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]], device=device, dtype=dtype)- transform = kornia.normal_transform_pixel3d(depth, height, width, device=device, dtype=dtype)- output = kornia.transform_points(transform, input)+ transform = kornia.geometry.transform.normal_transform_pixel3d(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)@@ -348,19 +356,23 @@ class TestHomographyWarper3D:device=device,dtype=dtype,)- norm = kornia.normal_transform_pixel3d(input_shape[0], input_shape[1], input_shape[2]).to(+ norm = kornia.geometry.transform.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_homo = kornia.normalize_homography3d(dst_homo_src, input_shape, input_shape).to(device=device, dtype=dtype)+ norm_homo = kornia.geometry.transform.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)- norm_homo = kornia.normalize_homography3d(dst_homo_src, input_shape, input_shape).to(device=device, dtype=dtype)+ norm_homo = kornia.geometry.transform.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)# change output scale- norm_homo = kornia.normalize_homography3d(+ norm_homo = kornia.geometry.transform.normalize_homography3d(dst_homo_src, input_shape, (input_shape[0] // 2, input_shape[1] * 2, input_shape[2] // 2)).to(device=device, dtype=dtype)res = torch.tensor(@@ -382,7 +394,7 @@ class TestHomographyWarper3D:dst_homo_src[..., 2, 3] = 3.0dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)- norm_homo = kornia.normalize_homography3d(dst_homo_src, (2, 2, 5), (2, 2, 5))+ norm_homo = kornia.geometry.transform.normalize_homography3d(dst_homo_src, (2, 2, 5), (2, 2, 5))res = torch.tensor([[[0.5, 0.0, 0.0, 0.0], [0.0, 0.5, 0.0, 3.5], [0.0, 0.0, 2.0, 7.0], [0.0, 0.0, 0.0, 1.0]]],device=device,@@ -397,8 +409,8 @@ class TestHomographyWarper3D:depth, height, width = shapedst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=4, device=device, dtype=dtype)dst_homo_src[..., 0, 3] = offset # apply offset in x- grid = kornia.create_meshgrid3d(depth, height, width, normalized_coordinates=False)- flow = kornia.warp_grid3d(grid, dst_homo_src)+ 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.diff --git a/test/geometry/transform/test_image_registrator.py b/test/geometry/transform/test_image_registrator.pyindex 774fe0913..678689818 100644--- a/test/geometry/transform/test_image_registrator.py+++ b/test/geometry/transform/test_image_registrator.py@@ -1,6 +1,5 @@import pytestimport torch-from torch.autograd import gradcheckimport korniaimport kornia.testing as utils # test utils@@ -26,12 +25,8 @@ class TestSimilarity:sc = 0.5sim = kornia.geometry.transform.Similarity(True, True, True).to(device, dtype)sim.scale.data *= sc- expected = torch.tensor([[0.5, 0, 0.],- [0, 0.5, 0],- [0, 0, 1]], device=device, dtype=dtype)[None]- inv_expected = torch.tensor([[2.0, 0, 0.],- [0, 2.0, 0],- [0, 0, 1]], device=device, dtype=dtype)[None]+ 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)@@ -59,11 +54,7 @@ class TestHomography:class TestImageRegistrator:def test_smoke(self, device, dtype):- for model_type in ['homography',- 'similarity',- 'translation',- 'scale',- 'rotation']:+ for model_type in ['homography', 'similarity', 'translation', 'scale', 'rotation']:ir = kornia.geometry.transform.ImageRegistrator(model_type).to(device, dtype)assert ir is not None@@ -74,28 +65,17 @@ class TestImageRegistrator:homography[..., 1, 1] = 1.05homography[..., 0, 2] = 0.01img_src = torch.rand(1, ch, height, width, device=device, dtype=dtype)- 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)+ 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)- model, intermediate = IR.register(img_src,- img_dst,- output_intermediate_models=True)+ model, intermediate = IR.register(img_src, img_dst, output_intermediate_models=True)assert len(intermediate) == 2@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)def test_registration_real(self, device, dtype, data):data_dev = utils.dict_to(data, device, dtype)- IR = ImageRegistrator('homography',- num_iterations=1200,- lr=2e-2,- pyramid_levels=5).to(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'])homography_gt = homography_gt / homography_gt[2, 2]@@ -105,10 +85,7 @@ class TestImageRegistrator:model_denormalized = denormalize_homography(model, (h0, w0), (h1, w1))model_denormalized = model_denormalized / model_denormalized[0, 2, 2]- bbox = torch.tensor([[[0, 0],- [w0, 0],- [w0, h0],- [0, h0]]], device=device, dtype=dtype)+ bbox = torch.tensor([[[0, 0], [w0, 0], [w0, h0], [0, h0]]], device=device, dtype=dtype)bbox_in_2_gt = transform_points(homography_gt[None], bbox)bbox_in_2_gt_est = transform_points(model_denormalized, bbox)# The tolerance is huge, because the error is in pixelsdiff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.pyindex 1627650eb..c12d33436 100644--- a/test/geometry/transform/test_imgwarp.py+++ b/test/geometry/transform/test_imgwarp.py@@ -151,7 +151,7 @@ class TestWarpAffine:img_a = kornia.geometry.warp_affine(img_b, aff_ab, (h, w))# invert the transform- aff_ba = kornia.convert_affinematrix_to_homography(aff_ab).inverse()[..., :2, :]+ aff_ba = kornia.geometry.conversions.convert_affinematrix_to_homography(aff_ab).inverse()[..., :2, :]img_b_hat = kornia.geometry.warp_affine(img_a, aff_ba, (h, w))assert_close(img_b_hat, img_b, atol=1e-3, rtol=1e-3)@@ -428,8 +428,9 @@ class TestRemap: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- assert gradcheck(kornia.geometry.remap, (img, grid[..., 0], grid[..., 1], 'bilinear', 'zeros', True),- raise_exception=True)+ assert gradcheck(+ kornia.geometry.remap, (img, grid[..., 0], grid[..., 1], 'bilinear', 'zeros', True), raise_exception=True+ )def test_jit(self, device, dtype):batch_size, channels, height, width = 1, 1, 3, 4diff --git a/test/geometry/transform/test_projwarp.py b/test/geometry/transform/test_projwarp.pyindex b253ad188..5b86c913c 100644--- a/test/geometry/transform/test_projwarp.py+++ b/test/geometry/transform/test_projwarp.py@@ -288,21 +288,25 @@ class TestPerspectiveTransform3D:points_dst = points_src + norm# compute transform from source to target- dst_homo_src = kornia.get_perspective_transform3d(points_src, points_dst)+ dst_homo_src = kornia.geometry.transform.get_perspective_transform3d(points_src, points_dst)# 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(kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-4, atol=1e-4)+ assert_close(+ kornia.geometry.linalg.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-4, atol=1e-4+ )# compute gradient checkpoints_src = utils.tensor_to_gradcheck_var(points_src) # to varpoints_dst = utils.tensor_to_gradcheck_var(points_dst) # to var- assert gradcheck(kornia.get_perspective_transform3d, (points_src, points_dst), raise_exception=True)+ assert gradcheck(+ kornia.geometry.transform.get_perspective_transform3d, (points_src, points_dst), raise_exception=True+ )@pytest.mark.parametrize("batch_size", [1, 2])def test_get_perspective_transform3d_2(self, batch_size, device, dtype):torch.manual_seed(0)- src = kornia.bbox_generator3d(+ src = kornia.geometry.bbox.bbox_generator3d(torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),@@ -310,7 +314,7 @@ class TestPerspectiveTransform3D:torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),).to(device=device, dtype=dtype)- dst = kornia.bbox_generator3d(+ dst = kornia.geometry.bbox.bbox_generator3d(torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),@@ -318,7 +322,7 @@ class TestPerspectiveTransform3D:torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),).to(device=device, dtype=dtype)- out = kornia.get_perspective_transform3d(src, dst)+ out = kornia.geometry.transform.get_perspective_transform3d(src, dst)if batch_size == 1:expected = torch.tensor([@@ -357,4 +361,6 @@ class TestPerspectiveTransform3D:# compute gradient checkpoints_src = utils.tensor_to_gradcheck_var(src) # to varpoints_dst = utils.tensor_to_gradcheck_var(dst) # to var- assert gradcheck(kornia.get_perspective_transform3d, (points_src, points_dst), raise_exception=True)+ assert gradcheck(+ kornia.geometry.transform.get_perspective_transform3d, (points_src, points_dst), raise_exception=True+ )diff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.pyindex 85e05872c..0e5e1f698 100644--- a/test/geometry/transform/test_pyramid.py+++ b/test/geometry/transform/test_pyramid.py@@ -126,7 +126,7 @@ class TestScalePyramid:class TestBuildPyramid:def test_smoke(self, device, dtype):input = torch.ones(1, 2, 4, 5, device=device, dtype=dtype)- pyramid = kornia.build_pyramid(input, max_level=1)+ pyramid = kornia.geometry.transform.build_pyramid(input, max_level=1)assert len(pyramid) == 1assert pyramid[0].shape == (1, 2, 4, 5)@@ -136,7 +136,7 @@ class TestBuildPyramid:def test_num_levels(self, batch_size, channels, max_level, device, dtype):height, width = 16, 20input = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)- pyramid = kornia.build_pyramid(input, max_level)+ pyramid = kornia.geometry.transform.build_pyramid(input, max_level)assert len(pyramid) == max_levelfor i in range(1, max_level):img = pyramid[i]@@ -149,4 +149,4 @@ class TestBuildPyramid:batch_size, channels, height, width = 1, 2, 7, 9img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = utils.tensor_to_gradcheck_var(img) # to var- assert gradcheck(kornia.build_pyramid, (img, max_level), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.build_pyramid, (img, max_level), raise_exception=True)diff --git a/test/geometry/transform/test_thin_plate_spline.py b/test/geometry/transform/test_thin_plate_spline.pyindex 121cd1e1f..3030da72b 100644--- a/test/geometry/transform/test_thin_plate_spline.py+++ b/test/geometry/transform/test_thin_plate_spline.py@@ -4,6 +4,7 @@ from torch.autograd import gradcheckimport korniafrom kornia.testing import assert_close+from kornia.utils._compat import torch_version_geqdef _sample_points(batch_size, device, dtype=torch.float32):@@ -17,13 +18,13 @@ class TestTransformParameters:@pytest.mark.parametrize('batch_size', [1, 3])def test_smoke(self, batch_size, device, dtype):src = torch.rand(batch_size, 4, 2, device=device)- out = kornia.get_tps_transform(src, src)+ out = kornia.geometry.transform.get_tps_transform(src, src)assert len(out) == 2@pytest.mark.parametrize('batch_size', [1, 3])def test_no_warp(self, batch_size, device, dtype):src = torch.rand(batch_size, 5, 2, device=device)- kernel, affine = kornia.get_tps_transform(src, src)+ kernel, affine = kornia.geometry.transform.get_tps_transform(src, src)target_kernel = torch.zeros(batch_size, 5, 2, device=device)target_affine = torch.zeros(batch_size, 3, 2, device=device)target_affine[:, [1, 2], [0, 1]] = 1.0@@ -36,18 +37,18 @@ class TestTransformParameters:batch_size, 1, 1)dst = src.clone() * 2.0- kernel, _ = kornia.get_tps_transform(src, dst)+ kernel, _ = kornia.geometry.transform.get_tps_transform(src, dst)assert_close(kernel, torch.zeros_like(kernel), atol=1e-4, rtol=1e-4)@pytest.mark.parametrize('batch_size', [1, 3])def test_exception(self, batch_size, device, dtype):with pytest.raises(TypeError):src = torch.rand(batch_size, 5, 2).numpy()- assert kornia.get_tps_transform(src, src)+ assert kornia.geometry.transform.get_tps_transform(src, src)with pytest.raises(ValueError):src = torch.rand(batch_size, 5)- assert kornia.get_tps_transform(src, src)+ assert kornia.geometry.transform.get_tps_transform(src, src)@pytest.mark.grad@pytest.mark.parametrize('batch_size', [1, 3])@@ -57,13 +58,13 @@ class TestTransformParameters:src, dst = _sample_points(batch_size, **opts)src.requires_grad_(requires_grad)dst.requires_grad_(not requires_grad)- assert gradcheck(kornia.get_tps_transform, (src, dst), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.get_tps_transform, (src, dst), raise_exception=True)@pytest.mark.jit@pytest.mark.parametrize('batch_size', [1, 3])def test_jit(self, batch_size, device, dtype):src, dst = _sample_points(batch_size, device)- op = kornia.get_tps_transform+ op = kornia.geometry.transform.get_tps_transformop_jit = torch.jit.script(op)op_output = op(src, dst)jit_output = op_jit(src, dst)@@ -75,15 +76,15 @@ class TestWarpPoints:@pytest.mark.parametrize('batch_size', [1, 3])def test_smoke(self, batch_size, device, dtype):src, dst = _sample_points(batch_size, device)- kernel, affine = kornia.get_tps_transform(src, dst)- warp = kornia.warp_points_tps(src, dst, kernel, affine)+ kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)+ warp = kornia.geometry.transform.warp_points_tps(src, dst, kernel, affine)assert warp.shape == src.shape@pytest.mark.parametrize('batch_size', [1, 3])def test_warp(self, batch_size, device, dtype):src, dst = _sample_points(batch_size, device)- kernel, affine = kornia.get_tps_transform(src, dst)- warp = kornia.warp_points_tps(src, dst, kernel, affine)+ kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)+ warp = kornia.geometry.transform.warp_points_tps(src, dst, kernel, affine)assert_close(warp, dst, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize('batch_size', [1, 3])@@ -93,32 +94,32 @@ class TestWarpPoints:affine = torch.zeros(batch_size, 3, 2)with pytest.raises(TypeError):- assert kornia.warp_points_tps(src.numpy(), src, kernel, affine)+ assert kornia.geometry.transform.warp_points_tps(src.numpy(), src, kernel, affine)with pytest.raises(TypeError):- assert kornia.warp_points_tps(src, src.numpy(), kernel, affine)+ assert kornia.geometry.transform.warp_points_tps(src, src.numpy(), kernel, affine)with pytest.raises(TypeError):- assert kornia.warp_points_tps(src, src, kernel.numpy(), affine)+ assert kornia.geometry.transform.warp_points_tps(src, src, kernel.numpy(), affine)with pytest.raises(TypeError):- assert kornia.warp_points_tps(src, src, kernel, affine.numpy())+ assert kornia.geometry.transform.warp_points_tps(src, src, kernel, affine.numpy())with pytest.raises(ValueError):src_bad = torch.rand(batch_size, 5)- assert kornia.warp_points_tps(src_bad, src, kernel, affine)+ assert kornia.geometry.transform.warp_points_tps(src_bad, src, kernel, affine)with pytest.raises(ValueError):src_bad = torch.rand(batch_size, 5)- assert kornia.warp_points_tps(src, src_bad, kernel, affine)+ assert kornia.geometry.transform.warp_points_tps(src, src_bad, kernel, affine)with pytest.raises(ValueError):kernel_bad = torch.rand(batch_size, 5)- assert kornia.warp_points_tps(src, src, kernel_bad, affine)+ assert kornia.geometry.transform.warp_points_tps(src, src, kernel_bad, affine)with pytest.raises(ValueError):affine_bad = torch.rand(batch_size, 3)- assert kornia.warp_points_tps(src, src, kernel, affine_bad)+ assert kornia.geometry.transform.warp_points_tps(src, src, kernel, affine_bad)@pytest.mark.grad@pytest.mark.parametrize('batch_size', [1, 3])@@ -126,17 +127,17 @@ class TestWarpPoints:def test_gradcheck(self, batch_size, device, dtype, requires_grad):opts = dict(device=device, dtype=torch.float64)src, dst = _sample_points(batch_size, **opts)- kernel, affine = kornia.get_tps_transform(src, dst)+ kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)kernel.requires_grad_(requires_grad)affine.requires_grad_(not requires_grad)- assert gradcheck(kornia.warp_points_tps, (src, dst, kernel, affine), raise_exception=True)+ assert gradcheck(kornia.geometry.transform.warp_points_tps, (src, dst, kernel, affine), raise_exception=True)@pytest.mark.jit@pytest.mark.parametrize('batch_size', [1, 3])def test_jit(self, batch_size, device, dtype):src, dst = _sample_points(batch_size, device)- kernel, affine = kornia.get_tps_transform(src, dst)- op = kornia.warp_points_tps+ kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)+ op = kornia.geometry.transform.warp_points_tpsop_jit = torch.jit.script(op)assert_close(op(src, dst, kernel, affine), op_jit(src, dst, kernel, affine))@@ -146,10 +147,13 @@ class TestWarpImage:def test_smoke(self, batch_size, device, dtype):src, dst = _sample_points(batch_size, device)tensor = torch.rand(batch_size, 3, 32, 32, device=device)- kernel, affine = kornia.get_tps_transform(src, dst)- warp = kornia.warp_image_tps(tensor, dst, kernel, affine)+ kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)+ warp = kornia.geometry.transform.warp_image_tps(tensor, dst, kernel, affine)assert warp.shape == tensor.shape+ @pytest.mark.skipif(+ torch_version_geq(1, 10),+ reason="for some reason the solver detects singular matrices in pytorch >=1.10.")@pytest.mark.parametrize('batch_size', [1, 3])def test_warp(self, batch_size, device, dtype):src = torch.tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, -1.0], [0.0, 0.0]]], device=device).repeat(@@ -165,8 +169,8 @@ class TestWarpImage:expected[:, :, [0, -1], :] *= 0.5expected[:, :, :, [0, -1]] *= 0.5- kernel, affine = kornia.get_tps_transform(dst, src)- warp = kornia.warp_image_tps(tensor, src, kernel, affine)+ kernel, affine = kornia.geometry.transform.get_tps_transform(dst, src)+ warp = kornia.geometry.transform.warp_image_tps(tensor, src, kernel, affine)assert_close(warp, expected, atol=1e-4, rtol=1e-4)@pytest.mark.parametrize('batch_size', [1, 3])@@ -177,50 +181,54 @@ class TestWarpImage:affine = torch.zeros(batch_size, 3, 2)with pytest.raises(TypeError):- assert kornia.warp_image_tps(image.numpy(), dst, kernel, affine)+ assert kornia.geometry.transform.warp_image_tps(image.numpy(), dst, kernel, affine)with pytest.raises(TypeError):- assert kornia.warp_image_tps(image, dst.numpy(), kernel, affine)+ assert kornia.geometry.transform.warp_image_tps(image, dst.numpy(), kernel, affine)with pytest.raises(TypeError):- assert kornia.warp_image_tps(image, dst, kernel.numpy(), affine)+ assert kornia.geometry.transform.warp_image_tps(image, dst, kernel.numpy(), affine)with pytest.raises(TypeError):- assert kornia.warp_image_tps(image, dst, kernel, affine.numpy())+ assert kornia.geometry.transform.warp_image_tps(image, dst, kernel, affine.numpy())with pytest.raises(ValueError):image_bad = torch.rand(batch_size, 32, 32)- assert kornia.warp_image_tps(image_bad, dst, kernel, affine)+ assert kornia.geometry.transform.warp_image_tps(image_bad, dst, kernel, affine)with pytest.raises(ValueError):dst_bad = torch.rand(batch_size, 5)- assert kornia.warp_image_tps(image, dst_bad, kernel, affine)+ assert kornia.geometry.transform.warp_image_tps(image, dst_bad, kernel, affine)with pytest.raises(ValueError):kernel_bad = torch.rand(batch_size, 5)- assert kornia.warp_image_tps(image, dst, kernel_bad, affine)+ assert kornia.geometry.transform.warp_image_tps(image, dst, kernel_bad, affine)with pytest.raises(ValueError):affine_bad = torch.rand(batch_size, 3)- assert kornia.warp_image_tps(image, dst, kernel, affine_bad)+ assert kornia.geometry.transform.warp_image_tps(image, dst, kernel, affine_bad)@pytest.mark.grad@pytest.mark.parametrize('batch_size', [1, 3])def test_gradcheck(self, batch_size, device, dtype):opts = dict(device=device, dtype=torch.float64)src, dst = _sample_points(batch_size, **opts)- kernel, affine = kornia.get_tps_transform(src, dst)+ kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)image = torch.rand(batch_size, 3, 8, 8, requires_grad=True, **opts)assert gradcheck(- kornia.warp_image_tps, (image, dst, kernel, affine), raise_exception=True, atol=1e-4, rtol=1e-4+ kornia.geometry.transform.warp_image_tps,+ (image, dst, kernel, affine),+ raise_exception=True,+ atol=1e-4,+ rtol=1e-4,)@pytest.mark.jit@pytest.mark.parametrize('batch_size', [1, 3])def test_jit(self, batch_size, device, dtype):src, dst = _sample_points(batch_size, device)- kernel, affine = kornia.get_tps_transform(src, dst)+ kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)image = torch.rand(batch_size, 3, 32, 32, device=device)- op = kornia.warp_image_tps+ op = kornia.geometry.transform.warp_image_tpsop_jit = torch.jit.script(op)assert_close(op(image, dst, kernel, affine), op_jit(image, dst, kernel, affine), rtol=1e-4, atol=1e-4)diff --git a/test/integration/test_conversions.py b/test/integration/test_conversions.pyindex 40c9610e4..11ed43e9d 100644--- a/test/integration/test_conversions.py+++ b/test/integration/test_conversions.py@@ -26,8 +26,10 @@ def rtol(device, dtype):class TestAngleAxisToQuaternionToAngleAxis:def test_zero_angle(self, device, dtype, atol, rtol):angle_axis = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ angle_axis_hat = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.WXYZ+ )assert_close(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -36,8 +38,10 @@ class TestAngleAxisToQuaternionToAngleAxis:array = [0.0, 0.0, 0.0]array[axis] = thetaangle_axis = torch.tensor(array, device=device, dtype=dtype)- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ angle_axis_hat = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.WXYZ+ )assert_close(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -46,8 +50,10 @@ class TestAngleAxisToQuaternionToAngleAxis:array = [0.0, 0.0, 0.0]array[axis] = kornia.pi / 2.0angle_axis = torch.tensor(array, device=device, dtype=dtype)- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ angle_axis_hat = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.WXYZ+ )assert_close(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)@@ -55,15 +61,21 @@ class TestQuaternionToAngleAxisToQuaternion:def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )with pytest.warns(UserWarning):- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion_hat = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)def test_unit_quaternion(self, device, dtype, atol, rtol):quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ quaternion_hat = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -72,9 +84,13 @@ class TestQuaternionToAngleAxisToQuaternion:array[axis] = 1.0quaternion = torch.tensor(array, device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )with pytest.warns(UserWarning):- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion_hat = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -82,13 +98,17 @@ class TestQuaternionToAngleAxisToQuaternion:array = [0.0, 0.0, 0.0, 0.0]array[1 + axis] = 1.0quaternion = torch.tensor(array, device=device, dtype=dtype)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ quaternion_hat = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)# just to be sure, check that mixing orders failswith pytest.warns(UserWarning):- quaternion_hat_wrong = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion_hat_wrong = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert not torch.allclose(quaternion_hat_wrong, quaternion, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -98,9 +118,13 @@ class TestQuaternionToAngleAxisToQuaternion:array[axis] = np.sin(theta / 2.0)quaternion = torch.tensor(array, device=device, dtype=dtype)with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )with pytest.warns(UserWarning):- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion_hat = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -109,13 +133,17 @@ class TestQuaternionToAngleAxisToQuaternion:array = [np.cos(theta / 2), 0.0, 0.0, 0.0]array[1 + axis] = np.sin(theta / 2.0)quaternion = torch.tensor(array, device=device, dtype=dtype)- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ quaternion_hat = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)# just to be sure, check that mixing orders failswith pytest.warns(UserWarning):- quaternion_hat_wrong = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion_hat_wrong = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert not torch.allclose(quaternion_hat_wrong, quaternion, atol=atol, rtol=rtol)@@ -128,11 +156,11 @@ class TestQuaternionToRotationMatrixToAngleAxis:assert quaternion.shape[-1] == 4with pytest.warns(UserWarning):- mm = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)+ mm = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)assert mm.shape[-1] == 3assert mm.shape[-2] == 3- angle_axis = kornia.rotation_matrix_to_angle_axis(mm)+ angle_axis = kornia.geometry.conversions.rotation_matrix_to_angle_axis(mm)assert angle_axis.shape[-1] == 3angle_axis_expected = [[0.0, 0.0, 0.0]]angle_axis_expected[0][axis] = kornia.pi@@ -140,7 +168,9 @@ class TestQuaternionToRotationMatrixToAngleAxis:assert_close(angle_axis, angle_axis_expected, atol=atol, rtol=rtol)with pytest.warns(UserWarning):- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion_hat = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -150,18 +180,20 @@ class TestQuaternionToRotationMatrixToAngleAxis:quaternion = torch.tensor(array, device=device, dtype=dtype)assert quaternion.shape[-1] == 4- mm = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)+ mm = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)assert mm.shape[-1] == 3assert mm.shape[-2] == 3- angle_axis = kornia.rotation_matrix_to_angle_axis(mm)+ angle_axis = kornia.geometry.conversions.rotation_matrix_to_angle_axis(mm)assert angle_axis.shape[-1] == 3angle_axis_expected = [[0.0, 0.0, 0.0]]angle_axis_expected[0][axis] = kornia.piangle_axis_expected = torch.tensor(angle_axis_expected, device=device, dtype=dtype)assert_close(angle_axis, angle_axis_expected, atol=atol, rtol=rtol)- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion_hat = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -172,15 +204,19 @@ class TestQuaternionToRotationMatrixToAngleAxis:assert quaternion.shape[-1] == 4with pytest.warns(UserWarning):- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert angle_axis.shape[-1] == 3- rot_m = kornia.angle_axis_to_rotation_matrix(angle_axis)+ rot_m = kornia.geometry.conversions.angle_axis_to_rotation_matrix(angle_axis)assert rot_m.shape[-1] == 3assert rot_m.shape[-2] == 3with pytest.warns(UserWarning):- quaternion_hat = kornia.rotation_matrix_to_quaternion(rot_m, order=QuaternionCoeffOrder.XYZW)+ quaternion_hat = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ rot_m, order=QuaternionCoeffOrder.XYZW+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -190,14 +226,16 @@ class TestQuaternionToRotationMatrixToAngleAxis:quaternion = torch.tensor(array, device=device, dtype=dtype)assert quaternion.shape[-1] == 4- angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis = kornia.geometry.conversions.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)assert angle_axis.shape[-1] == 3- rot_m = kornia.angle_axis_to_rotation_matrix(angle_axis)+ rot_m = kornia.geometry.conversions.angle_axis_to_rotation_matrix(angle_axis)assert rot_m.shape[-1] == 3assert rot_m.shape[-2] == 3- quaternion_hat = kornia.rotation_matrix_to_quaternion(rot_m, order=QuaternionCoeffOrder.WXYZ)+ quaternion_hat = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ rot_m, order=QuaternionCoeffOrder.WXYZ+ )assert_close(quaternion_hat, quaternion, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -207,16 +245,20 @@ class TestQuaternionToRotationMatrixToAngleAxis:angle_axis = torch.tensor(array, device=device, dtype=dtype)assert angle_axis.shape[-1] == 3- rot_m = kornia.angle_axis_to_rotation_matrix(angle_axis)+ rot_m = kornia.geometry.conversions.angle_axis_to_rotation_matrix(angle_axis)assert rot_m.shape[-1] == 3assert rot_m.shape[-2] == 3with pytest.warns(UserWarning):- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ rot_m, order=QuaternionCoeffOrder.XYZW+ )assert quaternion.shape[-1] == 4with pytest.warns(UserWarning):- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)+ angle_axis_hat = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert_close(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -226,14 +268,16 @@ class TestQuaternionToRotationMatrixToAngleAxis:angle_axis = torch.tensor(array, device=device, dtype=dtype)assert angle_axis.shape[-1] == 3- rot_m = kornia.angle_axis_to_rotation_matrix(angle_axis)+ rot_m = kornia.geometry.conversions.angle_axis_to_rotation_matrix(angle_axis)assert rot_m.shape[-1] == 3assert rot_m.shape[-2] == 3- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(rot_m, order=QuaternionCoeffOrder.WXYZ)assert quaternion.shape[-1] == 4- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)+ angle_axis_hat = kornia.geometry.conversions.quaternion_to_angle_axis(+ quaternion, order=QuaternionCoeffOrder.WXYZ+ )assert_close(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -244,15 +288,19 @@ class TestQuaternionToRotationMatrixToAngleAxis:assert angle_axis.shape[-1] == 3with pytest.warns(UserWarning):- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(+ angle_axis, order=QuaternionCoeffOrder.XYZW+ )assert quaternion.shape[-1] == 4with pytest.warns(UserWarning):- rot_m = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)+ rot_m = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ quaternion, order=QuaternionCoeffOrder.XYZW+ )assert rot_m.shape[-1] == 3assert rot_m.shape[-2] == 3- angle_axis_hat = kornia.rotation_matrix_to_angle_axis(rot_m)+ angle_axis_hat = kornia.geometry.conversions.rotation_matrix_to_angle_axis(rot_m)assert_close(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)@pytest.mark.parametrize("axis", (0, 1, 2))@@ -262,14 +310,14 @@ class TestQuaternionToRotationMatrixToAngleAxis:angle_axis = torch.tensor(array, device=device, dtype=dtype)assert angle_axis.shape[-1] == 3- quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)assert quaternion.shape[-1] == 4- rot_m = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)+ rot_m = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)assert rot_m.shape[-1] == 3assert rot_m.shape[-2] == 3- angle_axis_hat = kornia.rotation_matrix_to_angle_axis(rot_m)+ angle_axis_hat = kornia.geometry.conversions.rotation_matrix_to_angle_axis(rot_m)assert_close(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)@@ -367,7 +415,9 @@ class TestAngleOfRotations:axis_name=axis_name, angle=angle, device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ rot_m, eps=eps, order=QuaternionCoeffOrder.XYZW+ )# compute quaternion rotation angle# See Section 2.4.4 Equation (105a) in https://arxiv.org/pdf/1711.02508.pdfangle_hat = 2.0 * torch.atan2(quaternion[..., :3].norm(p=2, dim=-1, keepdim=True), quaternion[..., 3:4])@@ -395,7 +445,9 @@ class TestAngleOfRotations:rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name, angle=angle, device=device, dtype=dtype)- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ rot_m, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )# compute quaternion rotation angle# See Section 2.4.4 Equation (105a) in https://arxiv.org/pdf/1711.02508.pdfangle_hat = 2.0 * torch.atan2(quaternion[..., 1:4].norm(p=2, dim=-1, keepdim=True), quaternion[..., 0:1])@@ -420,7 +472,7 @@ class TestAngleOfRotations:rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name, angle=angle, device=device, dtype=dtype)- angle_axis = kornia.rotation_matrix_to_angle_axis(rot_m)+ angle_axis = kornia.geometry.conversions.rotation_matrix_to_angle_axis(rot_m)# compute angle_axis rotation angleangle_hat = angle_axis.norm(p=2, dim=-1, keepdim=True)# invert angle, if angle_axis axis points in the opposite direction of the original axis@@ -442,9 +494,13 @@ class TestAngleOfRotations:axis_name=axis_name, angle=angle, device=device, dtype=dtype)with pytest.warns(UserWarning):- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps, order=QuaternionCoeffOrder.XYZW)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ rot_m, eps=eps, order=QuaternionCoeffOrder.XYZW+ )with pytest.warns(UserWarning):- log_q = kornia.quaternion_exp_to_log(quaternion, eps=eps, order=QuaternionCoeffOrder.XYZW)+ log_q = kornia.geometry.conversions.quaternion_exp_to_log(+ quaternion, eps=eps, order=QuaternionCoeffOrder.XYZW+ )# compute angle_axis rotation angleangle_hat = 2.0 * log_q.norm(p=2, dim=-1, keepdim=True)# make sure it lands between [-pi..pi)@@ -470,8 +526,10 @@ class TestAngleOfRotations:rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name, angle=angle, device=device, dtype=dtype)- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps, order=QuaternionCoeffOrder.WXYZ)- log_q = kornia.quaternion_exp_to_log(quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ)+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(+ rot_m, eps=eps, order=QuaternionCoeffOrder.WXYZ+ )+ log_q = kornia.geometry.conversions.quaternion_exp_to_log(quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ)# compute angle_axis rotation angleangle_hat = 2.0 * log_q.norm(p=2, dim=-1, keepdim=True)# make sure it lands between [-pi..pi)diff --git a/test/integration/test_warp.py b/test/integration/test_warp.pyindex da4c2ea5b..4fa8df57b 100644--- a/test/integration/test_warp.py+++ b/test/integration/test_warp.py@@ -31,7 +31,7 @@ class TestWarping:).float()height, width = img_dst_t.shape[-2:]- warper = kornia.HomographyWarper(height, width)+ warper = kornia.geometry.transform.HomographyWarper(height, width)dst_homo_src = MyHomography(init_homo=init_homo).to(device)learning_rate = self.lrdiff --git a/test/losses/test_hd.py b/test/losses/test_hd.pyindex c54f81e12..6f532bed7 100644--- a/test/losses/test_hd.py+++ b/test/losses/test_hd.py@@ -31,9 +31,7 @@ class HausdorffERLossNumpy(nn.Module):self.kernel3D = np.array([bound, cross, bound]).squeeze()[None] * (1 / 7)@torch.no_grad()- def perform_erosion(- self, pred: np.ndarray, target: np.ndarray- ) -> np.ndarray:+ def perform_erosion(self, pred: np.ndarray, target: np.ndarray) -> np.ndarray:bound = (pred - target) ** 2if bound.ndim == 5:@@ -65,9 +63,7 @@ class HausdorffERLossNumpy(nn.Module):return eroted- def forward_one(- self, pred: torch.Tensor, target: torch.Tensor- ) -> torch.Tensor:+ def forward_one(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:"""Uses one binary channel: 1 - fg, 0 - bgpred: (b, 1, x, y, z) or (b, 1, x, y)@@ -76,43 +72,42 @@ class HausdorffERLossNumpy(nn.Module):assert pred.size(1) == target.size(1) == 1# pred = torch.sigmoid(pred)- eroted = torch.from_numpy(- self.perform_erosion(pred.cpu().numpy(), target.cpu().numpy())- ).to(dtype=pred.dtype, device=pred.device)+ eroted = torch.from_numpy(self.perform_erosion(pred.cpu().numpy(), target.cpu().numpy())).to(+ dtype=pred.dtype, device=pred.device+ )loss = eroted.mean()return loss- def forward(- self, pred: torch.Tensor, target: torch.Tensor- ) -> torch.Tensor:+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:"""Uses one binary channel: 1 - fg, 0 - bgpred: (b, 1, x, y, z) or (b, 1, x, y)target: (b, 1, x, y, z) or (b, 1, x, y)"""assert pred.dim() == 4 or pred.dim() == 5, "Only 2D and 3D supported"- assert (- pred.dim() == target.dim() and target.size(1) == 1- ), "Prediction and target need to be of same dimension"- return torch.stack([- self.forward_one(- pred[:, i:i + 1],- torch.where(- target == i,- torch.tensor(1, device=target.device, dtype=target.dtype),- torch.tensor(0, device=target.device, dtype=target.dtype))- ) for i in range(pred.size(1))]).mean()+ assert pred.dim() == target.dim() and target.size(1) == 1, "Prediction and target need to be of same dimension"+ return torch.stack(+ [+ self.forward_one(+ pred[:, i : i + 1],+ torch.where(+ target == i,+ torch.tensor(1, device=target.device, dtype=target.dtype),+ torch.tensor(0, device=target.device, dtype=target.dtype),+ ),+ )+ for i in range(pred.size(1))+ ]+ ).mean()class TestHausdorffLoss:-@pytest.mark.parametrize("reduction", ['mean', 'none', 'sum'])- @pytest.mark.parametrize("hd,shape", [- [kornia.losses.HausdorffERLoss, (10, 10)],- [kornia.losses.HausdorffERLoss3D, (10, 10, 10)],- ])+ @pytest.mark.parametrize(+ "hd,shape", [[kornia.losses.HausdorffERLoss, (10, 10)], [kornia.losses.HausdorffERLoss3D, (10, 10, 10)]]+ )def test_smoke_none(self, hd, shape, reduction, device, dtype):num_classes = 3logits = torch.rand(2, num_classes, *shape, dtype=dtype, device=device)@@ -121,10 +116,9 @@ class TestHausdorffLoss:loss(logits, labels)- @pytest.mark.parametrize("hd,shape", [- [kornia.losses.HausdorffERLoss, (50, 50)],- [kornia.losses.HausdorffERLoss3D, (50, 50, 50)],- ])+ @pytest.mark.parametrize(+ "hd,shape", [[kornia.losses.HausdorffERLoss, (50, 50)], [kornia.losses.HausdorffERLoss3D, (50, 50, 50)]]+ )def test_numeric(self, hd, shape, device, dtype):num_classes = 3logits = torch.rand(2, num_classes, *shape, dtype=dtype, device=device)@@ -136,10 +130,9 @@ class TestHausdorffLoss:actual = loss(logits, labels)assert_close(actual, expected)- @pytest.mark.parametrize("hd,shape", [- [kornia.losses.HausdorffERLoss, (5, 5)],- [kornia.losses.HausdorffERLoss3D, (5, 5, 5)],- ])+ @pytest.mark.parametrize(+ "hd,shape", [[kornia.losses.HausdorffERLoss, (5, 5)], [kornia.losses.HausdorffERLoss3D, (5, 5, 5)]]+ )def test_gradcheck(self, hd, shape, device):num_classes = 3logits = torch.rand(2, num_classes, *shape, device=device)@@ -147,6 +140,4 @@ class TestHausdorffLoss:loss = hd(k=2)logits = utils.tensor_to_gradcheck_var(logits) # to var- assert gradcheck(- loss, (logits, labels,), raise_exception=True- )+ assert gradcheck(loss, (logits, labels), raise_exception=True)diff --git a/test/morphology/test_dilation.py b/test/morphology/test_dilation.pyindex 02ca327fa..4ee69de30 100644--- a/test/morphology/test_dilation.py+++ b/test/morphology/test_dilation.py@@ -40,19 +40,20 @@ class TestDilate:None, None, :, :]assert_close(- dilation(tensor,- torch.ones_like(structural_element),- structuring_element=structural_element,- engine='unfold'),+ dilation(+ tensor, torch.ones_like(structural_element), structuring_element=structural_element, engine='unfold'+ ),expected,atol=1e-3,rtol=1e-3,)assert_close(- dilation(tensor,- torch.ones_like(structural_element),- structuring_element=structural_element,- engine='convolution'),+ dilation(+ tensor,+ torch.ones_like(structural_element),+ structuring_element=structural_element,+ engine='convolution',+ ),expected,atol=1e-3,rtol=1e-3,diff --git a/test/morphology/test_erosion.py b/test/morphology/test_erosion.pyindex 82d6d407d..410f7c660 100644--- a/test/morphology/test_erosion.py+++ b/test/morphology/test_erosion.py@@ -46,10 +46,12 @@ class TestErode:rtol=1e-4,)assert_close(- erosion(tensor,- torch.ones_like(structural_element),- structuring_element=structural_element,- engine='convolution'),+ erosion(+ tensor,+ torch.ones_like(structural_element),+ structuring_element=structural_element,+ engine='convolution',+ ),expected,atol=1e-3,rtol=1e-3,diff --git a/test/test_contrib.py b/test/test_contrib.pyindex b70fad89f..ab7ab625e 100644--- a/test/test_contrib.py+++ b/test/test_contrib.py@@ -17,11 +17,10 @@ class TestVisionTransformer:@pytest.mark.parametrize("image_size", [32, 224])def test_smoke(self, device, dtype, B, H, D, image_size):patch_size = 16- T = image_size**2 // patch_size**2 + 1 # tokens size+ T = image_size ** 2 // patch_size ** 2 + 1 # tokens sizeimg = torch.rand(B, 3, image_size, image_size, device=device, dtype=dtype)- vit = kornia.contrib.VisionTransformer(- image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)+ vit = kornia.contrib.VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)out = vit(img)assert isinstance(out, torch.Tensor) and out.shape == (B, T, D)@@ -34,6 +33,7 @@ class TestVisionTransformer:def test_backbone(self, device, dtype):def backbone_mock(x):return torch.ones(1, 128, 14, 14, device=device, dtype=dtype)+img = torch.rand(1, 3, 32, 32, device=device, dtype=dtype)vit = kornia.contrib.VisionTransformer(backbone=backbone_mock).to(device, dtype)out = vit(img)@@ -50,10 +50,7 @@ class TestMobileViT:channel = {'xxs': 320, 'xs': 384, 's': 640}img = torch.rand(B, 3, ih, iw, device=device, dtype=dtype)- mvit = kornia.contrib.MobileViT(- mode=mode,- patch_size=patch_size- ).to(device, dtype)+ mvit = kornia.contrib.MobileViT(mode=mode, patch_size=patch_size).to(device, dtype)out = mvit(img)assert isinstance(out, torch.Tensor) and out.shape == (B, channel[mode], 8, 8)@@ -74,9 +71,7 @@ class TestConnectedComponents:out = kornia.contrib.connected_components(img, num_iterations=10)assert out.shape == (1, 1, 3, 4)- @pytest.mark.parametrize("shape", [- (1, 3, 4), (2, 1, 3, 4)- ])+ @pytest.mark.parametrize("shape", [(1, 3, 4), (2, 1, 3, 4)])def test_cardinality(self, device, dtype, shape):img = torch.rand(shape, device=device, dtype=dtype)out = kornia.contrib.connected_components(img, num_iterations=10)@@ -251,7 +246,7 @@ class TestExtractTensorPatches:def test_jit(self, device):@torch.jit.scriptdef op_script(img: torch.Tensor, height: int, width: int) -> torch.Tensor:- return kornia.denormalize_pixel_coordinates(img, height, width)+ return kornia.geometry.denormalize_pixel_coordinates(img, height, width)height, width = 3, 4grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True).to(device)@@ -271,39 +266,38 @@ class TestCombineTensorPatches:def test_smoke(self, device, dtype):img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)m = kornia.contrib.CombineTensorPatches((2, 2))- patches = kornia.contrib.extract_tensor_patches(- img, window_size=(2, 2), stride=(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 (img == m(patches)).all()def test_error(self, device, dtype):patches = kornia.contrib.extract_tensor_patches(- torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2), padding=1)+ torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2), padding=1+ )with pytest.raises(NotImplementedError):kornia.contrib.combine_tensor_patches(patches, window_size=(2, 2), stride=(3, 2))def test_padding1(self, device, dtype):img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)- patches = kornia.contrib.extract_tensor_patches(- img, window_size=(2, 2), stride=(2, 2), padding=1)+ patches = kornia.contrib.extract_tensor_patches(img, window_size=(2, 2), stride=(2, 2), padding=1)m = kornia.contrib.CombineTensorPatches((2, 2), unpadding=1)assert m(patches).shape == (1, 1, 4, 4)assert (img == m(patches)).all()def test_gradcheck(self, device, dtype):patches = kornia.contrib.extract_tensor_patches(- torch.arange(16., device=device, dtype=dtype).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2))+ 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 varassert gradcheck(kornia.contrib.combine_tensor_patches, (img, (2, 2), (2, 2)), raise_exception=True)class TestLambdaModule:-def add_2_layer(self, tensor):return tensor + 2def add_x_mul_y(self, tensor, x, y=2):- return torch.mul(tensor + x , y)+ return torch.mul(tensor + x, y)def test_smoke(self, device, dtype):B, C, H, W = 1, 3, 4, 5@@ -326,7 +320,7 @@ class TestLambdaModule:def test_lambda(self, shape, device, dtype):B, C, H, W = shapeimg = torch.rand(B, C, H, W, device=device, dtype=dtype)- func = kornia.bgr_to_grayscale+ func = kornia.color.bgr_to_grayscalelambda_module = kornia.contrib.Lambda(func)out = lambda_module(img)assert isinstance(out, torch.Tensor)@@ -334,12 +328,11 @@ class TestLambdaModule:def test_gradcheck(self, device, dtype):B, C, H, W = 1, 3, 4, 5img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)- func = kornia.bgr_to_grayscale+ func = kornia.color.bgr_to_grayscaleassert gradcheck(kornia.contrib.Lambda(func), (img,), raise_exception=True)class TestImageStitcher:-@pytest.mark.parametrize("estimator", ['ransac', 'vanilla'])def test_smoke(self, estimator, device, dtype):B, C, H, W = 1, 3, 224, 224@@ -349,11 +342,10 @@ class TestImageStitcher:"keypoints0": torch.rand((15, 2), device=device, dtype=dtype),"keypoints1": torch.rand((15, 2), device=device, dtype=dtype),"confidence": torch.rand((15,), device=device, dtype=dtype),- "batch_indexes": torch.zeros((15,), device=device, dtype=dtype)+ "batch_indexes": torch.zeros((15,), device=device, dtype=dtype),}with patch(- 'kornia.contrib.ImageStitcher.on_matcher',- new_callable=PropertyMock, return_value=lambda x: return_value+ 'kornia.contrib.ImageStitcher.on_matcher', new_callable=PropertyMock, return_value=lambda x: return_value):# NOTE: This will need to download the pretrained weights.# To avoid that, we mock as belowdiff --git a/test/test_metrics.py b/test/test_metrics.pyindex b12d2df3e..9a46a5185 100644--- a/test/test_metrics.py+++ b/test/test_metrics.py@@ -42,10 +42,12 @@ class TestMeanIoU:def test_four_classes_2d_perfect(self, device, dtype):batch_size = 1num_classes = 4- actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)- predicted = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)+ actual = torch.tensor(+ [[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )+ predicted = torch.tensor(+ [[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )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)@@ -55,10 +57,12 @@ class TestMeanIoU:def test_four_classes_one_missing(self, device, dtype):batch_size = 1num_classes = 4- actual = torch.tensor([[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)- predicted = torch.tensor([[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)+ actual = torch.tensor(+ [[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )+ predicted = torch.tensor(+ [[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )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)@@ -88,90 +92,98 @@ class TestConfusionMatrix:def test_three_classes(self, device, dtype):num_classes = 3- actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]],- device=device, dtype=torch.long)- predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]],- device=device, dtype=torch.long)+ actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]], device=device, dtype=torch.long)+ predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]], device=device, dtype=torch.long)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)+ 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)def test_four_classes_one_missing(self, device, dtype):num_classes = 4- actual = torch.tensor([[3, 3, 1, 1, 2, 1, 1, 3, 2, 2, 1, 1, 2, 3, 2, 1]],- device=device, dtype=torch.long)- predicted = torch.tensor([[3, 2, 1, 1, 1, 1, 1, 2, 1, 3, 3, 2, 1, 1, 3, 3]],- device=device, dtype=torch.long)+ actual = torch.tensor([[3, 3, 1, 1, 2, 1, 1, 3, 2, 2, 1, 1, 2, 3, 2, 1]], device=device, dtype=torch.long)+ predicted = torch.tensor([[3, 2, 1, 1, 1, 1, 1, 2, 1, 3, 3, 2, 1, 1, 3, 3]], device=device, dtype=torch.long)conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)- 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)+ 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)def test_three_classes_normalized(self, device, dtype):num_classes = 3normalized = True- actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]],- device=device, dtype=torch.long)- predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]],- device=device, dtype=torch.long)+ actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]], device=device, dtype=torch.long)+ predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]], device=device, dtype=torch.long)conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes, normalized)conf_mat_real = torch.tensor([[[0.5000, 0.3333, 0.4000], [0.3750, 0.0000, 0.4000], [0.1250, 0.6667, 0.2000]]],- device=device, dtype=torch.float32)+ device=device,+ dtype=torch.float32,+ )assert_close(conf_mat, conf_mat_real)def test_four_classes_2d_perfect(self, device, dtype):num_classes = 4- actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)- predicted = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)+ actual = torch.tensor(+ [[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )+ predicted = torch.tensor(+ [[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)- 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)+ 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)def test_four_classes_2d_one_class_nonperfect(self, device, dtype):num_classes = 4- actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)- predicted = torch.tensor([[[0, 0, 1, 1], [0, 3, 0, 1], [2, 2, 1, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)+ actual = torch.tensor(+ [[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )+ predicted = torch.tensor(+ [[[0, 0, 1, 1], [0, 3, 0, 1], [2, 2, 1, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)- 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)+ 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)def test_four_classes_2d_one_class_missing(self, device, dtype):num_classes = 4- actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)- predicted = torch.tensor([[[3, 3, 1, 1], [3, 3, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)+ actual = torch.tensor(+ [[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )+ predicted = torch.tensor(+ [[[3, 3, 1, 1], [3, 3, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)- 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)+ 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)def test_four_classes_2d_one_class_no_predicted(self, device, dtype):num_classes = 4- actual = torch.tensor([[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)- predicted = torch.tensor([[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]],- device=device, dtype=torch.long)+ actual = torch.tensor(+ [[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )+ predicted = torch.tensor(+ [[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]], device=device, dtype=torch.long+ )conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)- 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)+ 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)diff --git a/test/tracking/test_planar_tracking.py b/test/tracking/test_planar_tracking.pyindex f131efdb7..0b120236d 100644--- a/test/tracking/test_planar_tracking.py+++ b/test/tracking/test_planar_tracking.py@@ -20,9 +20,7 @@ class TestHomographyTracker:def test_nomatch(self, device, dtype, data):# This is not unit test, but that is quite good integration test- matcher = LocalFeatureMatcher(SIFTFeature(100),- DescriptorMatcher('smnn', 0.95)).to(device,- dtype)+ matcher = LocalFeatureMatcher(SIFTFeature(100), DescriptorMatcher('smnn', 0.95)).to(device, dtype)tracker = HomographyTracker(matcher, matcher, minimum_inliers_num=100)for k in data.keys():if isinstance(data[k], torch.Tensor):@@ -34,8 +32,7 @@ class TestHomographyTracker:def test_real(self, device, dtype, data):# This is not unit test, but that is quite good integration test- matcher = LocalFeatureMatcher(GFTTAffNetHardNet(1000),- DescriptorMatcher('snn', 0.8)).to(device, dtype)+ matcher = LocalFeatureMatcher(GFTTAffNetHardNet(1000), DescriptorMatcher('snn', 0.8)).to(device, dtype)tracker = HomographyTracker(matcher, matcher).to(device, dtype)for k in data.keys():if isinstance(data[k], torch.Tensor):@@ -51,18 +48,10 @@ class TestHomographyTracker:pts_src = data['pts0'].to(device, dtype) / 2.0pts_dst = data['pts1'].to(device, dtype) / 2.0# Reprojection error of 5px is OK- assert_close(- transform_points(homography[None], pts_src[None]),- pts_dst[None],- rtol=5e-2,- atol=5)+ assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)# next framewith torch.no_grad():torch.random.manual_seed(0)homography, success = tracker(data["image1"])assert success- assert_close(- transform_points(homography[None], pts_src[None]),- pts_dst[None],- rtol=5e-2,- atol=5)+ assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)diff --git a/test/utils/test_grid.py b/test/utils/test_grid.pyindex 4c3ae7e04..0423f403e 100644--- a/test/utils/test_grid.py+++ b/test/utils/test_grid.py@@ -42,11 +42,13 @@ def test_normalize_pixel_grid(device, dtype):grid_pix = torch.unsqueeze(grid_pix, dim=0)# grid from pixel space to normalized- norm_trans_pix = kornia.normal_transform_pixel(height, width, device=device, dtype=dtype) # 1x3x3+ norm_trans_pix = kornia.geometry.transform.normal_transform_pixel(+ height, width, device=device, dtype=dtype+ ) # 1x3x3pix_trans_norm = torch.inverse(norm_trans_pix) # 1x3x3# transform grids- grid_pix_to_norm = kornia.transform_points(norm_trans_pix, grid_pix)- grid_norm_to_pix = kornia.transform_points(pix_trans_norm, grid_norm)+ grid_pix_to_norm = kornia.geometry.linalg.transform_points(norm_trans_pix, grid_pix)+ grid_norm_to_pix = kornia.geometry.linalg.transform_points(pix_trans_norm, grid_norm)assert_close(grid_pix, grid_norm_to_pix)assert_close(grid_norm, grid_pix_to_norm)diff --git a/test/utils/test_helpers.py b/test/utils/test_helpers.pyindex be158d168..ecc3c76ab 100644--- a/test/utils/test_helpers.py+++ b/test/utils/test_helpers.py@@ -123,12 +123,12 @@ class TestSolveWithMask:X2, _ = _torch_solve_cast(B, A)tol_val: float = 1e-1 if dtype == torch.float16 else 1e-4if mask.sum() > 0:- assert_close(X[mask],- X2[mask],- atol=tol_val, rtol=tol_val)+ assert_close(X[mask], X2[mask], atol=tol_val, rtol=tol_val)- @pytest.mark.skipif((int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 10),- reason='<1.10.0 not supporting')+ @pytest.mark.skipif(+ (int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 10),+ reason='<1.10.0 not supporting',+ )def test_all_bad(self, device, dtype):A = torch.ones(10, 3, 3, device=device, dtype=dtype)B = torch.ones(3, 10, device=device, dtype=dtype)@@ -148,8 +148,10 @@ class TestInverseWithMask:assert_close(y, y_expected)assert torch.equal(mask, torch.ones_like(mask))- @pytest.mark.skipif((int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 9),- reason='<1.9.0 not supporting')+ @pytest.mark.skipif(+ (int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 9),+ reason='<1.9.0 not supporting',+ )def test_all_bad(self, device, dtype):A = torch.ones(10, 3, 3, device=device, dtype=dtype)X, mask = safe_inverse_with_mask(A)diff --git a/test/utils/test_image.py b/test/utils/test_image.pyindex cc5513baa..adda12456 100644--- a/test/utils/test_image.py+++ b/test/utils/test_image.py@@ -17,27 +17,20 @@ def test_image_to_tensor_keep_dtype(input_dtype, expected_dtype):assert tensor.dtype == expected_dtype- "num_of_images, image_shape",- [- (2, (4, 3, 1)),- (0, (1, 2, 3)),- (5, (2, 3, 2, 5))- ]-)[email protected]("num_of_images, image_shape", [(2, (4, 3, 1)), (0, (1, 2, 3)), (5, (2, 3, 2, 5))])def test_list_of_images_to_tensor(num_of_images, image_shape):images: List[np.array] = []if num_of_images == 0:with pytest.raises(ValueError):- kornia.image_list_to_tensor([])+ kornia.utils.image_list_to_tensor([])returnfor _ in range(num_of_images):images.append(np.ones(shape=image_shape))if len(image_shape) != 3:with pytest.raises(ValueError):- kornia.image_list_to_tensor(images)+ kornia.utils.image_list_to_tensor(images)return- tensor = kornia.image_list_to_tensor(images)+ tensor = kornia.utils.image_list_to_tensor(images)assert tensor.shape == (num_of_images, image_shape[-1], image_shape[-3], image_shape[-2])diff --git a/test/utils/test_pointcloud_io.py b/test/utils/test_pointcloud_io.pyindex e3deabbaa..c41af96a9 100644--- a/test/utils/test_pointcloud_io.py+++ b/test/utils/test_pointcloud_io.py@@ -13,10 +13,10 @@ class TestSaveLoadPointCloud:# save to filefilename = "pointcloud.ply"- kornia.save_pointcloud_ply(filename, xyz_save)+ kornia.utils.save_pointcloud_ply(filename, xyz_save)# load file- xyz_load = kornia.load_pointcloud_ply(filename)+ xyz_load = kornia.utils.load_pointcloud_ply(filename)assert_close(xyz_save.reshape(-1, 3), xyz_load)# remove the temporal file@@ -39,13 +39,13 @@ class TestSaveLoadPointCloud:# save to filefilename = "pointcloud.ply"- kornia.save_pointcloud_ply(filename, xyz_save)+ kornia.utils.save_pointcloud_ply(filename, xyz_save)# same as xyz_save but with dropping the first pointxyz_correct = xyz_save.reshape(-1, 3)[1:, :]# load file- xyz_load = kornia.load_pointcloud_ply(filename)+ xyz_load = kornia.utils.load_pointcloud_ply(filename)assert_close(xyz_correct, xyz_load)if os.path.exists(filename):diff --git a/test/x/test_image_classification.py b/test/x/test_image_classification.pyindex 2214f8636..bcbf0758d 100644--- a/test/x/test_image_classification.py+++ b/test/x/test_image_classification.py@@ -17,10 +17,7 @@ class DummyDatasetClassification(Dataset):@pytest.fixturedef model():- return nn.Sequential(- VisionTransformer(image_size=32),- ClassificationHead(num_classes=10),- )+ return nn.Sequential(VisionTransformer(image_size=32), ClassificationHead(num_classes=10))@pytest.fixture@@ -52,16 +49,12 @@ def configuration():class TestImageClassifierTrainer:-def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration):- trainer = ImageClassifierTrainer(- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,- )+ trainer = ImageClassifierTrainer(model, dataloader, dataloader, criterion, optimizer, scheduler, configuration)trainer.fit()def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):with pytest.raises(ValueError):ImageClassifierTrainer(- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,- callbacks={'frodo': None},+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, callbacks={'frodo': None})diff --git a/test/x/test_segmentation.py b/test/x/test_segmentation.pyindex a38ea2c3c..c47c4930c 100644--- a/test/x/test_segmentation.py+++ b/test/x/test_segmentation.py@@ -50,13 +50,12 @@ def configuration():class TestsemanticSegmentationTrainer:def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration):trainer = SemanticSegmentationTrainer(- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration)trainer.fit()def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):with pytest.raises(ValueError):SemanticSegmentationTrainer(- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,- callbacks={'frodo': None},+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, callbacks={'frodo': None})diff --git a/test/x/test_x.py b/test/x/test_x.pyindex 7f05ad5db..27cf92522 100644--- a/test/x/test_x.py+++ b/test/x/test_x.py@@ -16,7 +16,7 @@ def test_callback_modelcheckpoint(tmp_path, model):assert cb is not Nonemetric = {'test_monitor': AverageMeter()}- metric['test_monitor'].avg = 1.+ metric['test_monitor'].avg = 1.0cb(model, epoch=0, valid_metric=metric)assert cb.best_metric == 1.0