Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

deprecate utils module across library (#3449)

Edgar Riba94882c52ae4e
diff --git a/conftest.py b/conftest.py
index 04a464bfe..37bc855db 100644
--- a/conftest.py
+++ b/conftest.py
@@ -49,7 +49,7 @@ def get_test_devices() -> dict[str, torch.device]:
if torch.cuda.is_available():
devices["cuda"] = torch.device("cuda:0")
- if kornia.xla_is_available():
+ if kornia.core.utils.xla_is_available():
import torch_xla.core.xla_model as xm
devices["tpu"] = xm.xla_device()
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 89e9f3e71..1ef549076 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -57,7 +57,7 @@ def read_img_from_url(url: str, resize_to: Optional[tuple[int, int]] = None, **r
# convert to image array and resize
img: np.ndarray = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)[..., :3]
# convert the image to a tensor
- img_t: torch.Tensor = K.utils.image_to_tensor(img, keepdim=False) # 1xCxHXW
+ img_t: torch.Tensor = K.image.image_to_tensor(img, keepdim=False) # 1xCxHXW
img_t = img_t.float() / 255.0
if resize_to is None:
img_t = K.geometry.resize(img_t, 184, **resize_kwargs)
@@ -80,7 +80,7 @@ def draw_bbox_kpts(imgs: torch.Tensor, bboxes: torch.Tensor, keypoints: torch.Te
rectangle[..., 2] = bboxes[..., 0] + bboxes[..., -2] # x2
rectangle[..., 3] = bboxes[..., 1] + bboxes[..., -1] # y2
color = torch.tensor([1, 0, 0]).repeat(imgs.shape[0], imgs.shape[1], 1)
- imgs_draw = K.utils.draw_rectangle(imgs, rectangle, color=color)
+ imgs_draw = K.image.draw_rectangle(imgs, rectangle, color=color)
rectangle2 = torch.zeros(imgs.shape[0], imgs.shape[1], 4)
for n in range(keypoints.shape[-2]):
@@ -219,7 +219,7 @@ def main():
out = torch.cat([ori, *(out[i] for i in range(out.size(0)))], dim=-1)
# save the output image
- out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ out_np = K.image.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{aug_name}.png"), out_np)
sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"
print(f"Generated image example for {aug_name}. {sig}")
@@ -373,7 +373,7 @@ def main():
)
else:
out = torch.cat([img2[0], *(out[i] for i in range(out.size(0)))], dim=-1)
- out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ out_np = K.image.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
sig = f"{fn_name}({', '.join([str(a) for a in args])})"
print(f"Generated image example for {fn_name}. {sig}")
@@ -389,7 +389,7 @@ def main():
out = torch.cat([bar_img, out], dim=-1)
- out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ out_np = K.image.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{colormap_name}.png"), out_np)
sig = f"{colormap_name}({', '.join([str(a) for a in args])})"
print(f"Generated image example for {colormap_name}. {sig}")
@@ -454,7 +454,7 @@ def main():
out = fn(*args_in)
# save the output image
out = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)
- out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ out_np = K.image.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
sig = f"{fn_name}({', '.join([str(a) for a in args])})"
print(f"Generated image example for {fn_name}. {sig}")
@@ -481,7 +481,7 @@ def main():
out = fn(*args_in)
# save the output image
out = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)
- out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ out_np = K.image.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
sig = f"{fn_name}({', '.join([str(a) for a in args])})"
print(f"Generated image example for {fn_name}. {sig}")
@@ -532,7 +532,7 @@ def main():
out = torch.cat([args_in[1], out], dim=-1)
# save the output image
out = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)
- out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ out_np = K.image.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
sig = f"{fn_name}({', '.join([str(a) for a in args])})"
print(f"Generated image example for {fn_name}. {sig}")
@@ -555,7 +555,7 @@ def main():
mask = mask.repeat(1, img1.shape[1], 1, 1)
# save the output image
out = torch.cat([img1[0], mask[0], filtered[0]], dim=-1)
- out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ out_np = K.image.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
sig = f"{fn_name}({', '.join([str(a) for a in args])})"
print(f"Generated image example for {fn_name}. {sig}")
@@ -585,7 +585,7 @@ def main():
),
"remap": (
(
- *(K.utils.create_meshgrid(h, w, normalized_coordinates=True) - 0.25).unbind(-1),
+ *(K.geometry.create_meshgrid(h, w, normalized_coordinates=True) - 0.25).unbind(-1),
"bilinear",
"zeros",
True,
@@ -642,7 +642,7 @@ def main():
out = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)
else:
out = torch.cat([*(out[i] for i in range(out.size(0)))], dim=-1)
- out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ out_np = K.image.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
sig = f"{fn_name}({', '.join([str(a) for a in args])})"
print(f"Generated image example for {fn_name}. {sig}")
@@ -713,7 +713,7 @@ def main():
# save the output image
out = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)
- out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ out_np = K.image.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
sig = f"{fn_name}({', '.join([str(a) for a in args])})"
print(f"Generated image example for response function {fn_name}")
diff --git a/docs/source/geometry.grid.rst b/docs/source/geometry.grid.rst
new file mode 100644
index 000000000..086427b7d
--- /dev/null
+++ b/docs/source/geometry.grid.rst
@@ -0,0 +1,11 @@
+kornia.geometry.grid
+====================
+
+.. meta::
+ :name: description
+ :content: "The kornia.geometry.grid module provides functions for generating coordinate grids for images. It includes functions for creating 2D and 3D mesh grids with optional coordinate normalization, making it easy to work with grid-based transformations and sampling operations in computer vision tasks."
+
+.. currentmodule:: kornia.geometry.grid
+
+.. autofunction:: create_meshgrid
+.. autofunction:: create_meshgrid3d
diff --git a/docs/source/geometry.pointcloud.rst b/docs/source/geometry.pointcloud.rst
new file mode 100644
index 000000000..7d31a1ba4
--- /dev/null
+++ b/docs/source/geometry.pointcloud.rst
@@ -0,0 +1,11 @@
+kornia.geometry.pointcloud
+==========================
+
+.. meta::
+ :name: description
+ :content: "The kornia.geometry.pointcloud module provides functionality for loading and saving point clouds in PLY format. It includes functions for reading and writing 3D point cloud data, making it easy to work with point cloud files in computer vision and geometric processing tasks."
+
+.. currentmodule:: kornia.geometry.pointcloud
+
+.. autofunction:: save_pointcloud_ply
+.. autofunction:: load_pointcloud_ply
diff --git a/docs/source/geometry.rst b/docs/source/geometry.rst
index fc4c9832e..404cea7f5 100644
--- a/docs/source/geometry.rst
+++ b/docs/source/geometry.rst
@@ -56,10 +56,12 @@ transforms, camera, conversions, linalg and depth. We next describe each of them
geometry.conversions
geometry.depth
geometry.epipolar
+ geometry.grid
geometry.homography
geometry.liegroup
geometry.linalg
geometry.line
+ geometry.pointcloud
geometry.quaternion
geometry.solvers
geometry.subpix
diff --git a/docs/source/get-started/highlights.rst b/docs/source/get-started/highlights.rst
index 76abc4a71..0dec0981d 100644
--- a/docs/source/get-started/highlights.rst
+++ b/docs/source/get-started/highlights.rst
@@ -41,5 +41,4 @@ At a granular level, Kornia is a library that consists of the following componen
+-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------+
| `kornia.morphology <https://kornia.readthedocs.io/en/latest/morphology.html>`_ | a module to perform morphological operations |
+-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------+
-| `kornia.utils <https://kornia.readthedocs.io/en/latest/utils.html>`_ | image to tensor utilities and metrics for vision problems |
+-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------+
diff --git a/docs/source/image.rst b/docs/source/image.rst
index e824957c3..186de2bf5 100644
--- a/docs/source/image.rst
+++ b/docs/source/image.rst
@@ -28,3 +28,32 @@ Module to provide a high level API to process images.
.. autoclass:: Image
:members:
:undoc-members:
+
+Drawing
+-------
+
+.. autofunction:: draw_line
+.. autofunction:: draw_rectangle
+.. autofunction:: draw_convex_polygon
+.. autofunction:: draw_point2d
+
+Image Conversion
+----------------
+
+.. autofunction:: tensor_to_image
+.. autofunction:: image_to_tensor
+.. autofunction:: image_list_to_tensor
+.. autoclass:: ImageToTensor
+
+Image Printing
+--------------
+
+.. autofunction:: image_to_string
+.. autofunction:: print_image
+
+Utilities
+---------
+
+.. autofunction:: make_grid
+.. autofunction:: perform_keep_shape_image
+.. autofunction:: perform_keep_shape_video
diff --git a/docs/source/index.rst b/docs/source/index.rst
index e705e382f..81c031e33 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -121,7 +121,6 @@ Join the community
morphology
onnx
tracking
- utils
.. toctree::
:caption: KORNIA APPLICATIONS
diff --git a/docs/source/losses.rst b/docs/source/losses.rst
index f874ebd55..dce565326 100644
--- a/docs/source/losses.rst
+++ b/docs/source/losses.rst
@@ -34,6 +34,7 @@ Reconstruction
Semantic Segmentation
---------------------
+.. autofunction:: one_hot
.. autofunction:: binary_focal_loss_with_logits
.. autofunction:: focal_loss
.. autofunction:: dice_loss
diff --git a/docs/source/models/segment_anything.rst b/docs/source/models/segment_anything.rst
index c6bd35365..9624a5696 100644
--- a/docs/source/models/segment_anything.rst
+++ b/docs/source/models/segment_anything.rst
@@ -96,7 +96,7 @@ to query the image masks from the SAM model.
from kornia.io import load_image, ImageLoadType
from kornia.geometry.keypoints import Keypoints
from kornia.geometry.boxes import Boxes
- from kornia.utils import get_cuda_or_mps_device_if_available
+ from kornia.core.utils import get_cuda_or_mps_device_if_available
model_type = 'vit_h'
checkpoint = './https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth'
@@ -180,7 +180,7 @@ parameters. If a checkpoint URL or path for a file is seted, the method will aut
.. code-block:: python
from kornia.models.sam import Sam, SamConfig
- from kornia.utils import get_cuda_or_mps_device_if_available
+ from kornia.core.utils import get_cuda_or_mps_device_if_available
# model_type can be:
# 0, 'vit_h' or `kornia.models.sam.SamModelType.vit_h`
@@ -216,7 +216,7 @@ If a URL is passed the model will automatically download and cache the weights u
.. code-block:: python
from kornia.models.sam import Sam, SamConfig
- from kornia.utils import get_cuda_or_mps_device_if_available
+ from kornia.core.utils import get_cuda_or_mps_device_if_available
model_type = 'vit_b'
@@ -245,7 +245,7 @@ This is a simple example, of how to directly use the SAM model loaded. We recomm
from kornia.models.sam import Sam
from kornia.models.structures import SegmentationResults
from kornia.io import load_image, ImageLoadType
- from kornia.utils import get_cuda_or_mps_device_if_available
+ from kornia.core.utils import get_cuda_or_mps_device_if_available
from kornia.geometry import resize
from kornia.enhance import normalize
diff --git a/docs/source/utils.rst b/docs/source/utils.rst
deleted file mode 100644
index 939fb6683..000000000
--- a/docs/source/utils.rst
+++ /dev/null
@@ -1,55 +0,0 @@
-kornia.utils
-===================
-
-.. meta::
- :name: description
- :content: "The `kornia.utils` module provides a variety of utility functions for computer vision tasks, including image manipulation, pointcloud handling, device management, memory operations, and automatic mixed precision support. These utilities streamline workflows for tasks like image transformation, grid generation, and point cloud file handling."
-
-.. currentmodule:: kornia.utils
-
-Draw
-----
-
-.. autofunction:: draw_line
-.. autofunction:: draw_rectangle
-.. autofunction:: draw_convex_polygon
-
-Image
------
-
-.. autofunction:: tensor_to_image
-.. autofunction:: image_to_tensor
-.. autofunction:: image_list_to_tensor
-.. autofunction:: image_to_string
-.. autofunction:: print_image
-
-Grid
-----
-
-.. autofunction:: create_meshgrid
-.. autofunction:: create_meshgrid3d
-
-Pointcloud
-----------
-
-.. autofunction:: save_pointcloud_ply
-.. autofunction:: load_pointcloud_ply
-
-Memory
--------
-
-.. autofunction:: one_hot
-.. autofunction:: batched_forward
-
-Device
--------
-
-.. autofunction:: get_cuda_device_if_available
-.. autofunction:: get_mps_device_if_available
-.. autofunction:: get_cuda_or_mps_device_if_available
-.. autofunction:: map_location_to_cpu
-
-
-Automatic Mixed Precision
--------------------------
-.. autofunction:: is_autocast_enabled
diff --git a/kornia/__init__.py b/kornia/__init__.py
index da5c6974c..258d41606 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -21,6 +21,8 @@ This package exposes core modules (filters, geometry, etc.) and provides
convenience imports at the top level.
"""
+from typing import Any
+
# 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
@@ -42,7 +44,6 @@ from . import (
morphology,
onnx,
tracking,
- utils,
)
@@ -51,14 +52,197 @@ from .transpiler import to_jax, to_numpy, to_tensorflow
# NOTE: we are going to expose to top level very few things
from kornia.constants import pi
-from kornia.utils import (
- eye_like,
- vec_like,
- create_meshgrid,
- image_to_tensor,
- tensor_to_image,
- xla_is_available,
+
+# Deprecated top-level imports - use kornia.core.ops or kornia.core.utils instead
+from kornia.core._compat import deprecated
+
+# Import the actual functions to wrap
+from kornia.core.ops import eye_like as _eye_like, vec_like as _vec_like
+from kornia.core.utils import (
+ get_cuda_device_if_available as _get_cuda_device_if_available,
+ get_cuda_or_mps_device_if_available as _get_cuda_or_mps_device_if_available,
+ get_mps_device_if_available as _get_mps_device_if_available,
+ is_autocast_enabled as _is_autocast_enabled,
+ xla_is_available as _xla_is_available,
+)
+from kornia.geometry import (
+ create_meshgrid as _create_meshgrid,
+ create_meshgrid3d as _create_meshgrid3d,
+ load_pointcloud_ply as _load_pointcloud_ply,
+ save_pointcloud_ply as _save_pointcloud_ply,
+)
+from kornia.image import (
+ draw_convex_polygon as _draw_convex_polygon,
+ draw_line as _draw_line,
+ draw_point2d as _draw_point2d,
+ draw_rectangle as _draw_rectangle,
+ image_to_string as _image_to_string,
+ image_to_tensor as _image_to_tensor,
+ print_image as _print_image,
+ tensor_to_image as _tensor_to_image,
+)
+from kornia.losses import one_hot as _one_hot
+
+
+@deprecated(replace_with="kornia.core.ops.eye_like", version="0.8.3")
+def eye_like(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.core.ops.eye_like` instead."""
+ return _eye_like(*args, **kwargs)
+
+
+@deprecated(replace_with="kornia.core.ops.vec_like", version="0.8.3")
+def vec_like(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.core.ops.vec_like` instead."""
+ return _vec_like(*args, **kwargs)
+
+
+@deprecated(replace_with="kornia.core.utils.xla_is_available", version="0.8.3")
+def xla_is_available(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.core.utils.xla_is_available` instead."""
+ return _xla_is_available(*args, **kwargs)
+
+
+@deprecated(replace_with="kornia.geometry.create_meshgrid", version="0.8.3")
+def create_meshgrid(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.geometry.create_meshgrid` instead."""
+ return _create_meshgrid(*args, **kwargs)
+
+
+@deprecated(replace_with="kornia.image.image_to_tensor", version="0.8.3")
+def image_to_tensor(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.image_to_tensor` instead."""
+ return _image_to_tensor(*args, **kwargs)
+
+
+@deprecated(replace_with="kornia.image.tensor_to_image", version="0.8.3")
+def tensor_to_image(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.tensor_to_image` instead."""
+ return _tensor_to_image(*args, **kwargs)
+
+
+@deprecated(replace_with="kornia.core.utils.get_cuda_device_if_available", version="0.8.3")
+def get_cuda_device_if_available(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.core.utils.get_cuda_device_if_available` instead."""
+ return _get_cuda_device_if_available(*args, **kwargs)
+
+
+@deprecated(replace_with="kornia.core.utils.get_mps_device_if_available", version="0.8.3")
+def get_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.core.utils.get_mps_device_if_available` instead."""
+ return _get_mps_device_if_available(*args, **kwargs)
+
+
+@deprecated(replace_with="kornia.core.utils.get_cuda_or_mps_device_if_available", version="0.8.3")
+def get_cuda_or_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.core.utils.get_cuda_or_mps_device_if_available` instead."""
+ return _get_cuda_or_mps_device_if_available(*args, **kwargs)
+
+
+@deprecated(replace_with="kornia.core.utils.is_autocast_enabled", version="0.8.3")
+def is_autocast_enabled(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.core.utils.is_autocast_enabled` instead."""
+ return _is_autocast_enabled(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.geometry.create_meshgrid3d",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.create_meshgrid3d`.",
)
+def create_meshgrid3d(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.geometry.create_meshgrid3d` instead (previously `kornia.utils.create_meshgrid3d`)."""
+ return _create_meshgrid3d(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.geometry.load_pointcloud_ply",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.load_pointcloud_ply`.",
+)
+def load_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.geometry.load_pointcloud_ply` instead (previously `kornia.utils.load_pointcloud_ply`)."""
+ return _load_pointcloud_ply(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.geometry.save_pointcloud_ply",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.save_pointcloud_ply`.",
+)
+def save_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.geometry.save_pointcloud_ply` instead (previously `kornia.utils.save_pointcloud_ply`)."""
+ return _save_pointcloud_ply(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.draw_line",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.draw_line`.",
+)
+def draw_line(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.draw_line` instead (previously `kornia.utils.draw_line`)."""
+ return _draw_line(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.draw_rectangle",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.draw_rectangle`.",
+)
+def draw_rectangle(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.draw_rectangle` instead (previously `kornia.utils.draw_rectangle`)."""
+ return _draw_rectangle(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.draw_point2d",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.draw_point2d`.",
+)
+def draw_point2d(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.draw_point2d` instead (previously `kornia.utils.draw_point2d`)."""
+ return _draw_point2d(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.draw_convex_polygon",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.draw_convex_polygon`.",
+)
+def draw_convex_polygon(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.draw_convex_polygon` instead (previously `kornia.utils.draw_convex_polygon`)."""
+ return _draw_convex_polygon(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.image_to_string",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.image_to_string`.",
+)
+def image_to_string(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.image_to_string` instead (previously `kornia.utils.image_to_string`)."""
+ return _image_to_string(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.print_image",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.print_image`.",
+)
+def print_image(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.print_image` instead (previously `kornia.utils.print_image`)."""
+ return _print_image(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.losses.one_hot",
+ version="0.8.3",
+ extra_reason=" Previously available as `kornia.utils.one_hot`.",
+)
+def one_hot(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.losses.one_hot` instead (previously `kornia.utils.one_hot`)."""
+ return _one_hot(*args, **kwargs)
+
# Version variable
__version__ = "0.8.2"
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index b9e1a5ca9..05f171eae 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -22,9 +22,10 @@ from torch import float16, float32, float64
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype
+from kornia.core.ops import eye_like
+from kornia.core.utils import is_autocast_enabled
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
-from kornia.utils import eye_like, is_autocast_enabled
class AugmentationBase2D(_AugmentationBase):
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index d8abcb2a6..dddc3a663 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -21,9 +21,9 @@ import torch
from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
from kornia.constants import Resample
+from kornia.core.utils import _torch_inverse_cast
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
-from kornia.utils.helpers import _torch_inverse_cast
class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
index 31ab715a5..e57a14da6 100644
--- a/kornia/augmentation/_2d/geometric/fisheye.py
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -21,8 +21,8 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.base import AugmentationBase2D
+from kornia.geometry.grid import create_meshgrid
from kornia.geometry.transform import remap
-from kornia.utils import create_meshgrid
class RandomFisheye(AugmentationBase2D):
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index e2035be01..6634a868e 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -22,8 +22,8 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
+from kornia.core.ops import eye_like
from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize
-from kornia.utils import eye_like
class Resize(GeometricAugmentationBase2D):
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index a5d778783..05cf68d50 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -22,9 +22,9 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
+from kornia.core.ops import eye_like
from kornia.geometry.transform import affine
from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
-from kornia.utils.misc import eye_like
class RandomRotation(GeometricAugmentationBase2D):
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 270941679..a02ffa881 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -24,9 +24,9 @@ from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
from kornia.constants import DataKey, Resample
from kornia.core.check import KORNIA_UNWRAP
+from kornia.core.ops import eye_like
from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
-from kornia.utils import eye_like
__all__ = ["RandomMosaic"]
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index f3b311be2..6e820c22f 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -57,7 +57,7 @@ class AugmentationBase3D(_AugmentationBase):
def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return 4x4 identity matrix."""
- return kornia.eye_like(4, input)
+ return kornia.core.ops.eye_like(4, input)
class RigidAffineAugmentationBase3D(AugmentationBase3D):
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index 0e8617453..aebd473a7 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -118,7 +118,7 @@ class RandomRotation3D(GeometricAugmentationBase3D):
rotation_mat: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center.expand(yaw.shape[0], -1))
# rotation_mat is B x 3 x 4 and we need a B x 4 x 4 matrix
- trans_mat: torch.Tensor = kornia.eye_like(4, input)
+ trans_mat: torch.Tensor = kornia.core.ops.eye_like(4, input)
trans_mat[:, 0] = rotation_mat[:, 0]
trans_mat[:, 1] = rotation_mat[:, 1]
trans_mat[:, 2] = rotation_mat[:, 2]
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index 520bf9847..2ad330786 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -25,7 +25,7 @@ from kornia.augmentation.auto.operations.policy import PolicySequential
from kornia.augmentation.container.base import ImageSequentialBase, TransformMatrixMinIn
from kornia.augmentation.container.ops import InputSequentialOps
from kornia.augmentation.container.params import ParamItem
-from kornia.utils import eye_like
+from kornia.core.ops import eye_like
NUMBER = Union[float, int]
OP_CONFIG = Tuple[str, NUMBER, Optional[NUMBER]]
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index efacc5b9b..23884d8ee 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -26,7 +26,7 @@ from kornia.augmentation.container.base import ImageSequentialBase, TransformMat
from kornia.augmentation.container.ops import InputSequentialOps
from kornia.augmentation.container.params import ParamItem
from kornia.augmentation.utils import _transform_input, override_parameters
-from kornia.utils import eye_like
+from kornia.core.ops import eye_like
class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index bdf15e6db..00b0e2af7 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -29,9 +29,9 @@ from kornia.augmentation.utils import (
_transform_output_shape,
override_parameters,
)
+from kornia.core.utils import is_autocast_enabled
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
-from kornia.utils import is_autocast_enabled
TensorWithTransformMat = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 8366f326a..61a894715 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -16,7 +16,7 @@
#
import warnings
-from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast
+from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union, cast
import torch
from torch import nn
@@ -25,9 +25,10 @@ from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3D
from kornia.augmentation.base import _AugmentationBase
from kornia.constants import DataKey, Resample
+from kornia.core.ops import eye_like
+from kornia.core.utils import is_autocast_enabled
from kornia.geometry.boxes import Boxes, VideoBoxes
from kornia.geometry.keypoints import Keypoints, VideoKeypoints
-from kornia.utils import eye_like, is_autocast_enabled
from .base import TransformMatrixMinIn
from .image import ImageSequential
@@ -336,7 +337,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
outputs = self.transform_op.inverse( # type: ignore
*outputs, module=module, param=param, extra_args=self.extra_args
)
- if not isinstance(outputs, (list, tuple)):
+ if not isinstance(outputs, list | tuple):
# Make sure we are unpacking a list whilst post-proc
outputs = [outputs]
@@ -400,7 +401,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:
_out_k = self._postproc_keypoint(in_arg, cast(Keypoints, out_arg), dcate)
- if is_autocast_enabled() and isinstance(in_arg, (torch.Tensor, Keypoints)):
+ if is_autocast_enabled() and isinstance(in_arg, torch.Tensor | Keypoints):
if isinstance(_out_k, list):
_out_k = [i.type(in_arg.dtype) for i in _out_k]
else:
@@ -409,7 +410,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
elif DataKey.get(dcate) in _BOXES_OPTIONS:
_out_b = self._postproc_boxes(in_arg, cast(Boxes, out_arg), dcate)
- if is_autocast_enabled() and isinstance(in_arg, (torch.Tensor, Boxes)):
+ if is_autocast_enabled() and isinstance(in_arg, torch.Tensor | Boxes):
if isinstance(_out_b, list):
_out_b = [i.type(in_arg.dtype) for i in _out_b]
else:
@@ -448,7 +449,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
# image data must exist if params is not provided.
if DataKey.INPUT in self.transform_op.data_keys:
inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)]
- if not isinstance(inp, (torch.Tensor,)):
+ if not isinstance(inp, torch.Tensor):
raise ValueError(f"`INPUT` should be a torch.tensor but `{type(inp)}` received.")
# A video input shall be BCDHW while an image input shall be BCHW
if self.contains_video_sequential or self.contains_3d_augmentation:
@@ -465,7 +466,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
outputs = self.transform_op.transform( # type: ignore
*outputs, module=module, param=param, extra_args=self.extra_args
)
- if not isinstance(outputs, (list, tuple)):
+ if not isinstance(outputs, list | tuple):
# Make sure we are unpacking a list whilst post-proc
outputs = [outputs]
self._update_transform_matrix_by_module(module)
@@ -491,7 +492,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
self,
*inputs: Any,
input_names_to_handle: Optional[List[Any]] = None,
- output_type: str = "torch.tensor",
+ output_type: Literal["pt", "numpy", "pil"] = "pt",
**kwargs: Any,
) -> Any:
"""Overwrite the __call__ function to handle various inputs.
@@ -499,7 +500,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
Args:
inputs: Inputs to operate on.
input_names_to_handle: List of input names to convert, if None, handle all inputs.
- output_type: Desired output type ('torch.tensor', 'numpy', or 'pil').
+ output_type: Desired output type ('pt', 'numpy', or 'pil').
kwargs: Additional arguments.
Returns:
@@ -525,7 +526,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if len(data_keys) > 1 and DataKey.INPUT in data_keys:
# NOTE: we may update it later for more supports of drawing boxes, etc.
idx = data_keys.index(DataKey.INPUT)
- if output_type == "torch.tensor":
+ if output_type == "pt":
self._output_image = _output_image
if isinstance(_output_image, dict):
self._output_image[original_keys[idx]] = _output_image[original_keys[idx]]
@@ -616,7 +617,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
mode = "xywh"
else:
raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")
- if isinstance(arg, (Boxes,)):
+ if isinstance(arg, Boxes):
return arg
elif self.contains_video_sequential:
arg = cast(torch.Tensor, arg)
@@ -640,7 +641,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")
# TODO: handle 3d scenarios
- if isinstance(in_arg, (Boxes,)):
+ if isinstance(in_arg, Boxes):
return out_arg
else:
return out_arg.to_tensor(mode=mode)
@@ -661,7 +662,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
return video_result.type(dtype) if dtype else video_result
elif self.contains_3d_augmentation:
raise NotImplementedError("3D keypoint handlers are not yet supported.")
- elif isinstance(arg, (Keypoints,)):
+ elif isinstance(arg, Keypoints):
return arg
else:
arg = cast(torch.Tensor, arg)
@@ -675,7 +676,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
def _postproc_keypoint(
self, in_arg: DataType, out_arg: Keypoints, dcate: DataKey
) -> Union[torch.Tensor, List[torch.Tensor], Keypoints]:
- if isinstance(in_arg, (Keypoints,)):
+ if isinstance(in_arg, Keypoints):
return out_arg
else:
return out_arg.to_tensor()
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 6054548b0..338319407 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast
+from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union, cast
import torch
from torch import nn
@@ -24,8 +24,8 @@ import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import override_parameters
from kornia.core import ImageModule
-from kornia.core.module import ImageModuleMixIn
-from kornia.utils import eye_like
+from kornia.core.mixin.image_module import ImageModuleMixIn
+from kornia.core.ops import eye_like
from .base import ImageSequentialBase
from .params import ParamItem
@@ -338,7 +338,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
self,
*inputs: Any,
input_names_to_handle: Optional[List[Any]] = None,
- output_type: str = "tensor",
+ output_type: Literal["pt", "numpy", "pil"] = "pt",
**kwargs: Any,
) -> Any:
"""Overwrite the __call__ function to handle various inputs.
@@ -346,7 +346,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
Args:
inputs: Inputs to operate on.
input_names_to_handle: List of input names to convert, if None, handle all inputs.
- output_type: Desired output type ('tensor', 'numpy', or 'pil').
+ output_type: Desired output type ('pt', 'numpy', or 'pil').
kwargs: Additional arguments.
Returns:
@@ -359,7 +359,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
input_names_to_handle=input_names_to_handle, output_type=output_type
)(super().__call__)
_output_image = decorated_forward(*inputs, **kwargs)
- if output_type == "tensor":
+ if output_type == "pt":
self._output_image = self._detach_tensor_to_cpu(_output_image)
else:
self._output_image = _output_image
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index baf5f60a3..be7220d52 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["AffineGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.py
index 1b975f5e2..7733cbcae 100644
--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py
+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py
@@ -22,7 +22,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["ColorJiggleGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index b7e59e03f..34a28371e 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -22,8 +22,8 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check
+from kornia.core.utils import _extract_device_dtype
from kornia.geometry.bbox import bbox_generator
-from kornia.utils.helpers import _extract_device_dtype
__all__ = ["CropGenerator", "ResizedCropGenerator", "center_crop_generator"]
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index 94cd79578..336ba6352 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -22,8 +22,8 @@ from torch.distributions import Bernoulli, Beta, Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _adapted_sampling, _common_param_check, _joint_range_check
+from kornia.core.utils import _extract_device_dtype
from kornia.geometry.bbox import bbox_generator
-from kornia.utils.helpers import _extract_device_dtype
__all__ = ["CutmixGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/jpeg.py b/kornia/augmentation/random_generator/_2d/jpeg.py
index 30ad9b0fb..99f7d96c3 100644
--- a/kornia/augmentation/random_generator/_2d/jpeg.py
+++ b/kornia/augmentation/random_generator/_2d/jpeg.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["JPEGGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/linear_illumination.py b/kornia/augmentation/random_generator/_2d/linear_illumination.py
index d657cccca..7d6b0240d 100644
--- a/kornia/augmentation/random_generator/_2d/linear_illumination.py
+++ b/kornia/augmentation/random_generator/_2d/linear_illumination.py
@@ -21,8 +21,8 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
+from kornia.core.utils import _extract_device_dtype
from kornia.enhance.normalize import normalize_min_max
-from kornia.utils import _extract_device_dtype
class LinearIlluminationGenerator(RandomGeneratorBase):
diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.py
index 3fbb910f7..949c81491 100644
--- a/kornia/augmentation/random_generator/_2d/mixup.py
+++ b/kornia/augmentation/random_generator/_2d/mixup.py
@@ -22,7 +22,7 @@ from torch.distributions import Bernoulli
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _adapted_sampling, _common_param_check, _joint_range_check
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["MixupGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.py
index b66918351..f9c75792a 100644
--- a/kornia/augmentation/random_generator/_2d/mosaic.py
+++ b/kornia/augmentation/random_generator/_2d/mosaic.py
@@ -22,8 +22,8 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
+from kornia.core.utils import _extract_device_dtype
from kornia.geometry.bbox import bbox_generator
-from kornia.utils.helpers import _extract_device_dtype
__all__ = ["MosaicGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.py
index 6e1fd0712..5752f5d58 100644
--- a/kornia/augmentation/random_generator/_2d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["MotionBlurGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.py
index 0f402229d..a99dd7771 100644
--- a/kornia/augmentation/random_generator/_2d/perspective.py
+++ b/kornia/augmentation/random_generator/_2d/perspective.py
@@ -22,7 +22,7 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["PerspectiveGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.py
index 2240daada..780c31e8b 100644
--- a/kornia/augmentation/random_generator/_2d/plain_uniform.py
+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py
@@ -22,7 +22,7 @@ from torch.distributions import Distribution
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["ParameterBound", "PlainUniformGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.py
index 7669984f9..20768133f 100644
--- a/kornia/augmentation/random_generator/_2d/posterize.py
+++ b/kornia/augmentation/random_generator/_2d/posterize.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["PosterizeGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/random_rain.py b/kornia/augmentation/random_generator/_2d/random_rain.py
index a4dedae3e..9d607766b 100644
--- a/kornia/augmentation/random_generator/_2d/random_rain.py
+++ b/kornia/augmentation/random_generator/_2d/random_rain.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.utils import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
class RainGenerator(RandomGeneratorBase):
diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
index 32855fc3f..f2f89bc49 100644
--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py
+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["RectangleEraseGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
index 1d61b68a6..f80320984 100644
--- a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
+++ b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _range_bound
-from kornia.utils import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
class SaltAndPepperGenerator(RandomGeneratorBase):
diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.py
index 9f5d151ae..f17c393ca 100644
--- a/kornia/augmentation/random_generator/_2d/shear.py
+++ b/kornia/augmentation/random_generator/_2d/shear.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["ShearGenerator"]
diff --git a/kornia/augmentation/random_generator/_2d/translate.py b/kornia/augmentation/random_generator/_2d/translate.py
index 837d575ee..fa02e319b 100644
--- a/kornia/augmentation/random_generator/_2d/translate.py
+++ b/kornia/augmentation/random_generator/_2d/translate.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
__all__ = ["TranslateGenerator"]
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
index 2dbff2c86..6dd02b97a 100644
--- a/kornia/augmentation/random_generator/_3d/affine.py
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _singular_range_check, _tuple_range_reader
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
class AffineGenerator3D(RandomGeneratorBase):
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 56b43413e..148b7796c 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -22,8 +22,8 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
+from kornia.core.utils import _extract_device_dtype
from kornia.geometry.bbox import bbox_generator3d
-from kornia.utils.helpers import _extract_device_dtype
class CropGenerator3D(RandomGeneratorBase):
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
index fc3f10063..50e8d3be9 100644
--- a/kornia/augmentation/random_generator/_3d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound, _tuple_range_reader
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
class MotionBlurGenerator3D(RandomGeneratorBase):
diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.py
index 03645c396..b5e2a75a4 100644
--- a/kornia/augmentation/random_generator/_3d/perspective.py
+++ b/kornia/augmentation/random_generator/_3d/perspective.py
@@ -22,7 +22,7 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
class PerspectiveGenerator3D(RandomGeneratorBase):
diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.py
index e9152b8c6..fba2d0037 100644
--- a/kornia/augmentation/random_generator/_3d/rotation.py
+++ b/kornia/augmentation/random_generator/_3d/rotation.py
@@ -21,7 +21,7 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _tuple_range_reader
-from kornia.utils.helpers import _extract_device_dtype
+from kornia.core.utils import _extract_device_dtype
class RotationGenerator3D(RandomGeneratorBase):
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 11c541d35..22a037da6 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -21,9 +21,9 @@ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
from torch.distributions import Beta, Uniform
+from kornia.core.utils import _extract_device_dtype
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
-from kornia.utils import _extract_device_dtype
def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:
diff --git a/kornia/contrib/boxmot_tracker.py b/kornia/contrib/boxmot_tracker.py
index f0353ca6c..eed984e00 100644
--- a/kornia/contrib/boxmot_tracker.py
+++ b/kornia/contrib/boxmot_tracker.py
@@ -29,8 +29,8 @@ from kornia.config import kornia_config
from kornia.contrib.object_detection import ObjectDetector, RTDETRDetectorBuilder
from kornia.core.external import boxmot
from kornia.core.external import numpy as np
+from kornia.image.utils import tensor_to_image
from kornia.io import write_image
-from kornia.utils.image import tensor_to_image
__all__ = ["BoxMotTracker"]
@@ -71,15 +71,9 @@ class BoxMotTracker:
fuse_first_associate: Whether to fuse appearance and motion information during the first association step.
with_reid: Whether to use ReID (Re-Identification) features for association.
- .. code-block:: python
-
- import kornia
- import torch
- image = kornia.utils.sample.get_sample_images()[0][None]
- model = BoxMotTracker()
- for i in range(4): # At least 4 frames are needed to initialize the tracking position
- model.update(image)
- model.save(image)
+ Note:
+ To use this tracker, load image tensors (shape: ``(1, C, H, W)``) and call ``model.update(image)``
+ for at least 4 frames before calling ``model.save(image)``.
.. note::
At least 4 frames are needed to initialize the tracking position.
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 3b37de999..888f8d1cd 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -21,7 +21,7 @@ import torch
from torch import nn
from kornia.filters import filter2d
-from kornia.utils import create_meshgrid
+from kornia.geometry.grid import create_meshgrid
def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.35) -> torch.Tensor:
diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.py
index 5ecbf0b51..85fc89860 100644
--- a/kornia/contrib/edge_detection.py
+++ b/kornia/contrib/edge_detection.py
@@ -212,11 +212,8 @@ class EdgeDetectorBuilder:
This is a high-level API that builds edge detection models like :py:class:`kornia.models.DexiNed`
and wraps them with :py:class:`EdgeDetector`.
- .. code-block:: python
-
- images = kornia.utils.sample.get_sample_images()
- model = EdgeDetectorBuilder.build()
- model.save(images)
+ Note:
+ To use this model, load image tensors and call ``model.save(images)``.
"""
@staticmethod
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 67b9ae950..608b5b52f 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -28,9 +28,9 @@ from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.external import PILImage as Image
from kornia.core.external import onnx
from kornia.core.mixin.onnx import ONNXExportMixin
+from kornia.image.draw import draw_rectangle
from kornia.models.base import ModelBase
from kornia.models.processors import ResizePreProcessor
-from kornia.utils.draw import draw_rectangle
__all__ = [
"BoundingBox",
@@ -402,11 +402,8 @@ class RTDETRDetectorBuilder:
- Build an object detection model from a model name or configuration.
- Export the model to ONNX format for inference.
- .. code-block:: python
-
- images = kornia.utils.sample.get_sample_images()
- model = RTDETRDetectorBuilder.build()
- model.save(images)
+ Note:
+ To use this model, load image tensors and call ``model.save(images)``.
"""
@staticmethod
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index 0f0e8a18c..6149b5c38 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -27,7 +27,7 @@ from kornia.core.mixin.onnx import ONNXExportMixin
from kornia.models.base import ModelBase
from kornia.models.processors import OutputRangePostProcessor, ResizePreProcessor
from kornia.models.small_sr import SmallSRNetWrapper
-from kornia.utils.download import CachedDownloader
+from kornia.onnx.download import CachedDownloader
__all__ = ["RRDBNetBuilder", "SmallSRBuilder", "SuperResolution"]
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index b1c24870d..bd40fefb1 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -28,7 +28,7 @@ from .mixin import (
ONNXRuntimeMixin,
)
from .module import ImageModule, ImageSequential
-from .tensor_wrapper import TensorWrapper # type: ignore
+from .tensor_wrapper import TensorWrapper
__all__ = [
"ImageModule",
@@ -39,4 +39,6 @@ __all__ = [
"ONNXRuntimeMixin",
"TensorWrapper",
"external",
+ "eye_like",
+ "vec_like",
]
diff --git a/kornia/core/_compat.py b/kornia/core/_compat.py
new file mode 100644
index 000000000..d12d3191f
--- /dev/null
+++ b/kornia/core/_compat.py
@@ -0,0 +1,221 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+
+import warnings
+from functools import wraps
+from inspect import isclass
+from typing import Any, Callable, Optional
+
+import torch
+from packaging import version
+
+
+def torch_version() -> str:
+ """Parse the PyTorch version string and remove build metadata.
+
+ Extracts the clean version number from `torch.__version__` by removing any
+ build suffixes like "+cu118" (CUDA builds) or "+cpu" (CPU builds).
+
+ Returns:
+ The clean version string (e.g., "2.0.1" from "2.0.1+cu118").
+
+ Example:
+ >>> torch_version()
+ '2.0.1'
+ """
+ return torch.__version__.partition("+")[0]
+
+
+def torch_version_lt(major: int, minor: int, patch: int) -> bool:
+ """Check if the current PyTorch version is less than the specified version.
+
+ Args:
+ major: Major version number (e.g., 2 for version 2.x.x).
+ minor: Minor version number (e.g., 0 for version x.0.x).
+ patch: Patch version number (e.g., 1 for version x.x.1).
+
+ Returns:
+ True if the current PyTorch version is strictly less than the specified version,
+ False otherwise.
+
+ Example:
+ >>> torch_version_lt(2, 0, 0) # True if PyTorch < 2.0.0
+ False
+ >>> torch_version_lt(3, 0, 0) # True if PyTorch < 3.0.0
+ True
+ """
+ _version = version.parse(torch_version())
+ return _version < version.parse(f"{major}.{minor}.{patch}")
+
+
+def torch_version_le(major: int, minor: int, patch: int) -> bool:
+ """Check if the current PyTorch version is less than or equal to the specified version.
+
+ Args:
+ major: Major version number (e.g., 2 for version 2.x.x).
+ minor: Minor version number (e.g., 0 for version x.0.x).
+ patch: Patch version number (e.g., 1 for version x.x.1).
+
+ Returns:
+ True if the current PyTorch version is less than or equal to the specified version,
+ False otherwise.
+
+ Example:
+ >>> torch_version_le(2, 0, 0) # True if PyTorch <= 2.0.0
+ True
+ >>> torch_version_le(1, 13, 0) # True if PyTorch <= 1.13.0
+ True
+ """
+ _version = version.parse(torch_version())
+ return _version <= version.parse(f"{major}.{minor}.{patch}")
+
+
+def torch_version_ge(major: int, minor: int, patch: Optional[int] = None) -> bool:
+ """Check if the current PyTorch version is greater than or equal to the specified version.
+
+ This function is useful for implementing version-specific behavior or compatibility checks.
+ When `patch` is None, only major and minor versions are compared.
+
+ Args:
+ major: Major version number (e.g., 2 for version 2.x.x).
+ minor: Minor version number (e.g., 0 for version x.0.x).
+ patch: Optional patch version number (e.g., 1 for version x.x.1).
+ If None, only major.minor version is compared.
+
+ Returns:
+ True if the current PyTorch version is greater than or equal to the specified version,
+ False otherwise.
+
+ Example:
+ >>> torch_version_ge(2, 0, 0) # True if PyTorch >= 2.0.0
+ True
+ >>> torch_version_ge(2, 4) # True if PyTorch >= 2.4.0 (any patch)
+ True
+ >>> torch_version_ge(3, 0, 0) # True if PyTorch >= 3.0.0
+ False
+ """
+ _version = version.parse(torch_version())
+ if patch is None:
+ return _version >= version.parse(f"{major}.{minor}")
+ else:
+ return _version >= version.parse(f"{major}.{minor}.{patch}")
+
+
+def _emit_deprecation_warning(
+ name: str, replace_with: Optional[str], version: Optional[str], extra_reason: Optional[str]
+) -> None:
+ """Emit a deprecation warning with the given parameters."""
+ beginning = f"Since kornia {version} the " if version is not None else ""
+ extra = f" {extra_reason}" if extra_reason else ""
+
+ warnings.simplefilter("always", DeprecationWarning)
+ try:
+ if replace_with is not None:
+ msg = f"{beginning}`{name}` is deprecated in favor of `{replace_with}`.{extra}"
+ else:
+ msg = f"{beginning}`{name}` is deprecated and will be removed in the future versions.{extra}"
+ warnings.warn(
+ msg,
+ category=DeprecationWarning,
+ stacklevel=3,
+ )
+ finally:
+ warnings.simplefilter("default", DeprecationWarning)
+
+
+def deprecated(
+ replace_with: Optional[str] = None, version: Optional[str] = None, extra_reason: Optional[str] = None
+) -> Any:
+ """Mark functions or classes as deprecated with a warning.
+
+ This decorator emits a :class:`DeprecationWarning` when the decorated function or class is called.
+ It provides information about when the deprecation was introduced and what should be used instead.
+
+ Args:
+ replace_with: The name of the replacement function/class that should be used instead.
+ If provided, the warning message will suggest using this replacement.
+ version: The kornia version when the deprecation was introduced (e.g., "0.8.3").
+ If provided, the warning message will include "Since kornia {version}".
+ extra_reason: Additional context or reason for the deprecation. This will be appended
+ to the warning message.
+
+ Returns:
+ A decorator that wraps the function or class with deprecation warnings.
+
+ Example:
+ Basic usage without replacement:
+ ```python
+ @deprecated(version="0.8.3")
+ def old_function():
+ pass
+ ```
+
+ With replacement suggestion:
+ ```python
+ @deprecated(replace_with="new_function", version="0.8.3")
+ def old_function():
+ pass
+ ```
+
+ With additional context:
+ ```python
+ @deprecated(
+ replace_with="new_function",
+ version="0.8.3",
+ extra_reason=" The old implementation has performance issues."
+ )
+ def old_function():
+ pass
+ ```
+
+ Works with classes too:
+ ```python
+ @deprecated(replace_with="NewClass", version="0.8.3")
+ class OldClass:
+ pass
+ ```
+ """
+
+ def _deprecated(func: Callable[..., Any]) -> Any:
+ # Get the name - use __name__ for both functions and classes
+ name = getattr(func, "__name__", "unknown")
+
+ if isclass(func):
+ # For classes, wrap in a function that emits warning and instantiates the class
+ # We manually preserve important class attributes since @wraps doesn't work on classes
+ def class_wrapper(*args: Any, **kwargs: Any) -> Any:
+ _emit_deprecation_warning(name, replace_with, version, extra_reason)
+ return func(*args, **kwargs)
+
+ # Preserve important class attributes
+ class_wrapper.__name__ = name
+ class_wrapper.__qualname__ = getattr(func, "__qualname__", name)
+ class_wrapper.__module__ = getattr(func, "__module__", None)
+ class_wrapper.__doc__ = func.__doc__
+ class_wrapper.__annotations__ = getattr(func, "__annotations__", {})
+ return class_wrapper
+ else:
+ # For functions, use @wraps normally
+ @wraps(func)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ _emit_deprecation_warning(name, replace_with, version, extra_reason)
+ return func(*args, **kwargs)
+
+ return wrapper
+
+ return _deprecated
diff --git a/kornia/core/check.py b/kornia/core/check.py
index d075135cc..e1d5d21f6 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -24,7 +24,6 @@ from typing import Any, Optional, Sequence, TypeVar, cast
import torch
from torch import float16, float32, float64
-from typing_extensions import TypeGuard
from kornia.core.exceptions import (
BaseError,
@@ -255,7 +254,7 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = True
return True
-def KORNIA_UNWRAP(maybe_obj: object, typ: Any) -> Any:
+def KORNIA_UNWRAP(maybe_obj: Any, typ: Any) -> Any:
"""Unwrap an optional contained value that may or not be present.
Args:
@@ -270,9 +269,7 @@ def KORNIA_UNWRAP(maybe_obj: object, typ: Any) -> Any:
T = TypeVar("T", bound=type)
-def KORNIA_CHECK_TYPE(
- x: object, typ: T | tuple[T, ...], msg: Optional[str] = None, raises: bool = True
-) -> TypeGuard[T]:
+def KORNIA_CHECK_TYPE(x: Any, typ: T | tuple[T, ...], msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check the type of an aribratry variable.
Args:
@@ -301,20 +298,29 @@ def KORNIA_CHECK_TYPE(
if not isinstance(x, typ):
if raises:
- expected_type_str = typ.__name__ if not isinstance(typ, tuple) else " | ".join(t.__name__ for t in typ)
- error_msg = f"Type mismatch: expected {expected_type_str}, got {type(x).__name__}."
- if msg is not None:
- error_msg += f"\n {msg}"
- raise TypeCheckError(
- error_msg,
- actual_type=type(x),
- expected_type=typ,
- )
+ # JIT doesn't support try-except or type introspection, so use simple message
+ if torch.jit.is_scripting():
+ error_msg = "Type mismatch."
+ if msg is not None:
+ error_msg += f"\n {msg}"
+ raise TypeCheckError(error_msg)
+ else:
+ # In Python mode, we can safely use type introspection
+ expected_type_str = typ.__name__ if not isinstance(typ, tuple) else " | ".join(t.__name__ for t in typ)
+ type_name = str(type(x))
+ error_msg = f"Type mismatch: expected {expected_type_str}, got {type_name}."
+ if msg is not None:
+ error_msg += f"\n {msg}"
+ raise TypeCheckError(
+ error_msg,
+ actual_type=type(x),
+ expected_type=typ,
+ )
return False
return True
-def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool = True) -> TypeGuard[torch.Tensor]:
+def KORNIA_CHECK_IS_TENSOR(x: Any, msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check the input variable is a Tensor.
Args:
@@ -343,19 +349,28 @@ def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool =
if not isinstance(x, torch.Tensor):
if raises:
- error_msg = f"Type mismatch: expected Tensor, got {type(x).__name__}."
- if msg is not None:
- error_msg += f"\n {msg}"
- raise TypeCheckError(
- error_msg,
- actual_type=type(x),
- expected_type=torch.Tensor,
- )
+ # JIT doesn't support try-except or type introspection, so use simple message
+ if torch.jit.is_scripting():
+ error_msg = "Type mismatch: expected Tensor."
+ if msg is not None:
+ error_msg += f"\n {msg}"
+ raise TypeCheckError(error_msg)
+ else:
+ # In Python mode, we can safely use type introspection
+ type_name = str(type(x))
+ error_msg = f"Type mismatch: expected Tensor, got {type_name}."
+ if msg is not None:
+ error_msg += f"\n {msg}"
+ raise TypeCheckError(
+ error_msg,
+ actual_type=type(x),
+ expected_type=torch.Tensor,
+ )
return False
return True
-def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool = True) -> TypeGuard[list[torch.Tensor]]:
+def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[Any]], raises: bool = True) -> bool:
"""Check the input variable is a List of Tensors.
Args:
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index ca1e9e574..c4d24d28b 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -19,7 +19,7 @@ import datetime
import math
import os
from functools import wraps
-from typing import Any, Callable, List, Optional, Tuple, Union
+from typing import Any, Callable, List, Literal, Optional, Tuple, Union
import torch
@@ -39,18 +39,21 @@ class ImageModuleMixIn:
def convert_input_output(
self,
input_names_to_handle: Optional[List[Any]] = None,
- output_type: str = "tensor",
+ output_type: Literal["pt", "numpy", "pil"] = "pt",
) -> Callable[[Any], Any]:
"""Convert input and output types for a function.
Args:
input_names_to_handle: List of input names to convert, if None, handle all inputs.
- output_type: Desired output type ('tensor', 'numpy', or 'pil').
+ output_type: Desired output type ('pt', 'numpy', or 'pil').
Returns:
Callable: Decorated function with converted input and output types.
"""
+ # Validate output_type at the start
+ if output_type not in ("pt", "numpy", "pil"):
+ raise ValueError(f"Invalid output_type '{output_type}'. Must be one of 'pt', 'numpy', or 'pil'.")
def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
@wraps(func)
@@ -75,20 +78,20 @@ class ImageModuleMixIn:
# Call the actual forward method
tensor_outputs = func(*args, **kwargs)
- if not isinstance(tensor_outputs, (tuple,)):
+ if not isinstance(tensor_outputs, tuple):
tensor_outputs = (tensor_outputs,)
# Convert outputs to the desired type
outputs = []
for output in tensor_outputs:
- if output_type == "tensor":
+ if output_type == "pt":
outputs.append(output)
elif output_type == "numpy":
outputs.append(self.to_numpy(output))
elif output_type == "pil":
outputs.append(self.to_pil(output))
else:
- raise ValueError("Output type not supported. Choose from 'tensor', 'numpy', or 'pil'.")
+ raise ValueError("Output type not supported. Choose from 'pt', 'numpy', or 'pil'.")
return outputs if len(outputs) > 1 else outputs[0]
@@ -106,12 +109,12 @@ class ImageModuleMixIn:
bool: True if valid, False otherwise.
"""
- if isinstance(arg, (str,)) and os.path.exists(arg):
+ if isinstance(arg, str) and os.path.exists(arg):
return True
- if isinstance(arg, (torch.Tensor,)):
+ if isinstance(arg, torch.Tensor):
return True
# Make sure that the numpy and PIL are not necessarily needed to be imported.
- if isinstance(arg, (np.ndarray,)): # type: ignore
+ if isinstance(arg, np.ndarray): # type: ignore
return True
if isinstance(arg, (Image.Image)): # type: ignore
return True
@@ -129,17 +132,17 @@ class ImageModuleMixIn:
Tensor: The converted tensor.
"""
- if isinstance(x, (str,)):
+ if isinstance(x, str):
from kornia.io import ImageLoadType, load_image # pylint: disable=C0415
return load_image(x, ImageLoadType.UNCHANGED) / 255
- if isinstance(x, (torch.Tensor,)):
+ if isinstance(x, torch.Tensor):
return x
- if isinstance(x, (np.ndarray,)): # type: ignore
- from kornia.utils.image import image_to_tensor # pylint: disable=C0415
+ if isinstance(x, np.ndarray): # type: ignore
+ from kornia.image.utils import image_to_tensor # pylint: disable=C0415
return image_to_tensor(x) / 255
- if isinstance(x, (Image.Image,)): # type: ignore
+ if isinstance(x, Image.Image): # type: ignore
return torch.from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore
raise TypeError("Input type not supported")
@@ -153,11 +156,11 @@ class ImageModuleMixIn:
np.array: The converted numpy array.
"""
- if isinstance(x, (torch.Tensor,)):
+ if isinstance(x, torch.Tensor):
return x.cpu().detach().numpy()
- if isinstance(x, (np.ndarray,)): # type: ignore
+ if isinstance(x, np.ndarray): # type: ignore
return x
- if isinstance(x, (Image.Image,)): # type: ignore
+ if isinstance(x, Image.Image): # type: ignore
return np.array(x) # type: ignore
raise TypeError("Input type not supported")
@@ -171,7 +174,7 @@ class ImageModuleMixIn:
Image.Image: The converted PIL image.
"""
- if isinstance(x, (torch.Tensor,)):
+ if isinstance(x, torch.Tensor):
x = x.cpu().detach() * 255
if x.dim() == 3:
x = x.permute(1, 2, 0)
@@ -181,24 +184,18 @@ class ImageModuleMixIn:
return [Image.fromarray(_x.byte().numpy()) for _x in x] # type: ignore
else:
raise NotImplementedError
- if isinstance(x, (np.ndarray,)): # type: ignore
+ if isinstance(x, np.ndarray): # type: ignore
raise NotImplementedError
- if isinstance(x, (Image.Image,)): # type: ignore
+ if isinstance(x, Image.Image): # type: ignore
return x
raise TypeError("Input type not supported")
def _detach_tensor_to_cpu(
self, output_image: Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]
) -> Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]:
- if isinstance(output_image, (torch.Tensor,)):
+ if isinstance(output_image, torch.Tensor):
return output_image.detach().cpu()
- if isinstance(
- output_image,
- (
- list,
- tuple,
- ),
- ):
+ if isinstance(output_image, list | tuple):
return type(output_image)([self._detach_tensor_to_cpu(out) for out in output_image]) # type: ignore
raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")
@@ -217,7 +214,7 @@ class ImageModuleMixIn:
if len(self._output_image.shape) == 3:
out_image = self._output_image
elif len(self._output_image.shape) == 4:
- from kornia.utils.image import make_grid # pylint: disable=C0415
+ from kornia.image.utils import make_grid # pylint: disable=C0415
if n_row is None:
n_row = math.ceil(self._output_image.shape[0] ** 0.5)
@@ -240,8 +237,8 @@ class ImageModuleMixIn:
n_row: Number of images displayed in each row of the grid.
"""
+ from kornia.image.utils import make_grid # pylint: disable=C0415
from kornia.io import write_image # pylint: disable=C0415
- from kornia.utils.image import make_grid # pylint: disable=C0415
if name is None:
name = f"Kornia-{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}.jpg"
diff --git a/kornia/core/module.py b/kornia/core/module.py
index 546d42e34..7b938f551 100644
--- a/kornia/core/module.py
+++ b/kornia/core/module.py
@@ -17,263 +17,14 @@
from __future__ import annotations
-import datetime
-import math
-import os
-from functools import wraps
-from typing import Any, Callable, Optional, Union
+from typing import Any, Literal, Optional
-import torch
from torch import nn
-# TODO: not use top level import
-import kornia
-
-from .external import PILImage as Image
-from .external import numpy as np
+from .mixin.image_module import ImageModuleMixIn
from .mixin.onnx import ONNXExportMixin
-class ImageModuleMixIn:
- """A MixIn that handles image-based operations.
-
- This modules accepts multiple input and output data types, provides end-to-end visualization, file saving features.
- Note that this MixIn fits the classes that return one image tensor only.
- """
-
- _output_image: Any
-
- def convert_input_output(
- self,
- input_names_to_handle: Optional[list[Any]] = None,
- output_type: str = "tensor",
- ) -> Callable[[Any], Any]:
- """Convert input and output types for a function.
-
- Args:
- input_names_to_handle: List of input names to convert, if None, handle all inputs.
- output_type: Desired output type ('tensor', 'numpy', or 'pil').
-
- Returns:
- Callable: Decorated function with converted input and output types.
-
- """
- # Ensure output_type has a valid default
- if not output_type or output_type not in ("tensor", "numpy", "pil"):
- output_type = "tensor"
-
- def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
- @wraps(func)
- def wrapper(*args: Any, **kwargs: Any) -> Union[Any, list[Any]]:
- # Remove output_type and input_names_to_handle from kwargs if present
- # (they are handled by the decorator, not the wrapped function)
- kwargs.pop("output_type", None)
- kwargs.pop("input_names_to_handle", None)
-
- # If input_names_to_handle is None, handle all inputs
- if input_names_to_handle is None:
- # Convert all args to tensors
- args = tuple(self.to_tensor(arg) if self._is_valid_arg(arg) else arg for arg in args)
- # Convert all kwargs to tensors
- kwargs = {k: self.to_tensor(v) if self._is_valid_arg(v) else v for k, v in kwargs.items()}
- else:
- # Convert specified args to tensors
- args = list(args) # type:ignore
- for i, (arg, name) in enumerate(zip(args, func.__code__.co_varnames)):
- if name in input_names_to_handle:
- args[i] = self.to_tensor(arg) # type:ignore
- # Convert specified kwargs to tensors
- for name, value in kwargs.items():
- if name in input_names_to_handle:
- kwargs[name] = self.to_tensor(value)
-
- # Call the actual forward method
- tensor_outputs = func(*args, **kwargs)
-
- if not isinstance(tensor_outputs, (tuple,)):
- tensor_outputs = (tensor_outputs,)
-
- # Convert outputs to the desired type
- outputs = []
- for output in tensor_outputs:
- if output_type == "tensor":
- outputs.append(output)
- elif output_type == "numpy":
- outputs.append(self.to_numpy(output))
- elif output_type == "pil":
- outputs.append(self.to_pil(output))
- else:
- raise ValueError("Output type not supported. Choose from 'tensor', 'numpy', or 'pil'.")
-
- return outputs if len(outputs) > 1 else outputs[0]
-
- return wrapper
-
- return decorator
-
- def _is_valid_arg(self, arg: Any) -> bool:
- """Check if the argument is a valid type for conversion.
-
- Args:
- arg: The argument to check.
-
- Returns:
- bool: True if valid, False otherwise.
-
- """
- if isinstance(arg, (str,)) and os.path.exists(arg):
- return True
- if isinstance(arg, (torch.Tensor,)):
- return True
- # Make sure that the numpy and PIL are not necessarily needed to be imported.
- if isinstance(arg, (np.ndarray,)): # type: ignore
- return True
- if isinstance(arg, (Image.Image)): # type: ignore
- return True
- return False
-
- def to_tensor(self, x: Any) -> torch.Tensor:
- """Convert input to tensor.
-
- Supports image path, numpy array, PIL image, and raw tensor.
-
- Args:
- x: The input to convert.
-
- Returns:
- Tensor: The converted tensor.
-
- """
- if isinstance(x, (str,)):
- return kornia.io.load_image(x, kornia.io.ImageLoadType.UNCHANGED) / 255
- if isinstance(x, (torch.Tensor,)):
- return x
- if isinstance(x, (np.ndarray,)): # type: ignore
- return kornia.utils.image.image_to_tensor(x) / 255
- if isinstance(x, (Image.Image,)): # type: ignore
- return torch.from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore
- raise TypeError("Input type not supported")
-
- def to_numpy(self, x: Any) -> np.array: # type: ignore
- """Convert input to numpy array.
-
- Args:
- x: The input to convert.
-
- Returns:
- np.array: The converted numpy array.
-
- """
- if isinstance(x, (torch.Tensor,)):
- return x.cpu().detach().numpy()
- if isinstance(x, (np.ndarray,)): # type: ignore
- return x
- if isinstance(x, (Image.Image,)): # type: ignore
- return np.array(x) # type: ignore
- raise TypeError("Input type not supported")
-
- def to_pil(self, x: Any) -> Image.Image: # type: ignore
- """Convert input to PIL image.
-
- Args:
- x: The input to convert.
-
- Returns:
- Image.Image: The converted PIL image.
-
- """
- if isinstance(x, (torch.Tensor,)):
- tensor = x.detach().cpu()
- if tensor.ndim == 3:
- tensor.mul_(255)
- arr = tensor.permute(1, 2, 0).contiguous().byte().numpy()
- if arr.shape[2] == 1:
- arr = arr[:, :, 0]
- return Image.fromarray(arr) # type: ignore
- if tensor.ndim == 4:
- tensor.mul_(255)
- tensor_chw = tensor.permute(0, 2, 3, 1).contiguous()
- numpy_batch = tensor_chw.byte().numpy()
- return [Image.fromarray(img) for img in numpy_batch] # type: ignore
- else:
- raise NotImplementedError
- if isinstance(x, (np.ndarray,)): # type: ignore
- raise NotImplementedError
- if isinstance(x, (Image.Image,)): # type: ignore
- return x
- raise TypeError("Input type not supported")
-
- def _detach_tensor_to_cpu(
- self, output_image: Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor]]
- ) -> Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor]]:
- """Detach the input tensor (or list/tuple of tensors) from the GPU and move it to the CPU.
-
- Args:
- output_image (Union[Tensor, list[Tensor], tuple[Tensor]]): The input tensor(s) to be moved.
-
- Returns:
- Union[Tensor, list[Tensor], tuple[Tensor]]: The tensor(s) moved to the CPU and detached from
- the computational graph.
- """
- if isinstance(output_image, (torch.Tensor,)):
- return output_image.detach().cpu()
- if isinstance(
- output_image,
- (
- list,
- tuple,
- ),
- ):
- return type(output_image)([self._detach_tensor_to_cpu(out) for out in output_image]) # type: ignore
- raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")
-
- def show(self, n_row: Optional[int] = None, backend: str = "pil", display: bool = True) -> Optional[Any]:
- """Return PIL images.
-
- Args:
- n_row: Number of images displayed in each row of the grid.
- backend: visualization backend. Only PIL is supported now.
- display: whether to display the image.
-
- """
- if self._output_image is None:
- raise ValueError("No pre-computed images found. Needs to execute first.")
-
- if len(self._output_image.shape) == 3:
- out_image = self._output_image
- elif len(self._output_image.shape) == 4:
- if n_row is None:
- n_row = math.ceil(self._output_image.shape[0] ** 0.5)
- out_image = kornia.utils.image.make_grid(self._output_image, n_row, padding=2)
- else:
- raise ValueError
-
- if backend == "pil" and display:
- Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)).show() # type: ignore
- return None
- if backend == "pil":
- return Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)) # type: ignore
- raise ValueError(f"Unsupported backend `{backend}`.")
-
- def save(self, name: Optional[str] = None, n_row: Optional[int] = None) -> None:
- """Save the output image(s) to a directory.
-
- Args:
- name: Directory to save the images.
- n_row: Number of images displayed in each row of the grid.
-
- """
- if name is None:
- name = f"Kornia-{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}.jpg"
- if len(self._output_image.shape) == 3:
- out_image = self._output_image
- if len(self._output_image.shape) == 4:
- if n_row is None:
- n_row = math.ceil(self._output_image.shape[0] ** 0.5)
- out_image = kornia.utils.image.make_grid(self._output_image, n_row, padding=2)
- kornia.io.write_image(name, out_image.mul(255.0).byte())
-
-
class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):
"""Handles image-based operations.
@@ -303,7 +54,7 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):
self,
*inputs: Any,
input_names_to_handle: Optional[list[Any]] = None,
- output_type: str = "tensor",
+ output_type: Literal["pt", "numpy", "pil"] = "pt",
**kwargs: Any,
) -> Any:
"""Overwrite the __call__ function to handle various inputs.
@@ -311,7 +62,7 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):
Args:
inputs: Inputs to operate on.
input_names_to_handle: List of input names to convert, if None, handle all inputs.
- output_type: Desired output type ('tensor', 'numpy', or 'pil').
+ output_type: Desired output type ('pt', 'numpy', or 'pil').
kwargs: Additional arguments.
Returns:
@@ -324,7 +75,7 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):
input_names_to_handle=input_names_to_handle, output_type=output_type
)(super().__call__)
_output_image = decorated_forward(*inputs, **kwargs)
- if output_type == "tensor":
+ if output_type == "pt":
self._output_image = self._detach_tensor_to_cpu(_output_image)
else:
self._output_image = _output_image
@@ -362,7 +113,7 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):
self,
*inputs: Any,
input_names_to_handle: Optional[list[Any]] = None,
- output_type: str = "tensor",
+ output_type: Literal["pt", "numpy", "pil"] = "pt",
**kwargs: Any,
) -> Any:
"""Overwrite the __call__ function to handle various inputs.
@@ -370,7 +121,7 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):
Args:
inputs: Inputs to operate on.
input_names_to_handle: List of input names to convert, if None, handle all inputs.
- output_type: Desired output type ('tensor', 'numpy', or 'pil').
+ output_type: Desired output type ('pt', 'numpy', or 'pil').
kwargs: Additional arguments.
Returns:
@@ -383,7 +134,7 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):
input_names_to_handle=input_names_to_handle, output_type=output_type
)(super().__call__)
_output_image = decorated_forward(*inputs, **kwargs)
- if output_type == "tensor":
+ if output_type == "pt":
self._output_image = self._detach_tensor_to_cpu(_output_image)
else:
self._output_image = _output_image
diff --git a/kornia/utils/misc.py b/kornia/core/ops.py
similarity index 54%
rename from kornia/utils/misc.py
rename to kornia/core/ops.py
index 7af3c35d2..82f3d59aa 100644
--- a/kornia/utils/misc.py
+++ b/kornia/core/ops.py
@@ -15,10 +15,10 @@
# limitations under the License.
#
-from typing import Optional
-
import torch
+from kornia.core.check import KORNIA_CHECK
+
def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
r"""Return a 2-D tensor with ones on the diagonal and zeros elsewhere with the same batch size as the input.
@@ -38,12 +38,11 @@ def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.
use this method with shared_memory=False, otherwise, prefer using it with shared_memory=True.
"""
- if n <= 0:
- raise AssertionError(type(n), n)
- if len(input.shape) < 1:
- raise AssertionError(input.shape)
+ KORNIA_CHECK(n > 0, f"n must be positive. Got: {n}")
+ KORNIA_CHECK(len(input.shape) >= 1, f"input must have at least 1 dimension. Got shape: {input.shape}")
- identity = torch.eye(n, device=input.device).type(input.dtype)
+ # Use torch.eye with dtype parameter directly (available since PyTorch 2.0+)
+ identity = torch.eye(n, device=input.device, dtype=input.dtype)
return identity[None].expand(input.shape[0], n, n) if shared_memory else identity[None].repeat(input.shape[0], 1, 1)
@@ -66,70 +65,8 @@ def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False) -> torch
use this method with shared_memory=False, otherwise, prefer using it with shared_memory=True.
"""
- if n <= 0:
- raise AssertionError(type(n), n)
- if len(tensor.shape) < 1:
- raise AssertionError(tensor.shape)
+ KORNIA_CHECK(n > 0, f"n must be positive. Got: {n}")
+ KORNIA_CHECK(len(tensor.shape) >= 1, f"tensor must have at least 1 dimension. Got shape: {tensor.shape}")
vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
return vec[None].expand(tensor.shape[0], n, 1) if shared_memory else vec[None].repeat(tensor.shape[0], 1, 1)
-
-
-def differentiable_polynomial_rounding(input: torch.Tensor) -> torch.Tensor:
- """Differentiable rounding.
-
- Args:
- input (torch.Tensor): Input tensor of any shape to be rounded.
-
- Returns:
- output (torch.Tensor): Pseudo rounded tensor of the same shape as input tensor.
-
- """
- # Perform differentiable rounding
- input_round = input.round()
- output: torch.Tensor = input_round + (input - input_round) ** 3
- return output
-
-
-def differentiable_polynomial_floor(input: torch.Tensor) -> torch.Tensor:
- """Perform floor via a differentiable operation.
-
- Args:
- input (torch.Tensor): Input tensor of any shape to be floored.
-
- Returns:
- output (torch.Tensor): Pseudo rounded tensor of the same shape as input tensor.
-
- """
- # Perform differentiable rounding
- input_floor = input.floor()
- output: torch.Tensor = input_floor + (input - 0.5 - input_floor) ** 3
- return output
-
-
-def differentiable_clipping(
- input: torch.Tensor,
- min_val: Optional[float] = None,
- max_val: Optional[float] = None,
- scale: float = 0.02,
-) -> torch.Tensor:
- """Clip via a differentiable and soft approximation of the clipping operation.
-
- Args:
- input (torch.Tensor): Input tensor of any shape.
- min_val (Optional[float]): Minimum value.
- max_val (Optional[float]): Maximum value.
- scale (float): Scale value. Default 0.02.
-
- Returns:
- output (torch.Tensor): Clipped output tensor of the same shape as the input tensor.
-
- """
- # Make a copy of the input tensor
- output: torch.Tensor = input.clone()
- # Perform differentiable soft clipping
- if max_val is not None:
- output[output > max_val] = -scale * (torch.exp(-output[output > max_val] + max_val) - 1.0) + max_val
- if min_val is not None:
- output[output < min_val] = scale * (torch.exp(output[output < min_val] - min_val) - 1.0) + min_val
- return output
diff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.py
index 9e4f398fb..b21e0cb62 100644
--- a/kornia/core/tensor_wrapper.py
+++ b/kornia/core/tensor_wrapper.py
@@ -15,169 +15,268 @@
# limitations under the License.
#
-# type: ignore
-# pytorch tensor wrapper class
-# insipired by:
-# https://github.com/pytorch/pytorch/blob/591dfffa38848de54b7f5f4e49260847024c9281/test/test_overrides.py#L748
-import collections
+from __future__ import annotations
+
+import collections.abc
+from typing import Any, Optional
import torch
from torch import Tensor
+from kornia.core.check import KORNIA_CHECK_IS_TENSOR
+
+
+def _wrap(v: Any, cls: type[TensorWrapper]) -> Any:
+ """Wrap type.
+
+ Args:
+ v: Value to wrap (tensor, list, tuple, or other).
+ cls: TensorWrapper class to use for wrapping.
-# TODO: promote to KORNIA_WRAP
-def wrap(v, cls):
- """Wrap type."""
+ Returns:
+ Wrapped value if tensor, otherwise original value or wrapped collection.
+ """
# wrap inputs if necessary
if type(v) in {tuple, list}:
- return type(v)(wrap(vi, cls) for vi in v)
+ return type(v)(_wrap(vi, cls) for vi in v)
return cls(v) if isinstance(v, Tensor) else v
-# TODO: promote to KORNIA_UNWRAP
-def unwrap(v):
- """Unwrap nested type."""
+def _unwrap(v: Any) -> Any:
+ """Unwrap nested type.
+
+ Args:
+ v: Value to unwrap (TensorWrapper, list, tuple, or other).
+
+ Returns:
+ Unwrapped value (underlying tensor or original value).
+ """
if type(v) in {tuple, list}:
- return type(v)(unwrap(vi) for vi in v)
+ return type(v)(_unwrap(vi) for vi in v)
return v._data if isinstance(v, TensorWrapper) else v
class TensorWrapper:
- """Wrap a PyTorch Tensor to provide additional metadata and specialized methods.
-
- Args:
- data: The underlying :class:`torch.Tensor` to be wrapped.
- """
+ """Wrapper around PyTorch tensors that tracks attribute and function usage.
- def __init__(self, data: Tensor) -> None:
- self.__dict__["_data"] = data
- self.__dict__["used_attrs"] = set()
- self.__dict__["used_calls"] = set()
+ This class provides a transparent wrapper around PyTorch tensors while
+ tracking which attributes and functions are accessed. Useful for debugging
+ and understanding tensor usage patterns.
- def unwrap(self):
- return unwrap(self)
+ Attributes:
+ _data: The underlying PyTorch tensor.
+ used_attrs: Set of attribute names that have been accessed.
+ used_calls: Set of functions that have been called.
+ """
- def __getstate__(self):
- return self.__dict__
+ __slots__ = ("_data", "used_attrs", "used_calls")
- def __setstate__(self, state):
- self.__dict__.update(state)
+ def __init__(self, data: Tensor) -> None:
+ """Initialize TensorWrapper with a PyTorch tensor.
+
+ Args:
+ data: The PyTorch tensor to wrap. If data is already a TensorWrapper,
+ its underlying tensor will be extracted.
+
+ Raises:
+ TypeCheckError: If data is not a PyTorch tensor or TensorWrapper.
+ """
+ # Handle case where data is already a TensorWrapper (e.g., Scalar wrapping another Scalar)
+ if isinstance(data, TensorWrapper):
+ data = data._data
+ KORNIA_CHECK_IS_TENSOR(data, "Expected Tensor for TensorWrapper")
+ object.__setattr__(self, "_data", data)
+ object.__setattr__(self, "used_attrs", set())
+ object.__setattr__(self, "used_calls", set())
+
+ def unwrap(self) -> Tensor:
+ """Return the underlying PyTorch tensor."""
+ return _unwrap(self)
+
+ @property
+ def data(self) -> Tensor:
+ """Access the underlying tensor."""
+ return self._data
+
+ def __getstate__(self) -> dict[str, Any]:
+ """Support for pickle serialization."""
+ return {
+ "_data": self._data,
+ "used_attrs": self.used_attrs,
+ "used_calls": self.used_calls,
+ }
+
+ def __setstate__(self, state: dict[str, Any]) -> None:
+ """Support for pickle deserialization."""
+ object.__setattr__(self, "_data", state["_data"])
+ object.__setattr__(self, "used_attrs", state.get("used_attrs", set()))
+ object.__setattr__(self, "used_calls", state.get("used_calls", set()))
def __repr__(self) -> str:
- return f"{self._data}"
+ """Return string representation."""
+ return f"{self.__class__.__name__}({self._data})"
- def __getattr__(self, name):
+ def __getattr__(self, name: str) -> Any:
+ """Get attribute from underlying tensor."""
+ # Handle special 'data' property
if name == "data":
return self._data
- elif name in self.__dict__:
- return self.__dict__[name]
+
+ # Track attribute usage
self.used_attrs.add(name)
+ # Get value from underlying tensor
val = getattr(self._data, name)
- # NOTE: not clear is really needed
- # If it's a method
- # if callable(val):
- # c = getattr(type(self._data), name)
- # # Don't append self to args if classmethod/staticmethod
- # if c is val:
- # return lambda *a, **kw: wrap(self.__torch_function__(c, (type(self),), args=a, kwargs=kw), type(self))
- # # Otherwise append self to args
- # return lambda *a, **kw: wrap(
- # #self.__torch_function__(c, (type(self),), args=(self,) + a, kwargs=kw), type(self)
- # )
-
- return wrap(val, type(self))
-
- def __setattr__(self, name, value) -> None:
- if name in self.__dict__:
- self.__dict__[name] = value
-
- self.used_attrs.add(name)
- setattr(self._data, name, value)
-
- def __setitem__(self, key, value) -> None:
+ # Wrap the result if it's a tensor
+ return _wrap(val, type(self))
+
+ def __setattr__(self, name: str, value: Any) -> None:
+ """Set attribute on underlying tensor."""
+ # Only track non-internal attributes
+ if name not in self.__slots__:
+ self.used_attrs.add(name)
+ setattr(self._data, name, value)
+ else:
+ # Use object.__setattr__ for internal attributes to avoid recursion
+ object.__setattr__(self, name, value)
+
+ def __setitem__(self, key: Any, value: Any) -> None:
+ """Set item on underlying tensor."""
self._data[key] = value
- def __getitem__(self, key):
- return wrap(self._data[key], type(self))
+ def __getitem__(self, key: Any) -> TensorWrapper:
+ """Get item from underlying tensor."""
+ return _wrap(self._data[key], type(self))
@classmethod
- def __torch_function__(cls, func, types, args=(), kwargs=None):
+ def __torch_function__(
+ cls,
+ func: Any,
+ types: tuple[type, ...],
+ args: tuple[Any, ...] = (),
+ kwargs: Optional[dict[str, Any]] = None,
+ ) -> Any:
+ """Intercept PyTorch function calls."""
if kwargs is None:
kwargs = {}
- # Find an instance of this class in the arguments
- args_of_this_cls = []
+
+ # Find instances of this class in the arguments
+ args_of_this_cls: list[TensorWrapper] = []
for a in args:
if isinstance(a, cls):
args_of_this_cls.append(a)
- elif isinstance(a, collections.abc.Sequence):
+ elif isinstance(a, collections.abc.Sequence) and not isinstance(a, str | bytes):
args_of_this_cls.extend(el for el in a if isinstance(el, cls))
- # assert len(args_of_this_cls) > 0
+
+ # Track function usage
for a in args_of_this_cls:
a.used_calls.add(func)
- args = unwrap(tuple(args))
- kwargs = {k: unwrap(v) for k, v in kwargs.items()}
- return wrap(func(*args, **kwargs), cls)
+ # Unwrap arguments and call the function
+ unwrapped_args = _unwrap(args)
+ unwrapped_kwargs = {k: _unwrap(v) for k, v in kwargs.items()}
- # TODO: `def __add__(self, other) -> Self:` when mypy release >0.991
- def __add__(self, other):
- return self.__unary_op__(torch.add, other)
+ return _wrap(func(*unwrapped_args, **unwrapped_kwargs), cls)
- def __radd__(self, other):
- return self.__unary_op__(torch.add, other)
+ def __add__(self, other: Any) -> TensorWrapper:
+ """Add operation."""
+ return self.__binary_op__(torch.add, other)
- def __mul__(self, other):
- return self.__unary_op__(torch.mul, other)
+ def __radd__(self, other: Any) -> TensorWrapper:
+ """Right-side add operation."""
+ return self.__binary_op__(torch.add, other, swap=True)
- def __rmul__(self, other):
- return self.__unary_op__(torch.mul, other)
+ def __mul__(self, other: Any) -> TensorWrapper:
+ """Multiply operation."""
+ return self.__binary_op__(torch.mul, other)
- def __sub__(self, other):
- return self.__unary_op__(torch.sub, other)
+ def __rmul__(self, other: Any) -> TensorWrapper:
+ """Right-side multiply operation."""
+ return self.__binary_op__(torch.mul, other, swap=True)
- def __rsub__(self, other):
- return self.__unary_op__(torch.sub, other)
+ def __sub__(self, other: Any) -> TensorWrapper:
+ """Subtract operation."""
+ return self.__binary_op__(torch.sub, other)
- def __truediv__(self, other):
- return self.__unary_op__(torch.true_divide, other)
+ def __rsub__(self, other: Any) -> TensorWrapper:
+ """Right-side subtract operation."""
+ return self.__binary_op__(torch.sub, other, swap=True)
- def __floordiv__(self, other):
- return self.__unary_op__(torch.floor_divide, other)
+ def __truediv__(self, other: Any) -> TensorWrapper:
+ """True division operation."""
+ return self.__binary_op__(torch.true_divide, other)
- def __ge__(self, other):
- return self.__unary_op__(torch.ge, other)
+ def __floordiv__(self, other: Any) -> TensorWrapper:
+ """Floor division operation."""
+ return self.__binary_op__(torch.floor_divide, other)
- def __gt__(self, other):
- return self.__unary_op__(torch.gt, other)
+ def __ge__(self, other: Any) -> TensorWrapper:
+ """Greater than or equal comparison."""
+ return self.__binary_op__(torch.ge, other)
- def __lt__(self, other):
- return self.__unary_op__(torch.lt, other)
+ def __gt__(self, other: Any) -> TensorWrapper:
+ """Greater than comparison."""
+ return self.__binary_op__(torch.gt, other)
- def __le__(self, other):
- return self.__unary_op__(torch.le, other)
+ def __lt__(self, other: Any) -> TensorWrapper:
+ """Less than comparison."""
+ return self.__binary_op__(torch.lt, other)
- def __eq__(self, other):
- return self.__unary_op__(torch.eq, other)
+ def __le__(self, other: Any) -> TensorWrapper:
+ """Less than or equal comparison."""
+ return self.__binary_op__(torch.le, other)
- def __ne__(self, other):
- return self.__unary_op__(torch.ne, other)
+ def __eq__(self, other: object) -> TensorWrapper:
+ """Equality comparison."""
+ return self.__binary_op__(torch.eq, other)
+
+ def __ne__(self, other: object) -> TensorWrapper:
+ """Inequality comparison."""
+ return self.__binary_op__(torch.ne, other)
def __bool__(self) -> bool:
- return self.__unary_op__(Tensor.__bool__)
+ """Convert to boolean (unwrapped)."""
+ return bool(self._data)
def __int__(self) -> int:
- return self.__unary_op__(Tensor.__int__)
-
- def __neg__(self):
- return self.__unary_op__(Tensor.negative)
+ """Convert to integer (unwrapped)."""
+ return int(self._data)
- def __unary_op__(self, func, other=None):
- args = (self, other) if other is not None else (self,)
- return self.__torch_function__(func, (type(self),), args)
+ def __neg__(self) -> TensorWrapper:
+ """Negation operation."""
+ return self.__unary_op__(torch.neg)
def __len__(self) -> int:
+ """Return length of tensor."""
return len(self._data)
+
+ def __binary_op__(self, func: Any, other: Any, swap: bool = False) -> TensorWrapper:
+ """Helper for binary operations.
+
+ Args:
+ func: The PyTorch function to call.
+ other: The other operand.
+ swap: If True, swap the order of operands (for right-side operations).
+
+ Returns:
+ Wrapped result of the operation.
+ """
+ if swap:
+ args = (other, self)
+ else:
+ args = (self, other)
+ return self.__torch_function__(func, (type(self),), args)
+
+ def __unary_op__(self, func: Any) -> TensorWrapper:
+ """Helper for unary operations.
+
+ Args:
+ func: The PyTorch function to call.
+
+ Returns:
+ Wrapped result of the operation.
+ """
+ return self.__torch_function__(func, (type(self),), (self,))
diff --git a/kornia/utils/helpers.py b/kornia/core/utils.py
similarity index 59%
rename from kornia/utils/helpers.py
rename to kornia/core/utils.py
index 1efed98c2..8c780dd24 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/core/utils.py
@@ -15,19 +15,19 @@
# limitations under the License.
#
+
import importlib.util
import platform
import sys
-import warnings
from dataclasses import asdict, fields, is_dataclass
-from functools import wraps
-from inspect import isclass, isfunction
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar, Union, overload
+from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union
import torch
from torch.linalg import inv_ex
-from kornia.utils._compat import torch_version_ge
+from kornia.core._compat import torch_version_ge
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_TYPE
+from kornia.core.exceptions import DeviceError
def xla_is_available() -> bool:
@@ -85,59 +85,11 @@ def get_cuda_or_mps_device_if_available() -> torch.device:
return get_cuda_device_if_available()
-@overload
-def map_location_to_cpu(storage: torch.Tensor, location: str) -> torch.Tensor: ...
-
-
-@overload
-def map_location_to_cpu(storage: str) -> str: ...
-
-
-def map_location_to_cpu(storage: Union[str, torch.Tensor], *args: Any, **kwargs: Any) -> Union[str, torch.Tensor]:
- """Map location of device to CPU, util for loading things from HUB."""
- return storage
-
-
-def deprecated(
- replace_with: Optional[str] = None, version: Optional[str] = None, extra_reason: Optional[str] = None
-) -> Any:
- """Mark methods as deprecated."""
-
- def _deprecated(func: Callable[..., Any]) -> Any:
- @wraps(func)
- def wrapper(*args: Any, **kwargs: Any) -> Any:
- name = ""
- beginning = f"Since kornia {version} the " if version is not None else ""
-
- if isclass(func):
- name = func.__class__.__name__
- if isfunction(func):
- name = func.__name__
- warnings.simplefilter("always", DeprecationWarning)
- if replace_with is not None:
- warnings.warn(
- f"{beginning}`{name}` is deprecated in favor of `{replace_with}`.{extra_reason}",
- category=DeprecationWarning,
- stacklevel=2,
- )
- else:
- warnings.warn(
- f"{beginning}`{name}` is deprecated and will be removed in the future versions.{extra_reason}",
- category=DeprecationWarning,
- stacklevel=2,
- )
- warnings.simplefilter("default", DeprecationWarning)
- return func(*args, **kwargs)
-
- return wrapper
-
- return _deprecated
-
-
def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:
"""Check if all the input are in the same device (only if when they are torch.Tensor).
- If so, it would return a tuple of (device, dtype). Default: (cpu, ``get_default_dtype()``).
+ If so, it would return a tuple of (device, dtype).
+ Default: (``torch.get_default_device()``, ``torch.get_default_dtype()``).
Returns:
[torch.device, torch.dtype]
@@ -146,7 +98,7 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
device, dtype = None, None
for tensor in tensor_list:
if tensor is not None:
- if not isinstance(tensor, (torch.Tensor,)):
+ if not isinstance(tensor, torch.Tensor):
continue
_device = tensor.device
_dtype = tensor.dtype
@@ -154,29 +106,39 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
device = _device
dtype = _dtype
elif device != _device or dtype != _dtype:
- raise ValueError(
- "Passed values are not in the same device and dtype."
- f"Got ({device}, {dtype}) and ({_device}, {_dtype})."
+ raise DeviceError(
+ f"Passed values are not in the same device and dtype. "
+ f"Got ({device}, {dtype}) and ({_device}, {_dtype}).",
+ actual_devices=[device, _device],
+ expected_device=device,
)
if device is None:
- # TODO: update this when having torch.get_default_device()
- device = torch.device("cpu")
+ device = torch.get_default_device()
if dtype is None:
dtype = torch.get_default_dtype()
return (device, dtype)
+def _normalize_to_float32_or_float64(dtype: torch.dtype) -> torch.dtype:
+ """Normalize dtype to float32 or float64 for operations that require full precision.
+
+ Args:
+ dtype: The input dtype to normalize.
+
+ Returns:
+ torch.float32 if dtype is not float32 or float64, otherwise returns the original dtype.
+ """
+ return dtype if dtype in (torch.float32, torch.float64) else torch.float32
+
+
def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
"""Make torch.inverse work with other than fp32/64.
The function torch.inverse is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
- if not isinstance(input, torch.Tensor):
- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
- dtype: torch.dtype = input.dtype
- if dtype not in (torch.float32, torch.float64):
- dtype = torch.float32
+ KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")
+ dtype = _normalize_to_float32_or_float64(input.dtype)
return torch.linalg.inv(input.to(dtype)).to(input.dtype)
@@ -186,11 +148,8 @@ def _torch_histc_cast(input: torch.Tensor, bins: int, min: Union[float, bool], m
The function torch.histc is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
- if not isinstance(input, torch.Tensor):
- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
- dtype: torch.dtype = input.dtype
- if dtype not in (torch.float32, torch.float64):
- dtype = torch.float32
+ KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")
+ dtype = _normalize_to_float32_or_float64(input.dtype)
return torch.histc(input.to(dtype), bins, min, max).to(input.dtype)
@@ -203,17 +162,11 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd
"""
- # if not isinstance(input, torch.Tensor):
- # raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
- dtype = input.dtype
- if dtype not in (torch.float32, torch.float64):
- dtype = torch.float32
+ dtype = _normalize_to_float32_or_float64(input.dtype)
out1, out2, out3H = torch.linalg.svd(input.to(dtype))
- if torch_version_ge(1, 11):
- out3 = out3H.mH
- else:
- out3 = out3H.transpose(-1, -2)
+ # Since kornia requires torch>=2.0.0, we can always use .mH
+ out3 = out3H.mH
return (out1.to(input.dtype), out2.to(input.dtype), out3.to(input.dtype))
@@ -226,29 +179,24 @@ def _torch_linalg_svdvals(input: torch.Tensor) -> torch.Tensor:
NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd
"""
- if not isinstance(input, torch.Tensor):
- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
- dtype: torch.dtype = input.dtype
- if dtype not in (torch.float32, torch.float64):
- dtype = torch.float32
+ KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")
+ dtype = _normalize_to_float32_or_float64(input.dtype)
- if TYPE_CHECKING:
- # TODO: remove this branch when kornia relies on torch >= 1.10
- out: torch.Tensor
- elif torch_version_ge(1, 10):
- out = torch.linalg.svdvals(input.to(dtype))
- else:
- # TODO: remove this branch when kornia relies on torch >= 1.10
- _, out, _ = torch.linalg.svd(input.to(dtype))
+ # Since kornia requires torch>=2.0.0, we can always use torch.linalg.svdvals
+ out = torch.linalg.svdvals(input.to(dtype))
return out.to(input.dtype)
-# TODO: return only `torch.Tensor` and review all the calls to adjust
def _torch_solve_cast(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
"""Make torch.solve work with other than fp32/64.
For stable operation, the input matrices should be cast to fp64, and the output will
be cast back to the input dtype. However, fp64 is not yet supported on MPS.
+
+ This function is actively used in:
+ - kornia.geometry.transform.imgwarp
+ - kornia.geometry.transform.thin_plate_spline
+ - kornia.geometry.epipolar.essential
"""
if is_mps_tensor_safe(A):
dtype = torch.float32
@@ -266,27 +214,14 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor
Avoids crashing because of singular matrix input and outputs the mask of valid solution.
"""
- if not torch_version_ge(1, 10):
- sol = _torch_solve_cast(A, B)
- warnings.warn("PyTorch version < 1.10, solve validness mask maybe not correct", RuntimeWarning, stacklevel=1)
- return sol, sol, torch.ones(len(A), dtype=torch.bool, device=A.device)
# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
- if not isinstance(B, torch.Tensor):
- raise AssertionError(f"B must be torch.Tensor. Got: {type(B)}.")
+ KORNIA_CHECK_IS_TENSOR(B, "B must be torch.Tensor")
dtype: torch.dtype = B.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
- if TYPE_CHECKING:
- # TODO: remove this branch when kornia relies on torch >= 1.13
- A_LU: torch.Tensor
- pivots: torch.Tensor
- info: torch.Tensor
- elif torch_version_ge(1, 13):
- A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))
- else:
- # TODO: remove this branch when kornia relies on torch >= 1.13
- A_LU, pivots, info = torch.lu(A.to(dtype), True, get_infos=True)
+ # Since kornia requires torch>=2.0.0, we can always use torch.linalg.lu_factor_ex and torch.linalg.lu_solve
+ A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))
valid_mask: torch.Tensor = info == 0
n_dim_B = len(B.shape)
@@ -294,14 +229,7 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor
if n_dim_A - n_dim_B == 1:
B = B.unsqueeze(-1)
- if TYPE_CHECKING:
- # TODO: remove this branch when kornia relies on torch >= 1.13
- X: torch.Tensor
- elif torch_version_ge(1, 13):
- X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))
- else:
- # TODO: remove this branch when kornia relies on torch >= 1.13
- X = torch.lu_solve(B.to(dtype), A_LU, pivots)
+ X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))
return X.to(B.dtype), A_LU.to(A.dtype), valid_mask
@@ -311,14 +239,10 @@ def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]
Avoids crashing because of non-invertable matrix input and outputs the mask of valid solution.
"""
- if not isinstance(A, torch.Tensor):
- raise AssertionError(f"A must be torch.Tensor. Got: {type(A)}.")
+ KORNIA_CHECK_IS_TENSOR(A, "A must be torch.Tensor")
dtype_original = A.dtype
- if dtype_original not in (torch.float32, torch.float64):
- dtype = torch.float32
- else:
- dtype = dtype_original
+ dtype = _normalize_to_float32_or_float64(dtype_original)
inverse, info = inv_ex(A.to(dtype))
mask = info == 0
@@ -338,13 +262,7 @@ def is_autocast_enabled(both: bool = True) -> bool:
`torch.is_autocast_enabled()`.
"""
- if TYPE_CHECKING:
- # TODO: remove this branch when kornia relies on torch >= 1.10.2
- return False
-
- if not torch_version_ge(1, 10, 2):
- return False
-
+ # Since kornia requires torch>=2.0.0, autocast is always available
if both:
if torch_version_ge(2, 4):
return torch.is_autocast_enabled() or torch.is_autocast_enabled("cpu")
@@ -358,7 +276,7 @@ def dataclass_to_dict(obj: Any) -> Any:
"""Recursively convert dataclass instances to dictionaries."""
if is_dataclass(obj) and not isinstance(obj, type):
return {key: dataclass_to_dict(value) for key, value in asdict(obj).items()}
- elif isinstance(obj, (list, tuple)):
+ elif isinstance(obj, list | tuple):
return type(obj)(dataclass_to_dict(item) for item in obj)
elif isinstance(obj, dict):
return {key: dataclass_to_dict(value) for key, value in obj.items()}
@@ -371,10 +289,8 @@ T = TypeVar("T")
def dict_to_dataclass(dict_obj: Dict[str, Any], dataclass_type: Type[T]) -> T:
"""Recursively convert dictionaries to dataclass instances."""
- if not isinstance(dict_obj, dict):
- raise TypeError("Input conf must be dict")
- if not is_dataclass(dataclass_type):
- raise TypeError("dataclass_type must be a dataclass")
+ KORNIA_CHECK_TYPE(dict_obj, dict, "Input conf must be dict")
+ KORNIA_CHECK(is_dataclass(dataclass_type), "dataclass_type must be a dataclass")
field_types: dict[str, Any] = {f.name: f.type for f in fields(dataclass_type)}
constructor_args = {}
for key, value in dict_obj.items():
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index af51a2f97..55be0f02c 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -30,8 +30,8 @@ from kornia.core.check import (
KORNIA_CHECK_IS_COLOR_OR_GRAY,
KORNIA_CHECK_IS_TENSOR,
)
-from kornia.utils.helpers import _torch_histc_cast
-from kornia.utils.image import perform_keep_shape_image, perform_keep_shape_video
+from kornia.core.utils import _torch_histc_cast
+from kornia.image.utils import perform_keep_shape_image, perform_keep_shape_video
def adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index 9c59ff1ef..ed85583c4 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -23,8 +23,8 @@ from typing import Tuple
import torch
import torch.nn.functional as F
-from kornia.utils.helpers import _torch_histc_cast
-from kornia.utils.image import perform_keep_shape_image
+from kornia.core.utils import _torch_histc_cast
+from kornia.image.utils import perform_keep_shape_image
from .histogram import histogram
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index 3ea1ebf61..4ad529057 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -32,12 +32,7 @@ from kornia.core.check import (
KORNIA_CHECK_SHAPE,
)
from kornia.geometry.transform.affwarp import rescale
-from kornia.utils.image import perform_keep_shape_image
-from kornia.utils.misc import (
- differentiable_clipping,
- differentiable_polynomial_floor,
- differentiable_polynomial_rounding,
-)
+from kornia.image.utils import perform_keep_shape_image
_DCT8_CACHE: dict[
tuple[Union[torch.dtype, None], Union[str, torch.device, None]], tuple[torch.Tensor, torch.Tensor]
@@ -46,6 +41,60 @@ _DCT8_CACHE: dict[
__all__ = ["JPEGCodecDifferentiable", "jpeg_codec_differentiable"]
+def _differentiable_polynomial_rounding(input: torch.Tensor) -> torch.Tensor:
+ """Differentiable rounding.
+
+ Args:
+ input: Input tensor of any shape to be rounded.
+
+ Returns:
+ Pseudo rounded tensor of the same shape as input tensor.
+
+ """
+ input_round = input.round()
+ return input_round + (input - input_round) ** 3
+
+
+def _differentiable_polynomial_floor(input: torch.Tensor) -> torch.Tensor:
+ """Perform floor via a differentiable operation.
+
+ Args:
+ input: Input tensor of any shape to be floored.
+
+ Returns:
+ Pseudo rounded tensor of the same shape as input tensor.
+
+ """
+ input_floor = input.floor()
+ return input_floor + (input - 0.5 - input_floor) ** 3
+
+
+def _differentiable_clipping(
+ input: torch.Tensor,
+ min_val: Union[float, None] = None,
+ max_val: Union[float, None] = None,
+ scale: float = 0.02,
+) -> torch.Tensor:
+ """Clip via a differentiable and soft approximation of the clipping operation.
+
+ Args:
+ input: Input tensor of any shape.
+ min_val: Minimum value.
+ max_val: Maximum value.
+ scale: Scale value. Default 0.02.
+
+ Returns:
+ Clipped output tensor of the same shape as the input tensor.
+
+ """
+ output: torch.Tensor = input.clone()
+ if max_val is not None:
+ output[output > max_val] = -scale * (torch.exp(-output[output > max_val] + max_val) - 1.0) + max_val
+ if min_val is not None:
+ output[output < min_val] = scale * (torch.exp(output[output < min_val] - min_val) - 1.0) + min_val
+ return output
+
+
def _get_default_qt_y(device: Union[str, torch.device, None], dtype: Union[torch.dtype, None]) -> torch.Tensor:
"""Generate default Quantization table of Y channel."""
return torch.tensor(
@@ -180,7 +229,7 @@ def _jpeg_quality_to_scale(
"""
# Get scale
- scale: torch.Tensor = differentiable_polynomial_floor(
+ scale: torch.Tensor = _differentiable_polynomial_floor(
torch.where(
compression_strength < 50,
5000.0 / compression_strength,
@@ -211,12 +260,12 @@ def _quantize(
quantization_table[:, None] * _jpeg_quality_to_scale(jpeg_quality)[:, None, None, None]
)
# Perform scaling
- quantization_table = differentiable_polynomial_floor(
- differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255)
+ quantization_table = _differentiable_polynomial_floor(
+ _differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255)
)
output: torch.Tensor = input / quantization_table
# Perform rounding
- output = differentiable_polynomial_rounding(output)
+ output = _differentiable_polynomial_rounding(output)
return output
@@ -241,8 +290,8 @@ def _dequantize(
quantization_table[:, None] * _jpeg_quality_to_scale(jpeg_quality)[:, None, None, None]
)
# Perform scaling
- output: torch.Tensor = input * differentiable_polynomial_floor(
- differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255)
+ output: torch.Tensor = input * _differentiable_polynomial_floor(
+ _differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255)
)
return output
@@ -579,7 +628,7 @@ def jpeg_codec_differentiable(
quantization_table_y=quantization_table_y,
)
# Clip coded image
- image_rgb_jpeg = differentiable_clipping(input=image_rgb_jpeg, min_val=0.0, max_val=255.0)
+ image_rgb_jpeg = _differentiable_clipping(input=image_rgb_jpeg, min_val=0.0, max_val=255.0)
# Crop the image again to the original shape
image_rgb_jpeg = image_rgb_jpeg[..., : H - h_pad, : W - w_pad]
return image_rgb_jpeg
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index 72457f4b0..cc7a0a069 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -22,7 +22,7 @@ from typing import List, Tuple, Union
import torch
from torch import nn
-from kornia.utils.image import perform_keep_shape_image
+from kornia.image.utils import perform_keep_shape_image
__all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_min_max"]
diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.py
index ba44700ae..bdab8c401 100644
--- a/kornia/feature/dedode/dedode.py
+++ b/kornia/feature/dedode/dedode.py
@@ -23,7 +23,6 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.enhance.normalize import Normalize
-from kornia.utils.helpers import map_location_to_cpu
from .dedode_models import DeDoDeDescriptor, DeDoDeDetector, get_descriptor, get_detector
from .utils import dedode_denormalize_pixel_coordinates, sample_keypoints
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 1fa958e73..0653db058 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -22,7 +22,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.utils.helpers import is_mps_tensor_safe
+from kornia.core.utils import is_mps_tensor_safe
urls: Dict[str, str] = {}
urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 41aacafef..a01029cd6 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -301,7 +301,7 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0) -> Tuple[List[int],
Examples:
x, y = get_laf_pts_to_draw(LAF, img_idx)
plt.figure()
- plt.imshow(kornia.utils.tensor_to_image(img[img_idx]))
+ plt.imshow(kornia.image.tensor_to_image(img[img_idx]))
plt.plot(x, y, 'r')
plt.show()
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index bba5adfc2..22d084e80 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -27,7 +27,6 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK
from kornia.feature.laf import laf_to_three_points, scale_laf
-from kornia.utils._compat import custom_fwd
try:
from flash_attn.modules.mha import FlashCrossAttention
@@ -45,7 +44,7 @@ def math_clamp(x, min_, max_): # type: ignore
return min(max(x, min_), max_)
-@custom_fwd(cast_inputs=torch.float32)
[email protected]_fwd(cast_inputs=torch.float32, device_type="cuda")
def normalize_keypoints(kpts: torch.Tensor, size: torch.Tensor) -> torch.Tensor:
"""Normalize torch.tensor of keypoints."""
if isinstance(size, torch.Size):
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index 72d92f1a7..309a0ebe7 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -24,8 +24,8 @@ import torch
import torch.nn.functional as F
from torch import nn
+from kornia.geometry.grid import create_meshgrid
from kornia.geometry.subpix import dsnt
-from kornia.utils.grid import create_meshgrid
class FineMatching(nn.Module):
diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.py
index ad914608f..3fed900c4 100644
--- a/kornia/feature/loftr/utils/supervision.py
+++ b/kornia/feature/loftr/utils/supervision.py
@@ -21,7 +21,7 @@ from typing import Any
import torch
-from kornia.utils import create_meshgrid
+from kornia.geometry.grid import create_meshgrid
from .geometry import warp_kpts
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index fb76e34bc..384641b91 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -22,9 +22,9 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE
+from kornia.core.utils import is_mps_tensor_safe
from kornia.feature.laf import get_laf_center
from kornia.feature.steerers import DiscreteSteerer
-from kornia.utils.helpers import is_mps_tensor_safe
from .adalam import get_adalam_default_config, match_adalam
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 84e962536..ff0b2fc18 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -24,7 +24,7 @@ from torch import nn
from kornia.constants import pi
from kornia.filters import GaussianBlur2d, SpatialGradient
from kornia.geometry.conversions import cart2pol
-from kornia.utils import create_meshgrid
+from kornia.geometry.grid import create_meshgrid
# Precomputed coefficients for Von Mises kernel, given N and K(appa).
sqrt2: float = 1.4142135623730951
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index a70a2750a..72dd98636 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -23,9 +23,9 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.utils import dataclass_to_dict, dict_to_dataclass
from kornia.feature.sold2.structures import DetectorCfg, LineMatcherCfg
from kornia.geometry.conversions import normalize_pixel_coordinates
-from kornia.utils import dataclass_to_dict, dict_to_dataclass
from .backbones import SOLD2Net
from .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 915270ea3..80c9ac53c 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -23,9 +23,9 @@ import torch
from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.utils import dataclass_to_dict, dict_to_dataclass
from kornia.feature.sold2.structures import DetectorCfg, HeatMapRefineCfg, JunctionRefineCfg, LineDetectorCfg
from kornia.geometry.bbox import nms
-from kornia.utils import dataclass_to_dict, dict_to_dataclass, torch_meshgrid
from .backbones import SOLD2Net
@@ -420,7 +420,7 @@ class LineSegmentDetectionModule:
device=device,
)
- h1_grid, w1_grid, h2_grid, w2_grid = torch_meshgrid(
+ h1_grid, w1_grid, h2_grid, w2_grid = torch.meshgrid(
[perturb_vec, perturb_vec, perturb_vec, perturb_vec], indexing="ij"
)
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index d1b43479f..8bdb07314 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -22,8 +22,8 @@ from typing import Any
import torch
from torch import nn
+from kornia.core._compat import deprecated
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
-from kornia.utils import deprecated
from .filter import filter2d, filter2d_separable
from .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel1d, get_gaussian_kernel2d
diff --git a/kornia/filters/in_range.py b/kornia/filters/in_range.py
index 03b7982f4..4597dda44 100644
--- a/kornia/filters/in_range.py
+++ b/kornia/filters/in_range.py
@@ -22,7 +22,7 @@ from typing import Any, Union
import torch
from torch import nn
-from kornia.utils.image import perform_keep_shape_image
+from kornia.image.utils import perform_keep_shape_image
@perform_keep_shape_image
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 61d68e016..453c0be9e 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -22,8 +22,8 @@ from typing import Any, Optional, Union
import torch
+from kornia.core._compat import deprecated
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
-from kornia.utils import deprecated
def _check_kernel_size(kernel_size: tuple[int, ...] | int, min_value: int = 0, allow_even: bool = False) -> None:
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index e72663e18..1b67c6ebe 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -21,8 +21,8 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.utils import _extract_device_dtype
from kornia.geometry.transform import rotate, rotate3d
-from kornia.utils import _extract_device_dtype
from .kernels import _check_kernel_size, _unpack_2d_ks, _unpack_3d_ks
diff --git a/kornia/filters/otsu_thresholding.py b/kornia/filters/otsu_thresholding.py
index 6a989107b..e8c3008c6 100644
--- a/kornia/filters/otsu_thresholding.py
+++ b/kornia/filters/otsu_thresholding.py
@@ -22,8 +22,8 @@ from typing import Optional, Tuple
import torch
from kornia.core.check import KORNIA_CHECK
+from kornia.core.utils import _torch_histc_cast
from kornia.enhance.histogram import histogram as diff_histogram
-from kornia.utils.helpers import _torch_histc_cast
class OtsuThreshold(torch.nn.Module):
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index 2d87fa256..923ed1ac7 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -26,10 +26,13 @@ from .camera import *
from .conversions import *
from .depth import *
from .epipolar import *
+from .grid import *
from .homography import *
from .liegroup import *
from .linalg import *
from .line import *
+from .plane import *
+from .pointcloud import *
from .pose import *
from .ransac import *
from .solvers import *
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 08fc40ce7..4dc7a94db 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -22,9 +22,9 @@ from typing import Optional, Tuple, cast
import torch
from torch import Size
+from kornia.core.ops import eye_like
from kornia.geometry.bbox import validate_bbox
from kornia.geometry.linalg import transform_points
-from kornia.utils import eye_like
__all__ = ["Boxes", "Boxes3D"]
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index c4bdc0bd2..51b5445ca 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -21,10 +21,10 @@ import torch
from torch.linalg import qr as linalg_qr
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE
+from kornia.core.ops import eye_like
+from kornia.core.utils import _torch_linalg_svdvals, _torch_svd_cast
from kornia.geometry.conversions import convert_points_to_homogeneous, normalize_points_with_intrinsics
from kornia.geometry.linalg import transform_points
-from kornia.utils import eye_like
-from kornia.utils.helpers import _torch_linalg_svdvals, _torch_svd_cast
def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 65bd3cd32..52bbf4eb4 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -23,9 +23,9 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.geometry.grid import create_meshgrid
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import remap
-from kornia.utils import create_meshgrid
from .distort import distort_points, tilt_projection
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 2e5298993..e5bbdc5c9 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -20,9 +20,9 @@ from typing import Iterable, List, Union
import torch
from kornia.core.check import KORNIA_CHECK_SAME_DEVICE
+from kornia.core.utils import _torch_inverse_cast
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import inverse_transformation, transform_points
-from kornia.utils.helpers import _torch_inverse_cast
class PinholeCamera:
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index 768cb5375..2c079fafc 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -19,8 +19,8 @@ from typing import Any
import torch
+from kornia.geometry.grid import create_meshgrid
from kornia.geometry.linalg import transform_points
-from kornia.utils.grid import create_meshgrid
class StereoException(Exception):
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 3fe4c611c..861728a83 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -23,9 +23,9 @@ import torch
import torch.nn.functional as F
from kornia.constants import pi
+from kornia.core._compat import deprecated
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
-from kornia.utils import deprecated
-from kornia.utils.helpers import _torch_inverse_cast
+from kornia.core.utils import _torch_inverse_cast
__all__ = [
"ARKitQTVecs_to_ColmapQTVecs",
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 1d9bcd92b..3cf28e7bf 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -28,7 +28,7 @@ from torch import nn
import kornia.core as kornia_ops
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters.sobel import spatial_gradient
-from kornia.utils import create_meshgrid
+from kornia.geometry.grid import create_meshgrid
from .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_points
from .conversions import normalize_pixel_coordinates, normalize_points_with_intrinsics
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index c0986cb30..c5579eeb9 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -22,9 +22,9 @@ from typing import Optional, Tuple
import torch
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE
+from kornia.core.ops import eye_like, vec_like
+from kornia.core.utils import _torch_solve_cast, _torch_svd_cast
from kornia.geometry import solvers
-from kornia.utils import eye_like, vec_like
-from kornia.utils.helpers import _torch_solve_cast, _torch_svd_cast
from .numeric import cross_product_matrix, matrix_cofactor_tensor
from .projection import depth_from_point, projection_from_KRt
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index e758f0abe..2238d3099 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -22,10 +22,10 @@ from typing import Literal, Optional, Tuple
import torch
from kornia.core.check import KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE
+from kornia.core.utils import _torch_svd_cast, safe_inverse_with_mask
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import transform_points
from kornia.geometry.solvers import solve_cubic
-from kornia.utils.helpers import _torch_svd_cast, safe_inverse_with_mask
def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index d08ffbd20..a9202ae4f 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -24,8 +24,8 @@ import torch.nn.functional as F
from torch.linalg import qr as linalg_qr
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.utils import eye_like, vec_like
-from kornia.utils.helpers import _torch_svd_cast
+from kornia.core.ops import eye_like, vec_like
+from kornia.core.utils import _torch_svd_cast
from .numeric import cross_product_matrix
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index 6656b0206..61cf9b624 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -20,8 +20,8 @@
import torch
from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.utils import _torch_svd_cast
from kornia.geometry.conversions import convert_points_from_homogeneous
-from kornia.utils.helpers import _torch_svd_cast
# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/triangulation.cpp#L68
diff --git a/kornia/utils/grid.py b/kornia/geometry/grid.py
similarity index 95%
rename from kornia/utils/grid.py
rename to kornia/geometry/grid.py
index bb1d91217..5a338c709 100644
--- a/kornia/utils/grid.py
+++ b/kornia/geometry/grid.py
@@ -15,12 +15,11 @@
# limitations under the License.
#
+
from typing import Optional
import torch
-from kornia.utils._compat import torch_meshgrid
-
def create_meshgrid(
height: int,
@@ -79,10 +78,10 @@ def create_meshgrid(
# generate grid by stacking coordinates
# TODO: torchscript doesn't like `torch_version_ge`
# if torch_version_ge(1, 13, 0):
- # x, y = torch_meshgrid([xs, ys], indexing="xy")
+ # x, y = torch.meshgrid([xs, ys], indexing="xy")
# return torch.stack([x, y], -1).unsqueeze(0) # 1xHxWx2
# TODO: remove after we drop support of old versions
- base_grid: torch.Tensor = torch.stack(torch_meshgrid([xs, ys], indexing="ij"), dim=-1) # WxHx2
+ base_grid: torch.Tensor = torch.stack(torch.meshgrid([xs, ys], indexing="ij"), dim=-1) # WxHx2
return base_grid.permute(1, 0, 2).unsqueeze(0) # 1xHxWx2
@@ -123,5 +122,5 @@ def create_meshgrid3d(
ys = (ys / (height - 1) - 0.5) * 2
zs = (zs / (depth - 1) - 0.5) * 2
# generate grid by stacking coordinates
- base_grid = torch.stack(torch_meshgrid([zs, xs, ys], indexing="ij"), dim=-1) # DxWxHx3
+ base_grid = torch.stack(torch.meshgrid([zs, xs, ys], indexing="ij"), dim=-1) # DxWxHx3
return base_grid.permute(0, 2, 1, 3).unsqueeze(0) # 1xDxHxWx3
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 713b92859..069f69c0c 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -21,8 +21,7 @@ from typing import Optional, Tuple
import torch
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.utils import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_mask
-from kornia.utils.helpers import _torch_svd_cast
+from kornia.core.utils import _extract_device_dtype, _torch_svd_cast, safe_inverse_with_mask, safe_solve_with_mask
from .conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from .epipolar import normalize_points
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 7510f9d97..7d5530bea 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -24,9 +24,9 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.utils import _torch_svd_cast
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.plane import Hyperplane
-from kornia.utils.helpers import _torch_svd_cast
__all__ = ["ParametrizedLine", "fit_line"]
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 9cac30490..5299c00db 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -24,10 +24,10 @@ import torch
from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
-from kornia.core.tensor_wrapper import unwrap, wrap # type: ignore[attr-defined]
+from kornia.core.tensor_wrapper import _unwrap, _wrap
+from kornia.core.utils import _torch_svd_cast
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.vector import Scalar, Vector3
-from kornia.utils.helpers import _torch_svd_cast
__all__ = ["Hyperplane", "fit_plane"]
@@ -75,7 +75,7 @@ class Hyperplane(nn.Module):
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L145
# TODO: tests
def signed_distance(self, p: Vector3) -> Scalar:
- KORNIA_CHECK(isinstance(p, (Vector3, torch.Tensor)))
+ KORNIA_CHECK(isinstance(p, Vector3 | torch.Tensor))
return self.normal.dot(p) + self.offset
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L154
@@ -106,7 +106,7 @@ class Hyperplane(nn.Module):
# TODO: implement `.unitOrthonormal`
normal2d = normalized(p1 - p0)
offset2d = -batched_dot_product(p0, normal2d)
- return Hyperplane(wrap(normal2d, Vector3), wrap(offset2d, Scalar))
+ return Hyperplane(_wrap(normal2d, Vector3), _wrap(offset2d, Scalar))
# 3d case
KORNIA_CHECK_SHAPE(p0, ["*", "3"])
KORNIA_CHECK(p0.shape == p1.shape)
@@ -118,15 +118,15 @@ class Hyperplane(nn.Module):
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L108
def compute_normal_svd(v0: torch.Tensor, v1: torch.Tensor) -> "Vector3":
# NOTE: for reason torch.TensorWrapper does not stack well
- m = torch.stack((unwrap(v0), unwrap(v1)), -2) # Bx2x3
+ m = torch.stack((_unwrap(v0), _unwrap(v1)), -2) # Bx2x3
_, _, V = _torch_svd_cast(m) # kornia solution lies in the last row
- return wrap(V[..., :, -1], Vector3) # Bx3
+ return _wrap(V[..., :, -1], Vector3) # Bx3
normal_mask = norm <= v0.norm(-1) * v1.norm(-1) * 1e-6
normal = torch.where(normal_mask, compute_normal_svd(v0, v1).data, normal / (norm + 1e-6))
offset = -batched_dot_product(p0, normal)
- return Hyperplane(wrap(normal, Vector3), wrap(offset, Scalar))
+ return Hyperplane(_wrap(normal, Vector3), _wrap(offset, Scalar))
# TODO: factor to avoid duplicated from line.py
diff --git a/kornia/utils/pointcloud_io.py b/kornia/geometry/pointcloud.py
similarity index 99%
rename from kornia/utils/pointcloud_io.py
rename to kornia/geometry/pointcloud.py
index c2baf61bd..7da0bd86d 100644
--- a/kornia/utils/pointcloud_io.py
+++ b/kornia/geometry/pointcloud.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+
import os
import torch
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 017727682..699933763 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -28,7 +28,7 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
-from kornia.utils.grid import create_meshgrid
+from kornia.geometry.grid import create_meshgrid
def _validate_batched_image_tensor_input(tensor: torch.Tensor) -> None:
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index dd960e2c6..d7d4e20c6 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -23,11 +23,11 @@ import torch
import torch.nn.functional as F
from torch import nn
+from kornia.core._compat import torch_version_ge
+from kornia.core.utils import safe_solve_with_mask
from kornia.filters.sobel import spatial_gradient3d
from kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3d
-from kornia.utils import create_meshgrid, create_meshgrid3d
-from kornia.utils._compat import torch_version_ge
-from kornia.utils.helpers import safe_solve_with_mask
+from kornia.geometry.grid import create_meshgrid, create_meshgrid3d
from .dsnt import spatial_expectation2d, spatial_softmax2d
from .nms import nms3d
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index a737325ea..6c9619a66 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -21,10 +21,10 @@ from typing import Optional, Tuple, Union
import torch
from torch import nn
+from kornia.core.ops import eye_like
+from kornia.core.utils import _extract_device_dtype
from kornia.filters import gaussian_blur2d
-from kornia.utils import _extract_device_dtype
-from kornia.utils.image import perform_keep_shape_image
-from kornia.utils.misc import eye_like
+from kornia.image.utils import perform_keep_shape_image
from .imgwarp import get_affine_matrix2d, get_projective_transform, get_rotation_matrix2d, warp_affine, warp_affine3d
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 17f08b8c3..8702c9f25 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -23,7 +23,7 @@ import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters import filter2d
from kornia.filters.kernels import get_gaussian_kernel2d
-from kornia.utils import create_meshgrid
+from kornia.geometry.grid import create_meshgrid
__all__ = ["elastic_transform2d"]
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index b6329c2f0..63b78cb7a 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -24,7 +24,7 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.utils import create_meshgrid
+from kornia.geometry.grid import create_meshgrid
from .imgwarp import homography_warp, warp_grid
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index d76c2812d..4fc6bcf62 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -23,6 +23,8 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.ops import eye_like
+from kornia.core.utils import _torch_inverse_cast, _torch_solve_cast
from kornia.geometry.conversions import (
angle_to_rotation_matrix,
axis_angle_to_rotation_matrix,
@@ -32,9 +34,8 @@ from kornia.geometry.conversions import (
normalize_homography3d,
normalize_pixel_coordinates,
)
+from kornia.geometry.grid import create_meshgrid, create_meshgrid3d
from kornia.geometry.linalg import transform_points
-from kornia.utils import create_meshgrid, create_meshgrid3d, eye_like
-from kornia.utils.helpers import _torch_inverse_cast, _torch_solve_cast
__all__ = [
"get_affine_matrix2d",
@@ -526,7 +527,7 @@ def remap(
Example:
>>> import torch
- >>> from kornia.utils import create_meshgrid
+ >>> from kornia.geometry import create_meshgrid
>>> grid = create_meshgrid(2, 2, False) # 1x2x2x2
>>> grid += 1 # apply offset in both directions
>>> input = torch.ones(1, 1, 2, 2)
@@ -535,7 +536,7 @@ def remap(
[0., 0.]]]])
.. note::
- This function is often used in conjunction with :func:`kornia.utils.create_meshgrid`.
+ This function is often used in conjunction with :func:`kornia.geometry.create_meshgrid`.
"""
KORNIA_CHECK_SHAPE(image, ["B", "C", "H", "W"])
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index 5d1f0f428..041efff0a 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -20,8 +20,8 @@ from __future__ import annotations
import torch
from torch import nn
-from kornia.utils import create_meshgrid
-from kornia.utils.helpers import _torch_solve_cast
+from kornia.core.utils import _torch_solve_cast
+from kornia.geometry.grid import create_meshgrid
__all__ = ["get_tps_transform", "warp_image_tps", "warp_points_tps"]
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index fdb308e5d..45c744270 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -21,7 +21,7 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK
-from kornia.core.tensor_wrapper import TensorWrapper, wrap # type: ignore[attr-defined]
+from kornia.core.tensor_wrapper import TensorWrapper, _wrap # type: ignore[attr-defined]
from kornia.geometry.linalg import batched_dot_product, batched_squared_norm
__all__ = ["Scalar", "Vector2", "Vector3"]
@@ -110,12 +110,12 @@ class Vector3(TensorWrapper):
dtype: Optional[torch.dtype] = None,
) -> "Vector3":
KORNIA_CHECK(type(x) is type(y) is type(z))
- KORNIA_CHECK(isinstance(x, (torch.Tensor, float)))
+ KORNIA_CHECK(isinstance(x, torch.Tensor | float))
if isinstance(x, float):
- return wrap(torch.as_tensor((x, y, z), device=device, dtype=dtype), Vector3)
+ return _wrap(torch.as_tensor((x, y, z), device=device, dtype=dtype), Vector3)
# TODO: this is totally insane ...
tensors: Tuple[torch.Tensor, ...] = (x, cast(torch.Tensor, y), cast(torch.Tensor, z))
- return wrap(torch.stack(tensors, -1), Vector3)
+ return _wrap(torch.stack(tensors, -1), Vector3)
class Vector2(TensorWrapper):
@@ -168,12 +168,12 @@ class Vector2(TensorWrapper):
dtype: Optional[torch.dtype] = None,
) -> "Vector2":
KORNIA_CHECK(type(x) is type(y))
- KORNIA_CHECK(isinstance(x, (torch.Tensor, float)))
+ KORNIA_CHECK(isinstance(x, torch.Tensor | float))
if isinstance(x, float):
- return wrap(torch.as_tensor((x, y), device=device, dtype=dtype), Vector2)
+ return _wrap(torch.as_tensor((x, y), device=device, dtype=dtype), Vector2)
# TODO: this is totally insane ...
tensors: Tuple[torch.Tensor, ...] = (x, cast(torch.Tensor, y))
- return wrap(torch.stack(tensors, -1), Vector2)
+ return _wrap(torch.stack(tensors, -1), Vector2)
Vec3 = Vector3
diff --git a/kornia/image/__init__.py b/kornia/image/__init__.py
index 2dd22c4f9..002ba3b54 100644
--- a/kornia/image/__init__.py
+++ b/kornia/image/__init__.py
@@ -22,6 +22,36 @@ and channel order definitions.
"""
from .base import ChannelsOrder, ImageLayout, ImageSize, PixelFormat
+from .draw import draw_convex_polygon, draw_line, draw_point2d, draw_rectangle
from .image import Image
+from .image_print import image_to_string, print_image
+from .utils import (
+ ImageToTensor,
+ image_list_to_tensor,
+ image_to_tensor,
+ make_grid,
+ perform_keep_shape_image,
+ perform_keep_shape_video,
+ tensor_to_image,
+)
-__all__ = ["ChannelsOrder", "Image", "ImageLayout", "ImageSize", "PixelFormat"]
+__all__ = [
+ "ChannelsOrder",
+ "Image",
+ "ImageLayout",
+ "ImageSize",
+ "ImageToTensor",
+ "PixelFormat",
+ "draw_convex_polygon",
+ "draw_line",
+ "draw_point2d",
+ "draw_rectangle",
+ "image_list_to_tensor",
+ "image_to_string",
+ "image_to_tensor",
+ "make_grid",
+ "perform_keep_shape_image",
+ "perform_keep_shape_video",
+ "print_image",
+ "tensor_to_image",
+]
diff --git a/kornia/utils/draw.py b/kornia/image/draw.py
similarity index 100%
rename from kornia/utils/draw.py
rename to kornia/image/draw.py
diff --git a/kornia/image/image.py b/kornia/image/image.py
index 469a5e709..d358a72b5 100644
--- a/kornia/image/image.py
+++ b/kornia/image/image.py
@@ -26,8 +26,8 @@ from torch.utils.dlpack import from_dlpack, to_dlpack
import kornia.color
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.image.base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat
+from kornia.image.image_print import image_to_string
from kornia.io.io import ImageLoadType, load_image, write_image
-from kornia.utils.image_print import image_to_string
# placeholder for numpy
np_ndarray = Any
diff --git a/kornia/utils/image_print.py b/kornia/image/image_print.py
similarity index 99%
rename from kornia/utils/image_print.py
rename to kornia/image/image_print.py
index 299e60ea4..54d21d28a 100644
--- a/kornia/utils/image_print.py
+++ b/kornia/image/image_print.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+
"""Convert an image torch.tensor to an ANSI text string (xterm-256color).
Nice long listing of all 256 colors and their codes.
@@ -30,7 +31,6 @@ from torch import float16, float32, float64
import kornia
from kornia.core.check import KORNIA_CHECK_IS_IMAGE, KORNIA_CHECK_SHAPE
-from kornia.io import ImageLoadType
# color look-up table
# 8-bit, RGB hex
@@ -410,6 +410,8 @@ def print_image(image: Union[str, torch.Tensor], max_width: int = 96) -> None:
"""
if isinstance(image, str):
+ from kornia.io import ImageLoadType # pylint: disable=C0415
+
img = kornia.io.load_image(image, ImageLoadType.RGB8)
elif isinstance(image, torch.Tensor):
img = image
diff --git a/kornia/utils/image.py b/kornia/image/utils.py
similarity index 99%
rename from kornia/utils/image.py
rename to kornia/image/utils.py
index f58863c38..9bc180a93 100644
--- a/kornia/utils/image.py
+++ b/kornia/image/utils.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+
from functools import wraps
from typing import Any, Callable, List, Optional
@@ -257,7 +258,7 @@ def make_grid(tensor: torch.Tensor, n_row: Optional[int] = None, padding: int =
B, C, H, W = tensor.shape
if n_row is None:
- n_row = int(torch.sqrt(tensor(B, dtype=torch.float32)).ceil().item())
+ n_row = int(torch.sqrt(torch.tensor(B, dtype=torch.float32)).ceil().item())
n_col = (B + n_row - 1) // n_row
padded_H = H + padding
diff --git a/kornia/io/io.py b/kornia/io/io.py
index cf04068ba..16681f13b 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -26,7 +26,7 @@ import torch
import kornia
from kornia.core.check import KORNIA_CHECK
-from kornia.utils import image_to_tensor, tensor_to_image
+from kornia.image.utils import image_to_tensor, tensor_to_image
class ImageLoadType(Enum):
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 0aa350bd7..76d2122a5 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -25,7 +25,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
from kornia.losses._utils import mask_ignore_pixels
-from kornia.utils.one_hot import one_hot
+from kornia.losses.one_hot import one_hot
# based on:
# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 53dd978bd..d7df190b1 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -24,7 +24,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.losses._utils import mask_ignore_pixels
-from kornia.utils.one_hot import one_hot
+from kornia.losses.one_hot import one_hot
# based on:
# https://github.com/zhezh/focalloss/blob/master/focalloss.py
diff --git a/kornia/utils/one_hot.py b/kornia/losses/one_hot.py
similarity index 62%
rename from kornia/utils/one_hot.py
rename to kornia/losses/one_hot.py
index 4497085fc..e465431c6 100644
--- a/kornia/utils/one_hot.py
+++ b/kornia/losses/one_hot.py
@@ -16,6 +16,9 @@
#
import torch
+import torch.nn.functional as F
+
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
def one_hot(
@@ -47,15 +50,23 @@ def one_hot(
[1.0000e+00, 1.0000e-06]]]])
"""
- if not isinstance(labels, torch.Tensor):
- raise TypeError(f"Input labels type is not a torch.Tensor. Got {type(labels)}")
+ KORNIA_CHECK_IS_TENSOR(labels, "Input labels must be a torch.Tensor")
+ KORNIA_CHECK(labels.dtype == torch.int64, f"labels must be of dtype torch.int64. Got: {labels.dtype}")
+ KORNIA_CHECK(num_classes >= 1, f"The number of classes must be >= 1. Got: {num_classes}")
+
+ # Use PyTorch's built-in one_hot function
+ one_hot_tensor = F.one_hot(labels, num_classes=num_classes)
- if not labels.dtype == torch.int64:
- raise ValueError(f"labels must be of the same dtype torch.int64. Got: {labels.dtype}")
+ # PyTorch's one_hot adds the class dimension at the end: (*, num_classes)
+ # We need it at position 1: (N, C, *)
+ # Permute: move the last dimension (num_classes) to position 1
+ ndim = labels.ndim
+ permute_dims = [0] + [ndim] + list(range(1, ndim))
+ one_hot_tensor = one_hot_tensor.permute(*permute_dims)
- if num_classes < 1:
- raise ValueError(f"The number of classes must be bigger than one. Got: {num_classes}")
+ # Convert to desired dtype and device, then apply eps for numerical stability
+ one_hot_tensor = one_hot_tensor.to(dtype=dtype, device=device)
+ # Apply eps: multiply by (1-eps) and add eps to all elements
+ one_hot_tensor = one_hot_tensor * (1.0 - eps) + eps
- shape = labels.shape
- one_hot = torch.full((shape[0], num_classes) + shape[1:], eps, device=device, dtype=dtype)
- return one_hot.scatter_(1, labels.unsqueeze(1), 1.0)
+ return one_hot_tensor
diff --git a/kornia/models/base.py b/kornia/models/base.py
index 61f02d1c1..dbdb552fa 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -27,8 +27,8 @@ import torch
from torch import nn
from kornia.core.external import PILImage as Image
+from kornia.image.utils import tensor_to_image
from kornia.io import write_image
-from kornia.utils.image import tensor_to_image
logger = logging.getLogger(__name__)
diff --git a/kornia/models/depth_estimation/depth_anything.py b/kornia/models/depth_estimation/depth_anything.py
index 0ee9b25d3..125530ae7 100644
--- a/kornia/models/depth_estimation/depth_anything.py
+++ b/kornia/models/depth_estimation/depth_anything.py
@@ -51,13 +51,10 @@ class DepthAnythingONNXBuilder:
The directory where the model should be cached.
Returns:
- str: The name of the output ONNX file.
+ DepthEstimation: The depth estimation model.
- .. code-block:: python
-
- images = kornia.utils.sample.get_sample_images()
- model = DepthAnythingONNXBuilder.build()
- model.save(images)
+ Note:
+ To use this model, load an image tensor (shape: ``(1, C, H, W)``) and call ``model.save(image)``.
"""
if model_name not in [
diff --git a/kornia/models/efficient_vit/nn/ops.py b/kornia/models/efficient_vit/nn/ops.py
index 7c86b2845..cb9f5bbc6 100644
--- a/kornia/models/efficient_vit/nn/ops.py
+++ b/kornia/models/efficient_vit/nn/ops.py
@@ -29,7 +29,6 @@ from torch import nn
from kornia.models.efficient_vit.nn.act import build_act
from kornia.models.efficient_vit.nn.norm import build_norm
from kornia.models.efficient_vit.utils import get_same_padding, val2tuple
-from kornia.utils._compat import autocast
__all__ = [
"ConvLayer",
@@ -430,7 +429,7 @@ class LiteMLA(nn.Module):
total_dim * (1 + len(scales)), out_channels, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1]
)
- @autocast(enabled=False)
+ @torch.amp.autocast(device_type="cuda", enabled=False)
def relu_linear_att(self, qkv: torch.Tensor) -> torch.Tensor:
B, _, H, W = list(qkv.size())
diff --git a/kornia/models/rt_detr/architecture/hybrid_encoder.py b/kornia/models/rt_detr/architecture/hybrid_encoder.py
index c3908f434..13fd7d075 100644
--- a/kornia/models/rt_detr/architecture/hybrid_encoder.py
+++ b/kornia/models/rt_detr/architecture/hybrid_encoder.py
@@ -31,7 +31,6 @@ from torch import nn
from torch.nn.utils.fusion import fuse_conv_bn_weights
from kornia.models.common import ConvNormAct
-from kornia.utils._compat import torch_meshgrid
class RepVggBlock(nn.Module):
@@ -181,7 +180,7 @@ class AIFI(nn.Module):
"""
xs = torch.arange(w, device=device, dtype=dtype)
ys = torch.arange(h, device=device, dtype=dtype)
- grid_x, grid_y = torch_meshgrid([xs, ys], indexing="ij")
+ grid_x, grid_y = torch.meshgrid([xs, ys], indexing="ij")
pos_dim = embed_dim // 4
omega = torch.arange(pos_dim, device=device, dtype=dtype) / pos_dim
diff --git a/kornia/models/rt_detr/architecture/rtdetr_head.py b/kornia/models/rt_detr/architecture/rtdetr_head.py
index 8ab3726c7..e45e29a6f 100644
--- a/kornia/models/rt_detr/architecture/rtdetr_head.py
+++ b/kornia/models/rt_detr/architecture/rtdetr_head.py
@@ -27,7 +27,6 @@ import torch
from torch import nn
from kornia.models.common import MLP, ConvNormAct
-from kornia.utils._compat import torch_meshgrid
def _inverse_sigmoid(x: torch.Tensor, eps: float = 1e-5) -> torch.Tensor:
@@ -476,8 +475,8 @@ class RTDETRHead(nn.Module):
anchors_list: list[torch.Tensor] = []
for i, (h, w) in enumerate(spatial_shapes):
- # TODO: fix later kornia.utils.create_meshgrid()
- grid_y, grid_x = torch_meshgrid(
+ # TODO: fix later kornia.geometry.create_meshgrid()
+ grid_y, grid_x = torch.meshgrid(
[torch.arange(h, device=device, dtype=dtype), torch.arange(w, device=device, dtype=dtype)],
indexing="ij",
)
diff --git a/kornia/models/small_sr.py b/kornia/models/small_sr.py
index ddef29384..1f79a6484 100644
--- a/kornia/models/small_sr.py
+++ b/kornia/models/small_sr.py
@@ -20,7 +20,7 @@ from torch import nn
from kornia.color.ycbcr import RgbToYcbcr, YcbcrToRgb
from kornia.config import kornia_config
-from kornia.utils.download import CachedDownloader
+from kornia.onnx.download import CachedDownloader
url = "https://s3.amazonaws.com/pytorch/test_data/export/superres_epoch100-44c6958e.pth"
diff --git a/kornia/utils/download.py b/kornia/onnx/download.py
similarity index 100%
rename from kornia/utils/download.py
rename to kornia/onnx/download.py
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index 12b9a360d..7a318db84 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -27,7 +27,7 @@ import kornia
from kornia.config import kornia_config
from kornia.core.external import numpy as np
from kornia.core.external import onnx, requests
-from kornia.utils.download import CachedDownloader
+from kornia.onnx.download import CachedDownloader
__all__ = ["ONNXLoader", "add_metadata", "io_name_conversion"]
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index 377644fb4..f477e4614 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -17,75 +17,195 @@
"""Utils submodule for Kornia.
-This package provides utility functions and helpers for image processing, device management, data conversion, and more.
+This module has been deprecated. Functions have been moved to their respective modules.
+Import from the new locations instead (e.g., `kornia.image.draw_line` instead of `kornia.utils.draw_line`).
"""
-from ._compat import torch_meshgrid
-from .download import CachedDownloader
-from .draw import draw_convex_polygon, draw_line, draw_point2d, draw_rectangle
-from .grid import create_meshgrid, create_meshgrid3d
-from .helpers import (
- _extract_device_dtype,
- dataclass_to_dict,
- deprecated,
- dict_to_dataclass,
- get_cuda_device_if_available,
- get_cuda_or_mps_device_if_available,
- get_mps_device_if_available,
- is_autocast_enabled,
- is_mps_tensor_safe,
- map_location_to_cpu,
- safe_inverse_with_mask,
- safe_solve_with_mask,
- xla_is_available,
-)
-from .image import ImageToTensor, image_list_to_tensor, image_to_tensor, tensor_to_image
-from .image_print import image_to_string, print_image
-from .memory import batched_forward
-from .misc import (
- differentiable_clipping,
- differentiable_polynomial_floor,
- differentiable_polynomial_rounding,
- eye_like,
- vec_like,
-)
-from .one_hot import one_hot
-from .pointcloud_io import load_pointcloud_ply, save_pointcloud_ply
-from .sample import get_sample_images
+from typing import Any
+
+from kornia.core._compat import deprecated
+from kornia.geometry import (
+ create_meshgrid as _create_meshgrid,
+)
+from kornia.geometry import (
+ create_meshgrid3d as _create_meshgrid3d,
+)
+from kornia.geometry import (
+ load_pointcloud_ply as _load_pointcloud_ply,
+)
+from kornia.geometry import (
+ save_pointcloud_ply as _save_pointcloud_ply,
+)
+from kornia.image import (
+ draw_convex_polygon as _draw_convex_polygon,
+)
+from kornia.image import (
+ draw_line as _draw_line,
+)
+from kornia.image import (
+ draw_point2d as _draw_point2d,
+)
+from kornia.image import (
+ draw_rectangle as _draw_rectangle,
+)
+from kornia.image import (
+ image_to_string as _image_to_string,
+)
+from kornia.image import (
+ image_to_tensor as _image_to_tensor,
+)
+from kornia.image import (
+ print_image as _print_image,
+)
+from kornia.image import (
+ tensor_to_image as _tensor_to_image,
+)
+from kornia.losses import one_hot as _one_hot
+
+
+# Re-export with deprecation warnings
+@deprecated(
+ replace_with="kornia.geometry.create_meshgrid",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",
+)
+def create_meshgrid(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.geometry.create_meshgrid` instead."""
+ return _create_meshgrid(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.geometry.create_meshgrid3d",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",
+)
+def create_meshgrid3d(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.geometry.create_meshgrid3d` instead."""
+ return _create_meshgrid3d(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.geometry.load_pointcloud_ply",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",
+)
+def load_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.geometry.load_pointcloud_ply` instead."""
+ return _load_pointcloud_ply(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.geometry.save_pointcloud_ply",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",
+)
+def save_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.geometry.save_pointcloud_ply` instead."""
+ return _save_pointcloud_ply(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.draw_line",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
+)
+def draw_line(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.draw_line` instead."""
+ return _draw_line(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.draw_rectangle",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
+)
+def draw_rectangle(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.draw_rectangle` instead."""
+ return _draw_rectangle(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.draw_point2d",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
+)
+def draw_point2d(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.draw_point2d` instead."""
+ return _draw_point2d(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.draw_convex_polygon",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
+)
+def draw_convex_polygon(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.draw_convex_polygon` instead."""
+ return _draw_convex_polygon(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.image_to_string",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
+)
+def image_to_string(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.image_to_string` instead."""
+ return _image_to_string(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.print_image",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
+)
+def print_image(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.print_image` instead."""
+ return _print_image(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.image_to_tensor",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
+)
+def image_to_tensor(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.image_to_tensor` instead."""
+ return _image_to_tensor(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.image.tensor_to_image",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
+)
+def tensor_to_image(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.image.tensor_to_image` instead."""
+ return _tensor_to_image(*args, **kwargs)
+
+
+@deprecated(
+ replace_with="kornia.losses.one_hot",
+ version="0.8.3",
+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.losses` instead.",
+)
+def one_hot(*args: Any, **kwargs: Any) -> Any:
+ """Deprecated: Use `kornia.losses.one_hot` instead."""
+ return _one_hot(*args, **kwargs)
+
__all__ = [
- "CachedDownloader",
- "ImageToTensor",
- "_extract_device_dtype",
- "batched_forward",
"create_meshgrid",
"create_meshgrid3d",
- "dataclass_to_dict",
- "deprecated",
- "dict_to_dataclass",
"draw_convex_polygon",
"draw_line",
"draw_point2d",
"draw_rectangle",
- "eye_like",
- "get_cuda_device_if_available",
- "get_cuda_or_mps_device_if_available",
- "get_mps_device_if_available",
- "get_sample_images",
- "image_list_to_tensor",
"image_to_string",
"image_to_tensor",
- "is_autocast_enabled",
- "is_mps_tensor_safe",
"load_pointcloud_ply",
- "map_location_to_cpu",
"one_hot",
"print_image",
- "safe_inverse_with_mask",
- "safe_solve_with_mask",
"save_pointcloud_ply",
"tensor_to_image",
- "torch_meshgrid",
- "vec_like",
- "xla_is_available",
]
diff --git a/kornia/utils/_compat.py b/kornia/utils/_compat.py
deleted file mode 100644
index fab710c3f..000000000
--- a/kornia/utils/_compat.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from typing import TYPE_CHECKING, Any, Callable, ContextManager, List, Optional, Tuple, TypeVar
-
-import torch
-from packaging import version
-from torch import Tensor
-
-
-def torch_version() -> str:
- """Parse the `torch.__version__` variable and removes +cu*/cpu."""
- return torch.__version__.partition("+")[0]
-
-
-def torch_version_lt(major: int, minor: int, patch: int) -> bool:
- _version = version.parse(torch_version())
- return _version < version.parse(f"{major}.{minor}.{patch}")
-
-
-def torch_version_le(major: int, minor: int, patch: int) -> bool:
- _version = version.parse(torch_version())
- return _version <= version.parse(f"{major}.{minor}.{patch}")
-
-
-def torch_version_ge(major: int, minor: int, patch: Optional[int] = None) -> bool:
- _version = version.parse(torch_version())
- if patch is None:
- return _version >= version.parse(f"{major}.{minor}")
- else:
- return _version >= version.parse(f"{major}.{minor}.{patch}")
-
-
-if TYPE_CHECKING:
- # TODO: remove this branch when kornia relies on torch >= 1.10.0
- def torch_meshgrid(tensors: List[Tensor], indexing: Optional[str] = None) -> Tuple[Tensor, ...]: ...
-
-elif torch_version_ge(1, 10, 0):
-
- def torch_meshgrid(tensors: List[Tensor], indexing: str):
- return torch.meshgrid(tensors, indexing=indexing)
-
-else:
- # TODO: remove this branch when kornia relies on torch >= 1.10.0
- def torch_meshgrid(tensors: List[Tensor], indexing: str):
- return torch.meshgrid(tensors)
-
-
-if TYPE_CHECKING:
- # TODO: remove this branch when kornia relies on torch >= 1.10.0
- _T = TypeVar("_T")
- torch_inference_mode: Callable[..., ContextManager[_T]]
-elif torch_version_ge(1, 10, 0):
- torch_inference_mode = torch.inference_mode
-else:
- # TODO: remove this branch when kornia relies on torch >= 1.10.0
- torch_inference_mode = torch.no_grad
-
-if TYPE_CHECKING: # TODO (@johnnv1): remove this branch when bump the pytorch CI to support torch 2.4
- custom_fwd: Callable[..., Any]
- autocast: Callable[..., Any]
-elif torch_version_ge(2, 4):
- from functools import partial
-
- from torch.amp import autocast as _autocast
- from torch.amp import custom_fwd as _custom_fwd
-
- custom_fwd = partial(_custom_fwd, device_type="cuda")
- autocast = partial(_autocast, "cuda")
-
-else:
- custom_fwd = torch.cuda.amp.custom_fwd
- autocast = torch.cuda.amp.autocast
diff --git a/kornia/utils/memory.py b/kornia/utils/memory.py
deleted file mode 100644
index c555f63ea..000000000
--- a/kornia/utils/memory.py
+++ /dev/null
@@ -1,75 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from typing import Any, Dict, Union
-
-import torch
-from torch import nn
-
-
-def batched_forward(
- model: nn.Module,
- data: torch.Tensor,
- device: Union[str, torch.device, None],
- batch_size: int = 128,
- **kwargs: Dict[str, Any],
-) -> torch.Tensor:
- r"""Run the forward in micro-batches.
-
- When the just model.forward(data) does not fit into device memory, e.g. on laptop GPU.
- In the end, it transfers the output to the device of the input data tensor.
- E.g. running HardNet on 8000x1x32x32 tensor.
-
- Args:
- model: Any torch model, which outputs a single tensor as an output.
- data: Input data of Bx(Any) shape.
- device: which device should we run on.
- batch_size: "micro-batch" size.
- **kwargs: any other arguments, which accepts model.
-
- Returns:
- output of the model.
-
- Example:
- >>> patches = torch.rand(8000, 1, 32, 32)
- >>> sift = kornia.feature.SIFTDescriptor(32)
- >>> desc_batched = batched_forward(sift, patches, torch.device('cpu'), 128)
- >>> desc = sift(patches)
- >>> assert torch.allclose(desc, desc_batched)
-
- """
- model_dev = model.to(device)
- B: int = len(data)
- bs: int = batch_size
- if B > batch_size:
- out_list = []
- n_batches = int(B // bs + 1)
- for batch_idx in range(n_batches):
- st = batch_idx * bs
- if batch_idx == n_batches - 1:
- if (batch_idx + 1) * bs > B:
- end = B
- else:
- end = (batch_idx + 1) * bs
- else:
- end = (batch_idx + 1) * bs
- if st >= end:
- continue
- out_list.append(model_dev(data[st:end].to(device), **kwargs))
- out = torch.cat(out_list, 0)
- return out.to(data.device)
- return model(data, **kwargs)
diff --git a/kornia/utils/sample.py b/kornia/utils/sample.py
deleted file mode 100644
index b0b855a1d..000000000
--- a/kornia/utils/sample.py
+++ /dev/null
@@ -1,116 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-"""Utilities for downloading and loading sample images."""
-
-import logging
-import os
-from typing import Any, List, Optional, Tuple, Union
-
-import torch
-
-import kornia
-from kornia.core.external import PILImage as Image
-from kornia.core.external import requests
-from kornia.io import load_image
-
-__all__ = [
- "get_sample_images",
-]
-
-IMAGE_URLS: List[str] = [
- "https://raw.githubusercontent.com/kornia/data/main/panda.jpg",
- "https://raw.githubusercontent.com/kornia/data/main/simba.png",
- "https://raw.githubusercontent.com/kornia/data/main/girona.png",
- "https://raw.githubusercontent.com/kornia/data/main/baby_giraffe.png",
- "https://raw.githubusercontent.com/kornia/data/main/persistencia_memoria.jpg",
- "https://raw.githubusercontent.com/kornia/data/main/delorean.png",
-]
-
-
-def download_image(url: str, save_to: str) -> None:
- """Download an image from a given URL and save it to a specified file path.
-
- Args:
- url: The URL of the image to download.
- save_to: The file path where the downloaded image will be saved.
-
- """
- im = Image.open(requests.get(url, stream=True, timeout=30).raw) # type:ignore
- im.save(save_to)
-
-
-def get_sample_images(
- resize: Optional[Tuple[int, int]] = None,
- paths: List[str] = IMAGE_URLS,
- download: bool = True,
- cache_dir: Optional[str] = None,
- as_list: Optional[bool] = None,
- divisible_factor: Optional[int] = None,
- **kwargs: Any,
-) -> Union[torch.Tensor, List[torch.Tensor]]:
- """Load multiple images from the given URLs.
-
- Optionally download them, resize them if specified, and return them as a batch of tensors or a list of tensors.
-
- Args:
- paths: A list of path or URL from which to load or download images.
- Defaults to a pre-defined constant `IMAGE_URLS` if not provided.
- resize: Optional target size for resizing all images as a tuple (height, width).
- If not provided, the images will not be resized, and their original sizes will be retained.
- download: Whether to download the images if they are not already cached. Defaults to True.
- cache_dir: The directory where the downloaded images will be cached.
- Defaults to ".kornia_hub/images".
- as_list: if to keep the output as a list. If None and `resize` is None, the output will be a list.
- If None and `resize` is not None, the output will be a single tensor.
- divisible_factor:
- If not None, the images will be resized to the nearest multiple of `divisible_factor`.
- **kwargs: Additional keyword arguments to pass to `kornia.geometry.resize`.
-
- Returns:
- torch.Tensor | list[torch.Tensor]:
- If `resize` is provided, returns a single stacked tensor with shape (B, C, H, W).
- Otherwise, returns a list of tensors, each with its original shape (C, H, W).
-
- """
- if cache_dir is None:
- cache_dir = ".kornia_hub/images"
- os.makedirs(cache_dir, exist_ok=True)
- tensors = []
- for path in paths:
- if path.startswith("http"):
- name = os.path.basename(path)
- fname = os.path.join(cache_dir, name)
- if not os.path.exists(fname) and download:
- logging.info(f"Downloading `{path}` to `{fname}`.")
- download_image(path, fname)
- elif not os.path.exists(fname) and not download:
- logging.error(
- f"Image `{path}` not found at `{fname}`. You may want to set `download=True` to download it."
- )
- else:
- fname = path
- img_tensor = load_image(fname)
- if resize is not None:
- img_tensor = kornia.geometry.resize(img_tensor, resize, **kwargs)
- if divisible_factor is not None:
- img_tensor = kornia.geometry.transform.resize_to_be_divisible(img_tensor, divisible_factor, **kwargs)
- tensors.append(img_tensor)
-
- if not as_list and resize is not None:
- return torch.stack(tensors)
-
- return tensors
diff --git a/testing/geometry/create.py b/testing/geometry/create.py
index 46d3bd9fb..c70e1323b 100644
--- a/testing/geometry/create.py
+++ b/testing/geometry/create.py
@@ -22,7 +22,7 @@ from typing import Optional, Union
import torch
import kornia.geometry.epipolar as epi
-from kornia.utils.misc import eye_like
+from kornia.core.ops import eye_like
def create_random_homography(data: torch.Tensor, eye_size: int, std_val: float = 1e-3) -> torch.Tensor:
diff --git a/tests/augmentation/_3d/test_random_equalize_3d.py b/tests/augmentation/_3d/test_random_equalize_3d.py
index f7d49683c..a62a947b9 100644
--- a/tests/augmentation/_3d/test_random_equalize_3d.py
+++ b/tests/augmentation/_3d/test_random_equalize_3d.py
@@ -48,7 +48,7 @@ class TestRandomEqualize3D(BaseTester):
)
expected = self.build_input(channels, depth, height, width, bs=1, row=row_expected, device=device, dtype=dtype)
- identity = kornia.eye_like(4, expected)
+ identity = kornia.core.ops.eye_like(4, expected)
self.assert_close(f(inputs3d), expected, rtol=1e-4, atol=1e-4)
self.assert_close(f.transform_matrix, identity, rtol=1e-4, atol=1e-4)
@@ -66,7 +66,7 @@ class TestRandomEqualize3D(BaseTester):
row_expected = torch.tensor([0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000])
expected = self.build_input(channels, depth, height, width, bs, row=row_expected, device=device, dtype=dtype)
- identity = kornia.eye_like(4, expected) # 2 x 4 x 4
+ identity = kornia.core.ops.eye_like(4, expected) # 2 x 4 x 4
self.assert_close(f(inputs3d), expected, rtol=1e-4, atol=1e-4)
self.assert_close(f.transform_matrix, identity, rtol=1e-4, atol=1e-4)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 6ffe546f5..7e66aecef 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -77,10 +77,9 @@ from kornia.augmentation import (
)
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import Resample, pi
-from kornia.geometry import transform_points
-from kornia.utils import create_meshgrid
-from kornia.utils._compat import torch_version, torch_version_le
-from kornia.utils.helpers import _torch_inverse_cast
+from kornia.core._compat import torch_version, torch_version_le
+from kornia.core.utils import _torch_inverse_cast
+from kornia.geometry import create_meshgrid, transform_points
from testing.augmentation.datasets import DummyMPDataset
from testing.base import BaseTester
@@ -295,7 +294,7 @@ class CommonTests(BaseTester):
output = augmentation(input_tensor)
transform = augmentation.transform_matrix
- if (transform == kornia.eye_like(3, transform)).all():
+ if (transform == kornia.core.ops.eye_like(3, transform)).all():
pytest.skip("Test not relevant for intensity augmentations.")
indices = create_meshgrid(
@@ -404,7 +403,7 @@ class TestRandomEqualizeAlternative(CommonTests):
)
expected_output = expected_output.repeat(2, 3, 20, 1)
- expected_transformation = kornia.eye_like(3, input_tensor)
+ expected_transformation = kornia.core.ops.eye_like(3, input_tensor)
parameters = {}
self._test_random_p_1_implementation(
input_tensor=input_tensor,
@@ -685,7 +684,7 @@ class TestRandomRotationAlternative(CommonTests):
dtype=self.dtype,
).repeat((2, 1, 1, 1))
expected_output = input_tensor
- expected_transformation = kornia.eye_like(3, input_tensor)
+ expected_transformation = kornia.core.ops.eye_like(3, input_tensor)
parameters = {"degrees": (-360.0, -360.0), "align_corners": True}
self._test_random_p_1_implementation(
input_tensor=input_tensor,
@@ -778,7 +777,7 @@ class TestRandomRotation90(CommonTests):
dtype=self.dtype,
).repeat((2, 1, 1, 1))
expected_output = input_tensor
- expected_transformation = kornia.eye_like(3, input_tensor)
+ expected_transformation = kornia.core.ops.eye_like(3, input_tensor)
parameters = {"times": (0, 0), "align_corners": True}
self._test_random_p_1_implementation(
input_tensor=input_tensor,
@@ -851,7 +850,7 @@ class TestRandomGrayscaleAlternative(CommonTests):
.repeat(1, 3, 1, 1)
)
- expected_transformation = kornia.eye_like(3, input_tensor)
+ expected_transformation = kornia.core.ops.eye_like(3, input_tensor)
parameters = {}
self._test_random_p_1_implementation(
input_tensor=input_tensor,
@@ -3813,7 +3812,7 @@ class TestRandomEqualize(BaseTester):
]
)
expected = self.build_input(channels, height, width, bs=1, row=row_expected, device=device, dtype=dtype)
- identity = kornia.eye_like(3, expected) # 3 x 3
+ identity = kornia.core.ops.eye_like(3, expected) # 3 x 3
self.assert_close(f(inputs), expected, low_tolerance=True)
self.assert_close(f.transform_matrix, identity, low_tolerance=True)
@@ -3854,7 +3853,7 @@ class TestRandomEqualize(BaseTester):
)
expected = self.build_input(channels, height, width, bs, row=row_expected, device=device, dtype=dtype)
- identity = kornia.eye_like(3, expected) # 2 x 3 x 3
+ identity = kornia.core.ops.eye_like(3, expected) # 2 x 3 x 3
self.assert_close(f(inputs), expected, low_tolerance=True)
self.assert_close(f.transform_matrix, identity, low_tolerance=True)
@@ -4417,7 +4416,7 @@ class TestNormalize(BaseTester):
expected = (inputs - 1) * 2
- identity = kornia.eye_like(3, expected)
+ identity = kornia.core.ops.eye_like(3, expected)
self.assert_close(f(inputs), expected)
self.assert_close(f.transform_matrix, identity)
@@ -4432,7 +4431,7 @@ class TestNormalize(BaseTester):
expected = (inputs - 1) * 2
- identity = kornia.eye_like(3, expected)
+ identity = kornia.core.ops.eye_like(3, expected)
self.assert_close(f(inputs), expected)
self.assert_close(f.transform_matrix, identity)
@@ -4467,7 +4466,7 @@ class TestDenormalize(BaseTester):
expected = inputs / 2 + 1
- identity = kornia.eye_like(3, expected)
+ identity = kornia.core.ops.eye_like(3, expected)
self.assert_close(f(inputs), expected)
self.assert_close(f.transform_matrix, identity)
@@ -4482,7 +4481,7 @@ class TestDenormalize(BaseTester):
expected = inputs / 2 + 1
- identity = kornia.eye_like(3, expected)
+ identity = kornia.core.ops.eye_like(3, expected)
self.assert_close(f(inputs), expected)
self.assert_close(f.transform_matrix, identity)
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index e25f774a2..d563a0cfd 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -35,7 +35,7 @@ from kornia.augmentation.random_generator import (
ResizedCropGenerator,
center_crop_generator,
)
-from kornia.utils._compat import torch_version_ge
+from kornia.core._compat import torch_version_ge
from testing.base import assert_close
diff --git a/tests/color/test_gray.py b/tests/color/test_gray.py
index 775d126b4..a8a93e109 100644
--- a/tests/color/test_gray.py
+++ b/tests/color/test_gray.py
@@ -20,7 +20,7 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.utils._compat import torch_version
+from kornia.core._compat import torch_version
from testing.base import BaseTester, assert_close
diff --git a/tests/contrib/test_extract_tensor_patch.py b/tests/contrib/test_extract_tensor_patch.py
index 28c3837f8..9f3e7dd06 100644
--- a/tests/contrib/test_extract_tensor_patch.py
+++ b/tests/contrib/test_extract_tensor_patch.py
@@ -128,7 +128,7 @@ class TestExtractTensorPatches(BaseTester):
return kornia.geometry.denormalize_pixel_coordinates(img, height, width)
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True).to(device)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True).to(device)
actual = op_script(grid, height, width)
expected = kornia.denormalize_pixel_coordinates(grid, height, width)
diff --git a/tests/utils/test_helpers.py b/tests/core/test_helpers.py
similarity index 97%
rename from tests/utils/test_helpers.py
rename to tests/core/test_helpers.py
index fb816ff23..533504db9 100644
--- a/tests/utils/test_helpers.py
+++ b/tests/core/test_helpers.py
@@ -18,8 +18,9 @@
import pytest
import torch
-from kornia.utils import _extract_device_dtype
-from kornia.utils.helpers import (
+from kornia.core.exceptions import DeviceError
+from kornia.core.utils import (
+ _extract_device_dtype,
_torch_histc_cast,
_torch_inverse_cast,
_torch_solve_cast,
@@ -70,7 +71,7 @@ def test_extract_device_dtype(tensor_list, out_device, out_dtype, will_throw_err
# warnings.warn("Add GPU tests.")
if will_throw_error:
- with pytest.raises(ValueError):
+ with pytest.raises(DeviceError):
_extract_device_dtype(tensor_list)
else:
device, dtype = _extract_device_dtype(tensor_list)
diff --git a/tests/core/test_tensor_wrapper.py b/tests/core/test_tensor_wrapper.py
index 5fa14a390..f9e983ef4 100644
--- a/tests/core/test_tensor_wrapper.py
+++ b/tests/core/test_tensor_wrapper.py
@@ -18,7 +18,8 @@
import pytest
import torch
-from kornia.core.tensor_wrapper import TensorWrapper, unwrap, wrap
+from kornia.core.exceptions import TypeCheckError
+from kornia.core.tensor_wrapper import TensorWrapper, _unwrap, _wrap
from testing.base import BaseTester
@@ -26,7 +27,7 @@ from testing.base import BaseTester
class TestTensorWrapper(BaseTester):
def test_smoke(self, device, dtype):
data = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- tensor = wrap(data, TensorWrapper)
+ tensor = _wrap(data, TensorWrapper)
assert isinstance(tensor, TensorWrapper)
assert isinstance(tensor.data, torch.Tensor)
assert tensor.shape == (1, 2, 3, 4)
@@ -34,18 +35,44 @@ class TestTensorWrapper(BaseTester):
assert tensor.dtype == dtype
self.assert_close(data, tensor.unwrap())
+ def test_init_validation(self):
+ """Test that TensorWrapper validates input type."""
+ with pytest.raises(TypeCheckError, match="Tensor"):
+ TensorWrapper([1, 2, 3]) # type: ignore
+
+ with pytest.raises(TypeCheckError, match="Tensor"):
+ TensorWrapper("not a tensor") # type: ignore
+
+ def test_repr(self, device, dtype):
+ """Test string representation."""
+ data = torch.rand(2, 3, device=device, dtype=dtype)
+ tensor = TensorWrapper(data)
+ repr_str = repr(tensor)
+ assert "TensorWrapper" in repr_str
+ assert str(data) in repr_str or repr(data) in repr_str
+
+ def test_data_property(self, device, dtype):
+ """Test data property access."""
+ data = torch.rand(2, 3, device=device, dtype=dtype)
+ tensor = TensorWrapper(data)
+ assert tensor.data is data
+ assert isinstance(tensor.data, torch.Tensor)
+
def test_serialization(self, device, dtype, tmp_path):
data = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- tensor: TensorWrapper = wrap(data, TensorWrapper)
+ tensor: TensorWrapper = _wrap(data, TensorWrapper)
file_path = tmp_path / "tensor.pt"
torch.save(tensor, file_path)
- file_path.is_file()
+ assert file_path.is_file()
loaded_tensor: TensorWrapper = torch.load(file_path, weights_only=False)
assert isinstance(loaded_tensor, TensorWrapper)
self.assert_close(loaded_tensor.unwrap(), tensor.unwrap())
+ # Check that used_attrs and used_calls are preserved
+ assert hasattr(loaded_tensor, "used_attrs")
+ assert hasattr(loaded_tensor, "used_calls")
def test_wrap_list(self, device, dtype):
data_list = [
@@ -55,11 +82,11 @@ class TestTensorWrapper(BaseTester):
1,
0.5,
]
- tensor_list = wrap(data_list, TensorWrapper)
+ tensor_list = _wrap(data_list, TensorWrapper)
assert isinstance(tensor_list, list)
assert len(tensor_list) == 5
- tensor_list_data = unwrap(tensor_list)
+ tensor_list_data = _unwrap(tensor_list)
assert len(tensor_list_data) == 5
self.assert_close(tensor_list_data[0], data_list[0])
@@ -71,14 +98,26 @@ class TestTensorWrapper(BaseTester):
for i in range(len(tensor_list_data[:3])):
self.assert_close(tensor_list[i].unwrap(), data_list[i])
+ def test_wrap_tuple(self, device, dtype):
+ """Test wrapping tuples."""
+ data_tuple = (
+ torch.rand(2, device=device, dtype=dtype),
+ torch.rand(3, device=device, dtype=dtype),
+ )
+ tensor_tuple = _wrap(data_tuple, TensorWrapper)
+ assert isinstance(tensor_tuple, tuple)
+ assert len(tensor_tuple) == 2
+ assert isinstance(tensor_tuple[0], TensorWrapper)
+ assert isinstance(tensor_tuple[1], TensorWrapper)
+
def test_accessors(self, device, dtype):
data = torch.tensor([0.0, 1.0, 0.0], device=device, dtype=dtype)
- x = wrap(data, TensorWrapper)
- self.assert_close(x[1], torch.tensor(1.0, device=device, dtype=dtype))
+ x = _wrap(data, TensorWrapper)
+ self.assert_close(x[1].unwrap(), torch.tensor(1.0, device=device, dtype=dtype))
y = x[0]
- self.assert_close(y, torch.tensor(0.0, device=device, dtype=dtype))
+ self.assert_close(y.unwrap(), torch.tensor(0.0, device=device, dtype=dtype))
x[1] = 0.0
- self.assert_close(x, torch.zeros_like(x))
+ self.assert_close(x.unwrap(), torch.zeros_like(data))
def test_unary_ops(self, device, dtype):
data = torch.rand(2, device=device, dtype=dtype)
@@ -86,30 +125,141 @@ class TestTensorWrapper(BaseTester):
x1 = TensorWrapper(data)
x2 = TensorWrapper(data)
- self.assert_close(x.add(x), x + x)
- self.assert_close(x.add(1), 1 + x)
- self.assert_close(x.add(1), x + 1)
- self.assert_close(x.mul(x), x * x)
- self.assert_close(x.mul(1), 1 * x)
- self.assert_close(x.mul(1), x * 1)
- self.assert_close(x.sub(x), x - x)
- self.assert_close(x.sub(1), x - 1)
- self.assert_close(x.div(x), x / x)
- self.assert_close(x.true_divide(x), x / x)
- self.assert_close(x.floor_divide(x), x // x)
- self.assert_close(x1.ge(x2), x1 >= x2)
- self.assert_close(x1.gt(x2), x1 > x2)
- self.assert_close(x1.lt(x2), x1 < x2)
- self.assert_close(x1.le(x2), x1 <= x2)
- self.assert_close(x1.eq(x2), x1 == x2)
- self.assert_close(x1.ne(x2), x1 != x2)
- self.assert_close(-x, -data)
+ # Methods like x.add() return unwrapped tensors, operators return wrapped tensors
+ self.assert_close(x.add(x), (x + x).unwrap())
+ self.assert_close(x.add(1), (1 + x).unwrap())
+ self.assert_close(x.add(1), (x + 1).unwrap())
+ self.assert_close(x.mul(x), (x * x).unwrap())
+ self.assert_close(x.mul(1), (1 * x).unwrap())
+ self.assert_close(x.mul(1), (x * 1).unwrap())
+ self.assert_close(x.sub(x), (x - x).unwrap())
+ self.assert_close(x.sub(1), (x - 1).unwrap())
+ self.assert_close(x.div(x), (x / x).unwrap())
+ self.assert_close(x.true_divide(x), (x / x).unwrap())
+ self.assert_close(x.floor_divide(x), (x // x).unwrap())
+ self.assert_close(x1.ge(x2), (x1 >= x2).unwrap())
+ self.assert_close(x1.gt(x2), (x1 > x2).unwrap())
+ self.assert_close(x1.lt(x2), (x1 < x2).unwrap())
+ self.assert_close(x1.le(x2), (x1 <= x2).unwrap())
+ self.assert_close(x1.eq(x2), (x1 == x2).unwrap())
+ self.assert_close(x1.ne(x2), (x1 != x2).unwrap())
+ self.assert_close((-x).unwrap(), -data)
+
+ def test_bool_int_conversion(self, device):
+ """Test boolean and integer conversion."""
+ # Test __bool__
+ data_true = torch.tensor([1.0], device=device)
+ tensor_true = TensorWrapper(data_true)
+ assert bool(tensor_true) is True
+
+ data_false = torch.tensor([0.0], device=device)
+ tensor_false = TensorWrapper(data_false)
+ assert bool(tensor_false) is False
+
+ # Test __int__
+ data_int = torch.tensor([42], device=device, dtype=torch.int32)
+ tensor_int = TensorWrapper(data_int)
+ assert int(tensor_int) == 42
+ assert isinstance(int(tensor_int), int)
+
+ def test_right_side_operations(self, device, dtype):
+ """Test right-side operations (radd, rsub, rmul)."""
+ data = torch.tensor([2.0, 3.0], device=device, dtype=dtype)
+ x = TensorWrapper(data)
+ scalar = 5.0
+
+ # Test __radd__: scalar + tensor
+ result_radd = scalar + x
+ expected_radd = scalar + data
+ self.assert_close(result_radd.unwrap(), expected_radd)
+
+ # Test __rsub__: scalar - tensor
+ result_rsub = scalar - x
+ expected_rsub = scalar - data
+ self.assert_close(result_rsub.unwrap(), expected_rsub)
+
+ # Test __rmul__: scalar * tensor
+ result_rmul = scalar * x
+ expected_rmul = scalar * data
+ self.assert_close(result_rmul.unwrap(), expected_rmul)
+
+ def test_used_attrs_tracking(self, device, dtype):
+ """Test that attribute usage is tracked."""
+ data = torch.rand(2, 3, device=device, dtype=dtype)
+ tensor = TensorWrapper(data)
+
+ # Initially empty
+ assert len(tensor.used_attrs) == 0
+
+ # Access some attributes
+ _ = tensor.shape
+ _ = tensor.device
+ _ = tensor.dtype
+
+ # Check that they're tracked
+ assert "shape" in tensor.used_attrs
+ assert "device" in tensor.used_attrs
+ assert "dtype" in tensor.used_attrs
+
+ def test_used_calls_tracking(self, device, dtype):
+ """Test that function calls are tracked."""
+ data = torch.rand(2, 3, device=device, dtype=dtype)
+ tensor = TensorWrapper(data)
+
+ # Initially empty
+ assert len(tensor.used_calls) == 0
+
+ # Call some operations
+ _ = tensor + tensor
+ _ = tensor * 2
+ _ = torch.sum(tensor)
+
+ # Check that they're tracked
+ assert len(tensor.used_calls) > 0
+ assert torch.add in tensor.used_calls or torch.mul in tensor.used_calls
+
+ def test_setattr_tracking(self, device, dtype):
+ """Test that setattr doesn't track internal attributes."""
+ data = torch.rand(2, 3, device=device, dtype=dtype)
+ tensor = TensorWrapper(data)
+
+ # Setting a new attribute on the underlying tensor should be tracked
+ tensor.some_new_attr = 42
+ assert "some_new_attr" in tensor.used_attrs
def test_callable(self, device, dtype):
data = torch.ones(2, device=device, dtype=dtype)
x = TensorWrapper(data)
y = (x * x).sum(-1, True)
- self.assert_close(y, torch.ones_like(y) * 2)
+ # sum() method returns unwrapped tensor, so compare directly
+ expected = torch.ones_like(y) * 2
+ self.assert_close(y, expected)
+
+ def test_len(self, device, dtype):
+ """Test __len__ method."""
+ data = torch.rand(5, device=device, dtype=dtype)
+ tensor = TensorWrapper(data)
+ assert len(tensor) == 5
+ assert len(tensor) == len(data)
+
+ def test_nested_wrapping(self, device, dtype):
+ """Test that wrapping already-wrapped tensors works correctly."""
+ data = torch.rand(2, 3, device=device, dtype=dtype)
+ wrapped_once = TensorWrapper(data)
+ wrapped_twice = _wrap(wrapped_once, TensorWrapper)
+
+ # Should still unwrap to original data
+ self.assert_close(_unwrap(wrapped_twice), data)
+
+ def test_string_bytes_not_wrapped(self):
+ """Test that strings and bytes are not treated as sequences in __torch_function__."""
+ # This tests the fix for not treating strings/bytes as sequences
+ data = torch.rand(2, 3)
+ tensor = TensorWrapper(data)
+
+ # Should not raise errors when strings/bytes are in args
+ result = torch.cat([tensor, tensor])
+ assert isinstance(result, TensorWrapper)
@pytest.mark.skip(reason="not implemented yet")
def test_cardinality(self, device, dtype):
@@ -119,9 +269,10 @@ class TestTensorWrapper(BaseTester):
def test_jit(self, device, dtype):
pass
- @pytest.mark.skip(reason="not implemented yet")
- def test_exception(self, device, dtype):
- pass
+ def test_exception(self):
+ """Test exception handling for invalid inputs."""
+ with pytest.raises(TypeCheckError):
+ TensorWrapper([1, 2, 3]) # type: ignore
@pytest.mark.skip(reason="not implemented yet")
def test_module(self, device, dtype):
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index 644a71a8a..bdc977504 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -1048,7 +1048,7 @@ class TestSharpness(BaseTester):
self.assert_close(actual, expected)
[email protected](kornia.xla_is_available(), reason="issues with xla device")
[email protected](kornia.core.utils.xla_is_available(), reason="issues with xla device")
class TestSolarize(BaseTester):
f = kornia.enhance.solarize
@@ -1165,7 +1165,7 @@ class TestPosterize(BaseTester):
assert TestPosterize.f(img, 1.0)
# TODO(jian): add better cases
- @pytest.mark.skipif(kornia.xla_is_available(), reason="issues with xla device")
+ @pytest.mark.skipif(kornia.core.utils.xla_is_available(), reason="issues with xla device")
def test_value(self, device, dtype):
torch.manual_seed(0)
diff --git a/tests/enhance/test_histogram.py b/tests/enhance/test_histogram.py
index 3f2f3ee15..e321bcfe3 100644
--- a/tests/enhance/test_histogram.py
+++ b/tests/enhance/test_histogram.py
@@ -146,7 +146,7 @@ class TestHistogram2d(BaseTester):
bandwidth = torch.tensor(2 * 0.4**2, device=device, dtype=dtype)
pdf = TestHistogram2d.fcn(sample1, sample2, bins, bandwidth)
- ans = 0.1 * kornia.eye_like(10, pdf)
+ ans = 0.1 * kornia.core.ops.eye_like(10, pdf)
self.assert_close(ans, pdf)
diff --git a/tests/utils/test_misc.py b/tests/enhance/test_jpeg_misc.py
similarity index 87%
rename from tests/utils/test_misc.py
rename to tests/enhance/test_jpeg_misc.py
index 0ee09a1dc..ba80a1045 100644
--- a/tests/utils/test_misc.py
+++ b/tests/enhance/test_jpeg_misc.py
@@ -17,10 +17,14 @@
import torch
-from kornia.utils.misc import (
- differentiable_clipping,
- differentiable_polynomial_floor,
- differentiable_polynomial_rounding,
+from kornia.enhance.jpeg import (
+ _differentiable_clipping as differentiable_clipping,
+)
+from kornia.enhance.jpeg import (
+ _differentiable_polynomial_floor as differentiable_polynomial_floor,
+)
+from kornia.enhance.jpeg import (
+ _differentiable_polynomial_rounding as differentiable_polynomial_rounding,
)
from testing.base import BaseTester
diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.py
index 7567736b9..351fa7d10 100644
--- a/tests/feature/test_integrated.py
+++ b/tests/feature/test_integrated.py
@@ -22,6 +22,7 @@ import torch
from torch import nn
import kornia
+from kornia.core._compat import torch_version_le
from kornia.feature import (
DescriptorMatcher,
GFTTAffNetHardNet,
@@ -39,7 +40,6 @@ from kornia.feature import (
)
from kornia.feature.integrated import LocalFeatureMatcher
from kornia.geometry import RANSAC, resize, transform_points
-from kornia.utils._compat import torch_version_le
from testing.base import BaseTester
from testing.casts import dict_to
diff --git a/tests/feature/test_lightglue_onnx.py b/tests/feature/test_lightglue_onnx.py
index afd69910f..3af670b25 100644
--- a/tests/feature/test_lightglue_onnx.py
+++ b/tests/feature/test_lightglue_onnx.py
@@ -18,9 +18,9 @@
import pytest
import torch
+from kornia.core._compat import torch_version_le
from kornia.feature import OnnxLightGlue
from kornia.feature.lightglue_onnx.utils import normalize_keypoints
-from kornia.utils._compat import torch_version_le
try:
import onnxruntime as ort
diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.py
index c587aaeff..44c9a9c06 100644
--- a/tests/feature/test_loftr.py
+++ b/tests/feature/test_loftr.py
@@ -20,9 +20,9 @@ import sys
import pytest
import torch
+from kornia.core._compat import torch_version_ge
from kornia.feature import LoFTR
from kornia.geometry import resize
-from kornia.utils._compat import torch_version_ge
from testing.base import BaseTester
from testing.casts import dict_to
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index a6605d32f..7d286eaa4 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -18,6 +18,7 @@
import pytest
import torch
+from kornia.core._compat import torch_version_le
from kornia.feature.integrated import LightGlueMatcher
from kornia.feature.laf import laf_from_center_scale_ori
from kornia.feature.matching import (
@@ -32,7 +33,6 @@ from kornia.feature.matching import (
match_snn,
)
from kornia.feature.steerers import DiscreteSteerer
-from kornia.utils._compat import torch_version_le
from testing.base import BaseTester
from testing.casts import dict_to
diff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.py
index e32ccef45..66dc2675f 100644
--- a/tests/filters/test_canny.py
+++ b/tests/filters/test_canny.py
@@ -18,8 +18,8 @@
import pytest
import torch
+from kornia.core._compat import torch_version
from kornia.filters import Canny, canny
-from kornia.utils._compat import torch_version
from testing.base import BaseTester
diff --git a/tests/filters/test_dissolving.py b/tests/filters/test_dissolving.py
index 6a3e325ed..fa16881fd 100644
--- a/tests/filters/test_dissolving.py
+++ b/tests/filters/test_dissolving.py
@@ -18,8 +18,8 @@
import pytest
import torch
+from kornia.core._compat import torch_version_le
from kornia.filters.dissolving import StableDiffusionDissolving
-from kornia.utils._compat import torch_version_le
WEIGHTS_CACHE_DIR = "weights/"
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index f910800df..12c8be7b0 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -18,8 +18,8 @@
import pytest
import torch
+from kornia.core._compat import torch_version_le
from kornia.filters import filter2d, filter2d_separable, filter3d
-from kornia.utils._compat import torch_version_le
from testing.base import BaseTester
diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.py
index 41a956e77..f70d6f16f 100644
--- a/tests/filters/test_guided.py
+++ b/tests/filters/test_guided.py
@@ -18,8 +18,8 @@
import pytest
import torch
+from kornia.core._compat import torch_version
from kornia.filters import GuidedBlur, guided_blur
-from kornia.utils._compat import torch_version
from testing.base import BaseTester
diff --git a/tests/filters/test_in_range.py b/tests/filters/test_in_range.py
index fc4bc90a5..1e531c2a5 100644
--- a/tests/filters/test_in_range.py
+++ b/tests/filters/test_in_range.py
@@ -20,8 +20,8 @@ import re
import pytest
import torch
+from kornia.core._compat import torch_version
from kornia.filters import InRange, in_range
-from kornia.utils._compat import torch_version
from testing.base import BaseTester, assert_close
diff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.py
index 94b6af363..aea1a3021 100644
--- a/tests/filters/test_sobel.py
+++ b/tests/filters/test_sobel.py
@@ -18,8 +18,8 @@
import pytest
import torch
+from kornia.core._compat import torch_version
from kornia.filters import Sobel, SpatialGradient, SpatialGradient3d, sobel, spatial_gradient, spatial_gradient3d
-from kornia.utils._compat import torch_version
from testing.base import BaseTester
diff --git a/tests/geometry/calibration/test_pnp.py b/tests/geometry/calibration/test_pnp.py
index cd2e13de3..c4313023d 100644
--- a/tests/geometry/calibration/test_pnp.py
+++ b/tests/geometry/calibration/test_pnp.py
@@ -154,7 +154,7 @@ class TestSolvePnpDlt(BaseTester):
pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)
- pred_world_to_cam_4x4 = kornia.eye_like(4, pred_world_to_cam)
+ pred_world_to_cam_4x4 = kornia.core.ops.eye_like(4, pred_world_to_cam)
pred_world_to_cam_4x4[:, :3, :] = pred_world_to_cam
repeated_intrinsics = intrinsics.unsqueeze(1).repeat(1, num_points, 1, 1)
diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.py
index 3e3fa762b..6716a018c 100644
--- a/tests/geometry/epipolar/test_essential.py
+++ b/tests/geometry/epipolar/test_essential.py
@@ -182,8 +182,8 @@ class TestRelativeCameraMotion(BaseTester):
t1 = torch.tensor([[[10.0], [0.0], [0.0]]]).type_as(R1)
- R2 = kornia.eye_like(3, R1)
- t2 = kornia.vec_like(3, t1)
+ R2 = kornia.core.ops.eye_like(3, R1)
+ t2 = kornia.core.ops.vec_like(3, t1)
R_expected = R1.clone()
t_expected = -t1
@@ -197,8 +197,8 @@ class TestRelativeCameraMotion(BaseTester):
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 = kornia.vec_like(3, R1)
- t2 = kornia.vec_like(3, R2)
+ t1 = kornia.core.ops.vec_like(3, R1)
+ t2 = kornia.core.ops.vec_like(3, R2)
R_expected = R2.clone()
t_expected = t1
diff --git a/tests/geometry/epipolar/test_numeric.py b/tests/geometry/epipolar/test_numeric.py
index 2ff9006fb..cf473def9 100644
--- a/tests/geometry/epipolar/test_numeric.py
+++ b/tests/geometry/epipolar/test_numeric.py
@@ -77,7 +77,7 @@ class TestSkewSymmetric:
class TestEyeLike:
def test_smoke(self, device, dtype):
image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
- identity = kornia.eye_like(3, image)
+ identity = kornia.core.ops.eye_like(3, image)
assert identity.shape == (1, 3, 3)
assert identity.device == image.device
assert identity.dtype == image.dtype
@@ -86,7 +86,7 @@ class TestEyeLike:
def test_shape(self, batch_size, eye_size, device, dtype):
B, N = batch_size, eye_size
image = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)
- identity = kornia.eye_like(N, image)
+ identity = kornia.core.ops.eye_like(N, image)
assert identity.shape == (B, N, N)
assert identity.device == image.device
assert identity.dtype == image.dtype
@@ -95,7 +95,7 @@ class TestEyeLike:
class TestVecLike:
def test_smoke(self, device, dtype):
image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
- vec = kornia.vec_like(3, image)
+ vec = kornia.core.ops.vec_like(3, image)
assert vec.shape == (1, 3, 1)
assert vec.device == image.device
assert vec.dtype == image.dtype
@@ -104,7 +104,7 @@ class TestVecLike:
def test_shape(self, batch_size, eye_size, device, dtype):
B, N = batch_size, eye_size
image = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)
- vec = kornia.vec_like(N, image)
+ vec = kornia.core.ops.vec_like(N, image)
assert vec.shape == (B, N, 1)
assert vec.device == image.device
assert vec.dtype == image.dtype
diff --git a/tests/geometry/epipolar/test_triangulation.py b/tests/geometry/epipolar/test_triangulation.py
index e9e310478..d61c12136 100644
--- a/tests/geometry/epipolar/test_triangulation.py
+++ b/tests/geometry/epipolar/test_triangulation.py
@@ -66,8 +66,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 = kornia.eye_like(3, points1)
+ P1 = kornia.core.ops.eye_like(3, points1)
P1 = torch.nn.functional.pad(P1, [0, 1])
- P2 = kornia.eye_like(3, points2)
+ P2 = kornia.core.ops.eye_like(3, points2)
P2 = torch.nn.functional.pad(P2, [0, 1])
assert gradcheck(epi.triangulate_points, (P1, P2, points1, points2), raise_exception=True, fast_mode=True)
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index e7331aa2f..fa048004b 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -23,6 +23,8 @@ import pytest
import torch
import kornia
+from kornia.core._compat import torch_version
+from kornia.core.ops import eye_like
from kornia.geometry.conversions import (
ARKitQTVecs_to_ColmapQTVecs,
Rt_to_matrix4x4,
@@ -38,8 +40,6 @@ from kornia.geometry.conversions import (
worldtocam_to_camtoworld_Rt,
)
from kornia.geometry.quaternion import Quaternion
-from kornia.utils._compat import torch_version
-from kornia.utils.misc import eye_like
from testing.base import BaseTester, assert_close
@@ -760,9 +760,11 @@ class TestNormalizePixelCoordinates(BaseTester):
def test_tensor_bhw2(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(
+ dtype=dtype
+ )
- expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(
+ expected = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(
dtype=dtype
)
@@ -773,10 +775,12 @@ class TestNormalizePixelCoordinates(BaseTester):
def test_list(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(
+ dtype=dtype
+ )
grid = grid.contiguous().view(-1, 2)
- expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(
+ expected = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(
dtype=dtype
)
expected = expected.contiguous().view(-1, 2)
@@ -793,7 +797,9 @@ class TestNormalizePixelCoordinates(BaseTester):
op_optimized = torch_optimizer(op)
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(
+ dtype=dtype
+ )
actual = op_optimized(grid, height, width)
expected = op(grid, height, width)
@@ -804,9 +810,11 @@ class TestNormalizePixelCoordinates(BaseTester):
class TestDenormalizePixelCoordinates(BaseTester):
def test_tensor_bhw2(self, device, dtype):
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(
+ dtype=dtype
+ )
- expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(
+ expected = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(
dtype=dtype
)
@@ -816,10 +824,12 @@ class TestDenormalizePixelCoordinates(BaseTester):
def test_list(self, device, dtype):
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(
+ dtype=dtype
+ )
grid = grid.contiguous().view(-1, 2)
- expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(
+ expected = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(
dtype=dtype
)
expected = expected.contiguous().view(-1, 2)
@@ -836,7 +846,9 @@ class TestDenormalizePixelCoordinates(BaseTester):
op_optimized = torch_optimizer(op)
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(
+ dtype=dtype
+ )
actual = op_optimized(grid, height, width)
expected = op(grid, height, width)
diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.py
index c97195170..d936c48fe 100644
--- a/tests/geometry/test_depth.py
+++ b/tests/geometry/test_depth.py
@@ -138,7 +138,7 @@ class TestDepthTo3d(BaseTester):
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)
+ points2d_expected = kornia.geometry.create_meshgrid(4, 3, False, device=device).to(dtype=dtype)
self.assert_close(points2d, points2d_expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
diff --git a/tests/utils/test_grid.py b/tests/geometry/test_grid.py
similarity index 85%
rename from tests/utils/test_grid.py
rename to tests/geometry/test_grid.py
index ff1146088..fb1ad8661 100644
--- a/tests/utils/test_grid.py
+++ b/tests/geometry/test_grid.py
@@ -28,7 +28,7 @@ def test_create_meshgrid(device, dtype):
normalized_coordinates = False
# create the meshgrid and verify shape
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates, device=device, dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates, device=device, dtype=dtype)
assert grid.device == device
assert grid.dtype == dtype
@@ -47,13 +47,13 @@ def test_normalize_pixel_grid(device, dtype):
height, width = 2, 4
# create points grid
- grid_norm = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device, dtype=dtype)
+ grid_norm = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device, dtype=dtype)
assert grid_norm.device == device
assert grid_norm.dtype == dtype
grid_norm = torch.unsqueeze(grid_norm, dim=0)
- grid_pix = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)
+ grid_pix = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)
assert grid_pix.device == device
assert grid_pix.dtype == dtype
@@ -76,7 +76,7 @@ def test_create_meshgrid3d(device, dtype):
normalized_coordinates = False
# create the meshgrid and verify shape
- grid = kornia.utils.create_meshgrid3d(depth, height, width, normalized_coordinates, device=device, dtype=dtype)
+ grid = kornia.geometry.create_meshgrid3d(depth, height, width, normalized_coordinates, device=device, dtype=dtype)
assert grid.device == device
assert grid.dtype == dtype
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index 979a0a018..90cf53626 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -21,6 +21,7 @@ import pytest
import torch
import kornia
+from kornia.core._compat import torch_version_le
from kornia.geometry.homography import (
find_homography_dlt,
find_homography_dlt_iterated,
@@ -31,7 +32,6 @@ from kornia.geometry.homography import (
sample_is_valid_for_homography,
symmetric_transfer_error,
)
-from kornia.utils._compat import torch_version_le
from testing.base import BaseTester
from testing.geometry.create import create_random_homography
@@ -218,7 +218,7 @@ class TestFindHomographyDLT(BaseTester):
def test_clean_points_svd(self, batch_size, device, dtype):
# generate input data
points_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)
- H = kornia.eye_like(3, points_src)
+ H = kornia.core.ops.eye_like(3, points_src)
H = H * 0.3 * torch.rand_like(H)
H = H / H[:, 2:3, 2:3]
@@ -238,7 +238,7 @@ class TestFindHomographyDLT(BaseTester):
def test_clean_points_lu(self, batch_size, device, dtype):
# generate input data
points_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)
- H = kornia.eye_like(3, points_src)
+ H = kornia.core.ops.eye_like(3, points_src)
H = H * 0.3 * torch.rand_like(H)
H = H / H[:, 2:3, 2:3]
@@ -352,7 +352,7 @@ class TestFindHomographyFromLinesDLT(BaseTester):
points_src_st = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)
points_src_end = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)
- H = kornia.eye_like(3, points_src_st)
+ H = kornia.core.ops.eye_like(3, points_src_st)
H = H * 0.3 * torch.rand_like(H)
H = H / H[:, 2:3, 2:3]
points_dst_st = kornia.geometry.transform_points(H, points_src_st)
@@ -377,7 +377,7 @@ class TestFindHomographyFromLinesDLT(BaseTester):
points_src_st = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)
points_src_end = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)
- H = kornia.eye_like(3, points_src_st)
+ H = kornia.core.ops.eye_like(3, points_src_st)
H = H * 0.3 * torch.rand_like(H)
H = H / H[:, 2:3, 2:3]
points_dst_st = kornia.geometry.transform_points(H, points_src_st)
@@ -434,7 +434,7 @@ class TestFindHomographyDLTIter(BaseTester):
def test_clean_points(self, batch_size, device, dtype):
# generate input data
points_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)
- H = kornia.eye_like(3, points_src)
+ H = kornia.core.ops.eye_like(3, points_src)
H = H * 0.3 * torch.rand_like(H)
H = H / H[:, 2:3, 2:3]
@@ -459,7 +459,7 @@ class TestFindHomographyDLTIter(BaseTester):
def test_dirty_points_and_gradcheck(self, batch_size, device, dtype):
# generate input data
points_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)
- H = kornia.eye_like(3, points_src)
+ H = kornia.core.ops.eye_like(3, points_src)
H = H * (1 + torch.rand_like(H))
H = H / H[:, 2:3, 2:3]
diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.py
index bc9a7f591..096039ada 100644
--- a/tests/geometry/test_linalg.py
+++ b/tests/geometry/test_linalg.py
@@ -59,7 +59,7 @@ class TestTransformPoints(BaseTester):
def test_dynamo(self, device, dtype, torch_optimizer):
points = torch.ones(1, 2, 2, device=device, dtype=dtype)
- transform = kornia.eye_like(3, points)
+ transform = kornia.core.ops.eye_like(3, points)
op = kornia.geometry.transform_points
op_script = torch_optimizer(op)
actual = op_script(transform, points)
diff --git a/tests/utils/test_pointcloud_io.py b/tests/geometry/test_pointcloud_io.py
similarity index 79%
rename from tests/utils/test_pointcloud_io.py
rename to tests/geometry/test_pointcloud_io.py
index ba9df360f..6fb02a9a9 100644
--- a/tests/utils/test_pointcloud_io.py
+++ b/tests/geometry/test_pointcloud_io.py
@@ -32,9 +32,9 @@ class TestSaveLoadPointCloud:
xyz_save = torch.rand(height, width, 3)
filename = "pointcloud.ply"
- kornia.utils.save_pointcloud_ply(filename, xyz_save)
+ kornia.geometry.save_pointcloud_ply(filename, xyz_save)
- xyz_load = kornia.utils.load_pointcloud_ply(filename)
+ xyz_load = kornia.geometry.load_pointcloud_ply(filename)
assert_close(xyz_save.reshape(-1, 3), xyz_load)
if os.path.exists(filename):
@@ -50,11 +50,11 @@ class TestSaveLoadPointCloud:
xyz_save[1, 0, :-1] = float("inf") # partial inf β†’ kept
filename = "pointcloud.ply"
- kornia.utils.save_pointcloud_ply(filename, xyz_save)
+ kornia.geometry.save_pointcloud_ply(filename, xyz_save)
xyz_correct = xyz_save.reshape(-1, 3)[1:, :]
- xyz_load = kornia.utils.load_pointcloud_ply(filename)
+ xyz_load = kornia.geometry.load_pointcloud_ply(filename)
assert_close(xyz_correct, xyz_load)
if os.path.exists(filename):
@@ -63,29 +63,29 @@ class TestSaveLoadPointCloud:
def test_invalid_filename_type(self):
xyz_save = torch.rand(10, 3)
with pytest.raises(TypeError):
- kornia.utils.save_pointcloud_ply(1234, xyz_save)
+ kornia.geometry.save_pointcloud_ply(1234, xyz_save)
def test_invalid_filename_extension(self):
xyz_save = torch.rand(10, 3)
with pytest.raises(TypeError):
- kornia.utils.save_pointcloud_ply("pointcloud.txt", xyz_save)
+ kornia.geometry.save_pointcloud_ply("pointcloud.txt", xyz_save)
def test_invalid_pointcloud_type(self):
with pytest.raises(TypeError):
- kornia.utils.save_pointcloud_ply("pointcloud.ply", [[1, 2, 3]])
+ kornia.geometry.save_pointcloud_ply("pointcloud.ply", [[1, 2, 3]])
def test_invalid_pointcloud_shape(self):
xyz_save = torch.rand(10, 4)
with pytest.raises(TypeError):
- kornia.utils.save_pointcloud_ply("pointcloud.ply", xyz_save)
+ kornia.geometry.save_pointcloud_ply("pointcloud.ply", xyz_save)
def test_save_pointcloud_with_nan(self):
xyz_save = torch.rand(5, 3)
xyz_save[0, :] = float("nan")
xyz_save[1, 0] = float("nan")
filename = "pointcloud_nan.ply"
- kornia.utils.save_pointcloud_ply(filename, xyz_save)
- xyz_load = kornia.utils.load_pointcloud_ply(filename)
+ kornia.geometry.save_pointcloud_ply(filename, xyz_save)
+ xyz_load = kornia.geometry.load_pointcloud_ply(filename)
expected = xyz_save[torch.isfinite(xyz_save).any(dim=1)]
# Use numpy to compare with NaNs considered equal
diff --git a/tests/geometry/transform/test_crop3d.py b/tests/geometry/transform/test_crop3d.py
index 5b4d611f6..7bb2a6488 100644
--- a/tests/geometry/transform/test_crop3d.py
+++ b/tests/geometry/transform/test_crop3d.py
@@ -19,7 +19,7 @@ import pytest
import torch
import kornia
-from kornia.utils._compat import torch_version
+from kornia.core._compat import torch_version
from testing.base import BaseTester
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index 19a6cf7a0..fbd7e7ced 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -19,8 +19,8 @@ import pytest
import torch
import kornia
-from kornia.utils.helpers import _torch_inverse_cast
-from kornia.utils.misc import eye_like
+from kornia.core.ops import eye_like
+from kornia.core.utils import _torch_inverse_cast
from testing.base import BaseTester
from testing.error import compute_patch_abs_error
@@ -151,7 +151,7 @@ class TestHomographyWarper(BaseTester):
def test_warp_grid_translation(self, shape, offset, device, dtype):
# create input data
height, width = shape
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)
dst_homo_src = eye_like(3, grid)
dst_homo_src[..., 0, 2] = offset # apply offset in x
flow = kornia.geometry.transform.warp_grid(grid, dst_homo_src)
@@ -282,7 +282,7 @@ class TestHomographyWarper(BaseTester):
if (
device == torch.device("cpu")
and batch_size != 1
- and kornia.utils._compat.torch_version() in {"2.3.0", "2.3.1"}
+ and kornia.core._compat.torch_version() in {"2.3.0", "2.3.1"}
):
pytest.skip("Failing to compile batched inputs see pytorch/pytorch#126617")
@@ -446,7 +446,7 @@ class TestHomographyWarper3D(BaseTester):
def test_warp_grid_translation(self, shape, offset, device, dtype):
# create input data
depth, height, width = shape
- grid = kornia.utils.create_meshgrid3d(
+ grid = kornia.geometry.create_meshgrid3d(
depth, height, width, normalized_coordinates=False, dtype=dtype, device=device
)
dst_homo_src = eye_like(4, grid)
diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.py
index dbf157685..c05044933 100644
--- a/tests/geometry/transform/test_image_registrator.py
+++ b/tests/geometry/transform/test_image_registrator.py
@@ -21,10 +21,10 @@ import pytest
import torch
import kornia
+from kornia.core._compat import torch_version
from kornia.geometry import transform_points
from kornia.geometry.conversions import denormalize_homography
from kornia.geometry.transform import ImageRegistrator
-from kornia.utils._compat import torch_version
from testing.base import BaseTester
from testing.casts import dict_to
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index c1b45266f..6a593128b 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -21,8 +21,8 @@ import pytest
import torch
import kornia
-from kornia.utils._compat import torch_version, torch_version_lt
-from kornia.utils.helpers import _torch_inverse_cast
+from kornia.core._compat import torch_version, torch_version_lt
+from kornia.core.utils import _torch_inverse_cast
from testing.base import BaseTester
@@ -332,7 +332,7 @@ class TestWarpPerspective(BaseTester):
def test_smoke(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 4
img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- H_ab = kornia.eye_like(3, img_b)
+ H_ab = kornia.core.ops.eye_like(3, img_b)
img_a = kornia.geometry.warp_perspective(img_b, H_ab, (height, width))
self.assert_close(img_b, img_a)
@@ -342,7 +342,7 @@ class TestWarpPerspective(BaseTester):
batch_size, channels, height, width = batch_shape
h_out, w_out = out_shape
img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- H_ab = kornia.eye_like(3, img_b)
+ H_ab = kornia.core.ops.eye_like(3, img_b)
img_a = kornia.geometry.warp_perspective(img_b, H_ab, (h_out, w_out))
assert img_a.shape == (batch_size, channels, h_out, w_out)
@@ -370,7 +370,7 @@ class TestWarpPerspective(BaseTester):
h, w = 3, 4
img_b = torch.arange(float(h * w), device=device, dtype=dtype).view(1, 1, h, w)
- homo_ab = kornia.eye_like(3, img_b)
+ homo_ab = kornia.core.ops.eye_like(3, img_b)
homo_ab[..., :2, -1] += offset
expected = torch.zeros_like(img_b)
@@ -385,7 +385,7 @@ class TestWarpPerspective(BaseTester):
h, w = 3, 4
img_b = torch.arange(float(h * w), device=device, dtype=dtype).view(1, 1, h, w)
- homo_ab = kornia.eye_like(3, img_b)
+ homo_ab = kornia.core.ops.eye_like(3, img_b)
homo_ab[..., :2, -1] += offset
expected = torch.zeros_like(img_b)
@@ -495,7 +495,7 @@ class TestWarpPerspective(BaseTester):
if dtype == torch.float64 and torch_version() in {"2.0.0", "2.0.1"} and sys.platform == "linux":
pytest.xfail("Failing on CI on ubuntu with torch 2.0.0 for float64")
img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- H_ab = kornia.eye_like(3, img)
+ H_ab = kornia.core.ops.eye_like(3, img)
args = (img, H_ab, (4, 5))
op = kornia.geometry.warp_perspective
op_optimized = torch_optimizer(op)
@@ -504,7 +504,7 @@ class TestWarpPerspective(BaseTester):
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 3, 4
img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
- H_ab = kornia.eye_like(3, img_b)
+ H_ab = kornia.core.ops.eye_like(3, img_b)
# TODO(dmytro/edgar): firgure out why gradient don't propagate for the tranaform
self.gradcheck(
kornia.geometry.warp_perspective, (img_b, H_ab, (height, width)), requires_grad=(True, False, False)
@@ -515,7 +515,7 @@ class TestWarpPerspective(BaseTester):
h, w = 3, 4
img_b = torch.arange(float(3 * h * w), device=device, dtype=dtype).view(1, 3, h, w)
- homo_ab = kornia.eye_like(3, img_b)
+ homo_ab = kornia.core.ops.eye_like(3, img_b)
homo_ab[..., :2, -1] += offset
# normally fill_value will also be converted to the right device and type in warp_perspective
@@ -532,7 +532,7 @@ class TestRemap(BaseTester):
def test_smoke(self, device, dtype):
height, width = 3, 4
input_org = torch.ones(1, 1, height, width, device=device, dtype=dtype)
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)
input_warped = kornia.geometry.remap(
input_org, grid[..., 0], grid[..., 1], normalized_coordinates=False, align_corners=True
)
@@ -540,7 +540,7 @@ class TestRemap(BaseTester):
def test_different_size(self, device, dtype):
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(height, width, device=device, dtype=dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, device=device, dtype=dtype)
img = torch.rand(1, 2, 6, 5, device=device, dtype=dtype)
img_warped = kornia.geometry.remap(img, grid[..., 0], grid[..., 1])
@@ -555,7 +555,7 @@ class TestRemap(BaseTester):
[[[[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]], device=device, dtype=dtype
)
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid += 1.0 # apply shift in both x/y direction
input_warped = kornia.geometry.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
@@ -577,7 +577,7 @@ class TestRemap(BaseTester):
)
# generate a batch of grids
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid = grid.repeat(2, 1, 1, 1)
grid[0, ..., 0] += 1.0 # apply shift in the x direction
grid[1, ..., 1] += 1.0 # apply shift in the y direction
@@ -594,7 +594,7 @@ class TestRemap(BaseTester):
[[[[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]], device=device, dtype=dtype
).repeat(2, 1, 1, 1)
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid += 1.0 # apply shift in both x/y direction
input_warped = kornia.geometry.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
@@ -610,7 +610,7 @@ class TestRemap(BaseTester):
[[[[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]]], device=device, dtype=dtype
).repeat(2, 1, 1, 1)
- grid = kornia.utils.create_meshgrid(
+ grid = kornia.geometry.create_meshgrid(
height, width, normalized_coordinates=normalized_coordinates, device=device
).to(dtype)
@@ -624,7 +624,7 @@ class TestRemap(BaseTester):
batch_size, channels, height, width = 1, 2, 3, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
- grid = kornia.utils.create_meshgrid(
+ grid = kornia.geometry.create_meshgrid(
height, width, normalized_coordinates=False, device=device, dtype=torch.float64
)
@@ -640,7 +640,7 @@ class TestRemap(BaseTester):
batch_size, channels, height, width = 1, 1, 3, 4
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid += 1.0 # apply some shift
op = kornia.geometry.remap
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index 51c66703c..c8521fb96 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -20,7 +20,7 @@ import torch
import kornia
import kornia.geometry.transform as proj
-from kornia.utils.helpers import _torch_inverse_cast
+from kornia.core.utils import _torch_inverse_cast
from testing.base import BaseTester
diff --git a/tests/utils/test_draw.py b/tests/image/test_draw.py
similarity index 99%
rename from tests/utils/test_draw.py
rename to tests/image/test_draw.py
index c8c45a5e4..26b9a5bd5 100644
--- a/tests/utils/test_draw.py
+++ b/tests/image/test_draw.py
@@ -20,8 +20,9 @@ import math
import pytest
import torch
-from kornia.utils import create_meshgrid, draw_convex_polygon, draw_rectangle
-from kornia.utils.draw import draw_line, draw_point2d
+from kornia.geometry import create_meshgrid
+from kornia.image import draw_convex_polygon, draw_rectangle
+from kornia.image.draw import draw_line, draw_point2d
from testing.base import assert_close
diff --git a/tests/image/test_image.py b/tests/image/test_image.py
index 4ea324fe7..7e5123b78 100644
--- a/tests/image/test_image.py
+++ b/tests/image/test_image.py
@@ -21,9 +21,9 @@ import numpy as np
import pytest
import torch
+from kornia.core._compat import torch_version_le
from kornia.image.base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat
from kornia.image.image import Image
-from kornia.utils._compat import torch_version_le
from testing.base import BaseTester
diff --git a/tests/utils/test_image_utils.py b/tests/image/test_image_utils.py
similarity index 85%
rename from tests/utils/test_image_utils.py
rename to tests/image/test_image_utils.py
index 3ccad26b3..f61b71996 100644
--- a/tests/utils/test_image_utils.py
+++ b/tests/image/test_image_utils.py
@@ -31,7 +31,7 @@ from testing.base import assert_close
)
def test_image_to_tensor_keep_dtype(input_dtype, expected_dtype):
image = np.ones((1, 3, 4, 5), dtype=input_dtype)
- tensor = kornia.image_to_tensor(image)
+ tensor = kornia.image.image_to_tensor(image)
assert tensor.dtype == expected_dtype
@@ -40,15 +40,15 @@ 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.utils.image_list_to_tensor([])
+ kornia.image.image_list_to_tensor([])
return
for _ in range(num_of_images):
images.append(np.ones(shape=image_shape))
if len(image_shape) != 3:
with pytest.raises(ValueError):
- kornia.utils.image_list_to_tensor(images)
+ kornia.image.image_list_to_tensor(images)
return
- tensor = kornia.utils.image_list_to_tensor(images)
+ tensor = kornia.image.image_list_to_tensor(images)
assert tensor.shape == (num_of_images, image_shape[-1], image_shape[-3], image_shape[-2])
@@ -65,7 +65,7 @@ def test_list_of_images_to_tensor(num_of_images, image_shape):
)
def test_tensor_to_image(device, input_shape, expected):
tensor = torch.ones(input_shape).to(device)
- image = kornia.utils.tensor_to_image(tensor)
+ image = kornia.image.tensor_to_image(tensor)
assert image.shape == expected
assert isinstance(image, np.ndarray)
@@ -83,7 +83,7 @@ def test_tensor_to_image(device, input_shape, expected):
)
def test_tensor_to_image_keepdim(device, input_shape, expected):
tensor = torch.ones(input_shape).to(device)
- image = kornia.utils.tensor_to_image(tensor, keepdim=True)
+ image = kornia.image.tensor_to_image(tensor, keepdim=True)
assert image.shape == expected
assert isinstance(image, np.ndarray)
@@ -101,11 +101,11 @@ def test_tensor_to_image_keepdim(device, input_shape, expected):
)
def test_image_to_tensor(input_shape, expected):
image = np.ones(input_shape)
- tensor = kornia.utils.image_to_tensor(image, keepdim=False)
+ tensor = kornia.image.image_to_tensor(image, keepdim=False)
assert tensor.shape == expected
assert isinstance(tensor, torch.Tensor)
- to_tensor = kornia.utils.ImageToTensor(keepdim=False)
+ to_tensor = kornia.image.ImageToTensor(keepdim=False)
assert_close(tensor, to_tensor(image))
@@ -122,7 +122,7 @@ def test_image_to_tensor(input_shape, expected):
)
def test_image_to_tensor_keepdim(input_shape, expected):
image = np.ones(input_shape)
- tensor = kornia.utils.image_to_tensor(image, keepdim=True)
+ tensor = kornia.image.image_to_tensor(image, keepdim=True)
assert tensor.shape == expected
assert isinstance(tensor, torch.Tensor)
@@ -130,8 +130,8 @@ def test_image_to_tensor_keepdim(input_shape, expected):
def test_tensor_to_image_contiguous(device, dtype):
tensor = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
- image = kornia.utils.tensor_to_image(tensor)
+ image = kornia.image.tensor_to_image(tensor)
assert not image.flags["C_CONTIGUOUS"]
- image = kornia.utils.tensor_to_image(tensor, force_contiguous=True)
+ image = kornia.image.tensor_to_image(tensor, force_contiguous=True)
assert image.flags["C_CONTIGUOUS"]
diff --git a/tests/utils/test_print.py b/tests/image/test_print.py
similarity index 97%
rename from tests/utils/test_print.py
rename to tests/image/test_print.py
index b20000382..8edefed79 100644
--- a/tests/utils/test_print.py
+++ b/tests/image/test_print.py
@@ -18,7 +18,7 @@
import pytest
import torch
-from kornia.utils import image_to_string, print_image
+from kornia.image import image_to_string, print_image
class TestImageToString:
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index 007dbbefa..a2800e455 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -24,8 +24,8 @@ import pytest
import requests
import torch
+from kornia.core._compat import torch_version_ge
from kornia.io import ImageLoadType, load_image, write_image
-from kornia.utils._compat import torch_version_ge
try:
import kornia_rs
diff --git a/tests/utils/test_one_hot.py b/tests/losses/test_one_hot.py
similarity index 70%
rename from tests/utils/test_one_hot.py
rename to tests/losses/test_one_hot.py
index 3a1d640d2..d58fd3e20 100644
--- a/tests/utils/test_one_hot.py
+++ b/tests/losses/test_one_hot.py
@@ -17,7 +17,7 @@
import torch
-import kornia
+from kornia.losses.one_hot import one_hot
from testing.base import assert_close
@@ -32,9 +32,9 @@ class TestOneHot:
labels[1, 1, 0] = 3
# convert labels to one hot tensor
- one_hot = kornia.utils.one_hot(labels, num_classes, device, dtype)
+ one_hot_tensor = one_hot(labels, num_classes, device, dtype)
- assert_close(one_hot[0, labels[0, 0, 0], 0, 0].item(), 1.0)
- assert_close(one_hot[0, labels[0, 1, 0], 1, 0].item(), 1.0)
- assert_close(one_hot[1, labels[1, 0, 0], 0, 0].item(), 1.0)
- assert_close(one_hot[1, labels[1, 1, 0], 1, 0].item(), 1.0)
+ assert_close(one_hot_tensor[0, labels[0, 0, 0], 0, 0].item(), 1.0)
+ assert_close(one_hot_tensor[0, labels[0, 1, 0], 1, 0].item(), 1.0)
+ assert_close(one_hot_tensor[1, labels[1, 0, 0], 0, 0].item(), 1.0)
+ assert_close(one_hot_tensor[1, labels[1, 1, 0], 1, 0].item(), 1.0)
diff --git a/tests/losses/test_total_variation.py b/tests/losses/test_total_variation.py
index e28ccc4a7..5cc3200cf 100644
--- a/tests/losses/test_total_variation.py
+++ b/tests/losses/test_total_variation.py
@@ -19,7 +19,6 @@ import pytest
import torch
import kornia
-from kornia.utils import torch_meshgrid
from testing.base import BaseTester
@@ -138,7 +137,7 @@ class TestTotalVariation(BaseTester):
@pytest.mark.parametrize("reduction, expected", [("sum", torch.tensor(20)), ("mean", torch.tensor(1))])
def test_tv_reduction(self, device, dtype, reduction, expected):
- pred, _ = torch_meshgrid([torch.arange(5), torch.arange(5)], "ij")
+ pred, _ = torch.meshgrid([torch.arange(5), torch.arange(5)], indexing="ij")
pred = pred.to(device, dtype)
actual = kornia.losses.total_variation(pred, reduction=reduction)
self.assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
diff --git a/tests/models/test_efficient_vit.py b/tests/models/test_efficient_vit.py
index d156b9edc..a357a4301 100644
--- a/tests/models/test_efficient_vit.py
+++ b/tests/models/test_efficient_vit.py
@@ -19,9 +19,9 @@
import pytest
import torch
+from kornia.core._compat import torch_version_lt
from kornia.models.efficient_vit import EfficientViT, EfficientViTConfig
from kornia.models.efficient_vit import backbone as vit
-from kornia.utils._compat import torch_version_lt
class TestEfficientViT:
diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.py
index 4c0caf9ed..76f1402f9 100644
--- a/tests/models/test_object_detector.py
+++ b/tests/models/test_object_detector.py
@@ -22,8 +22,8 @@ import pytest
import torch
import kornia
+from kornia.core._compat import torch_version_lt
from kornia.models.rt_detr import RTDETR, DETRPostProcessor, RTDETRConfig
-from kornia.utils._compat import torch_version_lt
from testing.base import BaseTester
diff --git a/tests/models/test_prompter.py b/tests/models/test_prompter.py
index 5a398a14f..ac6ec4abd 100644
--- a/tests/models/test_prompter.py
+++ b/tests/models/test_prompter.py
@@ -19,8 +19,8 @@ import pytest
import torch
from kornia.contrib.visual_prompter import VisualPrompter
+from kornia.core._compat import torch_version
from kornia.models.sam import SamConfig
-from kornia.utils._compat import torch_version
from testing.base import BaseTester
diff --git a/tests/tracking/test_planar_tracking.py b/tests/tracking/test_planar_tracking.py
index 6de49aa44..75e6dc2c6 100644
--- a/tests/tracking/test_planar_tracking.py
+++ b/tests/tracking/test_planar_tracking.py
@@ -18,10 +18,10 @@
import pytest
import torch
+from kornia.core._compat import torch_version_le
from kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, SIFTFeature
from kornia.geometry import rescale, transform_points
from kornia.tracking import HomographyTracker
-from kornia.utils._compat import torch_version_le
from testing.base import assert_close
diff --git a/tests/utils/test_memory.py b/tests/utils/test_memory.py
deleted file mode 100644
index 78bfc0997..000000000
--- a/tests/utils/test_memory.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import torch
-
-import kornia
-
-from testing.base import BaseTester
-
-
-class TestBatchedForward(BaseTester):
- def test_runbatch(self, device):
- patches = torch.rand(34, 1, 32, 32)
- sift = kornia.feature.SIFTDescriptor(32)
- desc_batched = kornia.utils.memory.batched_forward(sift, patches, device, 32)
- desc = sift(patches)
- assert torch.allclose(desc, desc_batched)
-
- def test_runone(self, device):
- patches = torch.rand(16, 1, 32, 32)
- sift = kornia.feature.SIFTDescriptor(32)
- desc_batched = kornia.utils.memory.batched_forward(sift, patches, device, 32)
- desc = sift(patches)
- assert torch.allclose(desc, desc_batched)
-
- def test_gradcheck(self, device):
- batch_size, channels, height, width = 3, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
- self.gradcheck(
- kornia.utils.memory.batched_forward, (kornia.feature.BlobHessian(), img, device, 2), nondet_tol=1e-4
- )
diff --git a/tests/utils/test_parametrized_tester_poc.py b/tests/utils/test_parametrized_tester_poc.py
deleted file mode 100644
index e67ce6cd9..000000000
--- a/tests/utils/test_parametrized_tester_poc.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""Proof of Concept: Parametrized test automation using the new decorator.
-
-This demonstrates the usage of the @parametrized_test decorator on existing
-test classes to automatically generate test_smoke, test_cardinality, and
-test_gradcheck methods parametrized across devices and dtypes.
-"""
-
-import torch
-
-from kornia.utils.misc import differentiable_clipping, differentiable_polynomial_floor
-
-from testing.base import BaseTester
-from testing.parametrized_tester import parametrized_test
-
-
-@parametrized_test(
- smoke_inputs=lambda device, dtype: (torch.tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=dtype),),
- cardinality_tests=[
- {
- "inputs": lambda device, dtype: (torch.tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=dtype),),
- "expected_shape": torch.Size([4]),
- }
- ],
- gradcheck_inputs=lambda device: (torch.tensor([1.0, 6.0, 11.0, 12.0], device=device, dtype=torch.float64),),
-)
-class TestDifferentiableClippingAutomated(BaseTester):
- """Demonstration of automated tests for differentiable_clipping function.
-
- The @parametrized_test decorator automatically generates:
- - test_smoke: Runs the function with valid inputs
- - test_cardinality: Verifies output shapes
- - test_gradcheck: Validates gradient computation
-
- All tests are parametrized across devices and dtypes automatically.
- """
-
- def setup_method(self) -> None:
- """Set up test fixtures."""
- self.func = lambda x: differentiable_clipping(x, min_val=5.0, max_val=10.0)
-
-
-@parametrized_test(
- smoke_inputs=lambda device, dtype: (torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=dtype),),
- cardinality_tests=[
- {
- "inputs": lambda device, dtype: (torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=dtype),),
- "expected_shape": torch.Size([4]),
- }
- ],
- gradcheck_inputs=lambda device: (torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=torch.float64),),
-)
-class TestDifferentiablePolynomialFloorAutomated(BaseTester):
- """Demonstration of automated tests for differentiable_polynomial_floor function.
-
- Uses the same @parametrized_test decorator pattern as TestDifferentiableClippingAutomated.
- """
-
- def setup_method(self) -> None:
- """Set up test fixtures."""
- self.func = differentiable_polynomial_floor