π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Init Kornia.onnx module (#3013)
Jian Shi0b9a2ed82e4d
diff --git a/README.md b/README.mdindex 3150bab19..4234aa9e3 100644--- a/README.md+++ b/README.md@@ -112,6 +112,9 @@ Kornia is an open-source project that is developed and maintained by volunteers.Kornia is not just another computer vision library β it's your gateway to effortless Computer Vision and AI.+<details>+<summary>Get started with Kornia image transformation and augmentation!</summary>+```pythonimport numpy as npimport kornia_rs as kr@@ -144,6 +147,31 @@ dslv_op(img, step_number=500)dslv_op.save("Kornia-enhanced.jpg")```+</details>++<details>+<summary>Find out Kornia ONNX models with ONNXSequential!</summary>++```python+import numpy as np+from kornia.onnx import ONNXSequential+# Chain ONNX models from HuggingFace repo and your own local model together+onnx_seq = ONNXSequential(+ "hf://operators/kornia.geometry.transform.flips.Hflip",+ "hf://models/kornia.models.detection.rtdetr_r18vd_640x640", # Or you may use "YOUR_OWN_MODEL.onnx"+)+# Prepare some input data+input_data = np.random.randn(1, 3, 384, 512).astype(np.float32)+# Perform inference+outputs = onnx_seq(input_data)+# Print the model outputs+print(outputs)++# Export a new ONNX model that chains up all three models together!+onnx_seq.export("chained_model.onnx")+```+</details>+## Call For ContributorsAre you passionate about computer vision, AI, and open-source development? Join us in shaping the future of Kornia! We are actively seeking contributors to help expand and enhance our library, making it even more powerful, accessible, and versatile. Whether you're an experienced developer or just starting, there's a place for you in our community.diff --git a/docs/source/conf.py b/docs/source/conf.pyindex 910818fb7..828b6a365 100644--- a/docs/source/conf.py+++ b/docs/source/conf.py@@ -1,9 +1,13 @@+import builtinsimport importlib.utilimport inspectimport osimport sysfrom datetime import datetime, timezone+# To add an evnironment variable+builtins.__sphinx_build__ = True+# readthedocs generated the whole documentation in an isolated environment# by cloning the git repo. Thus, any on-the-fly operation will not effect# on the resulting documentation. We therefore need to import and run the@@ -266,3 +270,6 @@ intersphinx_mapping = {"numpy": ("http://numpy.org/doc/stable/", None),"torch": ("http://pytorch.org/docs/stable/", None),}++# mock these modules and won't try to actually import them+autodoc_mock_imports = ["boxmot", "segmentation_models_pytorch"]diff --git a/docs/source/index.rst b/docs/source/index.rstindex 5aea3bd6f..a1e87c1b6 100644--- a/docs/source/index.rst+++ b/docs/source/index.rst@@ -15,6 +15,35 @@ within the context of an Open Source community.Ready to use with state-of-the art Deep Learning models:+DexiNed edge detection model.++.. code-block:: python++ image = kornia.utils.sample.get_sample_images()[0][None]+ model = DexiNedBuilder.build()+ model.save(image)++RTDETRDetector for object detection.++.. code-block:: python++ image = kornia.utils.sample.get_sample_images()[0][None]+ model = RTDETRDetectorBuilder.build()+ model.save(image)++BoxMotTracker for object tracking.++.. code-block:: python++ import kornia+ image = kornia.utils.sample.get_sample_images()[0][None]+ model = BoxMotTracker()+ for i in range(4):+ model.update(image)+ model.save(image)++Vision Transformer for image classification.+.. code:: python>>> import torch.nn as nn@@ -66,9 +95,11 @@ Join the communityioimagelosses+ modelsmetricsmorphologynerf+ onnxtrackingtestingutilsdiff --git a/docs/source/models.rst b/docs/source/models.rstnew file mode 100644index 000000000..91df12a09--- /dev/null+++ b/docs/source/models.rst@@ -0,0 +1,135 @@+Models Overview+===============++This section covers several of Kornia's built-in models for key computer vision tasks. Each model is documented with its respective API and example usage.++.. _RTDETRDetectorBuilder:++RTDETRDetectorBuilder+---------------------++The `RTDETRDetectorBuilder` class is a builder for constructing a detection model based on the RT-DETR architecture, which is designed for real-time object detection. It is capable of detecting multiple objects within an image and provides efficient inference suitable for real-world applications.++**Key Methods:**++- `build`: Constructs and returns an instance of the RTDETR detection model.+- `save`: Saves the processed image or results after applying the detection model.++.. autoclass:: kornia.models.detection.rtdetr.RTDETRDetectorBuilder+ :members:+ :undoc-members:+ :show-inheritance:++ .. rubric:: Example++ The following code demonstrates how to use `RTDETRDetectorBuilder` to detect objects in an image:++ .. code-block:: python++ import kornia+ image = kornia.utils.sample.get_sample_images()[0][None]+ model = kornia.models.detection.rtdetr.RTDETRDetectorBuilder.build()+ model.save(image)++.. _DexiNedBuilder:++DexiNedBuilder+--------------++The `DexiNedBuilder` class implements a state-of-the-art edge detection model based on DexiNed, which excels at detecting fine-grained edges in images. This model is well-suited for tasks like medical imaging, object contour detection, and more.++**Key Methods:**++- `build`: Builds and returns an instance of the DexiNed edge detection model.+- `save`: Saves the detected edges for further processing or visualization.++.. autoclass:: kornia.models.edge_detection.dexined.DexiNedBuilder+ :members:+ :undoc-members:+ :show-inheritance:++ .. rubric:: Example++ The following code shows how to use the `DexiNedBuilder` to detect edges in an image:++ .. code-block:: python++ import kornia+ image = kornia.utils.sample.get_sample_images()[0][None]+ model = kornia.models.edge_detection.dexined.DexiNedBuilder.build()+ model.save(image)++.. _SegmentationModels:++SegmentationModelsBuilder+-------------------------++The `SegmentationModelsBuilder` class offers a flexible API for implementing and running various segmentation models. It supports a variety of architectures such as UNet, FPN, and others, making it highly adaptable for tasks like semantic segmentation, instance segmentation, and more.++**Key Methods:**++- `__init__`: Initializes a segmentation model based on the chosen architecture (e.g., UNet, DeepLabV3, etc.).+- `forward`: Runs inference on an input tensor and returns segmented output.++**Parameters:**++- `model_name`: (str) Name of the segmentation architecture to use, e.g., `"Unet"`, `"DeepLabV3"`.+- `classes`: (int) The number of output classes for segmentation.++.. autoclass:: kornia.models.segmentation.segmentation_models.SegmentationModelsBuilder+ :members:+ :undoc-members:+ :show-inheritance:++ .. rubric:: Example++ Here's an example of how to use `SegmentationModelsBuilder` for binary segmentation:++ .. code-block:: python++ import kornia+ input_tensor = kornia.utils.sample.get_sample_images()[0][None]+ model = kornia.models.segmentation.segmentation_models.SegmentationModelsBuilder.build()+ segmented_output = model(input_tensor)+ print(segmented_output.shape)++.. _BoxMotTracker:++BoxMotTracker+-------------++The `BoxMotTracker` class is used for multi-object tracking in video streams. It is designed to track bounding boxes of objects across multiple frames, supporting various tracking algorithms for object detection and tracking continuity.++**Key Methods:**++- `__init__`: Initializes the multi-object tracker.+- `update`: Updates the tracker with a new image frame.+- `save`: Saves the tracked object data or visualization for post-processing.++**Parameters:**++- `max_lost`: (int) The maximum number of frames where an object can be lost before it is removed from the tracker.++.. autoclass:: kornia.models.tracking.boxmot_tracker.BoxMotTracker+ :members:+ :undoc-members:+ :show-inheritance:++ .. rubric:: Example++ The following example demonstrates how to track objects across multiple frames using `BoxMotTracker`:++ .. code-block:: python++ import kornia+ image = kornia.utils.sample.get_sample_images()[0][None]+ model = kornia.models.tracking.boxmot_tracker.BoxMotTracker()+ for i in range(4):+ model.update(image) # Update the tracker with new frames+ model.save(image) # Save the tracking result++---++.. note::++ This documentation provides detailed information about each model class, its methods, and usage examples. For further details on individual methods and arguments, refer to the respective code documentation.diff --git a/docs/source/onnx.rst b/docs/source/onnx.rstnew file mode 100644index 000000000..3e4d73c26--- /dev/null+++ b/docs/source/onnx.rst@@ -0,0 +1,183 @@+ONNXSequential: Chain Multiple ONNX Models with Ease+====================================================++The `ONNXSequential` class is a powerful new feature that allows users to effortlessly combine and chain multiple ONNX models together. This is especially useful when you have several pre-trained models or custom ONNX operators that you want to execute sequentially as part of a larger pipeline.++Whether you're working with models for inference, experimentation, or optimization, `ONNXSequential` makes it easier to manage, combine, and run ONNX models in a streamlined manner. It also supports flexibility in execution environments with ONNXRuntime's execution providers (CPU, CUDA, etc.).++Key Features+------------++- **Seamless Model Chaining**: Combine multiple ONNX models into a single computational graph.+- **Flexible Input/Output Mapping**: Control how the outputs of one model are passed as inputs to the next.+- **Export to ONNX**: Save the combined model into a single ONNX file for easy deployment and sharing.+- **PyTorch-like Interface**: Use the `ONNXSequential` class like a PyTorch `nn.Sequential` model, including calling it directly for inference.++Optimized Execution+-------------------+- **ONNXRuntime**: Automatically create optimized `ONNXRuntime` sessions to speed up inference.+- **Execution Providers Support**: Utilize ONNXRuntime's execution providers (e.g., `CUDAExecutionProvider`, `CPUExecutionProvider`, `TensorrtExecutionProvider`, `OpenVINOExecutionProvider`) for accelerated inference on different hardware.+- **Concurrent Sessions**: You can manage multiple inference sessions concurrently, allowing for parallel processing of multiple inputs.+- **Asynchronous API**: We offer asyncio-based execution along with the runtime's asynchronous functions to perform non-blocking inference.++Quickstart Guide+----------------++Here's how you can quickly get started with `ONNXSequential`:++1. **Install ONNX and ONNXRuntime**++ If you haven't already installed `onnx` and `onnxruntime`, you can install them using `pip`:++ .. code-block:: bash++ pip install onnx onnxruntime++2. **Combining ONNX Models**++ You can initialize the `ONNXSequential` with a list of ONNX models or file paths. Models will be automatically chained together and optimized for inference.++ .. code-block:: python++ import numpy as np+ from kornia.onnx import ONNXSequential++ # Initialize ONNXSequential with two models, loading from our only repo+ onnx_seq = ONNXSequential(+ "hf://operators/kornia.color.gray.RgbToGrayscale",+ "hf://operators/kornia.geometry.transform.affwarp.Resize_512x512"+ )++ # Prepare some input data+ input_data = np.random.randn(1, 3, 256, 512).astype(np.float32)++ # Perform inference+ outputs = onnx_seq(input_data)++ # Print the model outputs+ print(outputs)++ .. note::+ By default, we assume each ONNX model contains only one input node named "input" and one output node named "output". For complex models, you may need to pass an `io_maps` argument.++3. **Input/Output Mapping Between Models**++ When combining models, you can specify how the outputs of one model are mapped to the inputs of the next. This allows you to chain models in custom ways.++ .. code-block:: python++ io_map = [("model1_output_0", "model2_input_0"), ("model1_output_1", "model2_input_1")]+ onnx_seq = ONNXSequential("model1.onnx", "model2.onnx", io_map=io_map)++4. **Exporting the Combined Model**++ You can easily export the combined model to an ONNX file:++ .. code-block:: python++ # Export the combined model to a file+ onnx_seq.export("combined_model.onnx")++5. **Optimizing with Execution Providers**++ Leverage ONNXRuntime's execution providers for optimized inference. For example, to run the model on a GPU:++ .. code-block:: python++ # Initialize with CUDA execution provider+ onnx_seq = ONNXSequential(+ "hf://operators/kornia.geometry.transform.flips.Hflip",+ # Or you may use a local model with either a filepath "YOUR_OWN_MODEL.onnx" or a loaded ONNX model.+ "hf://models/kornia.models.detection.rtdetr_r18vd_640x640",+ providers=['CUDAExecutionProvider']+ )++ # Run inference+ outputs = onnx_seq(input_data)++Frequently Asked Questions (FAQ)+--------------------------------++**1. Can I chain models from different sources?**++Yes! You can chain models from different ONNX files or directly from `onnx.ModelProto` objects. `ONNXSequential` handles the integration and merging of their graphs.++**2. What happens if the input/output sizes of models don't match?**++You can use the `io_map` parameter to control how outputs of one model are mapped to the inputs of the next. This allows for greater flexibility when chaining models with different architectures.++**3. Can I use custom ONNXRuntime session options?**++Absolutely! You can pass your own session options to the `create_session` method to fine-tune performance, memory usage, or logging.++**4. How to run with CUDA?**++For using CUDA ONNXRuntime, you need to install `onnxruntime-gpu`.+For handling different CUDA version, you may refer to+https://github.com/microsoft/onnxruntime/issues/21769#issuecomment-2295342211.++For example, to install `onnxruntime-gpu==1.19.2` under CUDA 11.X, you may install with:++.. code-block:: console++ pip install onnxruntime-gpu==1.19.2 --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-11/pypi/simple/++You may then convert your sequence to CUDA, such as:++.. code-block:: python++ import kornia+ onnx_seq = ONNXSequential(+ "hf://operators/kornia.geometry.transform.flips.Hflip",+ "hf://models/kornia.models.detection.rtdetr_r18vd_640x640", # Or you may use "YOUR_OWN_MODEL.onnx"+ )+ inp = kornia.utils.sample.get_sample_images()[0].numpy()[None]+ import time+ onnx_seq.as_cuda()+ onnx_seq(inp) # GPU warm up+ start_time = time.time()+ onnx_seq(inp)+ print("--- GPU %s seconds ---" % (time.time() - start_time))+ onnx_seq.as_cpu()+ start_time = time.time()+ onnx_seq(inp)+ print("--- %s seconds ---" % (time.time() - start_time))++You may get a decent improvement:++.. code-block:: console++ --- GPU 0.014804363250732422 seconds ---+ --- CPU 0.17681646347045898 seconds ---++Why Choose ONNXSequential?+--------------------------++With the increasing adoption of ONNX for model interoperability and deployment, `ONNXSequential` provides a simple yet powerful interface for combining models and operators. By leveraging ONNXRuntime's optimization and execution provider capabilities, it gives you the flexibility to:+- Deploy on different hardware (CPU, GPU, TensorRT, OpenVINO, etc.).+- Run complex pipelines in production environments.+- Combine and experiment with models effortlessly.++Whether you're building an advanced deep learning pipeline or simply trying to chain pre-trained models, `ONNXSequential` makes it easy to manage, optimize, and execute ONNX models at scale.++Get started today and streamline your ONNX workflows!+++API Documentation+-----------------+.. autoclass:: kornia.onnx.module.ONNXModule+ :members:++.. autoclass:: kornia.onnx.sequential.ONNXSequential+ :members:++.. autoclass:: kornia.onnx.utils.ONNXLoader++ .. code-block:: python++ # Load a HuggingFace operator+ ONNXLoader.load_model("hf://operators/kornia.color.gray.GrayscaleToRgb") # doctest: +SKIP+ # Load a local converted/downloaded operator+ ONNXLoader.load_model("operators/kornia.color.gray.GrayscaleToRgb") # doctest: +SKIP++ :members:diff --git a/kornia/__init__.py b/kornia/__init__.pyindex 84f22f205..b1b978274 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -10,12 +10,15 @@ from . import (color,contrib,core,+ config,enhance,feature,io,losses,metrics,+ models,morphology,+ onnx,tracking,utils,x,diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex e91276837..a4cfa33e2 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -53,6 +53,10 @@ class _BasicAugmentationBase(Module):the batch form ``False``."""+ # TODO: Hard to support. Many codes are not ONNX-friendly that contains lots of if-else blocks, etc.+ # Please contribute if anyone interested.+ ONNX_EXPORTABLE = False+def __init__(self,p: float = 0.5,diff --git a/kornia/color/gray.py b/kornia/color/gray.pyindex 96223a7a6..f647cfd33 100644--- a/kornia/color/gray.py+++ b/kornia/color/gray.py@@ -1,6 +1,6 @@from __future__ import annotations-from typing import Optional+from typing import ClassVar, Optionalimport torch@@ -125,6 +125,9 @@ class GrayscaleToRgb(Module):>>> output = rgb(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return grayscale_to_rgb(image)@@ -147,6 +150,9 @@ class RgbToGrayscale(Module):>>> output = gray(input) # 2x1x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]+def __init__(self, rgb_weights: Optional[Tensor] = None) -> None:super().__init__()if rgb_weights is None:@@ -175,5 +181,8 @@ class BgrToGrayscale(Module):>>> output = gray(input) # 2x1x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]+def forward(self, image: Tensor) -> Tensor:return bgr_to_grayscale(image)diff --git a/kornia/color/hls.py b/kornia/color/hls.pyindex 39c457a7c..eaad3db62 100644--- a/kornia/color/hls.py+++ b/kornia/color/hls.py@@ -1,5 +1,6 @@+from __future__ import annotationsimport math-from typing import Tuple+from typing import ClassVar, List, Tupleimport torch@@ -142,6 +143,9 @@ class RgbToHls(Module):>>> output = hls(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return rgb_to_hls(image)@@ -167,5 +171,8 @@ class HlsToRgb(Module):>>> output = rgb(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return hls_to_rgb(image)diff --git a/kornia/color/hsv.py b/kornia/color/hsv.pyindex ce5cc4c55..ecdd3d90f 100644--- a/kornia/color/hsv.py+++ b/kornia/color/hsv.py@@ -1,4 +1,6 @@+from __future__ import annotationsimport math+from typing import ClassVar, Listimport torch@@ -116,6 +118,9 @@ class RgbToHsv(Module):>>> output = hsv(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def __init__(self, eps: float = 1e-6) -> None:super().__init__()self.eps = eps@@ -142,5 +147,8 @@ class HsvToRgb(Module):>>> output = rgb(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: torch.Tensor) -> torch.Tensor:return hsv_to_rgb(image)diff --git a/kornia/color/lab.py b/kornia/color/lab.pyindex c9bda065f..e279a039a 100644--- a/kornia/color/lab.py+++ b/kornia/color/lab.py@@ -2,6 +2,8 @@https://github.com/scikit-image/scikit-image/blob/a48bf6774718c64dade4548153ae16065b595ca9/skimage/color/colorconv.py"""+from __future__ import annotations+from typing import ClassVar, Listimport torch@@ -150,6 +152,9 @@ class RgbToLab(Module):[3] https://github.com/torch/image/blob/dc061b98fb7e946e00034a5fc73e883a299edc7f/generic/image.c#L1467"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: torch.Tensor) -> torch.Tensor:return rgb_to_lab(image)@@ -177,5 +182,8 @@ class LabToRgb(Module):[3] https://github.com/torch/image/blob/dc061b98fb7e946e00034a5fc73e883a299edc7f/generic/image.c#L1518"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: torch.Tensor, clip: bool = True) -> torch.Tensor:return lab_to_rgb(image, clip)diff --git a/kornia/color/luv.py b/kornia/color/luv.pyindex 4af051e4f..2bc2932bd 100644--- a/kornia/color/luv.py+++ b/kornia/color/luv.py@@ -2,8 +2,8 @@https://github.com/scikit-image/scikit-image/blob/a48bf6774718c64dade4548153ae16065b595ca9/skimage/color/colorconv.py"""--from typing import Tuple+from __future__ import annotations+from typing import ClassVar, List, Tupleimport torch@@ -141,6 +141,9 @@ class RgbToLuv(Module):[3] http://www.poynton.com/ColorFAQ.html"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: torch.Tensor) -> torch.Tensor:return rgb_to_luv(image)@@ -168,5 +171,8 @@ class LuvToRgb(Module):[3] http://www.poynton.com/ColorFAQ.html"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: torch.Tensor) -> torch.Tensor:return luv_to_rgb(image)diff --git a/kornia/color/raw.py b/kornia/color/raw.pyindex 7dca55037..738923ad4 100644--- a/kornia/color/raw.py+++ b/kornia/color/raw.py@@ -1,4 +1,6 @@+from __future__ import annotationsfrom enum import Enum+from typing import ClassVar, Listimport torch@@ -288,6 +290,9 @@ class RawToRgb(Module):>>> output = rgb(rawinput) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def __init__(self, cfa: CFA) -> None:super().__init__()self.cfa = cfa@@ -314,6 +319,9 @@ class RgbToRaw(Module):>>> output = raw(rgbinput) # 2x1x4x6"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]+def __init__(self, cfa: CFA) -> None:super().__init__()self.cfa = cfadiff --git a/kornia/color/rgb.py b/kornia/color/rgb.pyindex 04c952149..33b34d210 100644--- a/kornia/color/rgb.py+++ b/kornia/color/rgb.py@@ -1,4 +1,5 @@-from typing import Union, cast+from __future__ import annotations+from typing import ClassVar, Union, castimport torch@@ -321,6 +322,9 @@ class BgrToRgb(Module):>>> output = rgb(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return bgr_to_rgb(image)@@ -343,6 +347,9 @@ class RgbToBgr(Module):>>> output = bgr(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return rgb_to_bgr(image)@@ -371,6 +378,9 @@ class RgbToRgba(Module):>>> output = rgba(input) # 2x4x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]+def __init__(self, alpha_val: Union[float, Tensor]) -> None:super().__init__()self.alpha_val = alpha_val@@ -403,6 +413,9 @@ class BgrToRgba(Module):>>> output = rgba(input) # 2x4x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]+def __init__(self, alpha_val: Union[float, Tensor]) -> None:super().__init__()self.alpha_val = alpha_val@@ -429,6 +442,9 @@ class RgbaToRgb(Module):>>> output = rgba(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return rgba_to_rgb(image)@@ -451,6 +467,9 @@ class RgbaToBgr(Module):>>> output = rgba(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 4, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return rgba_to_bgr(image)@@ -481,6 +500,9 @@ class RgbToLinearRgb(Module):[3] https://en.wikipedia.org/wiki/SRGB"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return rgb_to_linear_rgb(image)@@ -510,6 +532,9 @@ class LinearRgbToRgb(Module):[3] https://en.wikipedia.org/wiki/SRGB"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return linear_rgb_to_rgb(image)diff --git a/kornia/color/xyz.py b/kornia/color/xyz.pyindex 8a611e16b..82b89ceff 100644--- a/kornia/color/xyz.py+++ b/kornia/color/xyz.py@@ -1,3 +1,6 @@+from __future__ import annotations+from typing import ClassVar+import torchfrom kornia.core import ImageModule as Module@@ -91,6 +94,9 @@ class RgbToXyz(Module):[1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return rgb_to_xyz(image)@@ -114,5 +120,8 @@ class XyzToRgb(Module):[1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return xyz_to_rgb(image)diff --git a/kornia/color/ycbcr.py b/kornia/color/ycbcr.pyindex 918dad106..cc291783c 100644--- a/kornia/color/ycbcr.py+++ b/kornia/color/ycbcr.py@@ -1,3 +1,6 @@+from __future__ import annotations+from typing import ClassVar+import torchfrom kornia.core import ImageModule as Module@@ -121,6 +124,9 @@ class RgbToYcbcr(Module):>>> output = ycbcr(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return rgb_to_ycbcr(image)@@ -143,5 +149,8 @@ class YcbcrToRgb(Module):>>> output = rgb(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, image: Tensor) -> Tensor:return ycbcr_to_rgb(image)diff --git a/kornia/color/yuv.py b/kornia/color/yuv.pyindex bf620c83e..dab622144 100644--- a/kornia/color/yuv.py+++ b/kornia/color/yuv.py@@ -1,4 +1,5 @@-from typing import Tuple+from __future__ import annotations+from typing import ClassVar, Tupleimport torch@@ -293,6 +294,9 @@ class RgbToYuv(Module):[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, input: Tensor) -> Tensor:return rgb_to_yuv(input)@@ -324,6 +328,9 @@ class RgbToYuv420(Module):[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV"""+ # TODO: Handle multiple inputs and outputs models later+ ONNX_EXPORTABLE = False+def forward(self, yuvinput: Tensor) -> Tuple[Tensor, Tensor]: # skipcq: PYL-R0201return rgb_to_yuv420(yuvinput)@@ -355,6 +362,9 @@ class RgbToYuv422(Module):[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV"""+ # TODO: Handle multiple inputs and outputs models later+ ONNX_EXPORTABLE = False+def forward(self, yuvinput: Tensor) -> Tuple[Tensor, Tensor]: # skipcq: PYL-R0201return rgb_to_yuv422(yuvinput)@@ -382,6 +392,9 @@ class YuvToRgb(Module):>>> output = rgb(input) # 2x3x4x5"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def forward(self, input: Tensor) -> Tensor:return yuv_to_rgb(input)@@ -413,6 +426,9 @@ class Yuv420ToRgb(Module):>>> output = rgb(inputy, inputuv) # 2x3x4x6"""+ # TODO: Handle multiple inputs and outputs models later+ ONNX_EXPORTABLE = False+def forward(self, inputy: Tensor, inputuv: Tensor) -> Tensor: # skipcq: PYL-R0201return yuv420_to_rgb(inputy, inputuv)@@ -444,5 +460,8 @@ class Yuv422ToRgb(Module):>>> output = rgb(inputy, inputuv) # 2x3x4x6"""+ # TODO: Handle multiple inputs and outputs models later+ ONNX_EXPORTABLE = False+def forward(self, inputy: Tensor, inputuv: Tensor) -> Tensor: # skipcq: PYL-R0201return yuv422_to_rgb(inputy, inputuv)diff --git a/kornia/config.py b/kornia/config.pynew file mode 100644index 000000000..2f171399d--- /dev/null+++ b/kornia/config.py@@ -0,0 +1,54 @@+import os+from dataclasses import dataclass, field+from enum import Enum++__all__ = ["kornia_config", "InstallationMode"]+++class InstallationMode(str, Enum):+ # Ask the user if to install the dependencies+ ASK = "ASK"+ # Install the dependencies+ AUTO = "AUTO"+ # Raise an error if the dependencies are not installed+ RAISE = "RAISE"++ def __eq__(self, other: object) -> bool:+ if isinstance(other, str):+ return self.value.lower() == other.lower() # Case-insensitive comparison+ return super().__eq__(other)+++class LazyLoaderConfig:+ _installation_mode: InstallationMode = InstallationMode.ASK++ @property+ def installation_mode(self) -> InstallationMode:+ return self._installation_mode++ @installation_mode.setter+ def installation_mode(self, value: str) -> None:+ # Allow setting via string by converting to the Enum+ if isinstance(value, str):+ try:+ self._installation_mode = InstallationMode(value.upper())+ except ValueError:+ raise ValueError(f"{value} is not a valid InstallationMode. Choose from: {list(InstallationMode)}")+ elif isinstance(value, InstallationMode):+ self._installation_mode = value+ else:+ raise TypeError("installation_mode must be a string or InstallationMode Enum.")+++@dataclass+class KorniaConfig:+ hub_models_dir: str+ hub_onnx_dir: str+ output_dir: str = "kornia_outputs"+ hub_cache_dir: str = ".kornia_hub"+ lazyloader: LazyLoaderConfig = field(default_factory=LazyLoaderConfig)+++kornia_config = KorniaConfig(+ hub_models_dir=os.path.join(".kornia_hub", "models"), hub_onnx_dir=os.path.join(".kornia_hub", "onnx_models")+)diff --git a/kornia/constants.py b/kornia/constants.pyindex 72ac09863..9bf340d32 100644--- a/kornia/constants.py+++ b/kornia/constants.py@@ -1,3 +1,4 @@+import loggingfrom enum import Enum, EnumMetafrom typing import Iterator, Type, TypeVar, Union@@ -7,6 +8,9 @@ from kornia.core import Tensor__all__ = ["pi", "DType", "Resample", "BorderType", "SamplePadding", "TKEnum"]+# NOTE: to remove later+logging.basicConfig(level=logging.INFO)+pi = torch.tensor(3.14159265358979323846)diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.pyindex a8d674043..061391233 100644--- a/kornia/contrib/edge_detection.py+++ b/kornia/contrib/edge_detection.py@@ -1,5 +1,3 @@-from typing import List-from kornia.core import Module, Tensorfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.filters.dexined import DexiNed@@ -31,9 +29,8 @@ class EdgeDetector(Module):def preprocess(self, image: Tensor) -> Tensor:return image- def postprocess(self, data: List[Tensor]) -> Tensor:- # input are intermediate layer -- for inference we need only last.- return data[-1] # Bx1xHxW+ def postprocess(self, data: Tensor) -> Tensor:+ return datadef forward(self, image: Tensor) -> Tensor:KORNIA_CHECK_SHAPE(image, ["B", "3", "H", "W"])diff --git a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.pyindex 6345577e5..3c731238b 100644--- a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py+++ b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py@@ -274,6 +274,7 @@ class RTDETRHead(Module):num_denoising: int = 100,) -> None:super().__init__()+ self.num_classes = num_classesself.num_queries = num_queries# TODO: verify this is correctif len(in_channels) > num_levels:diff --git a/kornia/contrib/models/rt_detr/model.py b/kornia/contrib/models/rt_detr/model.pyindex 3e6e6226b..f7d040f99 100644--- a/kornia/contrib/models/rt_detr/model.py+++ b/kornia/contrib/models/rt_detr/model.py@@ -63,6 +63,7 @@ class RTDETRConfig:model_type: RTDETRModelType | str | intnum_classes: int+ input_size: int = 640checkpoint: Optional[str] = Noneneck_hidden_dim: Optional[int] = None@@ -73,6 +74,29 @@ class RTDETRConfig:head_num_decoder_layers: Optional[int] = Noneconfidence_threshold: float = 0.3+ @staticmethod+ def from_name(model_name: str, num_classes: int = 80) -> RTDETRConfig:+ """Load model without pretrained weights.++ Args:+ model_name: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.+ """++ if model_name == "rtdetr_r18vd":+ config = RTDETRConfig(RTDETRModelType.resnet18d, num_classes, input_size=640)+ elif model_name == "rtdetr_r34vd":+ config = RTDETRConfig(RTDETRModelType.resnet34d, num_classes, input_size=640)+ elif model_name == "rtdetr_r50vd_m":+ config = RTDETRConfig(RTDETRModelType.resnet50d_m, num_classes, input_size=640)+ elif model_name == "rtdetr_r50vd":+ config = RTDETRConfig(RTDETRModelType.resnet50d, num_classes, input_size=640)+ elif model_name == "rtdetr_r101vd":+ config = RTDETRConfig(RTDETRModelType.resnet101d, num_classes, input_size=640)+ else:+ raise ValueError++ return config+class RTDETR(ModelBase[RTDETRConfig]):"""RT-DETR Object Detection model, as described in https://arxiv.org/abs/2304.08069."""@@ -229,20 +253,7 @@ class RTDETR(ModelBase[RTDETRConfig]):Args:model_name: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'."""-- if model_name == "rtdetr_r18vd":- model = RTDETR.from_config(RTDETRConfig(RTDETRModelType.resnet18d, num_classes))- elif model_name == "rtdetr_r34vd":- model = RTDETR.from_config(RTDETRConfig(RTDETRModelType.resnet34d, num_classes))- elif model_name == "rtdetr_r50vd_m":- model = RTDETR.from_config(RTDETRConfig(RTDETRModelType.resnet50d_m, num_classes))- elif model_name == "rtdetr_r50vd":- model = RTDETR.from_config(RTDETRConfig(RTDETRModelType.resnet50d, num_classes))- elif model_name == "rtdetr_r101vd":- model = RTDETR.from_config(RTDETRConfig(RTDETRModelType.resnet101d, num_classes))- else:- raise ValueError-+ model = RTDETR.from_config(RTDETRConfig.from_name(model_name, num_classes))return modeldef forward(self, images: Tensor) -> tuple[Tensor, Tensor]:diff --git a/kornia/contrib/models/rt_detr/post_processor.py b/kornia/contrib/models/rt_detr/post_processor.pyindex 95b35623d..0df2c1190 100644--- a/kornia/contrib/models/rt_detr/post_processor.py+++ b/kornia/contrib/models/rt_detr/post_processor.py@@ -2,11 +2,12 @@from __future__ import annotations-from typing import Optional+from typing import Optional, Unionimport torch-from kornia.core import Module, Tensor, concatenate+from kornia.core import Module, Tensor, concatenate, tensor+from kornia.models.detection.utils import BoxFilteringdef mod(a: Tensor, b: int) -> Tensor:@@ -37,14 +38,18 @@ class DETRPostProcessor(Module):num_classes: int = 80,num_top_queries: int = 300,confidence_filtering: bool = True,+ filter_as_zero: bool = False,) -> None:super().__init__()self.confidence_threshold = confidence_thresholdself.num_classes = num_classesself.confidence_filtering = confidence_filteringself.num_top_queries = num_top_queries+ self.box_filtering = BoxFiltering(+ tensor(confidence_threshold) if confidence_threshold is not None else None, filter_as_zero=filter_as_zero+ )- def forward(self, logits: Tensor, boxes: Tensor, original_sizes: Tensor) -> Tensor:+ def forward(self, logits: Tensor, boxes: Tensor, original_sizes: Tensor) -> Union[Tensor, list[Tensor]]:"""Post-process outputs from DETR.Args:@@ -88,6 +93,4 @@ class DETRPostProcessor(Module):if not self.confidence_filtering or self.confidence_threshold == 0:return all_boxes- return all_boxes[(all_boxes[:, :, 1] > self.confidence_threshold).unsqueeze(-1).expand_as(all_boxes)].view(- all_boxes.shape[0], -1, all_boxes.shape[-1]- )+ return self.box_filtering(all_boxes, self.confidence_threshold)diff --git a/kornia/contrib/models/sam/model.py b/kornia/contrib/models/sam/model.pyindex f9cbbfa14..c528baf36 100644--- a/kornia/contrib/models/sam/model.py+++ b/kornia/contrib/models/sam/model.py@@ -86,6 +86,25 @@ class Sam(ModelBase[SamConfig]):self.prompt_encoder = prompt_encoderself.mask_decoder = mask_decoder+ @staticmethod+ def from_name(name: str) -> Sam:+ """Build/load the SAM model based on it's name.++ Args:+ name: The name of the SAM model. Valid names are:+ - 'vit_b'+ - 'vit_l'+ - 'vit_h'+ - 'mobile_sam'++ Returns:+ The respective SAM model+ """+ if name in ["vit_b", "vit_l", "vit_h", "mobile_sam"]:+ return Sam.from_config(SamConfig(name))+ else:+ raise ValueError(f"Invalid SAM model name: {name}")+@staticmethoddef from_config(config: SamConfig) -> Sam:"""Build/load the SAM model based on it's config.diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex 4a4b965dc..e43d97394 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -1,21 +1,24 @@from __future__ import annotations-import datetime-import logging-import os-from dataclasses import dataclass-from enum import Enum-from typing import Optional, Union--import torch--from kornia.core import Module, Tensor, concatenate-from kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.core.external import PILImage as Image-from kornia.core.external import numpy as np-from kornia.geometry.transform import resize-from kornia.io import write_image-from kornia.utils.draw import draw_rectangle+import warnings+from typing import Any++from kornia.models.detection.base import (+ BoundingBox as BoundingBoxBase,+)+from kornia.models.detection.base import (+ BoundingBoxDataFormat,+)+from kornia.models.detection.base import (+ ObjectDetector as ObjectDetectorBase,+)+from kornia.models.detection.base import (+ ObjectDetectorResult as ObjectDetectorResultBase,+)+from kornia.models.detection.base import (+ results_from_detections as results_from_detections_base,+)+from kornia.models.utils import ResizePreProcessor as ResizePreProcessorBase__all__ = ["BoundingBoxDataFormat",@@ -26,218 +29,51 @@ __all__ = ["ObjectDetectorResult",]-logger = logging.getLogger(__name__)---class BoundingBoxDataFormat(Enum):- """Enum class that maps bounding box data format."""-- XYWH = 0- XYXY = 1- CXCYWH = 2- CENTER_XYWH = 2---# NOTE: probably we should use a more generic name like BoundingBox2D-# and add a BoundingBox3D class for 3D bounding boxes. Also for serialization-# we should have an explicit class for each format to make it more production ready-# specially to serialize to protobuf and not saturate at a high rates.---@dataclass(frozen=True)-class BoundingBox:- """Bounding box data class.-- Useful for representing bounding boxes in different formats for object detection.-- Args:- data: tuple of bounding box data. The length of the tuple depends on the data format.- data_format: bounding box data format.- """-- data: tuple[float, float, float, float]- data_format: BoundingBoxDataFormat---@dataclass(frozen=True)-class ObjectDetectorResult:- """Object detection result.-- Args:- class_id: class id of the detected object.- confidence: confidence score of the detected object.- bbox: bounding box of the detected object in xywh format.- """-- class_id: int- confidence: float- bbox: BoundingBox--def results_from_detections(detections: Tensor, format: str | BoundingBoxDataFormat) -> list[ObjectDetectorResult]:- """Convert a detection tensor to a list of :py:class:`ObjectDetectorResult`.-- Args:- detections: tensor with shape :math:`(D, 6)`, where :math:`D` is the number of detections in the given image,- :math:`6` represents class id, score, and `xywh` bounding box.-- Returns:- list of :py:class:`ObjectDetectorResult`.- """- KORNIA_CHECK_SHAPE(detections, ["D", "6"])-- if isinstance(format, str):- format = BoundingBoxDataFormat[format.upper()]-- results: list[ObjectDetectorResult] = []- for det in detections:- det = det.squeeze().tolist()- if len(det) != 6:- continue- results.append(- ObjectDetectorResult(- class_id=int(det[0]),- confidence=det[1],- bbox=BoundingBox(data=(det[2], det[3], det[4], det[5]), data_format=format),- )+class BoundingBox(BoundingBoxBase):+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ warnings.warn(+ "BoundingBox is deprecated and will be removed in v0.8.0. "+ "Use kornia.models.detection.BoundingBox instead.",+ DeprecationWarning,)- return results---class ResizePreProcessor(Module):- """This module resizes a list of image tensors to the given size.-- Additionally, also returns the original image sizes for further post-processing.- """-- def __init__(self, size: tuple[int, int], interpolation_mode: str = "bilinear") -> None:- """- Args:- size: images will be resized to this value. If a 2-integer tuple is given, it is interpreted as- (height, width).- interpolation_mode: interpolation mode for image resizing. Supported values: ``nearest``, ``bilinear``,- ``bicubic``, ``area``, and ``nearest-exact``.- """- super().__init__()- self.size = size- self.interpolation_mode = interpolation_mode- def forward(self, imgs: Union[Tensor, list[Tensor]]) -> tuple[Tensor, Tensor]:- """- Returns:- resized_imgs: resized images in a batch.- original_sizes: the original image sizes of (height, width).- """- # TODO: support other input formats e.g. file path, numpy- resized_imgs: list[Tensor] = []- iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]- original_sizes = imgs[0].new_zeros((iters, 2))- for i in range(iters):- img = imgs[i]- original_sizes[i, 0] = img.shape[-2] # Height- original_sizes[i, 1] = img.shape[-1] # Width- resized_imgs.append(resize(img[None], size=self.size, interpolation=self.interpolation_mode))- return concatenate(resized_imgs), original_sizes+def results_from_detections(*args: Any, **kwargs: Any) -> list[ObjectDetectorResultBase]:+ warnings.warn(+ "results_from_detections is deprecated and will be removed in v0.8.0. "+ "Use kornia.models.detection.results_from_detections instead.",+ DeprecationWarning,+ )+ return results_from_detections_base(*args, **kwargs)-# TODO: move this to kornia.models as AlgorithmicModel api-class ObjectDetector(Module):- """This class wraps an object detection model and performs pre-processing and post-processing."""-- def __init__(self, model: Module, pre_processor: Module, post_processor: Module) -> None:- """Construct an Object Detector object.-- Args:- model: an object detection model.- pre_processor: a pre-processing module- post_processor: a post-processing module.- """- super().__init__()- self.model = model.eval()- self.pre_processor = pre_processor.eval()- self.post_processor = post_processor.eval()-- @torch.inference_mode()- def forward(self, images: Union[Tensor, list[Tensor]]) -> Tensor:- """Detect objects in a given list of images.-- Args:- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.-- Returns:- list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`, where :math:`D` is the- number of detections in the given image, :math:`6` represents class id, score, and `xywh` bounding box.- """- images, images_sizes = self.pre_processor(images)- logits, boxes = self.model(images)- detections = self.post_processor(logits, boxes, images_sizes)- return detections-- def draw(- self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, output_type: str = "torch"- ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore- """Very simple drawing.+class ResizePreProcessor(ResizePreProcessorBase):+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ warnings.warn(+ "ResizePreProcessor is deprecated and will be removed in v0.8.0. "+ "Use kornia.models.utils.ResizePreProcessor instead.",+ DeprecationWarning,+ )- Needs to be more fancy later.- """- if detections is None:- detections = self.forward(images)- output = []- for image, detection in zip(images, detections):- out_img = image[None].clone()- for out in detection:- out_img = draw_rectangle(- out_img,- torch.Tensor([[[out[-4], out[-3], out[-4] + out[-2], out[-3] + out[-1]]]]),- )- if output_type == "torch":- output.append(out_img[0])- elif output_type == "pil":- output.append(Image.fromarray((out_img[0] * 255).permute(1, 2, 0).numpy().astype(np.uint8))) # type: ignore- else:- raise RuntimeError(f"Unsupported output type `{output_type}`.")- return output- def save(- self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, directory: Optional[str] = None- ) -> None:- """Saves the output image(s) to a directory.+class ObjectDetector(ObjectDetectorBase):+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ warnings.warn(+ "ObjectDetector is deprecated and will be removed in v0.8.0. "+ "Use kornia.models.detection.ObjectDetector instead.",+ DeprecationWarning,+ )- Args:- name: Directory to save the images.- n_row: Number of images displayed in each row of the grid.- """- if directory is None:- name = f"detection-{datetime.datetime.now(tz=datetime.timezone.utc).strftime('%Y%m%d%H%M%S')!s}"- directory = os.path.join("Kornia_outputs", name)- outputs = self.draw(images, detections)- os.makedirs(directory, exist_ok=True)- for i, out_image in enumerate(outputs):- write_image(- os.path.join(directory, f"{str(i).zfill(6)}.jpg"),- out_image.mul(255.0).byte(),- )- logger.info(f"Outputs are saved in {directory}")- def compile(- self,- *,- fullgraph: bool = False,- dynamic: bool = False,- backend: str = "inductor",- mode: Optional[str] = None,- options: Optional[dict[str, str | int | bool]] = None,- disable: bool = False,- ) -> None:- """Compile the internal object detection model with :py:func:`torch.compile()`."""- self.model = torch.compile( # type: ignore- self.model,- fullgraph=fullgraph,- dynamic=dynamic,- backend=backend,- mode=mode,- options=options,- disable=disable,+class ObjectDetectorResult(ObjectDetectorResultBase):+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ warnings.warn(+ "ObjectDetectorResult is deprecated and will be removed in v0.8.0. "+ "Use kornia.models.detection.ObjectDetectorResult instead.",+ DeprecationWarning,)diff --git a/kornia/core/__init__.py b/kornia/core/__init__.pyindex 2e1ebc2f7..3cc2f2853 100644--- a/kornia/core/__init__.py+++ b/kornia/core/__init__.py@@ -5,6 +5,7 @@ from ._backend import (Module,ModuleList,Parameter,+ Sequential,Tensor,arange,as_tensor,@@ -32,7 +33,13 @@ from ._backend import (zeros,zeros_like,)-from .module import ImageModule+from .mixin import (+ ImageModuleMixIn,+ ONNXExportMixin,+ ONNXMixin,+ ONNXRuntimeMixin,+)+from .module import ImageModule, ImageSequentialfrom .tensor_wrapper import TensorWrapper # type: ignore__all__ = [@@ -43,6 +50,7 @@ __all__ = ["Dtype","Module","ModuleList",+ "Sequential","Tensor","tensor","Parameter",@@ -70,4 +78,9 @@ __all__ = ["TensorWrapper","map_coordinates","ImageModule",+ "ImageSequential",+ "ImageModuleMixIn",+ "ONNXMixin",+ "ONNXExportMixin",+ "ONNXRuntimeMixin",]diff --git a/kornia/core/_backend.py b/kornia/core/_backend.pyindex b6b49a4bb..b33cd8116 100644--- a/kornia/core/_backend.py+++ b/kornia/core/_backend.py@@ -10,6 +10,7 @@ tensor = torch.tensorModule = torch.nn.ModuleModuleList = torch.nn.ModuleListParameter = torch.nn.Parameter+Sequential = torch.nn.Sequential# functions# NOTE: ideally we expose what we find in numpydiff --git a/kornia/core/external.py b/kornia/core/external.pyindex 1e0160035..a600eb352 100644--- a/kornia/core/external.py+++ b/kornia/core/external.py@@ -5,6 +5,8 @@ import sysfrom types import ModuleTypefrom typing import List, Optional+from kornia.config import InstallationMode, kornia_config+logger = logging.getLogger(__name__)@@ -22,14 +24,18 @@ class LazyLoader:auto_install: bool = False- def __init__(self, module_name: str) -> None:+ def __init__(self, module_name: str, dev_dependency: bool = False) -> None:"""Initializes the LazyLoader with the name of the module.Args:- module_name (str): The name of the module to be lazily loaded.+ module_name: The name of the module to be lazily loaded.+ dev_dependency: If the dependency is required in the dev environment.+ If True, the module will be loaded in the dev environment.+ If False, the module will not be loaded in the dev environment."""self.module_name = module_nameself.module: Optional[ModuleType] = None+ self.dev_dependency = dev_dependencydef _install_package(self, module_name: str) -> None:logger.info(f"Installing `{module_name}` ...")@@ -41,27 +47,52 @@ class LazyLoader:This method is called internally when an attribute of the module is accessed for the first time. It attempts toimport the module and raises an ImportError with a custom message if the module is not installed."""+ if not self.dev_dependency:+ if "--doctest-modules" in sys.argv:+ logger.info(f"Doctest detected, skipping loading of '{self.module_name}'")+ return+ try:+ if __sphinx_build__: # type:ignore+ logger.info(f"Sphinx detected, skipping loading of '{self.module_name}'")+ return+ except NameError:+ pass+if self.module is None:try:self.module = importlib.import_module(self.module_name)except ImportError as e:- if self.auto_install:+ if kornia_config.lazyloader.installation_mode == InstallationMode.AUTO or self.auto_install:self._install_package(self.module_name)- else:+ elif kornia_config.lazyloader.installation_mode == InstallationMode.ASK:+ to_ask = Trueif_install = input(f"Optional dependency '{self.module_name}' is not installed. "+ "You may silent this prompt by `kornia_config.lazyloader.installation_mode = 'auto'`. ""Do you wish to install the dependency? [Y]es, [N]o, [A]ll.")- if if_install.lower() == "y":- self._install_package(self.module_name)- elif if_install.lower() == "a":- self.auto_install = True- self._install_package(self.module_name)- else:- raise ImportError(- f"Optional dependency '{self.module_name}' is not installed. "- f"Please install it to use this functionality."- ) from e+ while to_ask:+ if if_install.lower() == "y" or if_install.lower() == "yes":+ self._install_package(self.module_name)+ to_ask = False+ elif if_install.lower() == "a" or if_install.lower() == "all":+ self.auto_install = True+ self._install_package(self.module_name)+ to_ask = False+ elif if_install.lower() == "n" or if_install.lower() == "no":+ raise ImportError(+ f"Optional dependency '{self.module_name}' is not installed. "+ f"Please install it to use this functionality."+ ) from e+ else:+ if_install = input("Invalid input. Please enter 'Y', 'N', or 'A'.")++ elif kornia_config.lazyloader.installation_mode == InstallationMode.RAISE:+ raise ImportError(+ f"Optional dependency '{self.module_name}' is not installed. "+ f"Please install it to use this functionality."+ ) from e+ self.module = importlib.import_module(self.module_name)def __getattr__(self, item: str) -> object:"""Loads the module (if not already loaded) and returns the requested attribute.@@ -91,6 +122,17 @@ class LazyLoader:return dir(self.module)-numpy = LazyLoader("numpy")-PILImage = LazyLoader("PIL.Image")+# NOTE: This section is used for lazy loading of external modules. However, sphinx+# would also try to support lazy loading of external modules. To avoid that, we+# may set the module name to `autodoc_mock_imports` in conf.py to avoid undesired+# installation of external modules.+numpy = LazyLoader("numpy", dev_dependency=True)+PILImage = LazyLoader("PIL.Image", dev_dependency=True)+onnx = LazyLoader("onnx", dev_dependency=True)diffusers = LazyLoader("diffusers")+transformers = LazyLoader("transformers")+onnxruntime = LazyLoader("onnxruntime")+boxmot = LazyLoader("boxmot")+segmentation_models_pytorch = LazyLoader("segmentation_models_pytorch")+basicsr = LazyLoader("basicsr")+requests = LazyLoader("requests")diff --git a/kornia/core/mixin/__init__.py b/kornia/core/mixin/__init__.pynew file mode 100644index 000000000..c705a1c70--- /dev/null+++ b/kornia/core/mixin/__init__.py@@ -0,0 +1,2 @@+from .image_module import ImageModuleMixIn+from .onnx import ONNXExportMixin, ONNXMixin, ONNXRuntimeMixindiff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pynew file mode 100644index 000000000..b003f4fe6--- /dev/null+++ b/kornia/core/mixin/image_module.py@@ -0,0 +1,228 @@+import datetime+import math+import os+from functools import wraps+from typing import Any, Callable, List, Optional, Tuple, Union++from kornia.core._backend import Tensor, from_numpy+from kornia.core.external import PILImage as Image+from kornia.core.external import numpy as np+++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]:+ """Decorator to 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.+ """++ def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:+ @wraps(func)+ def wrapper(*args: Any, **kwargs: Any) -> Union[Any, List[Any]]:+ # 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, (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) -> 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,)):+ from kornia.io import ImageLoadType, load_image # pylint: disable=C0415++ return load_image(x, ImageLoadType.UNCHANGED) / 255+ if isinstance(x, (Tensor,)):+ return x+ if isinstance(x, (np.ndarray,)): # type: ignore+ from kornia.utils.image import image_to_tensor # pylint: disable=C0415++ return image_to_tensor(x) / 255+ if isinstance(x, (Image.Image,)): # type: ignore+ return 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, (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, (Tensor,)):+ x = x.cpu().detach() * 255+ if x.dim() == 3:+ x = x.permute(1, 2, 0)+ return Image.fromarray(x.byte().numpy()) # type: ignore+ elif x.dim() == 4:+ x = x.permute(0, 2, 3, 1)+ return [Image.fromarray(_x.byte().numpy()) for _x in x] # 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[Tensor, List[Tensor], Tuple[Tensor]]+ ) -> Union[Tensor, List[Tensor], Tuple[Tensor]]:+ if isinstance(output_image, (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]:+ """Returns PIL images.++ Args:+ n_row: Number of images displayed in each row of the grid.+ backend: visualization backend. Only PIL is supported now.+ """+ 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:+ from kornia.utils.image import make_grid # pylint: disable=C0415++ if n_row is None:+ n_row = math.ceil(self._output_image.shape[0] ** 0.5)+ out_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:+ """Saves 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.+ """+ 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.timezone.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 = make_grid(self._output_image, n_row, padding=2)+ write_image(name, out_image.mul(255.0).byte())diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.pynew file mode 100644index 000000000..4d5498352--- /dev/null+++ b/kornia/core/mixin/onnx.py@@ -0,0 +1,384 @@+from __future__ import annotations++import copy+import io+from typing import (+ Any,+ ClassVar,+ Optional,+ Union,+)++import torch++import kornia+from kornia.core import Module, Tensor, rand+from kornia.core.external import numpy as np+from kornia.core.external import onnx+from kornia.core.external import onnxruntime as ort+++class ONNXExportMixin:+ """Mixin class that provides ONNX export functionality for objects that support it.++ Attributes:+ ONNX_EXPORTABLE:+ A flag indicating whether the object can be exported to ONNX. Default is True.+ ONNX_DEFAULT_INPUTSHAPE:+ Default input shape for the ONNX export. A list of integers where `-1` indicates+ dynamic dimensions. Default is [-1, -1, -1, -1].+ ONNX_DEFAULT_OUTPUTSHAPE:+ Default output shape for the ONNX export. A list of integers where `-1` indicates+ dynamic dimensions. Default is [-1, -1, -1, -1].+ ONNX_EXPORT_PSEUDO_SHAPE:+ This is used to create a dummy input tensor for the ONNX export. Default is [1, 3, 256, 256].+ It dimension shall match the ONNX_DEFAULT_INPUTSHAPE and ONNX_DEFAULT_OUTPUTSHAPE.+ Non-image dimensions are allowed.++ Note:+ - If `ONNX_EXPORTABLE` is False, indicating that the object cannot be exported to ONNX.+ """++ ONNX_EXPORTABLE: bool = True+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1]+ ONNX_EXPORT_PSEUDO_SHAPE: ClassVar[list[int]] = [1, 3, 256, 256]+ ADDITIONAL_METADATA: ClassVar[list[tuple[str, str]]] = []++ def to_onnx(+ self,+ onnx_name: Optional[str] = None,+ input_shape: Optional[list[int]] = None,+ output_shape: Optional[list[int]] = None,+ pseudo_shape: Optional[list[int]] = None,+ model: Optional[Module] = None,+ save: bool = True,+ additional_metadata: list[tuple[str, str]] = [],+ **kwargs: Any,+ ) -> onnx.ModelProto: # type: ignore+ """Exports the current object to an ONNX model file.++ Args:+ onnx_name:+ The name of the output ONNX file. If not provided, a default name in the+ format "Kornia-<ClassName>.onnx" will be used.+ input_shape:+ The input shape for the model as a list of integers. If None,+ `ONNX_DEFAULT_INPUTSHAPE` will be used. Dynamic dimensions can be indicated by `-1`.+ output_shape:+ The output shape for the model as a list of integers. If None,+ `ONNX_DEFAULT_OUTPUTSHAPE` will be used. Dynamic dimensions can be indicated by `-1`.+ pseudo_shape:+ The pseudo shape for the model as a list of integers. If None,+ `ONNX_EXPORT_PSEUDO_SHAPE` will be used.+ model:+ The model to export. If not provided, the current object will be used.+ save:+ If to save the model or load it.+ additional_metadata:+ Additional metadata to add to the ONNX model.+ **kwargs:+ Additional keyword arguments to pass to the `torch.onnx.export` function.++ Notes:+ - A dummy input tensor is created based on the provided or default input shape.+ - Dynamic axes for input and output tensors are configured where dimensions are marked `-1`.+ - The model is exported with `torch.onnx.export`, with constant folding enabled and opset version set to 17.+ """+ if not self.ONNX_EXPORTABLE:+ raise RuntimeError("This object cannot be exported to ONNX.")++ if input_shape is None:+ input_shape = self.ONNX_DEFAULT_INPUTSHAPE+ if output_shape is None:+ output_shape = self.ONNX_DEFAULT_OUTPUTSHAPE++ if onnx_name is None:+ onnx_name = f"Kornia-{self.__class__.__name__}.onnx"++ dummy_input = self._create_dummy_input(input_shape, pseudo_shape)+ dynamic_axes = self._create_dynamic_axes(input_shape, output_shape)++ default_args: dict[str, Any] = {+ "export_params": True,+ "opset_version": 17,+ "do_constant_folding": True,+ "input_names": ["input"],+ "output_names": ["output"],+ "dynamic_axes": dynamic_axes,+ }+ default_args.update(kwargs)++ onnx_buffer = io.BytesIO()+ torch.onnx.export(+ model or self, # type: ignore+ dummy_input,+ onnx_buffer,+ **default_args,+ )+ onnx_buffer.seek(0)+ onnx_model = onnx.load(onnx_buffer) # type: ignore++ additional_metadata = copy.deepcopy(additional_metadata)+ additional_metadata.extend(self.ADDITIONAL_METADATA)+ onnx_model = kornia.onnx.utils.add_metadata(onnx_model, additional_metadata)+ if save:+ onnx.save(onnx_model, onnx_name) # type: ignore+ return onnx_model++ def _create_dummy_input(+ self, input_shape: list[int], pseudo_shape: Optional[list[int]] = None+ ) -> Union[tuple[Any, ...], Tensor]:+ return rand(+ *[+ ((self.ONNX_EXPORT_PSEUDO_SHAPE[i] if pseudo_shape is None else pseudo_shape[i]) if dim == -1 else dim)+ for i, dim in enumerate(input_shape)+ ]+ )++ def _create_dynamic_axes(self, input_shape: list[int], output_shape: list[int]) -> dict[str, dict[int, str]]:+ return {+ "input": {i: "dim_" + str(i) for i, dim in enumerate(input_shape) if dim == -1},+ "output": {i: "dim_" + str(i) for i, dim in enumerate(output_shape) if dim == -1},+ }+++class ONNXRuntimeMixin:+ def _create_session(+ self,+ op: onnx.ModelProto, # type:ignore+ providers: Optional[list[str]] = None,+ session_options: Optional[ort.InferenceSession] = None, # type:ignore+ ) -> ort.InferenceSession: # type:ignore+ """Create an optimized ONNXRuntime InferenceSession for the combined model.++ Args:+ providers:+ Execution providers for ONNXRuntime (e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']).+ session_options:+ Optional ONNXRuntime session options for session configuration and optimizations.++ Returns:+ ort.InferenceSession: The ONNXRuntime session optimized for inference.+ """+ if session_options is None:+ sess_options = ort.SessionOptions() # type:ignore+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED # type:ignore+ session = ort.InferenceSession( # type:ignore+ op.SerializeToString(),+ sess_options=sess_options,+ providers=providers or ["CPUExecutionProvider"],+ )+ return session++ def set_session(self, session: ort.InferenceSession) -> None: # type: ignore+ """Set a custom ONNXRuntime InferenceSession.++ Args:+ session: ort.InferenceSession+ The custom ONNXRuntime session to be set for inference.+ """+ self._session = session++ def get_session(self) -> ort.InferenceSession: # type: ignore+ """Get the current ONNXRuntime InferenceSession.++ Returns:+ ort.InferenceSession: The current ONNXRuntime session.+ """+ return self._session++ def as_cpu(self, **kwargs: Any) -> None:+ """Set the session to run on CPU."""+ self._session.set_providers(["CPUExecutionProvider"], provider_options=[{**kwargs}])++ def as_cuda(self, device_id: int = 0, **kwargs: Any) -> None:+ """Set the session to run on CUDA.++ We set the ONNX runtime session to use CUDAExecutionProvider.+ For other CUDAExecutionProvider configurations, or CUDA/cuDNN/ONNX version issues,+ you may refer to https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html.++ Note:+ For using CUDA ONNXRuntime, you need to install `onnxruntime-gpu`.+ For handling different CUDA version, you may refer to+ https://github.com/microsoft/onnxruntime/issues/21769#issuecomment-2295342211.++ Args:+ device_id: Select GPU to execute.+ """+ self._session.set_providers(["CUDAExecutionProvider"], provider_options=[{"device_id": device_id, **kwargs}])++ def as_tensorrt(self, device_id: int = 0, **kwargs: Any) -> None:+ """Set the session to run on TensorRT.++ We set the ONNX runtime session to use TensorrtExecutionProvider.+ For other TensorrtExecutionProvider configurations, or CUDA/cuDNN/ONNX/TensorRT version issues,+ you may refer to https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html.++ Args:+ device_id: select GPU to execute.+ """+ self._session.set_providers(+ ["TensorrtExecutionProvider"], provider_options=[{"device_id": device_id, **kwargs}]+ )++ def as_openvino(self, device_type: str = "GPU", **kwargs: Any) -> None:+ """Set the session to run on TensorRT.++ We set the ONNX runtime session to use OpenVINOExecutionProvider.+ For other OpenVINOExecutionProvider configurations, or CUDA/cuDNN/ONNX/TensorRT version issues,+ you may refer to https://onnxruntime.ai/docs/execution-providers/OpenVINO-ExecutionProvider.html.++ Args:+ device_type: CPU, NPU, GPU, GPU.0, GPU.1 based on the available GPUs, NPU, Any valid Hetero combination,+ Any valid Multi or Auto devices combination.+ """+ self._session.set_providers(+ ["OpenVINOExecutionProvider"], provider_options=[{"device_type": device_type, **kwargs}]+ )++ def __call__(self, *inputs: np.ndarray) -> list[np.ndarray]: # type:ignore+ """Perform inference using the combined ONNX model.++ Args:+ *inputs: Inputs to the ONNX model. The number of inputs must match the expected inputs of the session.++ Returns:+ list: The outputs from the ONNX model inference.+ """+ ort_inputs = self._session.get_inputs()+ ort_input_values = {ort_inputs[i].name: inputs[i] for i in range(len(ort_inputs))}+ outputs = self._session.run(None, ort_input_values)++ return outputs+++class ONNXMixin:+ def _load_op(+ self,+ arg: Union[onnx.ModelProto, str], # type:ignore+ cache_dir: Optional[str] = None,+ ) -> onnx.ModelProto: # type:ignore+ """Loads an ONNX model, either from a file path or use the provided ONNX ModelProto.++ Args:+ arg: Either an ONNX ModelProto object or a file path to an ONNX model.++ Returns:+ onnx.ModelProto: The loaded ONNX model.+ """+ if isinstance(arg, str):+ return kornia.onnx.utils.ONNXLoader.load_model(arg, cache_dir=cache_dir)+ if isinstance(arg, onnx.ModelProto): # type:ignore+ return arg+ raise ValueError(f"Invalid argument type. Got {type(arg)}")++ def _load_ops(+ self,+ *args: Union[onnx.ModelProto, str], # type:ignore+ cache_dir: Optional[str] = None,+ ) -> list[onnx.ModelProto]: # type:ignore+ """Loads multiple ONNX models or operators and returns them as a list.++ Args:+ *args: A variable number of ONNX models (either ONNX ModelProto objects or file paths).+ For Hugging Face-hosted models, use the format 'hf://model_name'. Valid `model_name` can be found on+ https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.++ Returns:+ list[onnx.ModelProto]: The loaded ONNX models as a list of ONNX graphs.+ """+ op_list = []+ for arg in args:+ op_list.append(self._load_op(arg, cache_dir=cache_dir))+ return op_list++ def _combine(+ self,+ *args: list[onnx.ModelProto], # type:ignore+ io_maps: Optional[list[tuple[str, str]]] = None,+ ) -> onnx.ModelProto: # type:ignore+ """Combine the provided ONNX models into a single ONNX graph. Optionally, map inputs and outputs between+ operators using the `io_map`.++ Args:+ io_maps:+ A list of list of tuples representing input-output mappings for combining the models.+ Example: [[(model1_output_name, model2_input_name)], [(model2_output_name, model3_input_name)]].++ Returns:+ onnx.ModelProto: The combined ONNX model as a single ONNX graph.+ """+ if len(args) == 0:+ raise ValueError("No operators found.")++ combined_op = args[0]+ combined_op = onnx.compose.add_prefix(combined_op, prefix=f"K{str(0).zfill(2)}-") # type:ignore++ for i, op in enumerate(args[1:]):+ next_op = onnx.compose.add_prefix(op, prefix=f"K{str(i + 1).zfill(2)}-") # type:ignore+ if io_maps is None:+ io_map = [(f"K{str(i).zfill(2)}-output", f"K{str(i + 1).zfill(2)}-input")]+ else:+ io_map = [(f"K{str(i).zfill(2)}-{it[0]}", f"K{str(i + 1).zfill(2)}-{it[1]}") for it in io_maps[i]]+ combined_op = onnx.compose.merge_models(combined_op, next_op, io_map=io_map) # type:ignore++ return combined_op++ def _export(+ self,+ op: onnx.ModelProto, # type:ignore+ file_path: str,+ **kwargs: Any,+ ) -> None:+ """Export the combined ONNX model to a file.++ Args:+ file_path:+ The file path to export the combined ONNX model.+ """+ onnx.save(op, file_path, **kwargs) # type:ignore++ def _add_metadata(+ self,+ op: onnx.ModelProto, # type:ignore+ additional_metadata: list[tuple[str, str]] = [],+ ) -> onnx.ModelProto: # type:ignore+ """Add metadata to the combined ONNX model.++ Args:+ additional_metadata:+ A list of tuples representing additional metadata to add to the combined ONNX model.+ Example: [("version", 0.1)], [("date", 20240909)].+ """+ op = kornia.onnx.utils.add_metadata(op, additional_metadata)+ return op++ def _onnx_version_conversion(+ self,+ op: onnx.ModelProto, # type:ignore+ target_ir_version: Optional[int] = None,+ target_opset_version: Optional[int] = None,+ ) -> onnx.ModelProto: # type:ignore+ """Automatic conversion of the model's IR/OPSET version to the given target version.++ Args:+ target_ir_version: The target IR version to convert to.+ target_opset_version: The target OPSET version to convert to.+ """+ if op.ir_version != target_ir_version or op.opset_import[0].version != target_opset_version:+ # Check if all ops are supported in the current IR version+ model_bytes = io.BytesIO()+ onnx.save_model(op, model_bytes) # type:ignore+ loaded_model = onnx.load_model_from_string(model_bytes.getvalue()) # type:ignore+ if target_opset_version is not None:+ loaded_model = onnx.version_converter.convert_version( # type:ignore+ loaded_model, target_opset_version+ )+ onnx.checker.check_model(loaded_model) # type:ignore+ # Set the IR version if it passed the checking+ if target_ir_version is not None:+ loaded_model.ir_version = target_ir_version+ op = loaded_model+ return opdiff --git a/kornia/core/module.py b/kornia/core/module.pyindex 97132caf5..ab75ea6c0 100644--- a/kornia/core/module.py+++ b/kornia/core/module.py@@ -1,14 +1,18 @@+from __future__ import annotationsimport datetimeimport mathimport osfrom functools import wraps-from typing import Any, Callable, List, Optional, Tuple, Union+from typing import Any, Callable, ClassVar, List, Optional, Tuple, Union++import torchimport kornia-from ._backend import Module, Tensor, from_numpy+from ._backend import Module, Sequential, Tensor, from_numpyfrom .external import PILImage as Imagefrom .external import numpy as np+from .mixin.onnx import ONNXExportMixinclass ImageModuleMixIn:@@ -135,7 +139,7 @@ class ImageModuleMixIn:return np.array(x) # type: ignoreraise TypeError("Input type not supported")- def to_pil(self, x: Any) -> Image.Image: # type: ignore+ def to_pil(self, x: Any) -> "Image.Image": # type: ignore"""Convert input to PIL image.Args:@@ -219,7 +223,7 @@ class ImageModuleMixIn:kornia.io.write_image(name, out_image.mul(255.0).byte())-class ImageModule(Module, ImageModuleMixIn):+class ImageModule(Module, ImageModuleMixIn, ONNXExportMixin):"""Handles image-based operations.This modules accepts multiple input and output data types, provides end-to-end@@ -273,3 +277,59 @@ class ImageModule(Module, ImageModuleMixIn):else:_output_image = super().__call__(*inputs, **kwargs)return _output_image+++class ImageSequential(Sequential, ImageModuleMixIn, ONNXExportMixin):+ """Handles image-based operations as a sequential module.++ This modules accepts multiple input and output data types, provides end-to-end+ visualization, file saving features. Note that this module fits the classes that+ return one image tensor only.++ Note:+ The additional add-on features increase the use of memories. To restore the+ original behaviour, you may set `disable_features = True`.+ """++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ self._disable_features: bool = False++ @property+ def disable_features(self) -> bool:+ return self._disable_features++ @disable_features.setter+ def disable_features(self, value: bool = True) -> None:+ self._disable_features = value++ def __call__(+ self,+ *inputs: Any,+ input_names_to_handle: Optional[List[Any]] = None,+ output_type: str = "tensor",+ **kwargs: Any,+ ) -> Any:+ """Overwrites the __call__ function to handle various inputs.++ 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.+ """++ # Wrap the forward method with the decorator+ if not self._disable_features:+ decorated_forward = self.convert_input_output(+ input_names_to_handle=input_names_to_handle, output_type=output_type+ )(super().__call__)+ _output_image = decorated_forward(*inputs, **kwargs)+ if output_type == "tensor":+ self._output_image = self._detach_tensor_to_cpu(_output_image)+ else:+ self._output_image = _output_image+ else:+ _output_image = super().__call__(*inputs, **kwargs)+ return _output_imagediff --git a/kornia/enhance/__init__.py b/kornia/enhance/__init__.pyindex cf076f36c..d3bb21765 100644--- a/kornia/enhance/__init__.py+++ b/kornia/enhance/__init__.py@@ -35,6 +35,7 @@ from .histogram import histogram, histogram2d, image_histogram2dfrom .integral import IntegralImage, IntegralTensor, integral_image, integral_tensorfrom .jpeg import JPEGCodecDifferentiable, jpeg_codec_differentiablefrom .normalize import Denormalize, Normalize, denormalize, normalize, normalize_min_max+from .rescale import Rescalefrom .shift_rgb import shift_rgbfrom .zca import ZCAWhitening, linear_transform, zca_mean, zca_whiten@@ -83,6 +84,7 @@ __all__ = ["denormalize","Normalize","Denormalize",+ "Rescale","zca_mean","zca_whiten","linear_transform",diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 82b2bb0d0..379094747 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -1,5 +1,6 @@+from __future__ import annotationsfrom math import pi-from typing import Optional, Union+from typing import ClassVar, Optional, Unionimport torch@@ -1042,6 +1043,9 @@ class AdjustSaturation(Module):tensor(0.)"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def __init__(self, saturation_factor: Union[float, Tensor]) -> None:super().__init__()self.saturation_factor: Union[float, Tensor] = saturation_factor@@ -1089,6 +1093,9 @@ class AdjustSaturationWithGraySubtraction(Module):tensor(0.)"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def __init__(self, saturation_factor: Union[float, Tensor]) -> None:super().__init__()self.saturation_factor: Union[float, Tensor] = saturation_factor@@ -1136,6 +1143,9 @@ class AdjustHue(Module):torch.Size([2, 3, 3, 3])"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+def __init__(self, hue_factor: Union[float, Tensor]) -> None:super().__init__()self.hue_factor: Union[float, Tensor] = hue_factordiff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex 423d6ee3b..f46748eda 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -54,10 +54,10 @@ class Normalize(Module):std = torch.tensor([std])if isinstance(mean, (tuple, list)):- mean = torch.tensor(mean)+ mean = torch.tensor(mean)[None]if isinstance(std, (tuple, list)):- std = torch.tensor(std)+ std = torch.tensor(std)[None]self.mean = meanself.std = std@@ -100,28 +100,37 @@ def normalize(data: Tensor, mean: Tensor, std: Tensor) -> Tensor:torch.Size([1, 4, 3, 3])"""shape = data.shape- if len(mean.shape) == 0 or mean.shape[0] == 1:- mean = mean.expand(shape[1])- if len(std.shape) == 0 or std.shape[0] == 1:- std = std.expand(shape[1])- # Allow broadcast on channel dimension- if mean.shape and mean.shape[0] != 1:- if mean.shape[0] != data.shape[1] and mean.shape[:2] != data.shape[:2]:- raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")-- # Allow broadcast on channel dimension- if std.shape and std.shape[0] != 1:- if std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]:- raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")-- mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)- std = torch.as_tensor(std, device=data.device, dtype=data.dtype)-- if mean.shape:- mean = mean[..., :, None]- if std.shape:- std = std[..., :, None]+ if torch.onnx.is_in_onnx_export():+ if not isinstance(mean, Tensor) or not isinstance(std, Tensor):+ raise ValueError("Only tensor is accepted when converting to ONNX.")+ if mean.shape[0] != 1 or std.shape[0] != 1:+ raise ValueError(+ "Batch dimension must be one for broadcasting when converting to ONNX."+ f"Try changing mean shape and std shape from ({mean.shape}, {std.shape}) to (1, C) or (1, C, 1, 1)."+ )+ else:+ if isinstance(mean, float):+ mean = torch.tensor([mean] * shape[1], device=data.device, dtype=data.dtype)++ if isinstance(std, float):+ std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype)++ # Allow broadcast on channel dimension+ if mean.shape and mean.shape[0] != 1:+ if mean.shape[0] != data.shape[1] and mean.shape[:2] != data.shape[:2]:+ raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")++ # Allow broadcast on channel dimension+ if std.shape and std.shape[0] != 1:+ if std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]:+ raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")++ mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)+ std = torch.as_tensor(std, device=data.device, dtype=data.dtype)++ mean = mean[..., None]+ std = std[..., None]out: Tensor = (data.view(shape[0], shape[1], -1) - mean) / std@@ -203,38 +212,33 @@ def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, flo"""shape = data.shape- if isinstance(mean, float):- mean = torch.tensor([mean] * shape[1], device=data.device, dtype=data.dtype)-- if isinstance(std, float):- std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype)-- if not isinstance(data, Tensor):- raise TypeError(f"data should be a tensor. Got {type(data)}")-- if not isinstance(mean, Tensor):- raise TypeError(f"mean should be a tensor or a float. Got {type(mean)}")-- if not isinstance(std, Tensor):- raise TypeError(f"std should be a tensor or float. Got {type(std)}")-- # Allow broadcast on channel dimension- if mean.shape and mean.shape[0] != 1:- if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]:- raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")-- # Allow broadcast on channel dimension- if std.shape and std.shape[0] != 1:- if std.shape[0] != data.shape[-3] and std.shape[:2] != data.shape[:2]:- raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")-- mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)- std = torch.as_tensor(std, device=data.device, dtype=data.dtype)-- if mean.shape:- mean = mean[..., :, None]- if std.shape:- std = std[..., :, None]+ if torch.onnx.is_in_onnx_export():+ if not isinstance(mean, Tensor) or not isinstance(std, Tensor):+ raise ValueError("Only tensor is accepted when converting to ONNX.")+ if mean.shape[0] != 1 or std.shape[0] != 1:+ raise ValueError("Batch dimension must be one for broadcasting when converting to ONNX.")+ else:+ if isinstance(mean, float):+ mean = torch.tensor([mean] * shape[1], device=data.device, dtype=data.dtype)++ if isinstance(std, float):+ std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype)++ # Allow broadcast on channel dimension+ if mean.shape and mean.shape[0] != 1:+ if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]:+ raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")++ # Allow broadcast on channel dimension+ if std.shape and std.shape[0] != 1:+ if std.shape[0] != data.shape[-3] and std.shape[:2] != data.shape[:2]:+ raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")++ mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)+ std = torch.as_tensor(std, device=data.device, dtype=data.dtype)++ mean = mean[..., None]+ std = std[..., None]out: Tensor = (data.view(shape[0], shape[1], -1) * std) + meandiff --git a/kornia/enhance/rescale.py b/kornia/enhance/rescale.pynew file mode 100644index 000000000..add1e3318--- /dev/null+++ b/kornia/enhance/rescale.py@@ -0,0 +1,24 @@+from typing import Union++from kornia.core import ImageModule as Module+from kornia.core import Tensor, tensor+++class Rescale(Module):+ r"""Initialize the Rescale operator.++ Args:+ factor: The scaling factor. Could be a float or a 0-d tensor.+ """++ def __init__(self, factor: Union[float, Tensor]) -> None:+ super().__init__()+ if isinstance(factor, float):+ self.factor = tensor(factor)+ else:+ if not isinstance(factor, Tensor) or factor.ndim != 0:+ raise TypeError(f"Expected factor to be a float or a 0-d tensor, got {factor}.")+ self.factor = factor++ def forward(self, input: Tensor) -> Tensor:+ return input * self.factordiff --git a/kornia/filters/canny.py b/kornia/filters/canny.pyindex 35515bfbf..ff4f315b7 100644--- a/kornia/filters/canny.py+++ b/kornia/filters/canny.py@@ -170,6 +170,9 @@ class Canny(Module):torch.Size([5, 1, 4, 4])"""+ # TODO: Handle multiple inputs and outputs models later+ ONNX_EXPORTABLE = False+def __init__(self,low_threshold: float = 0.1,diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.pyindex d28d3f693..adb3d2437 100644--- a/kornia/filters/dexined.py+++ b/kornia/filters/dexined.py@@ -3,7 +3,7 @@from __future__ import annotationsfrom collections import OrderedDict-from typing import Optional+from typing import ClassVar, Optionalimport torchimport torch.nn.functional as F@@ -125,8 +125,7 @@ class UpConvBlock(Module):def forward(self, x: Tensor, out_shape: list[int]) -> Tensor:out = self.features(x)- if out.shape[-2:] != out_shape:- out = F.interpolate(out, out_shape, mode="bilinear")+ out = F.interpolate(out, out_shape, mode="bilinear")return out@@ -176,10 +175,13 @@ class DexiNed(Module):>>> img = torch.rand(1, 3, 320, 320)>>> net = DexiNed(pretrained=False)>>> out = net(img)- >>> out[-1].shape+ >>> out.shapetorch.Size([1, 1, 320, 320])"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]+def __init__(self, pretrained: bool) -> None:super().__init__()self.block_1 = DoubleConvBlock(3, 32, 64, stride=2)@@ -225,7 +227,7 @@ class DexiNed(Module):self.load_state_dict(pretrained_dict, strict=True)self.eval()- def forward(self, x: Tensor) -> list[Tensor]:+ def get_features(self, x: Tensor) -> list[Tensor]:# Block 1block_1 = self.block_1(x)block_1_side = self.side_1(block_1)@@ -269,11 +271,13 @@ class DexiNed(Module):out_5 = self.up_block_5(block_5, out_shape)out_6 = self.up_block_6(block_6, out_shape)results = [out_1, out_2, out_3, out_4, out_5, out_6]+ return results++ def forward(self, x: Tensor) -> Tensor:+ features = self.get_features(x)# concatenate multiscale outputs- block_cat = concatenate(results, 1) # Bx6xHxW+ block_cat = concatenate(features, 1) # Bx6xHxWblock_cat = self.block_cat(block_cat) # Bx1xHxW- # return results- results.append(block_cat)- return results+ return block_catdiff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 985004101..f084036eb 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -1,5 +1,7 @@from __future__ import annotations+from typing import ClassVar+from kornia.core import ImageModule as Modulefrom kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECK@@ -84,6 +86,10 @@ class MotionBlur3D(Module):>>> output = motion_blur(input) # 2x4x5x7x9"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1, -1]+ ONNX_EXPORT_PSEUDO_SHAPE: ClassVar[list[int]] = [1, 3, 80, 80, 80]+def __init__(self,kernel_size: int,diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex f18e61cb7..6b7a04879 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -1,5 +1,7 @@from __future__ import annotations+from typing import ClassVar+import torchimport torch.nn.functional as F@@ -172,6 +174,9 @@ class SpatialGradient(Module):>>> output = SpatialGradient()(input) # 1x3x2x4x4"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, -1, 2, -1, -1]+def __init__(self, mode: str = "sobel", order: int = 1, normalized: bool = True) -> None:super().__init__()self.normalized: bool = normalized@@ -206,6 +211,9 @@ class SpatialGradient3d(Module):torch.Size([1, 4, 3, 2, 4, 4])"""+ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1, -1, -1]+def __init__(self, mode: str = "diff", order: int = 1) -> None:super().__init__()self.order: int = orderdiff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex c85c5ddf3..1e5450f97 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -2,9 +2,9 @@ import warningsfrom typing import Optional, Tuple, Unionimport torch-from torch import nn-from kornia.core import ones, ones_like, zeros+from kornia.core import ImageModule as Module+from kornia.core import Tensor, ones, ones_like, zerosfrom kornia.filters import gaussian_blur2dfrom kornia.utils import _extract_device_dtypefrom kornia.utils.image import perform_keep_shape_image@@ -21,6 +21,7 @@ __all__ = ["translate","shear","resize",+ "resize_to_be_divisible","rescale","Scale","Rotate",@@ -34,18 +35,18 @@ __all__ = [# utilities to compute affine matrices-def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:+def _compute_tensor_center(tensor: Tensor) -> Tensor:"""Compute the center of tensor plane for (H, W), (C, H, W) and (B, C, H, W)."""if not 2 <= len(tensor.shape) <= 4:raise AssertionError(f"Must be a 3D tensor as HW, CHW and BCHW. Got {tensor.shape}.")height, width = tensor.shape[-2:]center_x: float = float(width - 1) / 2center_y: float = float(height - 1) / 2- center: torch.Tensor = torch.tensor([center_x, center_y], device=tensor.device, dtype=tensor.dtype)+ center: Tensor = torch.tensor([center_x, center_y], device=tensor.device, dtype=tensor.dtype)return center-def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:+def _compute_tensor_center3d(tensor: Tensor) -> Tensor:"""Compute the center of tensor plane for (D, H, W), (C, D, H, W) and (B, C, D, H, W)."""if not 3 <= len(tensor.shape) <= 5:raise AssertionError(f"Must be a 3D tensor as DHW, CDHW and BCDHW. Got {tensor.shape}.")@@ -53,20 +54,18 @@ def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:center_x: float = float(width - 1) / 2center_y: float = float(height - 1) / 2center_z: float = float(depth - 1) / 2- center: torch.Tensor = torch.tensor([center_x, center_y, center_z], device=tensor.device, dtype=tensor.dtype)+ center: Tensor = torch.tensor([center_x, center_y, center_z], device=tensor.device, dtype=tensor.dtype)return center-def _compute_rotation_matrix(angle: torch.Tensor, center: torch.Tensor) -> torch.Tensor:+def _compute_rotation_matrix(angle: Tensor, center: Tensor) -> Tensor:"""Compute a pure affine rotation matrix."""- scale: torch.Tensor = ones_like(center)- matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)+ scale: Tensor = ones_like(center)+ matrix: Tensor = get_rotation_matrix2d(center, angle, scale)return matrix-def _compute_rotation_matrix3d(- yaw: torch.Tensor, pitch: torch.Tensor, roll: torch.Tensor, center: torch.Tensor-) -> torch.Tensor:+def _compute_rotation_matrix3d(yaw: Tensor, pitch: Tensor, roll: Tensor, center: Tensor) -> Tensor:"""Compute a pure affine rotation matrix."""if len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 0:yaw = yaw.unsqueeze(dim=0)@@ -81,15 +80,15 @@ def _compute_rotation_matrix3d(if not (len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 2):raise AssertionError(f"Expected yaw, pitch, roll to be (B, 1). Got {yaw.shape}, {pitch.shape}, {roll.shape}.")- angles: torch.Tensor = torch.cat([yaw, pitch, roll], dim=1)- scales: torch.Tensor = ones_like(yaw)- matrix: torch.Tensor = get_projective_transform(center, angles, scales)+ angles: Tensor = torch.cat([yaw, pitch, roll], dim=1)+ scales: Tensor = ones_like(yaw)+ matrix: Tensor = get_projective_transform(center, angles, scales)return matrix-def _compute_translation_matrix(translation: torch.Tensor) -> torch.Tensor:+def _compute_translation_matrix(translation: Tensor) -> Tensor:"""Compute affine matrix for translation."""- matrix: torch.Tensor = eye_like(3, translation, shared_memory=False)+ matrix: Tensor = eye_like(3, translation, shared_memory=False)dx, dy = torch.chunk(translation, chunks=2, dim=-1)matrix[..., 0, 2:3] += dx@@ -97,16 +96,16 @@ def _compute_translation_matrix(translation: torch.Tensor) -> torch.Tensor:return matrix-def _compute_scaling_matrix(scale: torch.Tensor, center: torch.Tensor) -> torch.Tensor:+def _compute_scaling_matrix(scale: Tensor, center: Tensor) -> Tensor:"""Compute affine matrix for scaling."""- angle: torch.Tensor = zeros(scale.shape[:1], device=scale.device, dtype=scale.dtype)- matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)+ angle: Tensor = zeros(scale.shape[:1], device=scale.device, dtype=scale.dtype)+ matrix: Tensor = get_rotation_matrix2d(center, angle, scale)return matrix-def _compute_shear_matrix(shear: torch.Tensor) -> torch.Tensor:+def _compute_shear_matrix(shear: Tensor) -> Tensor:"""Compute affine matrix for shearing."""- matrix: torch.Tensor = eye_like(3, shear, shared_memory=False)+ matrix: Tensor = eye_like(3, shear, shared_memory=False)shx, shy = torch.chunk(shear, chunks=2, dim=-1)matrix[..., 0, 1:2] += shx@@ -119,12 +118,12 @@ def _compute_shear_matrix(shear: torch.Tensor) -> torch.Tensor:def affine(- tensor: torch.Tensor,- matrix: torch.Tensor,+ tensor: Tensor,+ matrix: Tensor,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = True,-) -> torch.Tensor:+) -> Tensor:r"""Apply an affine transformation to the image... image:: _static/img/warp_affine.png@@ -160,7 +159,7 @@ def affine(# warp the input tensorheight: int = tensor.shape[-2]width: int = tensor.shape[-1]- warped: torch.Tensor = warp_affine(tensor, matrix, (height, width), mode, padding_mode, align_corners)+ warped: Tensor = warp_affine(tensor, matrix, (height, width), mode, padding_mode, align_corners)# return in the original shapeif is_unbatched:@@ -170,12 +169,12 @@ def affine(def affine3d(- tensor: torch.Tensor,- matrix: torch.Tensor,+ tensor: Tensor,+ matrix: Tensor,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = False,-) -> torch.Tensor:+) -> Tensor:r"""Apply an affine transformation to the 3d volume.Args:@@ -211,7 +210,7 @@ def affine3d(depth: int = tensor.shape[-3]height: int = tensor.shape[-2]width: int = tensor.shape[-1]- warped: torch.Tensor = warp_affine3d(tensor, matrix, (depth, height, width), mode, padding_mode, align_corners)+ warped: Tensor = warp_affine3d(tensor, matrix, (depth, height, width), mode, padding_mode, align_corners)# return in the original shapeif is_unbatched:@@ -225,13 +224,13 @@ def affine3d(def rotate(- tensor: torch.Tensor,- angle: torch.Tensor,- center: Union[None, torch.Tensor] = None,+ tensor: Tensor,+ angle: Tensor,+ center: Union[None, Tensor] = None,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = True,-) -> torch.Tensor:+) -> Tensor:r"""Rotate the tensor anti-clockwise about the center... image:: _static/img/rotate.png@@ -262,14 +261,14 @@ def rotate(>>> print(out.shape)torch.Size([1, 3, 4, 4])"""- if not isinstance(tensor, torch.Tensor):- raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")+ if not isinstance(tensor, Tensor):+ raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")- if not isinstance(angle, torch.Tensor):- raise TypeError(f"Input angle type is not a torch.Tensor. Got {type(angle)}")+ if not isinstance(angle, Tensor):+ raise TypeError(f"Input angle type is not a Tensor. Got {type(angle)}")- if center is not None and not isinstance(center, torch.Tensor):- raise TypeError(f"Input center type is not a torch.Tensor. Got {type(center)}")+ if center is not None and not isinstance(center, Tensor):+ raise TypeError(f"Input center type is not a Tensor. Got {type(center)}")if len(tensor.shape) not in (3, 4):raise ValueError(f"Invalid tensor shape, we expect CxHxW or BxCxHxW. Got: {tensor.shape}")@@ -282,22 +281,22 @@ def rotate(# TODO: add broadcasting to get_rotation_matrix2d for centerangle = angle.expand(tensor.shape[0])center = center.expand(tensor.shape[0], -1)- rotation_matrix: torch.Tensor = _compute_rotation_matrix(angle, center)+ rotation_matrix: Tensor = _compute_rotation_matrix(angle, center)# warp using the affine transformreturn affine(tensor, rotation_matrix[..., :2, :3], mode, padding_mode, align_corners)def rotate3d(- tensor: torch.Tensor,- yaw: torch.Tensor,- pitch: torch.Tensor,- roll: torch.Tensor,- center: Union[None, torch.Tensor] = None,+ tensor: Tensor,+ yaw: Tensor,+ pitch: Tensor,+ roll: Tensor,+ center: Union[None, Tensor] = None,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = False,-) -> torch.Tensor:+) -> Tensor:r"""Rotate 3D the tensor anti-clockwise about the centre.Args:@@ -318,22 +317,22 @@ def rotate3d(align_corners: interpolation flag.Returns:- torch.Tensor: The rotated tensor with shape as input.+ Tensor: The rotated tensor with shape as input."""- if not isinstance(tensor, torch.Tensor):- raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")+ if not isinstance(tensor, Tensor):+ raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")- if not isinstance(yaw, torch.Tensor):- raise TypeError(f"yaw is not a torch.Tensor. Got {type(yaw)}")+ if not isinstance(yaw, Tensor):+ raise TypeError(f"yaw is not a Tensor. Got {type(yaw)}")- if not isinstance(pitch, torch.Tensor):- raise TypeError(f"pitch is not a torch.Tensor. Got {type(pitch)}")+ if not isinstance(pitch, Tensor):+ raise TypeError(f"pitch is not a Tensor. Got {type(pitch)}")- if not isinstance(roll, torch.Tensor):- raise TypeError(f"roll is not a torch.Tensor. Got {type(roll)}")+ if not isinstance(roll, Tensor):+ raise TypeError(f"roll is not a Tensor. Got {type(roll)}")- if center is not None and not isinstance(center, torch.Tensor):- raise TypeError(f"Input center type is not a torch.Tensor. Got {type(center)}")+ if center is not None and not isinstance(center, Tensor):+ raise TypeError(f"Input center type is not a Tensor. Got {type(center)}")if len(tensor.shape) not in (4, 5):raise ValueError(f"Invalid tensor shape, we expect CxDxHxW or BxCxDxHxW. Got: {tensor.shape}")@@ -348,19 +347,19 @@ def rotate3d(pitch = pitch.expand(tensor.shape[0])roll = roll.expand(tensor.shape[0])center = center.expand(tensor.shape[0], -1)- rotation_matrix: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center)+ rotation_matrix: Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center)# warp using the affine transformreturn affine3d(tensor, rotation_matrix[..., :3, :4], mode, padding_mode, align_corners)def translate(- tensor: torch.Tensor,- translation: torch.Tensor,+ tensor: Tensor,+ translation: Tensor,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = True,-) -> torch.Tensor:+) -> Tensor:r"""Translate the tensor in pixel units... image:: _static/img/translate.png@@ -386,30 +385,30 @@ def translate(>>> print(out.shape)torch.Size([1, 3, 4, 4])"""- if not isinstance(tensor, torch.Tensor):- raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")+ if not isinstance(tensor, Tensor):+ raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")- if not isinstance(translation, torch.Tensor):- raise TypeError(f"Input translation type is not a torch.Tensor. Got {type(translation)}")+ if not isinstance(translation, Tensor):+ raise TypeError(f"Input translation type is not a Tensor. Got {type(translation)}")if len(tensor.shape) not in (3, 4):raise ValueError(f"Invalid tensor shape, we expect CxHxW or BxCxHxW. Got: {tensor.shape}")# compute the translation matrix- translation_matrix: torch.Tensor = _compute_translation_matrix(translation)+ translation_matrix: Tensor = _compute_translation_matrix(translation)# warp using the affine transformreturn affine(tensor, translation_matrix[..., :2, :3], mode, padding_mode, align_corners)def scale(- tensor: torch.Tensor,- scale_factor: torch.Tensor,- center: Union[None, torch.Tensor] = None,+ tensor: Tensor,+ scale_factor: Tensor,+ center: Union[None, Tensor] = None,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = True,-) -> torch.Tensor:+) -> Tensor:r"""Scale the tensor by a factor... image:: _static/img/scale.png@@ -439,11 +438,11 @@ def scale(>>> print(out.shape)torch.Size([1, 3, 4, 4])"""- if not isinstance(tensor, torch.Tensor):- raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")+ if not isinstance(tensor, Tensor):+ raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")- if not isinstance(scale_factor, torch.Tensor):- raise TypeError(f"Input scale_factor type is not a torch.Tensor. Got {type(scale_factor)}")+ if not isinstance(scale_factor, Tensor):+ raise TypeError(f"Input scale_factor type is not a Tensor. Got {type(scale_factor)}")if len(scale_factor.shape) == 1:# convert isotropic scaling to x-y direction@@ -457,19 +456,19 @@ def scale(# TODO: add broadcasting to get_rotation_matrix2d for centercenter = center.expand(tensor.shape[0], -1)scale_factor = scale_factor.expand(tensor.shape[0], 2)- scaling_matrix: torch.Tensor = _compute_scaling_matrix(scale_factor, center)+ scaling_matrix: Tensor = _compute_scaling_matrix(scale_factor, center)# warp using the affine transformreturn affine(tensor, scaling_matrix[..., :2, :3], mode, padding_mode, align_corners)def shear(- tensor: torch.Tensor,- shear: torch.Tensor,+ tensor: Tensor,+ shear: Tensor,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = False,-) -> torch.Tensor:+) -> Tensor:r"""Shear the tensor... image:: _static/img/shear.png@@ -495,17 +494,17 @@ def shear(>>> print(out.shape)torch.Size([1, 3, 4, 4])"""- if not isinstance(tensor, torch.Tensor):- raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")+ if not isinstance(tensor, Tensor):+ raise TypeError(f"Input tensor type is not a Tensor. Got {type(tensor)}")- if not isinstance(shear, torch.Tensor):- raise TypeError(f"Input shear type is not a torch.Tensor. Got {type(shear)}")+ if not isinstance(shear, Tensor):+ raise TypeError(f"Input shear type is not a Tensor. Got {type(shear)}")if len(tensor.shape) not in (3, 4):raise ValueError(f"Invalid tensor shape, we expect CxHxW or BxCxHxW. Got: {tensor.shape}")# compute the translation matrix- shear_matrix: torch.Tensor = _compute_shear_matrix(shear)+ shear_matrix: Tensor = _compute_shear_matrix(shear)# warp using the affine transformreturn affine(tensor, shear_matrix[..., :2, :3], mode, padding_mode, align_corners)@@ -525,14 +524,14 @@ def _side_to_image_size(side_size: int, aspect_ratio: float, side: str = "short"@perform_keep_shape_imagedef resize(- input: torch.Tensor,+ input: Tensor,size: Union[int, Tuple[int, int]],interpolation: str = "bilinear",align_corners: Optional[bool] = None,side: str = "short",antialias: bool = False,-) -> torch.Tensor:- r"""Resize the input torch.Tensor to the given size.+) -> Tensor:+ r"""Resize the input Tensor to the given size... image:: _static/img/resize.png@@ -560,8 +559,8 @@ def resize(>>> print(out.shape)torch.Size([1, 3, 6, 8])"""- if not isinstance(input, torch.Tensor):- raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(input)}")+ if not isinstance(input, Tensor):+ raise TypeError(f"Input tensor type is not a Tensor. Got {type(input)}")if len(input.shape) < 2:raise ValueError(f"Input tensor must have at least two dimensions. Got {len(input.shape)}")@@ -606,14 +605,48 @@ def resize(return output+def resize_to_be_divisible(+ input: Tensor,+ divisible_factor: int,+ interpolation: str = "bilinear",+ align_corners: Optional[bool] = None,+ side: str = "short",+ antialias: bool = False,+) -> Tensor:+ """Resize the input tensor to be divisible by a certain factor.++ Args:+ input (Tensor): Input tensor to be resized.+ divisible_factor (int): The factor to which the image should be divisible.+ interpolation (str, optional): Interpolation flag. Defaults to "bilinear".+ align_corners (Optional[bool], optional):+ whether to align the corners of the input and output. Defaults to None.+ side (str, optional): Side to resize. Defaults to "short".+ antialias (bool, optional):+ If True, then image will be filtered with Gaussian before downscaling. Defaults to False.++ Returns:+ Tensor: The resized tensor.+ """++ if isinstance(input, Tensor) and len(input.shape) == 4:+ height, width = input.shape[2], input.shape[3]+ if isinstance(input, Tensor) and len(input.shape) == 3:+ height, width = input.shape[1], input.shape[2]++ height = round(height / divisible_factor) * divisible_factor+ width = round(width / divisible_factor) * divisible_factor+ return resize(input, (height, width), interpolation, align_corners, side, antialias)++def rescale(- input: torch.Tensor,+ input: Tensor,factor: Union[float, Tuple[float, float]],interpolation: str = "bilinear",align_corners: Optional[bool] = None,antialias: bool = False,-) -> torch.Tensor:- r"""Rescale the input torch.Tensor with the given factor.+) -> Tensor:+ r"""Rescale the input Tensor with the given factor... image:: _static/img/rescale.png@@ -648,8 +681,8 @@ def rescale(return resize(input, size, interpolation=interpolation, align_corners=align_corners, antialias=antialias)-class Resize(nn.Module):- r"""Resize the input torch.Tensor to the given size.+class Resize(Module):+ r"""Resize the input Tensor to the given size.Args:size: Desired output size. If size is a sequence like (h, w),@@ -693,7 +726,7 @@ class Resize(nn.Module):self.side: str = sideself.antialias: bool = antialias- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return resize(input,self.size,@@ -704,7 +737,7 @@ class Resize(nn.Module):)-class Affine(nn.Module):+class Affine(Module):r"""Apply multiple elementary affine transforms simultaneously.Args:@@ -741,11 +774,11 @@ class Affine(nn.Module):def __init__(self,- angle: Optional[torch.Tensor] = None,- translation: Optional[torch.Tensor] = None,- scale_factor: Optional[torch.Tensor] = None,- shear: Optional[torch.Tensor] = None,- center: Optional[torch.Tensor] = None,+ angle: Optional[Tensor] = None,+ translation: Optional[Tensor] = None,+ scale_factor: Optional[Tensor] = None,+ shear: Optional[Tensor] = None,+ center: Optional[Tensor] = None,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = True,@@ -785,7 +818,7 @@ class Affine(nn.Module):self.padding_mode = padding_modeself.align_corners = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:if self.shear is None:sx = sy = Noneelse:@@ -800,8 +833,8 @@ class Affine(nn.Module):return affine(input, matrix[..., :2, :3], self.mode, self.padding_mode, self.align_corners)-class Rescale(nn.Module):- r"""Rescale the input torch.Tensor with the given factor.+class Rescale(Module):+ r"""Rescale the input Tensor with the given factor.Args:factor: Desired scaling factor in each direction. If scalar, the value is used@@ -837,13 +870,13 @@ class Rescale(nn.Module):self.align_corners: Optional[bool] = align_cornersself.antialias: bool = antialias- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return rescale(input, self.factor, self.interpolation, align_corners=self.align_corners, antialias=self.antialias)-class Rotate(nn.Module):+class Rotate(Module):r"""Rotate the tensor anti-clockwise about the centre.Args:@@ -871,24 +904,24 @@ class Rotate(nn.Module):def __init__(self,- angle: torch.Tensor,- center: Union[None, torch.Tensor] = None,+ angle: Tensor,+ center: Union[None, Tensor] = None,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = True,) -> None:super().__init__()- self.angle: torch.Tensor = angle- self.center: Union[None, torch.Tensor] = center+ self.angle: Tensor = angle+ self.center: Union[None, Tensor] = centerself.mode: str = modeself.padding_mode: str = padding_modeself.align_corners: bool = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return rotate(input, self.angle, self.center, self.mode, self.padding_mode, self.align_corners)-class Translate(nn.Module):+class Translate(Module):r"""Translate the tensor in pixel units.Args:@@ -913,19 +946,19 @@ class Translate(nn.Module):"""def __init__(- self, translation: torch.Tensor, mode: str = "bilinear", padding_mode: str = "zeros", align_corners: bool = True+ self, translation: Tensor, mode: str = "bilinear", padding_mode: str = "zeros", align_corners: bool = True) -> None:super().__init__()- self.translation: torch.Tensor = translation+ self.translation: Tensor = translationself.mode: str = modeself.padding_mode: str = padding_modeself.align_corners: bool = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return translate(input, self.translation, self.mode, self.padding_mode, self.align_corners)-class Scale(nn.Module):+class Scale(Module):r"""Scale the tensor by a factor.Args:@@ -955,24 +988,24 @@ class Scale(nn.Module):def __init__(self,- scale_factor: torch.Tensor,- center: Union[None, torch.Tensor] = None,+ scale_factor: Tensor,+ center: Union[None, Tensor] = None,mode: str = "bilinear",padding_mode: str = "zeros",align_corners: bool = True,) -> None:super().__init__()- self.scale_factor: torch.Tensor = scale_factor- self.center: Union[None, torch.Tensor] = center+ self.scale_factor: Tensor = scale_factor+ self.center: Union[None, Tensor] = centerself.mode: str = modeself.padding_mode: str = padding_modeself.align_corners: bool = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return scale(input, self.scale_factor, self.center, self.mode, self.padding_mode, self.align_corners)-class Shear(nn.Module):+class Shear(Module):r"""Shear the tensor.Args:@@ -997,13 +1030,13 @@ class Shear(nn.Module):"""def __init__(- self, shear: torch.Tensor, mode: str = "bilinear", padding_mode: str = "zeros", align_corners: bool = True+ self, shear: Tensor, mode: str = "bilinear", padding_mode: str = "zeros", align_corners: bool = True) -> None:super().__init__()- self.shear: torch.Tensor = shear+ self.shear: Tensor = shearself.mode: str = modeself.padding_mode: str = padding_modeself.align_corners: bool = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return shear(input, self.shear, self.mode, self.padding_mode, self.align_corners)diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.pyindex 6519725dd..cd0030347 100644--- a/kornia/geometry/transform/flips.py+++ b/kornia/geometry/transform/flips.py@@ -1,6 +1,7 @@import torch-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensor__all__ = ["Vflip", "Hflip", "Rot180", "rot180", "hflip", "vflip"]diff --git a/kornia/io/io.py b/kornia/io/io.pyindex 1e8797d8b..a0bb81cfe 100644--- a/kornia/io/io.py+++ b/kornia/io/io.py@@ -6,9 +6,7 @@ from pathlib import Pathimport kornia_rsimport torch-from kornia.color import rgb_to_grayscale, rgba_to_rgb-from kornia.color.gray import grayscale_to_rgb-from kornia.color.rgb import rgb_to_rgba+import korniafrom kornia.core import Device, Tensorfrom kornia.core.check import KORNIA_CHECKfrom kornia.utils import image_to_tensor, tensor_to_image@@ -90,39 +88,39 @@ def load_image(if image.shape[0] == 1 and image.dtype == torch.uint8:return imageelif image.shape[0] == 3 and image.dtype == torch.uint8:- gray8 = rgb_to_grayscale(image)+ gray8 = kornia.color.rgb_to_grayscale(image)return gray8elif image.shape[0] == 4 and image.dtype == torch.uint8:- gray32 = rgb_to_grayscale(rgba_to_rgb(_to_float32(image)))+ gray32 = kornia.color.rgb_to_grayscale(kornia.color.rgba_to_rgb(_to_float32(image)))return _to_uint8(gray32)elif desired_type == ImageLoadType.RGB8:if image.shape[0] == 3 and image.dtype == torch.uint8:return imageelif image.shape[0] == 1 and image.dtype == torch.uint8:- rgb8 = grayscale_to_rgb(image)+ rgb8 = kornia.color.grayscale_to_rgb(image)return rgb8elif desired_type == ImageLoadType.RGBA8:if image.shape[0] == 3 and image.dtype == torch.uint8:- rgba32 = rgb_to_rgba(_to_float32(image), 0.0)+ rgba32 = kornia.color.rgb_to_rgba(_to_float32(image), 0.0)return _to_uint8(rgba32)elif desired_type == ImageLoadType.GRAY32:if image.shape[0] == 1 and image.dtype == torch.uint8:return _to_float32(image)elif image.shape[0] == 3 and image.dtype == torch.uint8:- gray32 = rgb_to_grayscale(_to_float32(image))+ gray32 = kornia.color.rgb_to_grayscale(_to_float32(image))return gray32elif image.shape[0] == 4 and image.dtype == torch.uint8:- gray32 = rgb_to_grayscale(rgba_to_rgb(_to_float32(image)))+ gray32 = kornia.color.rgb_to_grayscale(kornia.color.rgba_to_rgb(_to_float32(image)))return gray32elif desired_type == ImageLoadType.RGB32:if image.shape[0] == 3 and image.dtype == torch.uint8:return _to_float32(image)elif image.shape[0] == 1 and image.dtype == torch.uint8:- rgb32 = grayscale_to_rgb(_to_float32(image))+ rgb32 = kornia.color.grayscale_to_rgb(_to_float32(image))return rgb32raise NotImplementedError(f"Unknown type: {desired_type}")diff --git a/kornia/models/__init__.py b/kornia/models/__init__.pyindex e69de29bb..0d5b1c776 100644--- a/kornia/models/__init__.py+++ b/kornia/models/__init__.py@@ -0,0 +1,9 @@+from . import (+ depth_estimation,+ detection,+ edge_detection,+ segmentation,+ super_resolution,+ tracking,+)+from .utils import *diff --git a/kornia/models/_hf_models/__init__.py b/kornia/models/_hf_models/__init__.pynew file mode 100644index 000000000..d971a8c7b--- /dev/null+++ b/kornia/models/_hf_models/__init__.py@@ -0,0 +1 @@+from .hf_onnx_community import HFONNXComunnityModel, HFONNXComunnityModelLoaderdiff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.pynew file mode 100644index 000000000..a440aa32c--- /dev/null+++ b/kornia/models/_hf_models/hf_onnx_community.py@@ -0,0 +1,144 @@+from __future__ import annotations+import os+from typing import Any, Optional++from kornia.config import kornia_config+from kornia.core import ImageSequential, Tensor+from kornia.core.external import onnx+from kornia.geometry.transform import resize+from kornia.models.base import ModelBaseMixin+from kornia.onnx import ONNXSequential+from kornia.onnx.utils import ONNXLoader, io_name_conversion++from .preprocessor import PreprocessingLoader+++class HFONNXComunnityModelLoader:+ f"""Initializes the ONNXComunnityModelLoader for onnx-community repo of Hugging Face.++ Args:+ model_name: The name of the model to load.+ model_type: The type of the model to load.+ cache_dir: The directory where models are cached locally.+ Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.+ with_data: Whether to download the model weights such as `model.onnx_data`.+ """++ def __init__(+ self, model_name: str, model_type: str = "model", cache_dir: Optional[str] = None, with_data: bool = False+ ) -> None:+ self.model_name = model_name+ self.model_type = model_type+ self.with_data = with_data++ if cache_dir is None:+ cache_dir = kornia_config.hub_onnx_dir+ self.cache_dir = os.path.join(cache_dir, self.model_name)+ self.model_url = (+ f"https://huggingface.co/onnx-community/{self.model_name}/resolve/main/onnx/{self.model_type}.onnx"+ )+ self.config_url = (+ f"https://huggingface.co/onnx-community/{self.model_name}/resolve/main/preprocessor_config.json"+ )++ def load_model(+ self, download: bool = True, io_name_mapping: Optional[dict[str, str]] = None, **kwargs: Any+ ) -> "onnx.ModelProto": # type:ignore+ onnx_model = ONNXLoader.load_model(+ self.model_url, download=download, with_data=self.with_data, cache_dir=self.cache_dir, **kwargs+ )++ if io_name_mapping is not None:+ onnx_model = io_name_conversion(onnx_model, io_name_mapping)++ return onnx_model++ def load_preprocessing(+ self,+ ) -> ImageSequential:+ json_req = ONNXLoader.load_config(self.config_url)+ return PreprocessingLoader.from_json(json_req)++ def _add_metadata(+ self,+ model: "onnx.ModelProto", # type:ignore+ additional_metadata: dict[str, Any] = {},+ ) -> "onnx.ModelProto": # type:ignore+ for key, value in additional_metadata.items():+ metadata_props = model.metadata_props.add()+ metadata_props.key = key+ metadata_props.value = str(value)+ return model+++class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):+ name: str = "onnx_community_model"++ def __init__(+ self,+ model: "onnx.ModelProto", # type: ignore+ pre_processor: Optional["onnx.ModelProto"] = None, # type: ignore+ post_processor: Optional["onnx.ModelProto"] = None, # type: ignore+ name: Optional[str] = None,+ auto_ir_version_conversion: bool = True,+ io_maps: Optional[list[tuple[str, str]]] = None,+ ) -> None:+ model_list = [] if pre_processor is None else [pre_processor]+ model_list.append(model)+ if post_processor is not None:+ model_list.append(post_processor)+ super().__init__(*model_list, auto_ir_version_conversion=auto_ir_version_conversion, io_maps=io_maps)+ if name is not None:+ self.name = name+ self.model = model+ self.pre_processor = pre_processor+ self.post_processor = post_processor++ def resize_back(self, images: Tensor, target_images: Tensor) -> Tensor:+ """Resize the input images back to the original size of target images.++ Args:+ images: The input images to be resized.+ target_images: The target images whose size is used as the reference for resizing.++ Returns:+ The resized images.+ """+ if isinstance(target_images, Tensor):+ return resize(images, target_images.shape[-2:])+ raise RuntimeError++ def to_onnx(+ self,+ onnx_name: Optional[str] = None,+ include_pre_and_post_processor: bool = True,+ save: bool = True,+ additional_metadata: list[tuple[str, str]] = [],+ **kwargs: Any,+ ) -> "onnx.ModelProto": # type:ignore+ """Exports a depth estimation model to ONNX format.++ Args:+ onnx_name:+ The name of the output ONNX file. If not provided, a default name in the+ format "Kornia-<ClassName>.onnx" will be used.+ include_pre_and_post_processor:+ Whether to include the pre-processor and post-processor in the exported model.+ save:+ If to save the model or load it.+ additional_metadata:+ Additional metadata to add to the ONNX model.+ """+ if onnx_name is None:+ onnx_name = f"kornia_{self.name}.onnx"++ if not include_pre_and_post_processor:+ self._add_metadata(self.model, additional_metadata)+ if save:+ self._export(self.model, onnx_name, **kwargs)+ return self.model++ self._add_metadata(self._combined_op, additional_metadata)+ if save:+ self._export(self._combined_op, onnx_name, **kwargs)+ return self._combined_opdiff --git a/kornia/models/_hf_models/preprocessor.py b/kornia/models/_hf_models/preprocessor.pynew file mode 100644index 000000000..82d6aff5b--- /dev/null+++ b/kornia/models/_hf_models/preprocessor.py@@ -0,0 +1,49 @@+from __future__ import annotations+from typing import Any++from kornia.core import ImageSequential, Module, Tensor, tensor+from kornia.enhance.normalize import Normalize+from kornia.enhance.rescale import Rescale+from kornia.geometry.transform import Resize+++class PreprocessingLoader:+ @staticmethod+ def normalize(mean: Tensor, std: Tensor) -> Normalize:+ return Normalize(mean=mean, std=std)++ @staticmethod+ def rescale(rescale_factor: float) -> Rescale:+ return Rescale(factor=rescale_factor)++ @staticmethod+ def resize(width: int, height: int) -> Resize:+ return Resize((height, width))++ @staticmethod+ def from_json(req: dict[str, Any]) -> ImageSequential:+ if req["image_processor_type"] == "DPTImageProcessor":+ return DPTImageProcessor.from_json(req)+ raise RuntimeError(f"Unsupported image processor type: {req['image_processor_type']}")+++class DPTImageProcessor(PreprocessingLoader):+ @staticmethod+ def from_json(json_data: dict[str, Any]) -> ImageSequential:+ preproc_list: list[Module] = []+ if json_data["do_pad"]:+ raise NotImplementedError+ if json_data["do_resize"]:+ # Missing some parameters such as `ensure_multiple_of`, `keep_aspect_ratio`+ preproc_list.append(+ PreprocessingLoader.resize(width=json_data["size"]["width"], height=json_data["size"]["height"])+ )+ if json_data["do_rescale"]:+ preproc_list.append(PreprocessingLoader.rescale(rescale_factor=json_data["rescale_factor"] * 255))+ if json_data["do_normalize"]:+ preproc_list.append(+ PreprocessingLoader.normalize(+ mean=tensor([json_data["image_mean"]]), std=tensor([json_data["image_std"]])+ )+ )+ return ImageSequential(*preproc_list)diff --git a/kornia/models/base.py b/kornia/models/base.pynew file mode 100644index 000000000..7fa741054--- /dev/null+++ b/kornia/models/base.py@@ -0,0 +1,91 @@+import datetime+import logging+import os+from typing import List, Optional, Union++from kornia.core import Module, Tensor, stack+from kornia.core.external import PILImage as Image+from kornia.core.external import numpy as np+from kornia.core.mixin.onnx import ONNXExportMixin+from kornia.io import write_image+from kornia.utils.image import tensor_to_image++logger = logging.getLogger(__name__)+++class ModelBaseMixin:+ name: str = "model"++ def _tensor_to_type(+ self, output: Union[Tensor, List[Tensor]], output_type: str, is_batch: bool = False+ ) -> Union[Tensor, List[Tensor], List["Image.Image"]]: # type: ignore+ """Converts the output tensor to the desired type.++ Args:+ output: The output tensor or list of tensors.+ output_type: The desired output type. Accepted values are "torch" and "pil".+ is_batch: If True, the output is expected to be a batch of tensors.++ Returns:+ The converted output tensor or list of tensors.++ Raises:+ RuntimeError: If the output type is not supported.+ """+ if output_type == "torch":+ if is_batch and not isinstance(output, Tensor):+ return stack(output)+ elif is_batch and isinstance(output, Tensor):+ return output+ elif not is_batch and isinstance(output, Tensor):+ return list(output)+ elif not is_batch and not isinstance(output, Tensor):+ return output+ return output+ elif output_type == "pil":+ out = [Image.fromarray((tensor_to_image(out_img) * 255).astype(np.uint8)) for out_img in output] # type: ignore+ return list(out)++ raise RuntimeError(f"Unsupported output type `{output_type}`.")++ def _save_outputs(+ self, outputs: Union[Tensor, List[Tensor]], directory: Optional[str] = None, suffix: str = ""+ ) -> None:+ """Save the output image(s) to a directory.++ Args:+ outputs: output tensor.+ directory: directory to save the images.+ """+ if directory is None:+ name = f"{self.name}_{datetime.datetime.now(tz=datetime.timezone.utc).strftime('%Y%m%d%H%M%S')!s}"+ directory = os.path.join("kornia_outputs", name)++ os.makedirs(directory, exist_ok=True)+ for i, out_image in enumerate(outputs):+ write_image(+ os.path.join(directory, f"{str(i).zfill(6)}{suffix}.jpg"),+ out_image.mul(255.0).byte(),+ )+ logger.info(f"Outputs are saved in {directory}")+++class ModelBase(Module, ONNXExportMixin, ModelBaseMixin):+ """This class wraps a model and performs pre-processing and post-processing."""++ def __init__(+ self, model: Module, pre_processor: Module, post_processor: Module, name: Optional[str] = None+ ) -> None:+ """Construct an Object Detector object.++ Args:+ model: an object detection model.+ pre_processor: a pre-processing module+ post_processor: a post-processing module.+ """+ super().__init__()+ self.model = model.eval()+ self.pre_processor = pre_processor.eval()+ self.post_processor = post_processor.eval()+ if name is not None:+ self.name = namediff --git a/kornia/models/depth_estimation/__init__.py b/kornia/models/depth_estimation/__init__.pynew file mode 100644index 000000000..fe3fcf181--- /dev/null+++ b/kornia/models/depth_estimation/__init__.py@@ -0,0 +1,2 @@+from .base import *+from .depth_anything import *diff --git a/kornia/models/depth_estimation/base.py b/kornia/models/depth_estimation/base.pynew file mode 100644index 000000000..5bac1c7c4--- /dev/null+++ b/kornia/models/depth_estimation/base.py@@ -0,0 +1,100 @@+from __future__ import annotations++from typing import Optional, Union++from kornia.color.gray import grayscale_to_rgb+from kornia.core import Tensor, tensor+from kornia.core.external import PILImage as Image+from kornia.models._hf_models import HFONNXComunnityModel++__all__ = ["DepthEstimation"]+++class DepthEstimation(HFONNXComunnityModel):+ name: str = "depth_estimation"++ def __call__(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]: # type: ignore[override]+ """Detect objects in a given list of images.++ Args:+ images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`, where :math:`D` is the+ number of detections in the given image, :math:`6` represents class id, score, and `xywh` bounding box.+ """+ if isinstance(+ images,+ (+ list,+ tuple,+ ),+ ):+ results = [super(DepthEstimation, self).__call__(image[None].cpu().numpy())[0] for image in images]+ results = [+ self.resize_back(tensor(result, device=image.device, dtype=image.dtype), image)+ for result, image in zip(results, images)+ ]+ return results++ result = super().__call__(images.cpu().numpy())[0]+ result = tensor(result, device=images.device, dtype=images.dtype)+ return self.resize_back(result, images)++ def visualize(+ self,+ images: Tensor,+ depth_maps: Optional[Union[Tensor, list[Tensor]]] = None,+ output_type: str = "torch",+ depth_type: str = "relative",+ max_depth: int = 80,+ ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore+ """Draw the segmentation results.++ Args:+ images: input tensor.+ output_type: type of the output.+ depth_type: 'metric' or 'relative' depth.+ max_depth: maximum depth value. Only valid for metric depth.++ Returns:+ output tensor.+ """+ if depth_maps is None:+ depth_maps = self(images)+ output = []+ for depth_map in depth_maps:+ if depth_type == "metric":+ depth_map = depth_map / max_depth+ elif depth_type == "relative":+ depth_map = depth_map / depth_map.max()+ else:+ raise ValueError(f"Unsupported depth type `{depth_type}`.")+ output.append(grayscale_to_rgb(depth_map))++ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))++ def save(+ self,+ images: Tensor,+ depth_maps: Optional[Union[Tensor, list[Tensor]]] = None,+ directory: Optional[str] = None,+ output_type: str = "torch",+ depth_type: str = "relative",+ max_depth: int = 80,+ ) -> None:+ """Save the segmentation results.++ Args:+ images: input tensor.+ output_type: type of the output.+ depth_type: 'metric' or 'relative' depth.+ max_depth: maximum depth value. Only valid for metric depth.++ Returns:+ output tensor.+ """+ outputs = self.visualize(images, depth_maps, output_type, depth_type=depth_type, max_depth=max_depth)+ self._save_outputs(images, directory, suffix="_src")+ self._save_outputs(outputs, directory, suffix="_depth")diff --git a/kornia/models/depth_estimation/depth_anything.py b/kornia/models/depth_estimation/depth_anything.pynew file mode 100644index 000000000..7cde1eacb--- /dev/null+++ b/kornia/models/depth_estimation/depth_anything.py@@ -0,0 +1,55 @@+from typing import Optional++from kornia.models._hf_models import HFONNXComunnityModelLoader++from .base import DepthEstimation++__all__ = ["DepthAnythingONNXBuilder"]+++class DepthAnythingONNXBuilder:+ @staticmethod+ def build(+ model_name: str = "depth-anything-v2-small", model_type: str = "model", cache_dir: Optional[str] = None+ ) -> DepthEstimation:+ """Exports a DepthAnything model to an ONNX model file.++ Args:+ model_name: The name of the model to be loaded. Valid model names include:+ - `depth-anything-v2-small`+ - `depth-anything-v2-base`+ - `depth-anything-v2-large`+ model_type:+ The type of the model to be loaded. Valid model types include:+ - `model`+ - `model_bnb4`+ - `model_fp16`+ - `model_int8`+ - `model_q4`+ - `model_quantized`+ - `model_uint8`+ cache_dir:+ The directory where the model should be cached.++ Returns:+ str: The name of the output ONNX file.++ .. code-block:: python++ images = kornia.utils.sample.get_sample_images()+ model = DepthAnythingONNXBuilder.build()+ model.save(images)+ """+ if model_name not in [+ "depth-anything-v2-small",+ "depth-anything-v2-base",+ "depth-anything-v2-large",+ ]:+ raise ValueError(f"{model_name} is not a valid model name.")+ loader = HFONNXComunnityModelLoader(model_name, model_type=model_type, cache_dir=cache_dir)+ onnx_model = loader.load_model(+ download=True,+ io_name_mapping={"pixel_values": "input", "predicted_depth": "output"},+ )+ preproc = loader.load_preprocessing().to_onnx(save=False)+ return DepthEstimation(onnx_model, pre_processor=preproc, name=f"{model_name}_{model_type}")diff --git a/kornia/models/detection/__init__.py b/kornia/models/detection/__init__.pynew file mode 100644index 000000000..b511f133c--- /dev/null+++ b/kornia/models/detection/__init__.py@@ -0,0 +1,3 @@+from .base import *+from .rtdetr import *+from .utils import *diff --git a/kornia/models/detection/base.py b/kornia/models/detection/base.pynew file mode 100644index 000000000..45b39893d--- /dev/null+++ b/kornia/models/detection/base.py@@ -0,0 +1,217 @@+from __future__ import annotations++from dataclasses import dataclass+from enum import Enum+from typing import Any, Optional, Union++import torch++from kornia.core import Tensor+from kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.external import PILImage as Image+from kornia.core.external import onnx+from kornia.models.base import ModelBase+from kornia.utils.draw import draw_rectangle++__all__ = [+ "BoundingBoxDataFormat",+ "BoundingBox",+ "results_from_detections",+ "ObjectDetector",+ "ObjectDetectorResult",+]+++class BoundingBoxDataFormat(Enum):+ """Enum class that maps bounding box data format."""++ XYWH = 0+ XYXY = 1+ CXCYWH = 2+ CENTER_XYWH = 2+++# NOTE: probably we should use a more generic name like BoundingBox2D+# and add a BoundingBox3D class for 3D bounding boxes. Also for serialization+# we should have an explicit class for each format to make it more production ready+# specially to serialize to protobuf and not saturate at a high rates.+++@dataclass(frozen=True)+class BoundingBox:+ """Bounding box data class.++ Useful for representing bounding boxes in different formats for object detection.++ Args:+ data: tuple of bounding box data. The length of the tuple depends on the data format.+ data_format: bounding box data format.+ """++ data: tuple[float, float, float, float]+ data_format: BoundingBoxDataFormat+++@dataclass(frozen=True)+class ObjectDetectorResult:+ """Object detection result.++ Args:+ class_id: class id of the detected object.+ confidence: confidence score of the detected object.+ bbox: bounding box of the detected object in xywh format.+ """++ class_id: int+ confidence: float+ bbox: BoundingBox+++def results_from_detections(detections: Tensor, format: str | BoundingBoxDataFormat) -> list[ObjectDetectorResult]:+ """Convert a detection tensor to a list of :py:class:`ObjectDetectorResult`.++ Args:+ detections: tensor with shape :math:`(D, 6)`, where :math:`D` is the number of detections in the given image,+ :math:`6` represents class id, score, and `xywh` bounding box.++ Returns:+ list of :py:class:`ObjectDetectorResult`.+ """+ KORNIA_CHECK_SHAPE(detections, ["D", "6"])++ if isinstance(format, str):+ format = BoundingBoxDataFormat[format.upper()]++ results: list[ObjectDetectorResult] = []+ for det in detections:+ det = det.squeeze().tolist()+ if len(det) != 6:+ continue+ results.append(+ ObjectDetectorResult(+ class_id=int(det[0]),+ confidence=det[1],+ bbox=BoundingBox(data=(det[2], det[3], det[4], det[5]), data_format=format),+ )+ )+ return results+++class ObjectDetector(ModelBase):+ """This class wraps an object detection model and performs pre-processing and post-processing."""++ name: str = "detection"++ @torch.inference_mode()+ def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:+ """Detect objects in a given list of images.++ Args:+ images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`, where :math:`D` is the+ number of detections in the given image, :math:`6` represents class id, score, and `xywh` bounding box.+ """+ images, images_sizes = self.pre_processor(images)+ logits, boxes = self.model(images)+ detections = self.post_processor(logits, boxes, images_sizes)+ return detections++ def visualize(+ self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, output_type: str = "torch"+ ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore+ """Very simple drawing.++ Needs to be more fancy later.+ """+ dets = detections or self.forward(images)+ output = []+ for image, detection in zip(images, dets):+ out_img = image[None].clone()+ for out in detection:+ out_img = draw_rectangle(+ out_img,+ torch.Tensor([[[out[-4], out[-3], out[-4] + out[-2], out[-3] + out[-1]]]]),+ )+ output.append(out_img[0])++ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))++ def save(+ self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, directory: Optional[str] = None+ ) -> None:+ """Saves the output image(s) to a directory.++ Args:+ images: input tensor.+ detections: detection tensor.+ directory: directory to save the images.+ """+ outputs = self.visualize(images, detections)+ self._save_outputs(outputs, directory)++ def to_onnx( # type: ignore[override]+ self,+ onnx_name: Optional[str] = None,+ image_size: Optional[int] = 640,+ include_pre_and_post_processor: bool = True,+ save: bool = True,+ additional_metadata: list[tuple[str, str]] = [],+ **kwargs: Any,+ ) -> onnx.ModelProto: # type: ignore+ """Exports an RT-DETR object detection model to ONNX format.++ Either `model_name` or `config` must be provided. If neither is provided,+ a default pretrained model (`rtdetr_r18vd`) will be built.++ Args:+ onnx_name:+ The name of the output ONNX file. If not provided, a default name in the+ format "Kornia-<ClassName>.onnx" will be used.+ image_size:+ The size to which input images will be resized during preprocessing.+ If None, image_size will be dynamic.+ For RTDETR, recommended scales include [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].+ include_pre_and_post_processor:+ Whether to include the pre-processor and post-processor in the exported model.+ save:+ If to save the model or load it.+ additional_metadata:+ Additional metadata to add to the ONNX model.+ """+ if onnx_name is None:+ onnx_name = f"kornia_{self.name}_{image_size}.onnx"++ return super().to_onnx(+ onnx_name,+ input_shape=[-1, 3, image_size or -1, image_size or -1],+ output_shape=[-1, -1, 6],+ pseudo_shape=[1, 3, image_size or 352, image_size or 352],+ model=self if include_pre_and_post_processor else self.model,+ save=save,+ additional_metadata=additional_metadata,+ **kwargs,+ )++ def compile(+ self,+ *,+ fullgraph: bool = False,+ dynamic: bool = False,+ backend: str = "inductor",+ mode: Optional[str] = None,+ options: Optional[dict[str, str | int | bool]] = None,+ disable: bool = False,+ ) -> None:+ """Compile the internal object detection model with :py:func:`torch.compile()`."""+ self.model = torch.compile( # type: ignore+ self.model,+ fullgraph=fullgraph,+ dynamic=dynamic,+ backend=backend,+ mode=mode,+ options=options,+ disable=disable,+ )diff --git a/kornia/models/detection/rtdetr.py b/kornia/models/detection/rtdetr.pynew file mode 100644index 000000000..1a076b8f4--- /dev/null+++ b/kornia/models/detection/rtdetr.py@@ -0,0 +1,89 @@+import warnings+from typing import Optional++import torch++from kornia.contrib.models.rt_detr import DETRPostProcessor+from kornia.contrib.models.rt_detr.model import RTDETR, RTDETRConfig+from kornia.models.detection.base import ObjectDetector+from kornia.models.utils import ResizePreProcessor++__all__ = ["RTDETRDetectorBuilder"]+++class RTDETRDetectorBuilder:+ """A builder class for constructing RT-DETR object detection models.++ This class provides static methods to:+ - 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)+ """++ @staticmethod+ def build(+ model_name: Optional[str] = None,+ config: Optional[RTDETRConfig] = None,+ pretrained: bool = True,+ image_size: Optional[int] = None,+ confidence_threshold: Optional[float] = None,+ confidence_filtering: Optional[bool] = None,+ ) -> ObjectDetector:+ """Builds and returns an RT-DETR object detector model.++ Either `model_name` or `config` must be provided. If neither is provided,+ a default pretrained model (`rtdetr_r18vd`) will be built.++ Args:+ model_name:+ Name of the RT-DETR model to load. Can be one of the available pretrained models.+ Including 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.+ config:+ A custom configuration object for building the RT-DETR model.+ pretrained:+ Whether to load a pretrained version of the model (applies when `model_name` is provided).+ image_size:+ The size to which input images will be resized during preprocessing.+ If None, no resizing will be inferred from config file. Recommended scales include+ [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].++ Returns:+ ObjectDetector+ An object detector instance initialized with the specified model, preprocessor, and post-processor.+ """+ if model_name is not None and config is not None:+ raise ValueError("Either `model_name` or `config` should be `None`.")++ if config is not None:+ model = RTDETR.from_config(config)+ image_size = image_size or config.input_size+ elif model_name is not None:+ if pretrained:+ model = RTDETR.from_pretrained(model_name)+ image_size = RTDETRConfig.from_name(model_name).input_size+ else:+ model = RTDETR.from_name(model_name)+ image_size = RTDETRConfig.from_name(model_name).input_size+ else:+ warnings.warn("No `model_name` or `config` found. Will build pretrained `rtdetr_r18vd`.")+ model = RTDETR.from_pretrained("rtdetr_r18vd")+ image_size = RTDETRConfig.from_name("rtdetr_r18vd").input_size++ if confidence_threshold is None:+ confidence_threshold = config.confidence_threshold if config is not None else 0.3++ return ObjectDetector(+ model,+ ResizePreProcessor(image_size, image_size),+ DETRPostProcessor(+ confidence_threshold=confidence_threshold,+ confidence_filtering=confidence_filtering or not torch.onnx.is_in_onnx_export(),+ num_classes=model.decoder.num_classes,+ num_top_queries=model.decoder.num_queries,+ ),+ )diff --git a/kornia/models/detection/utils.py b/kornia/models/detection/utils.pynew file mode 100644index 000000000..5699c45d7--- /dev/null+++ b/kornia/models/detection/utils.py@@ -0,0 +1,105 @@+from typing import Any, ClassVar, List, Optional, Tuple, Union++from kornia.core import Module, Tensor, rand, tensor+from kornia.core.mixin.onnx import ONNXExportMixin++__all__ = ["BoxFiltering"]+++class BoxFiltering(Module, ONNXExportMixin):+ """Filter boxes according to the desired threshold.++ Args:+ confidence_threshold: an 0-d scalar that represents the desired threshold.+ classes_to_keep: a 1-d list of classes to keep. If None, keep all classes.+ filter_as_zero: whether to filter boxes as zero.+ """++ ONNX_DEFAULT_INPUTSHAPE: ClassVar[List[int]] = [-1, -1, 6]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[List[int]] = [-1, -1, 6]+ ONNX_EXPORT_PSEUDO_SHAPE: ClassVar[List[int]] = [5, 20, 6]++ def __init__(+ self,+ confidence_threshold: Optional[Union[Tensor, float]] = None,+ classes_to_keep: Optional[Union[Tensor, List[int]]] = None,+ filter_as_zero: bool = False,+ ) -> None:+ super().__init__()+ self.filter_as_zero = filter_as_zero+ self.classes_to_keep = None+ self.confidence_threshold = None+ if classes_to_keep is not None:+ self.classes_to_keep = classes_to_keep if isinstance(classes_to_keep, Tensor) else tensor(classes_to_keep)+ if confidence_threshold is not None:+ self.confidence_threshold = (+ confidence_threshold or confidence_threshold+ if isinstance(confidence_threshold, Tensor)+ else tensor(confidence_threshold)+ )++ def forward(+ self, boxes: Tensor, confidence_threshold: Optional[Tensor] = None, classes_to_keep: Optional[Tensor] = None+ ) -> Union[Tensor, List[Tensor]]:+ """Filter boxes according to the desired threshold.++ To be ONNX-friendly, the inputs for direct forwarding need to be all tensors.++ Args:+ boxes: [B, D, 6], where B is the batchsize, D is the number of detections in the image,+ 6 represent (class_id, confidence_score, x, y, w, h).+ confidence_threshold: an 0-d scalar that represents the desired threshold.+ classes_to_keep: a 1-d tensor of classes to keep. If None, keep all classes.++ Returns:+ Union[Tensor, List[Tensor]]+ If `filter_as_zero` is True, return a tensor of shape [D, 6], where D is the total number of+ detections as input.+ If `filter_as_zero` is False, return a list of tensors of shape [D, 6], where D is the number of+ valid detections for each element in the batch.+ """+ # Apply confidence filtering+ zero_tensor = tensor(0.0, device=boxes.device, dtype=boxes.dtype)+ confidence_threshold = (+ confidence_threshold or self.confidence_threshold or zero_tensor+ ) # If None, use 0 as threshold+ confidence_mask = boxes[:, :, 1] > confidence_threshold # [B, D]++ # Apply class filtering+ classes_to_keep = classes_to_keep or self.classes_to_keep+ if classes_to_keep is not None:+ class_ids = boxes[:, :, 0:1] # [B, D, 1]+ classes_to_keep = classes_to_keep.view(1, 1, -1) # [1, 1, C] for broadcasting+ class_mask = (class_ids == classes_to_keep).any(dim=-1) # [B, D]+ else:+ # If no class filtering is needed, just use a mask of all `True`+ class_mask = (confidence_mask * 0 + 1).bool()++ # Combine the confidence and class masks+ combined_mask = confidence_mask & class_mask # [B, D]++ if self.filter_as_zero:+ filtered_boxes = boxes * combined_mask[:, :, None]+ return filtered_boxes++ filtered_boxes_list = []+ for i in range(boxes.shape[0]):+ box = boxes[i]+ mask = combined_mask[i] # [D]+ valid_boxes = box[mask]+ filtered_boxes_list.append(valid_boxes)++ return filtered_boxes_list++ def _create_dummy_input(+ self, input_shape: List[int], pseudo_shape: Optional[List[int]] = None+ ) -> Union[Tuple[Any, ...], Tensor]:+ pseudo_input = rand(+ *[+ ((self.ONNX_EXPORT_PSEUDO_SHAPE[i] if pseudo_shape is None else pseudo_shape[i]) if dim == -1 else dim)+ for i, dim in enumerate(input_shape)+ ]+ )+ if self.confidence_threshold is None:+ return pseudo_input, 0.1+ return pseudo_inputdiff --git a/kornia/models/detector/__init__.py b/kornia/models/detector/__init__.pydeleted file mode 100644index 55a62efc2..000000000--- a/kornia/models/detector/__init__.py+++ /dev/null@@ -1 +0,0 @@-from .rtdetr import *diff --git a/kornia/models/detector/rtdetr.py b/kornia/models/detector/rtdetr.pydeleted file mode 100644index f6ed6a3a4..000000000--- a/kornia/models/detector/rtdetr.py+++ /dev/null@@ -1,154 +0,0 @@-import warnings-from typing import Optional--import torch-from torch import nn--from kornia.contrib.models.rt_detr import DETRPostProcessor-from kornia.contrib.models.rt_detr.model import RTDETR, RTDETRConfig-from kornia.contrib.object_detection import ObjectDetector, ResizePreProcessor-from kornia.core import rand--__all__ = ["RTDETRDetectorBuilder"]---class RTDETRDetectorBuilder:- """A builder class for constructing RT-DETR object detection models.-- This class provides static methods to:- - Build an object detection model from a model name or configuration.- - Export the model to ONNX format for inference.- """-- @staticmethod- def build(- model_name: Optional[str] = None,- config: Optional[RTDETRConfig] = None,- pretrained: bool = True,- image_size: Optional[int] = 640,- confidence_threshold: float = 0.5,- confidence_filtering: Optional[bool] = None,- ) -> ObjectDetector:- """Builds and returns an RT-DETR object detector model.-- Either `model_name` or `config` must be provided. If neither is provided,- a default pretrained model (`rtdetr_r18vd`) will be built.-- Args:- model_name:- Name of the RT-DETR model to load. Can be one of the available pretrained models.- Including 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.- config:- A custom configuration object for building the RT-DETR model.- pretrained:- Whether to load a pretrained version of the model (applies when `model_name` is provided).- image_size:- The size to which input images will be resized during preprocessing.- If None, no resizing will be performed before passing to the model. Recommended scales include- [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].- confidence_threshold:- The confidence threshold used during post-processing to filter detections.- confidence_filtering:- If to perform filtering on resulting boxes. If None, the filtering will be blocked when exporting- to ONNX, while it would perform as per confidence_threshold when build the model.-- Returns:- ObjectDetector- An object detector instance initialized with the specified model, preprocessor, and post-processor.- """- if model_name is not None and config is not None:- raise ValueError("Either `model_name` or `config` should be `None`.")-- if config is not None:- model = RTDETR.from_config(config)- elif model_name is not None:- if pretrained:- model = RTDETR.from_pretrained(model_name)- else:- model = RTDETR.from_name(model_name)- else:- warnings.warn("No `model_name` or `config` found. Will build pretrained `rtdetr_r18vd`.")- model = RTDETR.from_pretrained("rtdetr_r18vd")-- return ObjectDetector(- model,- ResizePreProcessor((image_size, image_size)) if image_size is not None else nn.Identity(),- DETRPostProcessor(- confidence_threshold,- num_classes=config.num_classes if config is not None else 80,- confidence_filtering=confidence_filtering or not torch.onnx.is_in_onnx_export(),- ),- )-- @staticmethod- def to_onnx(- model_name: Optional[str] = None,- onnx_name: Optional[str] = None,- config: Optional[RTDETRConfig] = None,- pretrained: bool = True,- image_size: Optional[int] = 640,- confidence_threshold: float = 0.5,- confidence_filtering: Optional[bool] = None,- ) -> tuple[str, ObjectDetector]:- """Exports an RT-DETR object detection model to ONNX format.-- Either `model_name` or `config` must be provided. If neither is provided,- a default pretrained model (`rtdetr_r18vd`) will be built.-- Args:- model_name:- Name of the RT-DETR model to load. Can be one of the available pretrained models.- config:- A custom configuration object for building the RT-DETR model.- pretrained:- Whether to load a pretrained version of the model (applies when `model_name` is provided).- image_size:- The size to which input images will be resized during preprocessing.- If None, image_size will be dynamic. Recommended scales include- [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].- confidence_threshold:- The confidence threshold used during post-processing to filter detections.- confidence_filtering:- If to perform filtering on resulting boxes. If None, the filtering will be blocked when exporting- to ONNX, while it would perform as per confidence_threshold when build the model.-- Returns:- - The name of the ONNX model.- - The exported torch model.- """-- detector = RTDETRDetectorBuilder.build(- model_name=model_name,- config=config,- pretrained=pretrained,- image_size=image_size,- confidence_threshold=confidence_threshold,- confidence_filtering=confidence_filtering,- )- if onnx_name is None:- _model_name = model_name- if model_name is None and config is not None:- _model_name = "rtdetr-customized"- elif model_name is None and config is None:- _model_name = "rtdetr_r18vd"- onnx_name = f"Kornia-RTDETR-{_model_name}-{image_size}.onnx"-- if image_size is None:- val_image = rand(1, 3, 640, 640)- else:- val_image = rand(1, 3, image_size, image_size)-- dynamic_axes = {"input": {0: "batch_size", 2: "height", 3: "width"}, "output": {0: "batch_size"}}- torch.onnx.export(- detector,- val_image,- onnx_name,- export_params=True,- opset_version=17,- do_constant_folding=True,- input_names=["input"],- output_names=["output"],- dynamic_axes=dynamic_axes,- )-- return onnx_name, detectordiff --git a/kornia/models/edge_detection/__init__.py b/kornia/models/edge_detection/__init__.pynew file mode 100644index 000000000..c9359ff78--- /dev/null+++ b/kornia/models/edge_detection/__init__.py@@ -0,0 +1,2 @@+from .base import *+from .dexined import *diff --git a/kornia/models/edge_detection/base.py b/kornia/models/edge_detection/base.pynew file mode 100644index 000000000..a1eda20a1--- /dev/null+++ b/kornia/models/edge_detection/base.py@@ -0,0 +1,116 @@+from __future__ import annotations++from typing import Any, Optional, Union++import torch++from kornia.color.gray import grayscale_to_rgb+from kornia.core import Tensor+from kornia.core.external import PILImage as Image+from kornia.core.external import onnx+from kornia.models.base import ModelBase++__all__ = ["EdgeDetector"]+++class EdgeDetector(ModelBase):+ """EdgeDetector is a module that wraps an edge detection model."""++ name: str = "edge_detection"++ @torch.inference_mode()+ def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:+ """Forward pass of the edge detection model.++ Args:+ images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ output tensor.+ """+ images, image_sizes = self.pre_processor(images)+ out_images = self.model(images)+ return self.post_processor(out_images, image_sizes)++ def visualize(+ self,+ images: Union[Tensor, list[Tensor]],+ edge_maps: Optional[Union[Tensor, list[Tensor]]] = None,+ output_type: str = "torch",+ ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore+ """Draw the edge detection results.++ Args:+ images: input tensor.+ output_type: type of the output.++ Returns:+ output tensor.+ """+ if edge_maps is None:+ edge_maps = self.forward(images)+ output = []+ for edge_map in edge_maps:+ output.append(grayscale_to_rgb(edge_map)[0])++ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))++ def save(+ self,+ images: Union[Tensor, list[Tensor]],+ edge_maps: Optional[Union[Tensor, list[Tensor]]] = None,+ directory: Optional[str] = None,+ output_type: str = "torch",+ ) -> None:+ """Save the edge detection results.++ Args:+ images: input tensor.+ output_type: type of the output.++ Returns:+ output tensor.+ """+ outputs = self.visualize(images, edge_maps, output_type)+ self._save_outputs(images, directory, suffix="_src")+ self._save_outputs(outputs, directory, suffix="_edge")++ def to_onnx( # type: ignore[override]+ self,+ onnx_name: Optional[str] = None,+ image_size: Optional[int] = 352,+ include_pre_and_post_processor: bool = True,+ save: bool = True,+ additional_metadata: list[tuple[str, str]] = [],+ **kwargs: Any,+ ) -> onnx.ModelProto: # type: ignore+ """Exports the current edge detection model to an ONNX model file.++ Args:+ onnx_name:+ The name of the output ONNX file. If not provided, a default name in the+ format "Kornia-<ClassName>.onnx" will be used.+ image_size:+ The size to which input images will be resized during preprocessing.+ If None, image_size will be dynamic. For DexiNed, recommended scale is 352.+ include_pre_and_post_processor:+ Whether to include the pre-processor and post-processor in the exported model.+ save:+ If to save the model or load it.+ additional_metadata:+ Additional metadata to add to the ONNX model.+ """+ if onnx_name is None:+ onnx_name = f"kornia_{self.name}_{image_size}.onnx"++ return super().to_onnx(+ onnx_name,+ input_shape=[-1, 3, image_size or -1, image_size or -1],+ output_shape=[-1, 1, image_size or -1, image_size or -1],+ pseudo_shape=[1, 3, image_size or 352, image_size or 352],+ model=self if include_pre_and_post_processor else self.model,+ save=save,+ additional_metadata=additional_metadata,+ **kwargs,+ )diff --git a/kornia/models/edge_detection/dexined.py b/kornia/models/edge_detection/dexined.pynew file mode 100644index 000000000..57fa81529--- /dev/null+++ b/kornia/models/edge_detection/dexined.py@@ -0,0 +1,36 @@+from torch import nn++from kornia.core import tensor+from kornia.enhance.normalize import Normalize+from kornia.filters.dexined import DexiNed+from kornia.models.edge_detection.base import EdgeDetector+from kornia.models.utils import ResizePostProcessor, ResizePreProcessor++__all__ = ["DexiNedBuilder"]+++class DexiNedBuilder:+ """DexiNedBuilder is a class that builds a DexiNed model.++ .. code-block:: python++ images = kornia.utils.sample.get_sample_images()+ model = DexiNedBuilder.build()+ model.save(images)+ """++ @staticmethod+ def build(model_name: str = "dexined", pretrained: bool = True, image_size: int = 352) -> EdgeDetector:+ if model_name.lower() == "dexined":+ # Normalize then scale to [0, 255]+ norm = Normalize(mean=tensor([[0.485, 0.456, 0.406]]), std=tensor([[1.0 / 255.0] * 3]))+ model = nn.Sequential(norm, DexiNed(pretrained=pretrained), nn.Sigmoid())+ else:+ raise ValueError(f"Model {model_name} not found. Please choose from 'DexiNed'.")++ return EdgeDetector(+ model,+ ResizePreProcessor(image_size, image_size),+ ResizePostProcessor(),+ name="dexined",+ )diff --git a/kornia/models/segmentation/__init__.py b/kornia/models/segmentation/__init__.pynew file mode 100644index 000000000..ffcce20f4--- /dev/null+++ b/kornia/models/segmentation/__init__.py@@ -0,0 +1,2 @@+from .base import *+from .segmentation_models import *diff --git a/kornia/models/segmentation/base.py b/kornia/models/segmentation/base.pynew file mode 100644index 000000000..ecb7e809c--- /dev/null+++ b/kornia/models/segmentation/base.py@@ -0,0 +1,215 @@+from __future__ import annotations++from typing import ClassVar, Optional, Union++import torch++import kornia+from kornia.core import Tensor+from kornia.core.external import PILImage as Image+from kornia.models.base import ModelBase++__all__ = ["SemanticSegmentation"]+++class SemanticSegmentation(ModelBase):+ """Semantic Segmentation is a module that wraps a semantic segmentation model.++ This module uses SegmentationModel library for semantic segmentation.+ """++ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1]++ @torch.inference_mode()+ def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:+ """Forward pass of the semantic segmentation model.++ Args:+ images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ output tensor.+ """+ outputs: Union[Tensor, list[Tensor]]++ if isinstance(+ images,+ (+ list,+ tuple,+ ),+ ):+ outputs = []+ for image in images:+ image = self.pre_processor(image[None])+ output = self.model(image)+ output = self.post_processor(output)+ outputs.append(output[0])+ else:+ images = self.pre_processor(images)+ outputs = self.model(images)+ outputs = self.post_processor(outputs)++ return outputs++ def get_colormap(self, num_classes: int, colormap: str = "random", manual_seed: int = 2147) -> Tensor:+ """Get a color map of size num_classes.++ Args:+ num_classes: The number of colors in the color map.+ colormap: The colormap to use, can be "random" or a custom color map.+ manual_seed: The manual seed to use for the colormap.++ Returns:+ A tensor of shape (num_classes, 3) representing the color map.+ """+ if colormap == "random":+ # Generate a color for each class+ g_cpu = torch.Generator()+ g_cpu.manual_seed(manual_seed)+ colors = torch.rand(num_classes, 3, generator=g_cpu)+ else:+ raise ValueError(f"Unsupported colormap: {colormap}")++ return colors++ def visualize_output(self, semantic_mask: Tensor, colors: Tensor) -> Tensor:+ """Visualize the output of the segmentation model.++ Args:+ semantic_mask: The output of the segmentation model. Shape should be (C, H, W) or (B, C, H, W).+ colors: The color map to use for visualizing the output of the segmentation model.+ Shape should be (num_classes, 3).++ Returns:+ A tensor of shape (3, H, W) or (B, 3, H, W) representing the visualized output of the segmentation model.++ Raises:+ ValueError: If the shape of the semantic mask is not of shape (C, H, W) or (B, C, H, W).+ ValueError: If the shape of the colors is not of shape (num_classes, 3).+ ValueError: If only muliclass segmentation is supported. Please ensure a softmax is used, or submit a PR.+ """+ if semantic_mask.dim() == 3:+ channel_dim = 0+ elif semantic_mask.dim() == 4:+ channel_dim = 1+ else:+ raise ValueError(f"Semantic mask must be of shape (C, H, W) or (B, C, H, W), got {semantic_mask.shape}.")++ if torch.allclose(+ semantic_mask.sum(dim=channel_dim), torch.tensor(1, dtype=semantic_mask.dtype, device=semantic_mask.device)+ ):+ # Softmax is used, thus, muliclass segmentation+ semantic_mask = semantic_mask.argmax(dim=channel_dim, keepdim=True)+ # Create a colormap for each pixel based on the class with the highest probability+ output = colors[semantic_mask.squeeze(channel_dim)]+ if semantic_mask.dim() == 3:+ output = output.permute(2, 0, 1)+ elif semantic_mask.dim() == 4:+ output = output.permute(0, 3, 1, 2)+ else:+ raise ValueError(+ f"Semantic mask must be of shape (C, H, W) or (B, C, H, W), got {semantic_mask.shape}."+ )+ else:+ raise ValueError(+ "Only muliclass segmentation is supported. Please ensure a softmax is used, or submit a PR."+ )++ return output++ def visualize(+ self,+ images: Union[Tensor, list[Tensor]],+ semantic_masks: Optional[Union[Tensor, list[Tensor]]] = None,+ output_type: str = "torch",+ colormap: str = "random",+ manual_seed: int = 2147,+ ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore+ """Visualize the segmentation masks.++ Args:+ images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.+ semantic_masks: If list of segmentation masks. Each mask is a Tensor with shape :math:`(C, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, C, H, W)`.+ output_type: The type of output, can be "torch" or "PIL".+ colormap: The colormap to use, can be "random" or a custom color map.+ manual_seed: The manual seed to use for the colormap.+ """+ if semantic_masks is None:+ semantic_masks = self.forward(images)++ outputs: Union[Tensor, list[Tensor]]+ if isinstance(+ semantic_masks,+ (+ list,+ tuple,+ ),+ ):+ outputs = []+ for semantic_mask in semantic_masks:+ if semantic_mask.ndim != 3:+ raise ValueError(f"Semantic mask must be of shape (C, H, W), got {semantic_mask.shape}.")+ # Generate a color for each class+ colors = self.get_colormap(semantic_mask.size(0), colormap, manual_seed=manual_seed)+ outputs.append(self.visualize_output(semantic_mask, colors))++ else:+ # Generate a color for each class+ colors = self.get_colormap(semantic_masks.size(1), colormap, manual_seed=manual_seed)+ outputs = self.visualize_output(semantic_masks, colors)++ return self._tensor_to_type(outputs, output_type, is_batch=True if isinstance(outputs, Tensor) else False)++ def save(+ self,+ images: Union[Tensor, list[Tensor]],+ semantic_masks: Optional[Union[Tensor, list[Tensor]]] = None,+ directory: Optional[str] = None,+ output_type: str = "torch",+ colormap: str = "random",+ manual_seed: int = 2147,+ ) -> None:+ """Save the segmentation results.++ Args:+ images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.+ semantic_masks: If list of segmentation masks. Each mask is a Tensor with shape :math:`(C, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, C, H, W)`.+ directory: The directory to save the results.+ output_type: The type of output, can be "torch" or "PIL".+ colormap: The colormap to use, can be "random" or a custom color map.+ manual_seed: The manual seed to use for the colormap.+ """++ colored_masks = self.visualize(images, semantic_masks, output_type, colormap=colormap, manual_seed=manual_seed)+ overlaid: Union[Tensor, list[Tensor]]+ if isinstance(images, Tensor) and isinstance(colored_masks, Tensor):+ overlaid = kornia.enhance.add_weighted(images, 0.5, colored_masks, 0.5, 1.0)+ elif isinstance(+ images,+ (+ list,+ tuple,+ ),+ ) and isinstance(+ colored_masks,+ (+ list,+ tuple,+ ),+ ):+ overlaid = []+ for i in range(len(images)):+ overlaid.append(kornia.enhance.add_weighted(images[i][None], 0.5, colored_masks[i][None], 0.5, 1.0)[0])+ else:+ raise ValueError(f"`images` should be a Tensor or a list of Tensors. Got {type(images)}")++ self._save_outputs(images, directory, suffix="_src")+ self._save_outputs(colored_masks, directory, suffix="_mask")+ self._save_outputs(overlaid, directory, suffix="_overlay")diff --git a/kornia/models/segmentation/segmentation_models.py b/kornia/models/segmentation/segmentation_models.pynew file mode 100644index 000000000..7cfc811f4--- /dev/null+++ b/kornia/models/segmentation/segmentation_models.py@@ -0,0 +1,99 @@+from __future__ import annotations++from typing import Any, Optional++from torch import nn++import kornia+from kornia.core import Module, tensor+from kornia.core.external import segmentation_models_pytorch as smp++from .base import SemanticSegmentation++__all__ = ["SegmentationModelsBuilder"]+++class SegmentationModelsBuilder:+ @staticmethod+ def build(+ model_name: str = "Unet",+ encoder_name: str = "resnet34",+ encoder_weights: Optional[str] = "imagenet",+ in_channels: int = 3,+ classes: int = 1,+ activation: str = "softmax",+ **kwargs: Any,+ ) -> SemanticSegmentation:+ """SegmentationModel is a module that wraps a segmentation model.++ This module uses SegmentationModel library for segmentation.++ Args:+ model_name: Name of the model to use. Valid options are:+ "Unet", "UnetPlusPlus", "MAnet", "LinkNet", "FPN", "PSPNet", "PAN", "DeepLabV3", "DeepLabV3Plus".+ encoder_name: Name of the encoder to use.+ encoder_depth: Depth of the encoder.+ encoder_weights: Weights of the encoder.+ decoder_channels: Number of channels in the decoder.+ in_channels: Number of channels in the input.+ classes: Number of classes to predict.+ **kwargs: Additional arguments to pass to the model. Detailed arguments can be found at:+ https://github.com/qubvel-org/segmentation_models.pytorch/tree/main/segmentation_models_pytorch/decoders++ Note:+ Only encoder weights are available.+ Pretrained weights for the whole model are not available.+ """++ preproc_params = smp.encoders.get_preprocessing_params(encoder_name) # type: ignore+ preprocessor = SegmentationModelsBuilder.get_preprocessing_pipeline(preproc_params)+ segmentation_model = getattr(smp, model_name)(+ encoder_name=encoder_name,+ encoder_weights=encoder_weights,+ in_channels=in_channels,+ classes=classes,+ activation=activation,+ **kwargs,+ )++ return SemanticSegmentation(+ model=segmentation_model,+ pre_processor=preprocessor,+ post_processor=nn.Identity(),+ name=f"{model_name}_{encoder_name}",+ )++ @staticmethod+ def get_preprocessing_pipeline(preproc_params: dict[str, Any]) -> kornia.augmentation.container.ImageSequential:+ # Ensure the color space transformation is ONNX-friendly+ proc_sequence: list[Module] = []+ input_space = preproc_params["input_space"]+ if input_space == "BGR":+ proc_sequence.append(kornia.color.BgrToRgb())+ elif input_space == "RGB":+ pass+ else:+ raise ValueError(f"Unsupported input space: {input_space}")++ # Normalize input range if needed+ input_range = preproc_params["input_range"]+ if input_range[1] == 255:+ proc_sequence.append(kornia.enhance.Normalize(mean=0.0, std=1 / 255.0))+ elif input_range[1] == 1:+ pass+ else:+ raise ValueError(f"Unsupported input range: {input_range}")++ # Handle mean and std normalization+ if preproc_params["mean"] is not None:+ mean = tensor([preproc_params["mean"]])+ else:+ mean = tensor(0.0)++ if preproc_params["std"] is not None:+ std = tensor([preproc_params["std"]])+ else:+ std = tensor(1.0)+ proc_sequence.append(kornia.enhance.Normalize(mean=mean, std=std))++ return kornia.augmentation.container.ImageSequential(*proc_sequence)diff --git a/kornia/models/super_resolution/__init__.py b/kornia/models/super_resolution/__init__.pynew file mode 100644index 000000000..0ce362cad--- /dev/null+++ b/kornia/models/super_resolution/__init__.py@@ -0,0 +1,3 @@+from .base import *+from .rrdbnet import *+from .small_sr import *diff --git a/kornia/models/super_resolution/base.py b/kornia/models/super_resolution/base.pynew file mode 100644index 000000000..bb87410fa--- /dev/null+++ b/kornia/models/super_resolution/base.py@@ -0,0 +1,129 @@+from typing import Any, List, Optional, Tuple, Union++import torch++from kornia.core import Tensor+from kornia.core.external import PILImage as Image+from kornia.core.external import onnx+from kornia.models.base import ModelBase++__all__ = ["SuperResolution"]+++# TODO: support patching -> SR -> unpatching pipeline+class SuperResolution(ModelBase):+ """SuperResolution is a module that wraps an super resolution model."""++ name: str = "super_resolution"+ input_image_size: Optional[int]+ output_image_size: Optional[int]+ pseudo_image_size: Optional[int]++ @torch.inference_mode()+ def forward(self, images: Union[Tensor, List[Tensor]]) -> Union[Tensor, List[Tensor]]:+ """Forward pass of the super resolution model.++ Args:+ images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ output tensor.+ """+ output = self.pre_processor(images)+ if isinstance(+ output,+ (+ list,+ tuple,+ ),+ ):+ images = output[0]+ else:+ images = output+ if isinstance(images, list):+ out_images = [self.model(image[None])[0] for image in images]+ else:+ out_images = self.model(images)+ return self.post_processor(out_images)++ def visualize(+ self,+ images: Union[Tensor, List[Tensor]],+ edge_maps: Optional[Union[Tensor, List[Tensor]]] = None,+ output_type: str = "torch",+ ) -> Union[Tensor, List[Tensor], List["Image.Image"]]: # type: ignore+ """Draw the super resolution results.++ Args:+ images: input tensor.+ output_type: type of the output.++ Returns:+ output tensor.+ """+ if edge_maps is None:+ edge_maps = self.forward(images)+ output = []+ for edge_map in edge_maps:+ output.append(edge_map)++ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))++ def save(+ self,+ images: Union[Tensor, List[Tensor]],+ edge_maps: Optional[Union[Tensor, List[Tensor]]] = None,+ directory: Optional[str] = None,+ output_type: str = "torch",+ ) -> None:+ """Save the super resolution results.++ Args:+ images: input tensor.+ output_type: type of the output.++ Returns:+ output tensor.+ """+ outputs = self.visualize(images, edge_maps, output_type)+ self._save_outputs(images, directory, suffix="_src")+ self._save_outputs(outputs, directory, suffix="_sr")++ def to_onnx( # type: ignore[override]+ self,+ onnx_name: Optional[str] = None,+ include_pre_and_post_processor: bool = True,+ save: bool = True,+ additional_metadata: List[Tuple[str, str]] = [],+ **kwargs: Any,+ ) -> "onnx.ModelProto": # type: ignore+ """Exports the current super resolution model to an ONNX model file.++ Args:+ onnx_name:+ The name of the output ONNX file. If not provided, a default name in the+ format "Kornia-<ClassName>.onnx" will be used.+ image_size:+ The size to which input images will be resized during preprocessing.+ If None, image_size will be dynamic. For DexiNed, recommended scale is 352.+ include_pre_and_post_processor:+ Whether to include the pre-processor and post-processor in the exported model.+ save:+ If to save the model or load it.+ additional_metadata:+ Additional metadata to add to the ONNX model.+ """+ if onnx_name is None:+ onnx_name = f"kornia_{self.name}.onnx"++ return super().to_onnx(+ onnx_name,+ input_shape=[-1, 3, self.input_image_size or -1, self.input_image_size or -1],+ output_shape=[-1, 3, self.output_image_size or -1, self.output_image_size or -1],+ pseudo_shape=[1, 3, self.pseudo_image_size or 352, self.pseudo_image_size or 352],+ model=self if include_pre_and_post_processor else self.model,+ save=save,+ additional_metadata=additional_metadata,+ **kwargs,+ )diff --git a/kornia/models/super_resolution/rrdbnet.py b/kornia/models/super_resolution/rrdbnet.pynew file mode 100644index 000000000..f73782210--- /dev/null+++ b/kornia/models/super_resolution/rrdbnet.py@@ -0,0 +1,60 @@+import torch+from torch import nn++from kornia.config import kornia_config+from kornia.core.external import basicsr+from kornia.models.utils import OutputRangePostProcessor+from kornia.utils.download import CachedDownloader++from .base import SuperResolution++__all__ = ["RRDBNetBuilder"]++URLs = {+ "RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",+ "RealESRNet_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth",+ "RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",+ "RealESRGAN_x2plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",+}+++class RRDBNetBuilder:+ @staticmethod+ def build(model_name: str = "RealESRNet_x4plus", pretrained: bool = True) -> SuperResolution:+ if model_name == "RealESRGAN_x4plus":+ model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore+ num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4+ )+ elif model_name == "RealESRNet_x4plus":+ model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore+ num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4+ )+ elif model_name == "RealESRGAN_x4plus_anime_6B":+ model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore+ num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4+ )+ elif model_name == "RealESRGAN_x2plus":+ model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore+ num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2+ )+ else:+ raise ValueError(+ f"Model {model_name} not found. Please choose from "+ "'RealESRGAN_x4plus', 'RealESRNet_x4plus', 'RealESRGAN_x4plus_anime_6B', 'RealESRGAN_x2plus'."+ )++ model_path = None+ if pretrained:+ url = URLs[model_name]+ model_path = CachedDownloader.download_to_cache(+ url, model_name, download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir+ )+ model.load_state_dict(torch.load(model_path, map_location=torch.device("cpu"))["params_ema"], strict=True)+ model.eval()++ return SuperResolution(+ model,+ pre_processor=nn.Identity(),+ post_processor=OutputRangePostProcessor(min_val=0.0, max_val=1.0),+ name=model_name,+ )diff --git a/kornia/models/super_resolution/small_sr.py b/kornia/models/super_resolution/small_sr.pynew file mode 100644index 000000000..21494bd11--- /dev/null+++ b/kornia/models/super_resolution/small_sr.py@@ -0,0 +1,105 @@+from typing import Optional++import torch+from torch import nn++from kornia.color.ycbcr import RgbToYcbcr, YcbcrToRgb+from kornia.config import kornia_config+from kornia.core import Module, Tensor, concatenate+from kornia.models.utils import ResizePreProcessor+from kornia.utils.download import CachedDownloader++from .base import SuperResolution++url = "https://s3.amazonaws.com/pytorch/test_data/export/superres_epoch100-44c6958e.pth"+++class SmallSRNet(Module):+ """A small super-resolution model.++ This model uses the efficient sub-pixel convolution layer described in+ "Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network"+ - Shi et al for increasing the resolution of an image by an upscale factor.+ Taken from https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html.+ """++ def __init__(self, upscale_factor: int, inplace: bool = False, pretrained: bool = True) -> None:+ super().__init__()++ self.relu = nn.ReLU(inplace=inplace)+ self.conv1 = nn.Conv2d(1, 64, (5, 5), (1, 1), (2, 2))+ self.conv2 = nn.Conv2d(64, 64, (3, 3), (1, 1), (1, 1))+ self.conv3 = nn.Conv2d(64, 32, (3, 3), (1, 1), (1, 1))+ self.conv4 = nn.Conv2d(32, upscale_factor**2, (3, 3), (1, 1), (1, 1))+ self.pixel_shuffle = nn.PixelShuffle(upscale_factor)++ if pretrained:+ self.load_from_file(url)+ else:+ self.apply(weight_init)++ def load_from_file(self, path_file: str) -> None:+ # use torch.hub to load pretrained model+ model_path = CachedDownloader.download_to_cache(+ path_file, "small_sr.pth", download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir+ )+ pretrained_dict = torch.load(model_path, map_location=torch.device("cpu"))+ self.load_state_dict(pretrained_dict, strict=True)+ self.eval()++ def forward(self, x: Tensor) -> Tensor:+ x = self.relu(self.conv1(x))+ x = self.relu(self.conv2(x))+ x = self.relu(self.conv3(x))+ x = self.pixel_shuffle(self.conv4(x))+ return x+++def weight_init(model: Module) -> None:+ torch.nn.init.orthogonal_(model.conv1.weight, torch.nn.init.calculate_gain("relu"))+ torch.nn.init.orthogonal_(model.conv2.weight, torch.nn.init.calculate_gain("relu"))+ torch.nn.init.orthogonal_(model.conv3.weight, torch.nn.init.calculate_gain("relu"))+ torch.nn.init.orthogonal_(model.conv4.weight)+++class SmallSRNetWrapper(Module):+ def __init__(self, upscale_factor: int = 3, pretrained: bool = True) -> None:+ super().__init__()+ self.rgb_to_ycbcr = RgbToYcbcr()+ self.ycbcr_to_rgb = YcbcrToRgb()+ self.model = SmallSRNet(upscale_factor=upscale_factor, pretrained=pretrained)+ self.upscale_factor = upscale_factor++ def forward(self, input: Tensor) -> Tensor:+ ycbcr = self.rgb_to_ycbcr(input)+ y, cb, cr = ycbcr.split(1, dim=1)+ out_y = self.model(y)+ out_cb = torch.nn.functional.interpolate(cb, scale_factor=self.upscale_factor, mode="bicubic")+ out_cr = torch.nn.functional.interpolate(cr, scale_factor=self.upscale_factor, mode="bicubic")+ out = concatenate([out_y, out_cb, out_cr], dim=1)+ return self.ycbcr_to_rgb(out)+++class SmallSRBuilder:+ @staticmethod+ def build(+ model_name: str = "small_sr", pretrained: bool = True, upscale_factor: int = 3, image_size: Optional[int] = None+ ) -> SuperResolution:+ if model_name.lower() == "small_sr":+ model = SmallSRNetWrapper(upscale_factor, pretrained=pretrained)+ else:+ raise ValueError(f"Model {model_name} not found. Please choose from 'small_sr'.")++ sr = SuperResolution(+ model,+ pre_processor=ResizePreProcessor(224, 224),+ post_processor=nn.Identity(),+ name=model_name,+ )+ if image_size is None:+ sr.pseudo_image_size = 224+ else:+ sr.input_image_size = image_size+ sr.output_image_size = image_size * 3+ sr.pseudo_image_size = image_size+ return srdiff --git a/kornia/models/tracking/__init__.py b/kornia/models/tracking/__init__.pynew file mode 100644index 000000000..a68c9dce9--- /dev/null+++ b/kornia/models/tracking/__init__.py@@ -0,0 +1 @@+from .boxmot_tracker import *diff --git a/kornia/models/tracking/boxmot_tracker.py b/kornia/models/tracking/boxmot_tracker.pynew file mode 100644index 000000000..cb1486448--- /dev/null+++ b/kornia/models/tracking/boxmot_tracker.py@@ -0,0 +1,164 @@+from __future__ import annotations+import datetime+import logging+import os+from pathlib import Path+from typing import Any, Optional, Union++from kornia.config import kornia_config+from kornia.core import Tensor, tensor+from kornia.core.external import boxmot+from kornia.core.external import numpy as np+from kornia.io import write_image+from kornia.models.detection.base import ObjectDetector+from kornia.models.detection.rtdetr import RTDETRDetectorBuilder+from kornia.utils.image import tensor_to_image++__all__ = ["BoxMotTracker"]++logger = logging.getLogger(__name__)+++class BoxMotTracker:+ """BoxMotTracker is a module that wraps a detector and a tracker model.++ This module uses BoxMot library for tracking.++ Args:+ detector: ObjectDetector: The detector model.+ tracker_model_name: The name of the tracker model. Valid options are:+ - "BoTSORT"+ - "DeepOCSORT"+ - "OCSORT"+ - "HybridSORT"+ - "ByteTrack"+ - "StrongSORT"+ - "ImprAssoc"+ tracker_model_weights: Path to the model weights for ReID (Re-Identification).+ device: Device on which to run the model (e.g., 'cpu' or 'cuda').+ fp16: Whether to use half-precision (fp16) for faster inference on compatible devices.+ per_class: Whether to perform per-class tracking+ track_high_thresh: High threshold for detection confidence.+ Detections above this threshold are used in the first association round.+ track_low_thresh: Low threshold for detection confidence.+ Detections below this threshold are ignored.+ new_track_thresh: Threshold for creating a new track.+ Detections above this threshold will be considered as potential new tracks.+ track_buffer: Number of frames to keep a track alive after it was last detected.+ match_thresh: Threshold for the matching step in data association.+ proximity_thresh: Threshold for IoU (Intersection over Union) distance in first-round association.+ appearance_thresh: Threshold for appearance embedding distance in the ReID module.+ cmc_method: Method for correcting camera motion. Options include "sof" (simple optical flow).+ frame_rate: Frame rate of the video being processed. Used to scale the track buffer size.+ 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+ 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::+ At least 4 frames are needed to initialize the tracking position.+ """++ name: str = "boxmot_tracker"++ def __init__(+ self,+ detector: Union[ObjectDetector, str] = "rtdetr_r18vd",+ tracker_model_name: str = "DeepOCSORT",+ tracker_model_weights: str = "osnet_x0_25_msmt17.pt",+ device: str = "cpu",+ fp16: bool = False,+ **kwargs: Any,+ ) -> None:+ super().__init__()+ if isinstance(detector, str):+ if detector.startswith("rtdetr"):+ detector = RTDETRDetectorBuilder.build(model_name=detector)+ else:+ raise ValueError(+ f"Detector `{detector}` not available. You may pass an ObjectDetector instance instead."+ )+ self.detector = detector+ os.makedirs(f"{kornia_config.hub_models_dir}/boxmot", exist_ok=True)+ self.tracker = getattr(boxmot, tracker_model_name)(+ model_weights=Path(os.path.join(f"{kornia_config.hub_models_dir}/boxmot", tracker_model_weights)),+ device=device,+ fp16=fp16,+ **kwargs,+ )++ def update(self, image: Tensor) -> None:+ """Update the tracker with a new image.++ Args:+ image: The input image.+ """++ if not (image.ndim == 4 and image.shape[0] == 1) and not image.ndim == 3:+ raise ValueError(f"Input tensor must be of shape (1, 3, H, W) or (3, H, W). Got {image.shape}")++ if image.ndim == 3:+ image = image.unsqueeze(0)++ detections_raw: Union[Tensor, list[Tensor]] = self.detector(image)++ detections = detections_raw[0].cpu().numpy() # Batch size is 1++ detections = np.array( # type: ignore+ [+ detections[:, 2],+ detections[:, 3],+ detections[:, 2] + detections[:, 4],+ detections[:, 3] + detections[:, 5],+ detections[:, 1],+ detections[:, 0],+ ]+ ).T++ if detections.shape[0] == 0:+ # empty N X (x, y, x, y, conf, cls)+ detections = np.empty((0, 6)) # type: ignore++ frame_raw = (tensor_to_image(image) * 255).astype(np.uint8)+ # --> M X (x, y, x, y, id, conf, cls, ind)+ return self.tracker.update(detections, frame_raw)++ def visualize(self, image: Tensor, show_trajectories: bool = True) -> Tensor:+ """Visualize the results of the tracker.++ Args:+ image: The input image.+ show_trajectories: Whether to show the trajectories.++ Returns:+ The image with the results of the tracker.+ """+ frame_raw = (tensor_to_image(image) * 255).astype(np.uint8)+ self.tracker.plot_results(frame_raw, show_trajectories=show_trajectories)++ return tensor(frame_raw).permute(2, 0, 1)++ def save(self, image: Tensor, show_trajectories: bool = True, directory: Optional[str] = None) -> None:+ """Save the model to ONNX format.++ Args:+ image: The input image.+ """+ if directory is None:+ name = f"{self.name}_{datetime.datetime.now(tz=datetime.timezone.utc).strftime('%Y%m%d%H%M%S')!s}"+ directory = os.path.join("kornia_outputs", name)+ output = self.visualize(image, show_trajectories=show_trajectories)++ os.makedirs(directory, exist_ok=True)+ write_image(+ os.path.join(directory, f"{str(0).zfill(6)}.jpg"),+ output.byte(),+ )+ logger.info(f"Outputs are saved in {directory}")diff --git a/kornia/models/utils.py b/kornia/models/utils.pynew file mode 100644index 000000000..5f351f2b4--- /dev/null+++ b/kornia/models/utils.py@@ -0,0 +1,90 @@+import warnings+from typing import List, Tuple, Union++import torch+from torch import Tensor++from kornia.core import Module, concatenate+from kornia.geometry.transform import resize++__all__ = ["ResizePreProcessor", "ResizePostProcessor", "OutputRangePostProcessor"]+++class ResizePreProcessor(Module):+ """This module resizes a list of image tensors to the given size.++ Additionally, also returns the original image sizes for further post-processing.+ """++ def __init__(self, height: int, width: int, interpolation_mode: str = "bilinear") -> None:+ """+ Args:+ height: height of the resized image.+ width: width of the resized image.+ interpolation_mode: interpolation mode for image resizing. Supported values: ``nearest``, ``bilinear``,+ ``bicubic``, ``area``, and ``nearest-exact``.+ """+ super().__init__()+ self.size = (height, width)+ self.interpolation_mode = interpolation_mode++ def forward(self, imgs: Union[Tensor, List[Tensor]]) -> Tuple[Tensor, Tensor]:+ """+ Returns:+ resized_imgs: resized images in a batch.+ original_sizes: the original image sizes of (height, width).+ """+ # TODO: support other input formats e.g. file path, numpy+ resized_imgs: list[Tensor] = []++ iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]+ original_sizes = imgs[0].new_zeros((iters, 2))+ for i in range(iters):+ img = imgs[i]+ original_sizes[i, 0] = img.shape[-2] # Height+ original_sizes[i, 1] = img.shape[-1] # Width+ resized_imgs.append(resize(img[None], size=self.size, interpolation=self.interpolation_mode))+ return concatenate(resized_imgs), original_sizes+++class ResizePostProcessor(Module):+ def __init__(self, interpolation_mode: str = "bilinear") -> None:+ super().__init__()+ self.interpolation_mode = interpolation_mode++ def forward(self, imgs: Union[Tensor, List[Tensor]], original_sizes: Tensor) -> Union[Tensor, List[Tensor]]:+ """+ Returns:+ resized_imgs: resized images in a batch.+ original_sizes: the original image sizes of (height, width).+ """+ # TODO: support other input formats e.g. file path, numpy+ resized_imgs: list[Tensor] = []++ if torch.onnx.is_in_onnx_export():+ warnings.warn(+ "ResizePostProcessor is not supported in ONNX export. "+ "The output will not be resized back to the original size."+ )+ return imgs++ iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]+ for i in range(iters):+ img = imgs[i]+ size = original_sizes[i]+ resized_imgs.append(+ resize(img[None], size=size.cpu().long().numpy().tolist(), interpolation=self.interpolation_mode)+ )+ return resized_imgs+++class OutputRangePostProcessor(Module):+ def __init__(self, min_val: float = 0.0, max_val: float = 1.0) -> None:+ super().__init__()+ self.min_val = min_val+ self.max_val = max_val++ def forward(self, imgs: Union[Tensor, List[Tensor]]) -> Union[Tensor, List[Tensor]]:+ if isinstance(imgs, Tensor):+ return torch.clamp(imgs, self.min_val, self.max_val)+ return [img.clamp_(self.min_val, self.max_val) for img in imgs]diff --git a/kornia/onnx/__init__.py b/kornia/onnx/__init__.pynew file mode 100644index 000000000..069c23c03--- /dev/null+++ b/kornia/onnx/__init__.py@@ -0,0 +1,3 @@+from .module import *+from .sequential import *+from .utils import *diff --git a/kornia/onnx/module.py b/kornia/onnx/module.pynew file mode 100644index 000000000..66ee579f1--- /dev/null+++ b/kornia/onnx/module.py@@ -0,0 +1,69 @@+from __future__ import annotations++from typing import Any, Optional, Union++from kornia.config import kornia_config+from kornia.core.external import onnx+from kornia.core.external import onnxruntime as ort+from kornia.core.mixin.onnx import ONNXMixin, ONNXRuntimeMixin++__all__ = ["ONNXModule", "load"]+++class ONNXModule(ONNXMixin, ONNXRuntimeMixin):+ f"""ONNXModule to wrap an ONNX operator.++ Args:+ arg: A variable number of ONNX models (either ONNX ModelProto objects or file paths).+ For Hugging Face-hosted models, use the format 'hf://model_name'. Valid `model_name` can be found on+ https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.+ providers: A list of execution providers for ONNXRuntime+ (e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']).+ session_options: Optional ONNXRuntime session options for optimizing the session.+ cache_dir: The directory where ONNX models are cached locally (only for downloading from HuggingFace).+ Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.+ target_ir_version: The target IR version to convert to.+ target_opset_version: The target OPSET version to convert to.+ """++ def __init__(+ self,+ op: Union[onnx.ModelProto, str], # type:ignore+ providers: Optional[list[str]] = None,+ session_options: Optional[ort.SessionOptions] = None, # type:ignore+ cache_dir: Optional[str] = None,+ target_ir_version: Optional[int] = None,+ target_opset_version: Optional[int] = None,+ ) -> None:+ self.op = self._load_op(op, cache_dir)+ if target_ir_version is not None or target_opset_version is not None:+ self.op = self._onnx_version_conversion(+ self.op, target_ir_version=target_ir_version, target_opset_version=target_opset_version+ )+ session = self.create_session(providers=providers, session_options=session_options)+ self.set_session(session=session)++ def create_session(+ self, providers: list[str] | None = None, session_options: Any | None = None+ ) -> ort.InferenceSession: # type: ignore+ return super()._create_session(self.op, providers, session_options)++ def export(self, file_path: str, **kwargs: Any) -> None:+ return super()._export(self.op, file_path, **kwargs)++ def add_metadata(self, additional_metadata: list[tuple[str, str]] = []) -> onnx.ModelProto: # type:ignore+ return super()._add_metadata(self.op, additional_metadata)+++def load(model_name: Union[onnx.ModelProto, str]) -> ONNXModule: # type:ignore+ """Load an ONNX model from either a file path or HuggingFace.++ The loaded model is an ONNXModule object, of which you may run the model with+ the `__call__` method, with less boilerplate.++ Args:+ model_name: The name of the model to load. For Hugging Face-hosted models,+ use the format 'hf://model_name'. Valid `model_name` can be found on+ https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.+ """+ return ONNXModule(model_name)diff --git a/kornia/onnx/sequential.py b/kornia/onnx/sequential.pynew file mode 100644index 000000000..f882bae64--- /dev/null+++ b/kornia/onnx/sequential.py@@ -0,0 +1,96 @@+from __future__ import annotations++from typing import Any, Optional, Union++from kornia.config import kornia_config+from kornia.core.external import onnx+from kornia.core.external import onnxruntime as ort+from kornia.core.mixin import ONNXMixin, ONNXRuntimeMixin++__all__ = ["ONNXSequential"]+++class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):+ f"""ONNXSequential to chain multiple ONNX operators together.++ Args:+ *args: A variable number of ONNX models (either ONNX ModelProto objects or file paths).+ For Hugging Face-hosted models, use the format 'hf://model_name'. Valid `model_name` can be found on+ https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.+ providers: A list of execution providers for ONNXRuntime+ (e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']).+ session_options: Optional ONNXRuntime session options for optimizing the session.+ io_maps: An optional list of list of tuples specifying input-output mappings for combining models.+ If None, we assume the default input name and output name are "input" and "output" accordingly, and+ only one input and output node for each graph.+ If not None, `io_maps[0]` shall represent the `io_map` for combining the first and second ONNX models.+ cache_dir: The directory where ONNX models are cached locally (only for downloading from HuggingFace).+ Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.+ auto_ir_version_conversion: If True, automatically convert the model's IR version to 9, and OPSET version to 17.+ Other versions may be pointed to by `target_ir_version` and `target_opset_version`.+ target_ir_version: The target IR version to convert to.+ target_opset_version: The target OPSET version to convert to.+ """++ def __init__(+ self,+ *args: Union[onnx.ModelProto, str], # type:ignore+ providers: Optional[list[str]] = None,+ session_options: Optional[ort.SessionOptions] = None, # type:ignore+ io_maps: Optional[list[tuple[str, str]]] = None,+ cache_dir: Optional[str] = None,+ auto_ir_version_conversion: bool = False,+ target_ir_version: Optional[int] = None,+ target_opset_version: Optional[int] = None,+ ) -> None:+ self.operators = self._load_ops(*args, cache_dir=cache_dir)+ if auto_ir_version_conversion:+ self.operators = self._auto_version_conversion(+ *self.operators, target_ir_version=target_ir_version, target_opset_version=target_opset_version+ )+ self._combined_op = self.combine(io_maps=io_maps)+ session = self.create_session(providers=providers, session_options=session_options)+ self.set_session(session=session)++ def _auto_version_conversion(+ self,+ *args: list[onnx.ModelProto], # type:ignore+ target_ir_version: Optional[int] = None,+ target_opset_version: Optional[int] = None,+ ) -> list[onnx.ModelProto]: # type:ignore+ """Automatic conversion of the model's IR/OPSET version to the given target version.++ If `target_ir_version` is not provided, the model is converted to 9 by default.+ If `target_opset_version` is not provided, the model is converted to 17 by default.++ Args:+ target_ir_version: The target IR version to convert to.+ target_opset_version: The target OPSET version to convert to.+ """+ # TODO: maybe another logic for versioning.+ if target_ir_version is None:+ target_ir_version = 9+ if target_opset_version is None:+ target_opset_version = 17++ op_list = []+ for op in args:+ op = super()._onnx_version_conversion(+ op, target_ir_version=target_ir_version, target_opset_version=target_opset_version+ )+ op_list.append(op)+ return op_list++ def combine(self, io_maps: list[tuple[str, str]] | None = None) -> onnx.ModelProto: # type: ignore+ return super()._combine(*self.operators, io_maps=io_maps)++ def create_session(+ self, providers: list[str] | None = None, session_options: Any | None = None+ ) -> ort.InferenceSession: # type: ignore+ return super()._create_session(self._combined_op, providers, session_options)++ def export(self, file_path: str, **kwargs: Any) -> None:+ return super()._export(self._combined_op, file_path, **kwargs)++ def add_metadata(self, additional_metadata: list[tuple[str, str]] = []) -> onnx.ModelProto: # type:ignore+ return super()._add_metadata(self._combined_op, additional_metadata)diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.pynew file mode 100644index 000000000..00eaa080f--- /dev/null+++ b/kornia/onnx/utils.py@@ -0,0 +1,225 @@+from __future__ import annotations++import json+import logging+import os+import pprint+from typing import Any++import kornia+from kornia.config import kornia_config+from kornia.core.external import numpy as np+from kornia.core.external import onnx+from kornia.core.external import requests+from kornia.utils.download import CachedDownloader++__all__ = ["ONNXLoader", "io_name_conversion", "add_metadata"]++logger = logging.getLogger(__name__)+++class ONNXLoader(CachedDownloader):+ """Manages ONNX models, handling local caching, downloading from Hugging Face, and loading models."""++ @classmethod+ def load_config(cls, url: str, download: bool = True, **kwargs: Any) -> dict[str, Any]:+ """Loads JSON config from the specified URL.++ Args:+ url: The URL of the preprocessor config to load.+ download: If True, the config will be downloaded if it's not already in the local cache.++ Returns:+ dict[str, Any]: The loaded preprocessor config.+ """+ if url.startswith(("http:", "https:")):+ file_path = cls.download_to_cache(+ url,+ os.path.split(url)[-1],+ download=download,+ suffix=".json",+ **kwargs,+ )+ with open(file_path) as f:+ json_data = json.load(f)+ return json_data++ if not download:+ raise RuntimeError(f"File `{url}` not found. You may set `download=True`.")++ raise RuntimeError(f"File `{file_path}` not found.")++ @classmethod+ def load_model(cls, model_name: str, download: bool = True, with_data: bool = False, **kwargs) -> onnx.ModelProto: # type:ignore+ """Loads an ONNX model from the local cache or downloads it from Hugging Face if necessary.++ Args:+ model_name: The name of the ONNX model or operator. For Hugging Face-hosted models,+ use the format 'hf://model_name'. Valid `model_name` can be found on+ https://huggingface.co/kornia/ONNX_models.+ Or a URL to the ONNX model.+ download: If True, the model will be downloaded from Hugging Face if it's not already in the local cache.+ cache_dir: The directory where the model should be cached.+ Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.+ with_data: If True, the model will be loaded with its `.onnx_data` weights.+ **kwargs: Additional arguments to pass to the download method, if needed.++ Returns:+ onnx.ModelProto: The loaded ONNX model.+ """+ if model_name.startswith("hf://"):+ model_name = model_name[len("hf://") :]+ url = f"https://huggingface.co/kornia/ONNX_models/resolve/main/{model_name}.onnx"+ cache_dir = kwargs.get("cache_dir", None) or os.path.join(+ kornia_config.hub_onnx_dir, model_name.split("/")[0]+ )+ kwargs.update({"cache_dir": cache_dir})+ file_path = cls.download_to_cache(+ url, model_name.split("/")[1], download=download, suffix=".onnx", **kwargs+ )+ if with_data:+ url_data = f"https://huggingface.co/kornia/ONNX_models/resolve/main/{model_name}.onnx_data"+ cls.download_to_cache(+ url_data, model_name.split("/")[1], download=download, suffix=".onnx_data", **kwargs+ )+ return onnx.load(file_path) # type:ignore++ elif model_name.startswith("http://") or model_name.startswith("https://"):+ cache_dir = kwargs.get("cache_dir", None) or kornia_config.hub_onnx_dir+ kwargs.update({"cache_dir": cache_dir})+ file_path = cls.download_to_cache(+ model_name,+ os.path.split(model_name)[-1],+ download=download,+ suffix=".onnx",+ **kwargs,+ )+ if with_data:+ url_data = model_name[:-5] + ".onnx_data"+ cls.download_to_cache(+ url_data,+ os.path.split(model_name)[-1][:-5] + ".onnx_data",+ download=download,+ suffix=".onnx_data",+ **kwargs,+ )+ return onnx.load(file_path) # type:ignore++ elif os.path.exists(model_name):+ return onnx.load(model_name) # type:ignore++ raise ValueError(f"File {model_name} not found")++ @staticmethod+ def _fetch_repo_contents(folder: str) -> list[dict[str, Any]]:+ """Fetches the contents of the Hugging Face repository using the Hugging Face API.++ Returns:+ A list of all files in the repository as dictionaries containing file details.+ """+ url = f"https://huggingface.co/api/models/kornia/ONNX_models/tree/main/{folder}"++ response = requests.get(url, timeout=10) # type:ignore++ if response.status_code == 200:+ return response.json() # Returns the JSON content of the repo+ else:+ raise ValueError(f"Failed to fetch repository contents: {response.status_code}")++ @classmethod+ def list_operators(cls) -> None:+ """Lists all available ONNX operators in the 'operators' folder of the Hugging Face repository."""+ repo_contents = cls._fetch_repo_contents("operators")++ # Filter for operators in the 'operators' directory+ operators = [file["path"] for file in repo_contents]++ pprint.pp(operators)++ @classmethod+ def list_models(cls) -> None:+ """Lists all available ONNX models in the 'models' folder of the Hugging Face repository."""+ repo_contents = cls._fetch_repo_contents("models")++ # Filter for models in the 'models' directory+ models = [file["path"] for file in repo_contents]++ pprint.pp(models)+++def io_name_conversion(+ onnx_model: onnx.ModelProto, # type:ignore+ io_name_mapping: dict[str, str],+) -> onnx.ModelProto: # type:ignore+ """Converts the input and output names of an ONNX model to 'input' and 'output'.++ Args:+ onnx_model: The ONNX model to convert.+ io_name_mapping: A dictionary mapping the original input and output names to the new ones.+ """+ # Convert I/O nodes+ for i in range(len(onnx_model.graph.input)):+ in_name = onnx_model.graph.input[i].name+ if in_name in io_name_mapping:+ onnx_model.graph.input[i].name = io_name_mapping[in_name]++ for i in range(len(onnx_model.graph.output)):+ out_name = onnx_model.graph.output[i].name+ if out_name in io_name_mapping:+ onnx_model.graph.output[i].name = io_name_mapping[out_name]++ # Convert intermediate nodes+ for i in range(len(onnx_model.graph.node)):+ for j in range(len(onnx_model.graph.node[i].input)):+ if onnx_model.graph.node[i].input[j] in io_name_mapping:+ onnx_model.graph.node[i].input[j] = io_name_mapping[in_name]++ for j in range(len(onnx_model.graph.node[i].output)):+ if onnx_model.graph.node[i].output[j] in io_name_mapping:+ onnx_model.graph.node[i].output[j] = io_name_mapping[out_name]++ return onnx_model+++def add_metadata(+ onnx_model: onnx.ModelProto, # type: ignore+ additional_metadata: list[tuple[str, str]] = [],+) -> onnx.ModelProto: # type: ignore+ """Adds metadata to an ONNX model.++ The metadata includes the source library (set to "kornia"), the version of kornia,+ and any additional metadata provided as a list of key-value pairs.++ Args:+ onnx_model: The ONNX model to add metadata to.+ additional_metadata: A list of tuples, where each tuple contains a key and a value+ for the additional metadata to add to the ONNX model.++ Returns:+ The ONNX model with the added metadata.+ """+ for key, value in [+ ("source", "kornia"),+ ("version", kornia.__version__),+ *additional_metadata,+ ]:+ metadata_props = onnx_model.metadata_props.add()+ metadata_props.key = key+ metadata_props.value = str(value)+ return onnx_model+++def onnx_type_to_numpy(onnx_type: str) -> Any:+ type_mapping = {+ "tensor(float)": np.float32,+ "tensor(float16)": np.float16,+ "tensor(double)": np.float64,+ "tensor(int32)": np.int32,+ "tensor(int64)": np.int64,+ "tensor(uint8)": np.uint8,+ "tensor(int8)": np.int8,+ "tensor(bool)": np.bool_,+ }+ if onnx_type not in type_mapping:+ raise TypeError(f"ONNX type {onnx_type} not understood")+ return type_mapping[onnx_type]diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.pyindex 8fc674f6f..b1622667e 100644--- a/kornia/utils/__init__.py+++ b/kornia/utils/__init__.py@@ -1,4 +1,5 @@from ._compat import torch_meshgrid+from .download import CachedDownloaderfrom .draw import draw_convex_polygon, draw_line, draw_point2d, draw_rectanglefrom .grid import create_meshgrid, create_meshgrid3dfrom .helpers import (@@ -28,6 +29,7 @@ from .misc import ()from .one_hot import one_hotfrom .pointcloud_io import load_pointcloud_ply, save_pointcloud_ply+from .sample import get_sample_images__all__ = ["batched_forward",@@ -62,4 +64,6 @@ __all__ = ["is_mps_tensor_safe","dataclass_to_dict","dict_to_dataclass",+ "get_sample_images",+ "CachedDownloader",]diff --git a/kornia/utils/download.py b/kornia/utils/download.pynew file mode 100644index 000000000..177a0e25a--- /dev/null+++ b/kornia/utils/download.py@@ -0,0 +1,82 @@+from __future__ import annotations++import logging+import os+import urllib.request+from typing import Any, Optional++from kornia.config import kornia_config++__all__ = ["CachedDownloader"]++logger = logging.getLogger(__name__)+++class CachedDownloader:+ """Downloads files from URLs to the local cache or .kornia_hub directory."""++ @classmethod+ def _get_file_path(cls, model_name: str, cache_dir: Optional[str], suffix: Optional[str] = None) -> str:+ f"""Constructs the file path for the ONNX model based on the model name and cache directory.++ Args:+ model_name: The name of the model or operator, typically in the format 'operators/model_name'.+ cache_dir: The directory where the model should be cached.+ Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.++ Returns:+ str: The full local path where the model should be stored or loaded from.+ """+ # Determine the local file path+ if cache_dir is None:+ cache_dir = kornia_config.hub_cache_dir++ # The filename is the model name (without directory path)+ if suffix is not None and not model_name.endswith(suffix):+ file_name = f"{os.path.split(model_name)[-1]}{suffix}"+ else:+ file_name = os.path.split(model_name)[-1]+ file_path = os.path.join(*cache_dir.split(os.sep), *model_name.split(os.sep)[:-1], file_name)+ return file_path++ @classmethod+ def download_to_cache(cls, url: str, name: str, download: bool = True, **kwargs: Any) -> str:+ if url.startswith(("http:", "https:")):+ cache_dir = kwargs.get("cache_dir", None)+ suffix = kwargs.get("suffix", None)+ file_path = cls._get_file_path(name, cache_dir, suffix=suffix)+ cls.download(url, file_path, download_if_not_exists=download)+ return file_path+ raise ValueError(f"URL must start with 'http:' or 'https:'. Got {url}")++ @classmethod+ def download(+ cls,+ url: str,+ file_path: str,+ download_if_not_exists: bool = True,+ ) -> None:+ """Downloads an ONNX model from the specified URL and saves it to the specified file path.++ Args:+ url: The URL of the ONNX model to download.+ file_path: The local path where the downloaded model should be saved.+ download_if_not_exists: If True, the file will be downloaded if it's not already downloaded.+ """+ if os.path.exists(file_path):+ logger.info(f"Loading `{url}` from `{file_path}`.")+ return++ if not download_if_not_exists:+ raise ValueError(f"`{file_path}` not found. You may set `download=True`.")++ os.makedirs(os.path.dirname(file_path), exist_ok=True) # Create the cache directory if it doesn't exist++ if url.startswith(("http:", "https:")):+ try:+ logger.info(f"Downloading `{url}` to `{file_path}`.")+ urllib.request.urlretrieve(url, file_path) # noqa: S310+ except urllib.error.HTTPError as e:+ raise ValueError(f"Error in resolving `{url}`. {e}.")+ else:+ raise ValueError("URL must start with 'http:' or 'https:'")diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex 050326db5..e8c27af7f 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -345,11 +345,11 @@ def dict_to_dataclass(dict_obj: Dict[str, Any], dataclass_type: Type[T]) -> T:raise TypeError("Input conf must be dict")if not is_dataclass(dataclass_type):raise TypeError("dataclass_type must be a dataclass")- field_types = {f.name: f.type for f in fields(dataclass_type)}+ field_types: dict[str, Any] = {f.name: f.type for f in fields(dataclass_type)}constructor_args = {}for key, value in dict_obj.items():if key in field_types and is_dataclass(field_types[key]):- constructor_args[key] = dict_to_dataclass(value, field_types[key]) # type: ignore+ constructor_args[key] = dict_to_dataclass(value, field_types[key])else:constructor_args[key] = value# TODO: remove type ignore when https://github.com/python/mypy/issues/14941 be andresseddiff --git a/kornia/utils/sample.py b/kornia/utils/sample.pynew file mode 100644index 000000000..f6b44852f--- /dev/null+++ b/kornia/utils/sample.py@@ -0,0 +1,95 @@+import logging+import os+from typing import Any, List, Optional, Tuple, Union++import kornia+from kornia.core import Tensor, stack+from kornia.core.external import PILImage as Image+from kornia.io import load_image+from kornia.core.external import requests++__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[Tensor, List[Tensor]]:+ """Loads 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 stack(tensors)++ return tensorsdiff --git a/requirements/requirements-dev.txt b/requirements/requirements-dev.txtindex 359835d62..ccc7a85c4 100644--- a/requirements/requirements-dev.txt+++ b/requirements/requirements-dev.txt@@ -4,6 +4,7 @@ diffusersmypynumpy<2onnx+onnxruntimepillowpre-commit>=2pytest==8.3.3@@ -11,3 +12,4 @@ pytest-timeoutrequestssetuptools>=61.2 # needed by pytorch dynamo / tritontransformers+types-requestsdiff --git a/requirements/requirements-docs.txt b/requirements/requirements-docs.txtindex 770406e84..87d2805a7 100644--- a/requirements/requirements-docs.txt+++ b/requirements/requirements-docs.txt@@ -1,6 +1,8 @@furokornia_moonsmatplotlib+onnx+onnxruntimeopencv-pythonPyYAML>=5.1sphinxdiff --git a/tests/contrib/test_object_detector.py b/tests/contrib/test_object_detector.pyindex 00eee98b8..072a56635 100644--- a/tests/contrib/test_object_detector.py+++ b/tests/contrib/test_object_detector.py@@ -16,9 +16,9 @@ class TestObjectDetector(BaseTester):confidence = 0.3config = RTDETRConfig("resnet50d", 10, head_num_queries=10)model = RTDETR.from_config(config).to(device, dtype).eval()- pre_processor = kornia.contrib.object_detection.ResizePreProcessor((32, 32))+ pre_processor = kornia.models.utils.ResizePreProcessor(32, 32)post_processor = DETRPostProcessor(confidence, num_top_queries=3).to(device, dtype).eval()- detector = kornia.contrib.ObjectDetector(model, pre_processor, post_processor)+ detector = kornia.models.detection.ObjectDetector(model, pre_processor, post_processor)sizes = torch.randint(5, 10, (batch_size, 2)) * 32imgs = [torch.randn(3, h, w, device=device, dtype=dtype) for h, w in sizes]@@ -29,7 +29,7 @@ class TestObjectDetector(BaseTester):assert pre_processor_out[0].shape[-2] == 32assert len(detections) == batch_sizefor dets in detections:- assert dets.shape[1] == 6+ assert dets.shape[1] == 6, dets.shapeassert torch.all(dets[:, 0].int() == dets[:, 0])assert torch.all(dets[:, 1] >= 0.3)@@ -39,9 +39,9 @@ class TestObjectDetector(BaseTester):def test_onnx(self, device, dtype, tmp_path: Path, variant: str):config = RTDETRConfig(variant, 1)model = RTDETR.from_config(config).to(device=device, dtype=dtype).eval()- pre_processor = kornia.contrib.object_detection.ResizePreProcessor((640, 640))+ pre_processor = kornia.models.utils.ResizePreProcessor(640, 640)post_processor = DETRPostProcessor(0.3, num_top_queries=3)- detector = kornia.contrib.ObjectDetector(model, pre_processor, post_processor)+ detector = kornia.models.detection.ObjectDetector(model, pre_processor, post_processor)data = torch.rand(3, 400, 640, device=device, dtype=dtype)diff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.pyindex 51dc469f8..d6f6deeac 100644--- a/tests/enhance/test_normalize.py+++ b/tests/enhance/test_normalize.py@@ -10,7 +10,7 @@ class TestNormalize(BaseTester):def test_smoke(self, device, dtype):mean = [0.5]std = [0.1]- repr = "Normalize(mean=tensor([0.5000]), std=tensor([0.1000]))"+ repr = "Normalize(mean=tensor([[0.5000]]), std=tensor([[0.1000]]))"assert str(kornia.enhance.Normalize(mean, std)) == reprdef test_normalize(self, device, dtype):@@ -137,7 +137,7 @@ class TestNormalize(BaseTester):def test_random_normalize_invalid_parameter_shape(self, mean, std):f = kornia.enhance.Normalize(mean=mean, std=std)inputs = torch.arange(0.0, 16.0, step=1).reshape(1, 4, 4).unsqueeze(0)- with pytest.raises(ValueError):+ with pytest.raises((ValueError, RuntimeError)):f(inputs)@pytest.mark.skip(reason="not implemented yet")diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex 77e669d50..d566b637b 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -729,9 +729,10 @@ class TestDexiNed(BaseTester):def test_smoke(self, device, dtype):img = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)net = DexiNed(pretrained=False).to(device, dtype)+ feat = net.get_features(img)+ assert len(feat) == 6out = net(img)- assert len(out) == 7- assert out[-1].shape == (2, 1, 32, 32)+ assert out.shape == (2, 1, 32, 32)@pytest.mark.slow@pytest.mark.parametrize("data", ["dexined"], indirect=True)@@ -750,7 +751,7 @@ class TestDexiNed(BaseTester):dtype=dtype,)- out = model(img)[-1]+ out = model(img)self.assert_close(out, expect, atol=3e-4, rtol=3e-4)@pytest.mark.skip(reason="DexiNed do not compile with dynamo.")diff --git a/tests/models/box_filtering.py b/tests/models/box_filtering.pynew file mode 100644index 000000000..6d489d27a--- /dev/null+++ b/tests/models/box_filtering.py@@ -0,0 +1,100 @@+import pytest+import torch+from numpy.testing import assert_almost_equal++from kornia.core import tensor+from kornia.models.detection.utils import BoxFiltering # Replace with the actual module path+++class TestBoxFiltering:+ @pytest.fixture+ def sample_boxes(self):+ # Setup some sample boxes with the format [class_id, confidence_score, x, y, w, h]+ return tensor(+ [+ [+ [1, 0.9, 10, 10, 20, 20], # High confidence, class 1+ [2, 0.7, 15, 15, 25, 25], # Medium confidence, class 2+ [3, 0.7, 15, 15, 25, 25], # Medium confidence, class 3+ [4, 0.3, 5, 5, 10, 10],+ ], # Low confidence, class 4+ [+ [1, 0.95, 12, 12, 18, 18], # High confidence, class 1+ [2, 0.5, 13, 13, 20, 20], # Low confidence, class 2+ [3, 0.5, 13, 13, 20, 20], # Low confidence, class 3+ [4, 0.2, 7, 7, 14, 14],+ ], # Very low confidence, class 4+ [+ [1, 0.1, 12, 12, 18, 18], # Very Low confidence, class 1+ [2, 0.1, 13, 13, 20, 20], # Very Low confidence, class 2+ [3, 0.1, 13, 13, 20, 20], # Very Low confidence, class 3+ [4, 0.1, 7, 7, 14, 14],+ ], # Very Low confidence, class 4+ ]+ ) # Shape: [3, 4, 6], i.e., [B, D, 6]++ def test_confidence_filtering(self, sample_boxes):+ """Test filtering based on confidence threshold."""+ # Set a confidence threshold of 0.7+ filter = BoxFiltering(confidence_threshold=0.7)+ filtered_boxes = filter(sample_boxes)++ # Expected output: only boxes with confidence > 0.7 should be kept+ assert len(filtered_boxes[0]) == 1 # Only one box in the first batch+ assert_almost_equal(filtered_boxes[0][0][1].item(), 0.9) # Box with confidence 0.9+ assert len(filtered_boxes[1]) == 1 # Only one box in the second batch+ assert_almost_equal(filtered_boxes[1][0][1].item(), 0.95) # Box with confidence 0.95+ assert len(filtered_boxes[2]) == 0 # No boxes in the third batch++ def test_class_filtering(self, sample_boxes):+ """Test filtering based on class IDs."""+ # Set classes_to_keep to [1, 2]+ filter = BoxFiltering(classes_to_keep=tensor([1, 2]))+ filtered_boxes = filter(sample_boxes)++ # Expected output: only boxes with class_id 1 and 2 should be kept+ assert len(filtered_boxes[0]) == 2 # Two boxes in the first batch+ assert filtered_boxes[0][0][0].item() == 1 # Box with class_id 1+ assert filtered_boxes[0][1][0].item() == 2 # Box with class_id 2+ assert len(filtered_boxes[1]) == 2 # Two boxes in the second batch+ assert filtered_boxes[1][0][0].item() == 1 # Box with class_id 1+ assert filtered_boxes[1][1][0].item() == 2 # Box with class_id 2+ assert len(filtered_boxes[2]) == 2 # Two boxes in the third batch+ assert filtered_boxes[2][0][0].item() == 1 # Box with class_id 1+ assert filtered_boxes[2][1][0].item() == 2 # Box with class_id 2++ def test_combined_confidence_and_class_filtering(self, sample_boxes):+ """Test filtering based on both confidence and class IDs."""+ # Set confidence threshold to 0.6 and classes_to_keep to [1, 3]+ filter = BoxFiltering(confidence_threshold=0.6, classes_to_keep=tensor([1, 3]))+ filtered_boxes = filter(sample_boxes)++ # Expected output: only boxes with confidence > 0.6 and class_id in [1, 3] should be kept+ assert len(filtered_boxes[0]) == 2 # Two boxes in the first batch+ assert filtered_boxes[0][0][0].item() == 1 # Class_id 1+ assert filtered_boxes[0][1][0].item() == 3 # Class_id 3+ assert filtered_boxes[1][0][0].item() == 1 # Class_id 1+ assert len(filtered_boxes[1]) == 1 # No boxes in the second batch+ assert len(filtered_boxes[2]) == 0 # No boxes in the third batch++ def test_filter_as_zero(self, sample_boxes):+ """Test filtering boxes as zero when filter_as_zero is True."""+ filter = BoxFiltering(confidence_threshold=0.8, filter_as_zero=True)+ filtered_boxes = filter(sample_boxes)++ # Expected output: boxes with confidence <= 0.8 should be zeroed out+ assert torch.all(filtered_boxes[0][0] != 0) # Box with confidence 0.9 should remain+ assert torch.all(filtered_boxes[0][1:] == 0) # Remaining boxes should be zeroed+ assert torch.all(filtered_boxes[1][0] != 0) # Box with confidence 0.95 should remain+ assert torch.all(filtered_boxes[1][1:] == 0) # Remaining boxes should be zeroed+ assert torch.all(filtered_boxes[2] == 0) # All boxes in the third batch should be zeroed++ def test_no_class_or_confidence_filtering(self, sample_boxes):+ """Test when no class or confidence filtering is applied."""+ filter = BoxFiltering() # No thresholds set+ filtered_boxes = filter(sample_boxes)++ # Expected output: all boxes should be returned as-is+ assert len(filtered_boxes[0]) == 4 # All boxes in the first batch should be kept+ assert len(filtered_boxes[1]) == 4 # All boxes in the second batch should be kept+ assert len(filtered_boxes[2]) == 4 # All boxes in the third batch should be keptdiff --git a/tests/onnx/test_sequential.py b/tests/onnx/test_sequential.pynew file mode 100644index 000000000..d7e44aff7--- /dev/null+++ b/tests/onnx/test_sequential.py@@ -0,0 +1,69 @@+from unittest.mock import MagicMock, patch++import onnx+import onnxruntime as ort+import pytest+from onnx.helper import make_graph, make_model, make_node, make_tensor_value_info++from kornia.onnx.sequential import ONNXSequential+++class TestONNXSequential:+ @pytest.fixture+ def mock_model_proto(self):+ # Create a minimal ONNX model with an input and output+ input_info = make_tensor_value_info("input", onnx.TensorProto.FLOAT, [1, 2])+ output_info = make_tensor_value_info("output", onnx.TensorProto.FLOAT, [1, 2])+ node = make_node("Identity", ["input"], ["output"])+ graph = make_graph([node], "test_graph", [input_info], [output_info])+ op = onnx.OperatorSetIdProto()+ op.version = 17+ model = make_model(graph, opset_imports=[op])+ return model++ @pytest.fixture+ def onnx_sequential(self, mock_model_proto):+ # Return an ONNXSequential instance with mocked models+ return ONNXSequential(mock_model_proto, mock_model_proto)++ def test_load_op_from_proto(self, mock_model_proto, onnx_sequential):+ # Test loading a model from an ONNX ModelProto object+ model = onnx_sequential._load_op(mock_model_proto)+ assert model == mock_model_proto++ @patch("onnx.compose.merge_models")+ def test_combine_models(self, mock_merge_models, mock_model_proto):+ # Create a small ONNX model as the return value of merge_models+ input_info = make_tensor_value_info("input", onnx.TensorProto.FLOAT, [1, 2])+ output_info = make_tensor_value_info("output", onnx.TensorProto.FLOAT, [1, 2])+ node = make_node("Identity", ["input"], ["output"])+ graph = make_graph([node], "combined_graph", [input_info], [output_info])+ op = onnx.OperatorSetIdProto()+ op.version = 17+ combined_model = make_model(graph, opset_imports=[op])++ mock_merge_models.return_value = combined_model++ # Test combining multiple ONNX models with io_maps+ onnx_sequential = ONNXSequential(mock_model_proto, mock_model_proto)+ combined_op = onnx_sequential.combine([("output1", "input2")])++ assert isinstance(combined_op, onnx.ModelProto)++ @patch("onnx.save")+ def test_export_combined_model(self, mock_save, onnx_sequential):+ # Test exporting the combined ONNX model+ onnx_sequential.export("exported_model.onnx")+ mock_save.assert_called_once_with(onnx_sequential._combined_op, "exported_model.onnx")++ @patch("onnxruntime.InferenceSession")+ def test_create_session(self, mock_inference_session, onnx_sequential):+ # Test creating an ONNXRuntime session+ session = onnx_sequential.create_session()+ assert session == mock_inference_session()++ def test_set_get_session(self, onnx_sequential):+ # Test setting and getting a custom session+ mock_session = MagicMock(spec=ort.InferenceSession)+ onnx_sequential.set_session(mock_session)+ assert onnx_sequential.get_session() == mock_sessiondiff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.pynew file mode 100644index 000000000..a89e31b9a--- /dev/null+++ b/tests/onnx/test_utils.py@@ -0,0 +1,123 @@+import os+import urllib+from unittest import mock++import pytest+from onnx import ModelProto # Assuming `onnx` is installed and ModelProto is part of the library++from kornia.onnx.utils import ONNXLoader+++class TestONNXLoader:+ def test_get_file_path_with_custom_cache_dir(+ self,+ ):+ model_name = os.path.join("operators", "some_model")+ expected_path = os.path.join(".test_cache", "operators", "some_model.onnx")+ assert ONNXLoader._get_file_path(model_name, ".test_cache", suffix=".onnx") == expected_path++ def test_get_file_path_with_default_cache_dir(self):+ model_name = os.path.join("onnx_models", "some_model")+ expected_path = os.path.join(".kornia_hub", "onnx_models", "some_model.onnx")+ assert ONNXLoader._get_file_path(model_name, None, suffix=".onnx") == expected_path++ @mock.patch("onnx.load")+ @mock.patch("os.path.exists")+ def test_load_model_local(self, mock_exists, mock_onnx_load):+ model_name = "local_model.onnx"+ mock_exists.return_value = True++ # Simulate onnx.load returning a dummy ModelProto+ mock_model = mock.Mock(spec=ModelProto)+ mock_onnx_load.return_value = mock_model++ model = ONNXLoader.load_model(model_name)+ assert model == mock_model+ mock_onnx_load.assert_called_once_with(model_name)++ @mock.patch("urllib.request.urlretrieve")+ @mock.patch("os.path.exists")+ def test_load_model_download(self, mock_exists, mock_urlretrieve):+ model_name = "hf://operators/some_model"+ mock_exists.return_value = False+ mock_urlretrieve.return_value = None # Simulating successful download++ with mock.patch("onnx.load") as mock_onnx_load:+ mock_model = mock.Mock(spec=ModelProto)+ mock_onnx_load.return_value = mock_model++ model = ONNXLoader.load_model(model_name)+ assert model == mock_model+ mock_urlretrieve.assert_called_once_with(+ "https://huggingface.co/kornia/ONNX_models/resolve/main/operators/some_model.onnx",+ os.path.join(".kornia_hub", "onnx_models", "operators", "some_model.onnx"),+ )++ def test_load_model_file_not_found(self):+ model_name = "non_existent_model.onnx"++ with pytest.raises(ValueError, match=f"File {model_name} not found"):+ ONNXLoader.load_model(model_name)++ @mock.patch("urllib.request.urlretrieve")+ @mock.patch("os.makedirs")+ def test_download_success(self, mock_makedirs, mock_urlretrieve):+ url = "https://huggingface.co/some_model.onnx"+ file_path = os.path.join(".test_cache", "some_model.onnx")++ ONNXLoader.download(url, file_path)++ mock_makedirs.assert_called_once_with(os.path.dirname(file_path), exist_ok=True)+ mock_urlretrieve.assert_called_once_with(url, file_path)++ @mock.patch(+ "urllib.request.urlretrieve",+ side_effect=urllib.error.HTTPError(url=None, code=404, msg="Not Found", hdrs=None, fp=None),+ )+ def test_download_failure(self, mock_urlretrieve):+ url = "https://huggingface.co/non_existent_model.onnx"+ file_path = os.path.join(".test_cache", "non_existent_model.onnx")++ with pytest.raises(ValueError, match="Error in resolving"):+ ONNXLoader.download(url, file_path)++ @mock.patch("requests.get")+ def test_fetch_repo_contents_success(self, mock_get):+ mock_response = mock.Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = [{"path": os.path.join("operators", "model.onnx")}]+ mock_get.return_value = mock_response++ contents = ONNXLoader._fetch_repo_contents("operators")+ assert contents == [{"path": os.path.join("operators", "model.onnx")}]++ @mock.patch("requests.get")+ def test_fetch_repo_contents_failure(self, mock_get):+ mock_response = mock.Mock()+ mock_response.status_code = 404+ mock_get.return_value = mock_response++ with pytest.raises(ValueError, match="Failed to fetch repository contents"):+ ONNXLoader._fetch_repo_contents("operators")++ @mock.patch("kornia.onnx.utils.ONNXLoader._fetch_repo_contents")+ def test_list_operators(self, mock_fetch_repo_contents, capsys):+ mock_fetch_repo_contents.return_value = [{"path": os.path.join("operators", "some_model.onnx")}]++ ONNXLoader.list_operators()++ captured = capsys.readouterr()+ assert (+ os.path.join("operators", "some_model.onnx").replace("\\", "\\\\") in captured.out+ ) # .replace() for Windows++ @mock.patch("kornia.onnx.utils.ONNXLoader._fetch_repo_contents")+ def test_list_models(self, mock_fetch_repo_contents, capsys):+ mock_fetch_repo_contents.return_value = [{"path": os.path.join("operators", "some_model.onnx")}]++ ONNXLoader.list_models()++ captured = capsys.readouterr()+ assert (+ os.path.join("operators", "some_model.onnx").replace("\\", "\\\\") in captured.out+ ) # .replace() for Windows