Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(models)!: resize Depth-Anything input as transformers does; return (B, 1, H, W) depth (#6030)

Dmytro Mishkindd3bddb7e774
diff --git a/changelog.d/6030.breaking.md b/changelog.d/6030.breaking.md
new file mode 100644
index 000000000..a5b57164c
--- /dev/null
+++ b/changelog.d/6030.breaking.md
@@ -0,0 +1 @@
+`DepthEstimation` called on a `(B, 3, H, W)` tensor returns depth maps of shape `(B, 1, H, W)`, kornia's image layout; it returned `(B, H, W)`. A list of `(3, H, W)` images still returns `(1, H, W)` items. The graph exported by `to_onnx(include_pre_and_post_processor=True)` from a `DepthAnythingONNXBuilder` model takes an image that is already resized, such as `model.resize(image)`; it took an image of any size and squashed it to 518 x 518. The resize keeps the aspect ratio, so its output size depends on the input size, and it runs in torch before the graph.
diff --git a/changelog.d/6030.fixed.md b/changelog.d/6030.fixed.md
new file mode 100644
index 000000000..42d31c9dc
--- /dev/null
+++ b/changelog.d/6030.fixed.md
@@ -0,0 +1 @@
+The model `DepthAnythingONNXBuilder.build` returns resizes each image to the size transformers' `DPTImageProcessor` computes from the model's `preprocessor_config.json`: it keeps the aspect ratio, fitting the side whose scale is closer to 1, and makes each side a multiple of 14. The filter is an antialiased bicubic, the one of transformers' DPT image processor (its torchvision backend, `torchvision.transforms.v2.functional.resize` with `antialias=True`), which approximates PIL's resize. The depth is resized back to the image size bicubically, as transformers' `post_process_depth_estimation` does; it was resized back bilinearly. Every image used to be squashed to 518 x 518 with a bilinear resize without antialiasing, so a 16:9 frame was squeezed 1.78x horizontally before the network saw it; a 300 x 400 image now reaches the network at 392 x 518, and a 1080 x 1920 frame at 518 x 924. Every image other than 518 x 518 is now resized by this rule and these filters, so its depth changes. The config parser behind it reads `keep_aspect_ratio`, `ensure_multiple_of` and `resample` (PIL's nearest, bilinear or bicubic), with the processor's defaults (`False`, `1`, bicubic) when they are absent, and raises `NotImplementedError` for any other `resample` filter, which it used to replace with bilinear. `DepthEstimation` accepts images of any floating dtype: it runs the graph in float32 and returns the depth in the image's dtype, where a float64, float16 or bfloat16 image raised inside ONNX Runtime or NumPy. An integer image raises kornia's `BaseError` instead of ONNX Runtime's `InvalidArgument`. `DepthEstimation.visualize` and `save` accept a tensor batch, on which they raised `ValueError`.
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.py
index 1f0387f33..ef34bd212 100644
--- a/kornia/models/_hf_models/hf_onnx_community.py
+++ b/kornia/models/_hf_models/hf_onnx_community.py
@@ -22,6 +22,7 @@ import os
from typing import Any, Optional
import torch
+from torch import nn
from kornia.config import kornia_config
from kornia.core import ImageSequential
@@ -148,6 +149,11 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
conversion when composing the sequence.
io_maps: Optional list of input/output name mappings used when connecting the
ONNX graphs together.
+ resize: Optional torch module that resizes an image before the ONNX graphs, for a
+ resize whose output size depends on the input size and so cannot be part of a
+ graph with dynamic height and width. It is kept as ``self.resize``; the subclass
+ that runs the graphs applies it (:class:`~kornia.models.depth_estimation.DepthEstimation`
+ does), and it is not part of the graph :meth:`to_onnx` exports.
"""
name: str = "onnx_community_model"
@@ -160,6 +166,7 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
name: Optional[str] = None,
auto_ir_version_conversion: bool = True,
io_maps: Optional[list[tuple[str, str]]] = None,
+ resize: Optional[nn.Module] = None,
) -> None:
model_list = [] if pre_processor is None else [pre_processor]
model_list.append(model)
@@ -171,13 +178,14 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
self.model = model
self.pre_processor = pre_processor
self.post_processor = post_processor
+ self.resize = resize
def resize_back(self, images: torch.Tensor, target_images: torch.Tensor) -> torch.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.
+ images: The images to be resized, of shape :math:`(B, C, h, w)`.
+ target_images: The target images whose size ``(H, W)`` is used as the reference for resizing.
Returns:
The resized images.
@@ -195,14 +203,16 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
) -> onnx.ModelProto:
- """Export a depth estimation model to ONNX format.
+ """Export the ONNX model, alone or combined with its pre- and post-processing graphs, 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.
+ The name of the output ONNX file. If not provided, ``"kornia_<name>.onnx"`` is used, with the
+ model's ``name``.
include_pre_and_post_processor:
- Whether to include the pre-processor and post-processor in the exported model.
+ Whether to include the pre-processor and post-processor graphs in the exported model. The
+ ``resize`` stage runs in torch and is in neither graph: for a model that has one, the exported
+ graph takes an image that is already resized, such as ``model.resize(image)``.
save:
If to save the model or load it.
additional_metadata:
diff --git a/kornia/models/_hf_models/preprocessor.py b/kornia/models/_hf_models/preprocessor.py
index 64dafe396..86bf51826 100644
--- a/kornia/models/_hf_models/preprocessor.py
+++ b/kornia/models/_hf_models/preprocessor.py
@@ -20,6 +20,7 @@ from __future__ import annotations
from typing import Any
import torch
+import torch.nn.functional as F
from torch import nn
from kornia.core import ImageSequential
@@ -27,6 +28,77 @@ from kornia.enhance.normalize import Normalize
from kornia.enhance.rescale import Rescale
from kornia.geometry.transform import Resize
+# The PIL resampling filters a processor config's ``resample`` may name, as torch.nn.functional.interpolate modes:
+# PIL's NEAREST samples the pixel centres, which is torch's "nearest-exact"
+_RESAMPLE_TO_INTERPOLATION = {0: "nearest-exact", 2: "bilinear", 3: "bicubic"}
+
+
+def _dpt_output_size(
+ height: int, width: int, size: tuple[int, int], keep_aspect_ratio: bool, multiple: int
+) -> tuple[int, int]:
+ """Return the ``(height, width)`` to which transformers' ``DPTImageProcessor`` resizes an image.
+
+ A transcription of ``get_resize_output_image_size`` and its ``constrain_to_multiple_of`` in
+ ``transformers.models.dpt.image_processing_dpt``. With ``keep_aspect_ratio``, the side whose scale to ``size`` is
+ closer to 1 is fitted to ``size`` and the other side is scaled by the same factor; without it, each side is scaled
+ to its target. Each side is then rounded to the nearest multiple of ``multiple`` with Python ``round``, so a tie
+ goes to the even multiple. A side that would round to 0, on an image more elongated than about 74:1 at the
+ Depth-Anything settings, is kept at one ``multiple``: transformers passes 0 to its resize, which raises.
+ """
+ scale_height = size[0] / height
+ scale_width = size[1] / width
+ if keep_aspect_ratio:
+ # scale as little as possible
+ if abs(1 - scale_width) < abs(1 - scale_height):
+ scale_height = scale_width
+ else:
+ scale_width = scale_height
+ out_height = max(multiple, round(scale_height * height / multiple) * multiple)
+ out_width = max(multiple, round(scale_width * width / multiple) * multiple)
+ return out_height, out_width
+
+
+class _DPTResize(nn.Module):
+ """Resize an image to the size transformers' ``DPTImageProcessor`` computes from each input's shape.
+
+ The output size is :func:`_dpt_output_size` of the input's height and width. The filter is the one of
+ transformers' DPT image processor (its torchvision backend, ``torchvision.transforms.v2.functional.resize`` with
+ ``antialias=True``), which makes this :func:`torch.nn.functional.interpolate` call: ``"bicubic"`` and
+ ``"bilinear"`` with ``align_corners=False`` and ``antialias=True``, and ``"nearest-exact"``, to which it maps PIL's
+ ``NEAREST``, without a filter. It approximates PIL's ``Image.resize`` to a mean of 0.29/255 on photos.
+
+ This departs from kornia's :func:`~kornia.geometry.transform.resize` on purpose: its antialiasing, a Gaussian blur
+ followed by torch's bicubic with ``a = -0.75``, is 2.3 to 3.8 times further from PIL (a mean of 0.7/255 to
+ 1.1/255 on the same photos), since PIL uses a bicubic with ``a = -0.5`` and widens it when it downscales.
+
+ The size depends on the input shape, so this module runs in torch: it cannot be exported to an ONNX graph with
+ dynamic height and width.
+
+ Args:
+ size: Target ``(height, width)`` before the aspect ratio and the multiple are applied.
+ keep_aspect_ratio: Whether to scale both sides by the same factor.
+ multiple: Each output side is a multiple of this number.
+ interpolation: ``"bicubic"``, ``"bilinear"`` or ``"nearest-exact"``.
+ """
+
+ def __init__(self, size: tuple[int, int], keep_aspect_ratio: bool, multiple: int, interpolation: str) -> None:
+ super().__init__()
+ self.size = size
+ self.keep_aspect_ratio = keep_aspect_ratio
+ self.multiple = multiple
+ self.interpolation = interpolation
+
+ def forward(self, image: torch.Tensor) -> torch.Tensor:
+ """Resize ``image`` of shape :math:`(*, C, H, W)` to the DPT output size of its ``H`` and ``W``."""
+ height, width = image.shape[-2:]
+ output_size = _dpt_output_size(height, width, self.size, self.keep_aspect_ratio, self.multiple)
+ batch = image.reshape(-1, *image.shape[-3:])
+ if self.interpolation == "nearest-exact":
+ out = F.interpolate(batch, size=output_size, mode="nearest-exact")
+ else:
+ out = F.interpolate(batch, size=output_size, mode=self.interpolation, align_corners=False, antialias=True)
+ return out.reshape(*image.shape[:-2], *output_size)
+
class PreprocessingLoader:
"""Factory for converting image-processor settings into Kornia modules.
@@ -106,11 +178,15 @@ class PreprocessingLoader:
class DPTImageProcessor(PreprocessingLoader):
"""Parser for DPT image processor configurations.
- DPT models use a fixed image preprocessing recipe before inference. This parser
- reads the supported JSON fields and constructs the equivalent Kornia pipeline in
- the same order used by the processor configuration: resize, rescale, and normalize.
- Padding is intentionally not handled here because the current implementation does
- not include the extra parameters needed to reproduce that branch safely.
+ This parser reads the fields of a transformers ``DPTImageProcessor`` configuration and builds a Kornia pipeline
+ in the processor's order: resize, rescale, and normalize. The resize computes the processor's output size: it
+ keeps the aspect ratio when ``keep_aspect_ratio`` is set and makes each side a multiple of ``ensure_multiple_of``,
+ so the size depends on the input's. Its filter is the one of transformers' DPT image processor (its torchvision
+ backend, ``torchvision.transforms.v2.functional.resize`` with ``antialias=True``), which approximates PIL's
+ ``Image.resize``. That resize runs in torch; it cannot be part of an ONNX graph with dynamic height and width.
+
+ Padding (``do_pad`` with its ``size_divisor``) is not supported, nor are the ``resample`` filters other than
+ nearest, bilinear and bicubic.
"""
@staticmethod
@@ -118,25 +194,37 @@ class DPTImageProcessor(PreprocessingLoader):
"""Convert a DPT processor JSON dictionary into a Kornia preprocessing pipeline.
Args:
- json_data: Parsed DPT processor configuration. Supported fields include
- ``do_resize``, ``size``, ``do_rescale``, ``rescale_factor``,
- ``do_normalize``, ``image_mean``, and ``image_std``.
+ json_data: Parsed DPT processor configuration. The fields read are
+ ``do_pad``, which must be false, ``do_resize``, ``size``, ``keep_aspect_ratio``,
+ ``ensure_multiple_of``, ``resample``, ``do_rescale``, ``rescale_factor``,
+ ``do_normalize``, ``image_mean`` and ``image_std``. An absent ``keep_aspect_ratio``,
+ ``ensure_multiple_of`` or ``resample`` takes the processor's default:
+ ``False``, ``1`` and ``3`` (bicubic).
Returns:
:class:`~kornia.core.ImageSequential` containing the enabled preprocessing
modules in execution order.
Raises:
- NotImplementedError: If the configuration requests padding, which is not
- implemented by this loader.
+ NotImplementedError: If the configuration requests padding, or a ``resample``
+ filter other than nearest (0), bilinear (2) or bicubic (3).
"""
preproc_list: list[nn.Module] = []
if json_data["do_pad"]:
raise NotImplementedError
if json_data["do_resize"]:
- # Missing some parameters such as `ensure_multiple_of`, `keep_aspect_ratio`
+ resample = json_data.get("resample", 3)
+ if resample not in _RESAMPLE_TO_INTERPOLATION:
+ raise NotImplementedError(
+ f"Unsupported resample {resample}: kornia implements nearest (0), bilinear (2) and bicubic (3)."
+ )
preproc_list.append(
- PreprocessingLoader.resize(width=json_data["size"]["width"], height=json_data["size"]["height"])
+ _DPTResize(
+ size=(json_data["size"]["height"], json_data["size"]["width"]),
+ keep_aspect_ratio=json_data.get("keep_aspect_ratio", False),
+ multiple=json_data.get("ensure_multiple_of", 1),
+ interpolation=_RESAMPLE_TO_INTERPOLATION[resample],
+ )
)
if json_data["do_rescale"]:
preproc_list.append(PreprocessingLoader.rescale(rescale_factor=json_data["rescale_factor"] * 255))
diff --git a/kornia/models/depth_estimation/base.py b/kornia/models/depth_estimation/base.py
index cfd3da838..087b9205f 100644
--- a/kornia/models/depth_estimation/base.py
+++ b/kornia/models/depth_estimation/base.py
@@ -20,8 +20,10 @@ from __future__ import annotations
from typing import Optional, Union
import torch
+import torch.nn.functional as F
from kornia.color.gray import grayscale_to_rgb
+from kornia.core.check import KORNIA_CHECK
from kornia.core.external import PILImage as Image
from kornia.models._hf_models import HFONNXComunnityModel
@@ -34,53 +36,67 @@ class DepthEstimation(HFONNXComunnityModel):
name: str = "depth_estimation"
def __call__(self, images: Union[torch.Tensor, list[torch.Tensor]]) -> Union[torch.Tensor, list[torch.Tensor]]:
- """Detect objects in a given list of images.
+ """Estimate the depth map of each image.
+
+ The image is cast to float32, moved to the CPU and resized there by the ``resize`` stage, if the model has
+ one. ONNX Runtime runs the graphs on a NumPy array of it. The depth map is resized back to the image size on
+ the CPU in float32 with a bicubic interpolation, as transformers' ``post_process_depth_estimation`` does, then
+ cast to the dtype of the image and moved to its device.
Args:
images: If list of RGB images. Each image is a torch.Tensor with shape :math:`(3, H, W)`.
- If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.
+ If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`. Any floating dtype.
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.
+ The depth maps at the size of the images: a tensor of shape :math:`(B, 1, H, W)` for a tensor, and a
+ list of tensors of shape :math:`(1, H, W)` for a list.
+
+ Raises:
+ BaseError: If an image is not of a floating dtype.
"""
- if isinstance(
- images,
- (
- list,
- tuple,
- ),
- ):
- results = [super(DepthEstimation, self).__call__(image[None].cpu().numpy())[0] for image in images]
- return [
- self.resize_back(torch.tensor(result, device=image.device, dtype=image.dtype), image)
- for result, image in zip(results, images)
- ]
-
- result = super().__call__(images.cpu().numpy())[0]
- result = torch.tensor(result, device=images.device, dtype=images.dtype)
- return self.resize_back(result, images)
+ if isinstance(images, (list, tuple)):
+ return [self._estimate(image[None])[0] for image in images]
+ return self._estimate(images)
+
+ def _estimate(self, images: torch.Tensor) -> torch.Tensor:
+ """Return the depth maps :math:`(B, 1, H, W)` of a batch of images :math:`(B, 3, H, W)`."""
+ KORNIA_CHECK(images.is_floating_point(), f"images must be of a floating dtype, got {images.dtype}")
+ # float32 is the dtype the graph takes, and the resizes run in it as well, so that the depth does not depend on
+ # the input dtype. They run on the CPU, where ONNX Runtime reads its input: torch 2.5.1 has no bicubic kernel
+ # on MPS, and the depth does not depend on the device either.
+ inputs = images.float().cpu()
+ if self.resize is not None:
+ inputs = self.resize(inputs)
+ depth = torch.from_numpy(super().__call__(inputs.numpy())[0])
+ # Depth-Anything's graphs return (B, H, W); a graph that returns (B, 1, H, W) already has the layout
+ if depth.ndim == 3:
+ depth = depth.unsqueeze(1)
+ # as transformers' DPT post_process_depth_estimation resizes the predicted depth to the target size
+ depth = F.interpolate(depth, size=tuple(images.shape[-2:]), mode="bicubic", align_corners=False)
+ return depth.to(images.dtype).to(images.device)
def visualize(
self,
- images: torch.Tensor,
+ images: Union[torch.Tensor, list[torch.Tensor]],
depth_maps: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,
output_type: str = "torch",
depth_type: str = "relative",
max_depth: int = 80,
) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]:
- """Draw the segmentation results.
+ """Draw the depth maps.
Args:
- images: input tensor.
- depth_maps: estimated depths.
+ images: a tensor of shape :math:`(B, 3, H, W)` or a list of tensors of shape :math:`(3, H, W)`.
+ depth_maps: estimated depths, as the model returns them: :math:`(B, 1, H, W)` or a list of
+ :math:`(1, H, W)`. Estimated from ``images`` if not given.
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.
+ A list with one RGB image of shape :math:`(3, H, W)` per depth map, the depth divided by its maximum
+ (``"relative"``) or by ``max_depth`` (``"metric"``), converted according to ``output_type``.
"""
if depth_maps is None:
@@ -99,26 +115,24 @@ class DepthEstimation(HFONNXComunnityModel):
def save(
self,
- images: torch.Tensor,
+ images: Union[torch.Tensor, list[torch.Tensor]],
depth_maps: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,
directory: Optional[str] = None,
output_type: str = "torch",
depth_type: str = "relative",
max_depth: int = 80,
) -> None:
- """Save the segmentation results.
+ """Save the images and their depth maps.
Args:
- images: input tensor.
- depth_maps: estimated depths.
+ images: a tensor of shape :math:`(B, 3, H, W)` or a list of tensors of shape :math:`(3, H, W)`.
+ depth_maps: estimated depths, as the model returns them: :math:`(B, 1, H, W)` or a list of
+ :math:`(1, H, W)`. Estimated from ``images`` if not given.
output_type: type of the output.
depth_type: 'metric' or 'relative' depth.
max_depth: maximum depth value. Only valid for metric depth.
directory: where to store outputs.
- 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")
diff --git a/kornia/models/depth_estimation/depth_anything.py b/kornia/models/depth_estimation/depth_anything.py
index 125530ae7..d73a4d881 100644
--- a/kornia/models/depth_estimation/depth_anything.py
+++ b/kornia/models/depth_estimation/depth_anything.py
@@ -17,7 +17,9 @@
from typing import Optional
+from kornia.core import ImageSequential
from kornia.models._hf_models import HFONNXComunnityModelLoader
+from kornia.models._hf_models.preprocessor import _DPTResize
from .base import DepthEstimation
@@ -31,7 +33,15 @@ class DepthAnythingONNXBuilder:
def build(
model_name: str = "depth-anything-v2-small", model_type: str = "model", cache_dir: Optional[str] = None
) -> DepthEstimation:
- """Export a DepthAnything model to an ONNX model file.
+ """Build a ``DepthEstimation`` around the onnx-community graph (downloaded on first use).
+
+ The returned model resizes each image to the size transformers' ``DPTImageProcessor`` computes from the
+ repository's ``preprocessor_config.json``: it keeps the aspect ratio and makes each side a multiple of
+ ``ensure_multiple_of`` when the config asks for it. The filter is the one of transformers' DPT image
+ processor (its torchvision backend, ``torchvision.transforms.v2.functional.resize`` with ``antialias=True``),
+ which approximates PIL's ``Image.resize``. The output size depends on the input size, so the resize runs in
+ torch, as the model's ``resize`` stage. The rescale and normalize steps are exported to an ONNX graph that
+ runs before the model's.
Args:
model_name: The name of the model to be loaded. Valid model names include:
@@ -54,7 +64,7 @@ class DepthAnythingONNXBuilder:
DepthEstimation: The depth estimation model.
Note:
- To use this model, load an image tensor (shape: ``(1, C, H, W)``) and call ``model.save(image)``.
+ To use this model, load an image tensor (shape: ``(B, 3, H, W)``) and call ``model.save(image)``.
"""
if model_name not in [
@@ -68,5 +78,8 @@ class DepthAnythingONNXBuilder:
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}")
+ preprocessing = loader.load_preprocessing()
+ resize = next((m for m in preprocessing if isinstance(m, _DPTResize)), None)
+ others = [m for m in preprocessing if not isinstance(m, _DPTResize)]
+ preproc = ImageSequential(*others).to_onnx(save=False) if others else None
+ return DepthEstimation(onnx_model, pre_processor=preproc, name=f"{model_name}_{model_type}", resize=resize)
diff --git a/tests/models/test_depth_estimation.py b/tests/models/test_depth_estimation.py
new file mode 100644
index 000000000..ab98971f1
--- /dev/null
+++ b/tests/models/test_depth_estimation.py
@@ -0,0 +1,457 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+
+onnx = pytest.importorskip("onnx")
+pytest.importorskip("onnxruntime")
+
+import torch # noqa: E402
+from onnx import TensorProto, helper # noqa: E402
+
+from kornia.models.depth_estimation import DepthEstimation # noqa: E402
+
+from testing.base import BaseTester # noqa: E402
+
+# onnx-community/depth-anything-v2-small preprocessor_config.json (fetched 2026-10-16)
+_DEPTH_ANYTHING_V2_SMALL_CONFIG = {
+ "do_normalize": True,
+ "do_pad": False,
+ "do_rescale": True,
+ "do_resize": True,
+ "ensure_multiple_of": 14,
+ "image_mean": [0.485, 0.456, 0.406],
+ "image_processor_type": "DPTImageProcessor",
+ "image_std": [0.229, 0.224, 0.225],
+ "keep_aspect_ratio": True,
+ "resample": 3,
+ "rescale_factor": 0.00392156862745098,
+ "size": {"height": 518, "width": 518},
+ "size_divisor": None,
+}
+
+
+def _stand_in_graph(keepdims: bool = False) -> onnx.ModelProto:
+ """Return a graph with Depth-Anything's I/O contract, ``(B, 3, H, W) -> (B, H, W)``: the mean over channels.
+
+ With ``keepdims`` the graph returns ``(B, 1, H, W)`` instead, as a depth graph other than Depth-Anything's may.
+ The real onnx-community graph is not downloaded. ``axes`` is an input of ``ReduceMean`` from opset 18.
+ """
+ axes = helper.make_tensor("axes", TensorProto.INT64, [1], [1])
+ output_shape = ["B", 1, "H", "W"] if keepdims else ["B", "H", "W"]
+ graph = helper.make_graph(
+ [helper.make_node("ReduceMean", ["input", "axes"], ["output"], keepdims=int(keepdims))],
+ "stand_in_depth",
+ [helper.make_tensor_value_info("input", TensorProto.FLOAT, ["B", 3, "H", "W"])],
+ [helper.make_tensor_value_info("output", TensorProto.FLOAT, output_shape)],
+ initializer=[axes],
+ )
+ return helper.make_model(graph, opset_imports=[helper.make_opsetid("", 18)])
+
+
+def _depth_anything_resize():
+ from kornia.models._hf_models.preprocessor import _DPTResize
+
+ return _DPTResize(size=(518, 518), keep_aspect_ratio=True, multiple=14, interpolation="bicubic")
+
+
+class _SessionSpy:
+ """Wrap an ONNX Runtime session and keep every array the graph receives and returns."""
+
+ def __init__(self, session) -> None:
+ self.session = session
+ self.inputs: list = []
+ self.outputs: list = []
+
+ def get_inputs(self):
+ return self.session.get_inputs()
+
+ def run(self, output_names, feeds):
+ self.inputs.extend(feeds.values())
+ outputs = self.session.run(output_names, feeds)
+ self.outputs.extend(outputs)
+ return outputs
+
+
+def _spy_on(model) -> _SessionSpy:
+ spy = _SessionSpy(model.get_session())
+ model.set_session(spy)
+ return spy
+
+
+ "height, width, size, keep_aspect_ratio, expected",
+ [
+ # transformers DPTImageProcessor (size 518x518, ensure_multiple_of 14), the issue #6001 table. The side whose
+ # scale is closer to 1 is fitted; the other keeps the aspect ratio and is rounded to a multiple of 14:
+ # 518/400 = 1.295 beats 518/300 = 1.727, so H = round(300 * 1.295 / 14) * 14 = round(27.75) * 14 = 392
+ (300, 400, (518, 518), True, (392, 518)),
+ # 518/480 = 1.079 beats 518/640 = 0.809, so W = round(640 * 1.079 / 14) * 14 = round(49.33) * 14 = 686
+ (480, 640, (518, 518), True, (518, 686)),
+ # 518/1080 = 0.480 beats 518/1920 = 0.270, so W = round(1920 * 0.480 / 14) * 14 = round(65.78) * 14 = 924
+ (1080, 1920, (518, 518), True, (518, 924)),
+ # 518/500 = 1.036 beats 518/1000 = 0.518, so H = round(1000 * 1.036 / 14) * 14 = 74 * 14 = 1036
+ (1000, 500, (518, 518), True, (1036, 518)),
+ # without keep_aspect_ratio each side is scaled to its target: 518 = 37 * 14
+ (300, 400, (518, 518), False, (518, 518)),
+ # Python round sends a tie to the even integer: 35 / 14 = 2.5 -> 2 -> 28, and 21 / 14 = 1.5 -> 2 -> 28
+ (10, 10, (35, 21), False, (28, 28)),
+ # 518/296 = 1.75 and 518/2072 = 0.25 are both 0.75 from 1: the strict < fits the height, so
+ # W = 2072 * 1.75 = 3626 = 259 * 14
+ (296, 2072, (518, 518), True, (518, 3626)),
+ # 518/1000 = 0.518 beats 518/10 = 51.8, so H = round(10 * 0.518 / 14) * 14 = round(0.37) * 14 = 0, which is
+ # kept at one multiple, 14 (transformers would pass 0 to the resize and raise); and the transposed image
+ (10, 1000, (518, 518), True, (14, 518)),
+ (1000, 10, (518, 518), True, (518, 14)),
+ ],
+)
+def test_dpt_output_size(height, width, size, keep_aspect_ratio, expected):
+ from kornia.models._hf_models.preprocessor import _dpt_output_size
+
+ assert _dpt_output_size(height, width, size, keep_aspect_ratio, 14) == expected
+
+
+def test_from_json_keeps_the_aspect_ratio():
+ from kornia.models._hf_models.preprocessor import DPTImageProcessor
+
+ pipeline = DPTImageProcessor.from_json(dict(_DEPTH_ANYTHING_V2_SMALL_CONFIG))
+
+ assert pipeline(torch.rand(1, 3, 300, 400)).shape[-2:] == (392, 518)
+ # resample 3 is PIL's BICUBIC
+ assert pipeline[0].interpolation == "bicubic"
+
+
+ "dropped, changes, expected",
+ [
+ # absent keep_aspect_ratio and ensure_multiple_of take DPTImageProcessor's defaults, False and 1: each side is
+ # scaled to 500, which a multiple of 14 would round to 504
+ (("keep_aspect_ratio", "ensure_multiple_of"), {"size": {"height": 500, "width": 500}}, (500, 500)),
+ # a non-square size is (height, width): 518 = 37 * 14 and 700 = 50 * 14
+ ((), {"keep_aspect_ratio": False, "size": {"height": 518, "width": 700}}, (518, 700)),
+ ],
+)
+def test_from_json_reads_the_size_and_the_defaults(dropped, changes, expected):
+ from kornia.models._hf_models.preprocessor import DPTImageProcessor
+
+ config = {k: v for k, v in _DEPTH_ANYTHING_V2_SMALL_CONFIG.items() if k not in dropped}
+ config.update(changes)
+
+ assert DPTImageProcessor.from_json(config)(torch.rand(1, 3, 300, 400)).shape[-2:] == expected
+
+
+ "resample, interpolation", [(0, "nearest-exact"), (2, "bilinear"), (3, "bicubic"), (None, "bicubic")]
+)
+def test_from_json_maps_resample_to_the_interpolation(resample, interpolation):
+ # PIL's NEAREST (0), which samples the pixel centres, is torch's "nearest-exact"; BILINEAR (2) and BICUBIC (3).
+ # An absent key is DPTImageProcessor's default, BICUBIC
+ from kornia.models._hf_models.preprocessor import DPTImageProcessor
+
+ config = {k: v for k, v in _DEPTH_ANYTHING_V2_SMALL_CONFIG.items() if k != "resample"}
+ if resample is not None:
+ config["resample"] = resample
+
+ assert DPTImageProcessor.from_json(config)[0].interpolation == interpolation
+
+
+def test_dpt_resize_nearest_matches_pil():
+ # PIL 12.3.0 NEAREST samples the pixel centres, without a filter:
+ # np.asarray(Image.fromarray(np.arange(24).reshape(4, 6).astype(np.uint8)).resize((3, 2), Image.NEAREST))
+ from kornia.models._hf_models.preprocessor import _DPTResize
+
+ image = torch.arange(24, dtype=torch.float32).reshape(1, 1, 4, 6)
+ out = _DPTResize(size=(2, 3), keep_aspect_ratio=False, multiple=1, interpolation="nearest-exact")(image)
+
+ BaseTester.assert_close(out, torch.tensor([[[[7.0, 9.0, 11.0], [19.0, 21.0, 23.0]]]]), rtol=0.0, atol=0.0)
+
+
+# PIL 12.3.0, the filter of transformers' slow DPTImageProcessor, on mid-range values, so its uint8 passes never clip an
+# overshoot: src = 64 + np.arange(h * w).reshape(h, w) * 53 % 128, then
+# np.asarray(Image.fromarray(src.astype(np.uint8)).resize((out_w, out_h), Image.BICUBIC or Image.BILINEAR))
+_PIL_DOWNSCALE_8X12_TO_4X6 = {
+ "bicubic": [
+ [129, 133, 101, 137, 129, 112],
+ [151, 121, 124, 137, 120, 101],
+ [141, 110, 146, 136, 119, 126],
+ [133, 102, 136, 127, 119, 150],
+ ],
+ "bilinear": [
+ [131, 130, 108, 134, 128, 112],
+ [147, 123, 125, 135, 121, 105],
+ [139, 115, 141, 135, 121, 125],
+ [132, 108, 134, 128, 122, 145],
+ ],
+}
+_PIL_BICUBIC_UPSCALE_3X4_TO_6X8 = [
+ [51, 68, 103, 138, 171, 158, 105, 80],
+ [78, 85, 98, 121, 156, 155, 122, 107],
+ [138, 121, 85, 85, 123, 148, 160, 166],
+ [149, 133, 99, 88, 103, 128, 164, 181],
+ [112, 121, 138, 130, 97, 99, 133, 150],
+ [94, 114, 156, 150, 94, 84, 119, 136],
+]
+
+
+def _pil_source(height: int, width: int) -> torch.Tensor:
+ return (64 + torch.arange(height * width).reshape(1, 1, height, width) * 53 % 128).float() / 255
+
+
[email protected]("interpolation", ["bicubic", "bilinear"])
+def test_dpt_resize_downscale_matches_pil(interpolation):
+ # 4/8 = 0.5 beats 4/12 = 0.33, so the 8x12 image is halved to 4x6. PIL widens its kernel on a downscale, which the
+ # antialiased interpolate matches to within its uint8 rounding (max 0.62/255 measured); without antialiasing the
+ # bicubic is up to 27/255 off. The tolerance is 1/255.
+ from kornia.models._hf_models.preprocessor import _DPTResize
+
+ resize = _DPTResize(size=(4, 4), keep_aspect_ratio=True, multiple=2, interpolation=interpolation)
+
+ out = resize(_pil_source(8, 12))
+
+ expected = torch.tensor(_PIL_DOWNSCALE_8X12_TO_4X6[interpolation], dtype=torch.float32)[None, None] / 255
+ BaseTester.assert_close(out, expected, rtol=0.0, atol=1 / 255)
+
+
+def test_dpt_resize_bicubic_upscale_matches_pil():
+ # PIL's bicubic has a = -0.5, as the antialiased interpolate does (max 0.78/255 measured); the plain bicubic has
+ # a = -0.75 and is up to 6.2/255 off. The tolerance is 1/255.
+ from kornia.models._hf_models.preprocessor import _DPTResize
+
+ resize = _DPTResize(size=(6, 8), keep_aspect_ratio=False, multiple=1, interpolation="bicubic")
+
+ out = resize(_pil_source(3, 4))
+
+ expected = torch.tensor(_PIL_BICUBIC_UPSCALE_3X4_TO_6X8, dtype=torch.float32)[None, None] / 255
+ BaseTester.assert_close(out, expected, rtol=0.0, atol=1 / 255)
+
+
[email protected]("resample", [1, 4, 5])
+def test_from_json_rejects_an_unsupported_resample(resample):
+ # PIL's LANCZOS (1), BOX (4) and HAMMING (5) have no kornia resize mode
+ from kornia.models._hf_models.preprocessor import DPTImageProcessor
+
+ with pytest.raises(NotImplementedError, match="resample"):
+ DPTImageProcessor.from_json({**_DEPTH_ANYTHING_V2_SMALL_CONFIG, "resample": resample})
+
+
+class TestDepthEstimation(BaseTester):
+ @staticmethod
+ def _skip_float64_on_mps(device, dtype) -> None:
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+
+ def test_tensor_batch_returns_b1hw(self, device, dtype):
+ self._skip_float64_on_mps(device, dtype)
+ model = DepthEstimation(_stand_in_graph(), pre_processor=None)
+ images = torch.rand(2, 3, 300, 400, device=device, dtype=dtype)
+
+ depth = model(images)
+
+ assert depth.shape == (2, 1, 300, 400)
+ # the stand-in's depth is the channel mean; without a resize stage it is computed at the input size
+ self.assert_close(depth, images.float().mean(1, keepdim=True).to(dtype))
+
+ @pytest.mark.parametrize("sizes", [[(300, 400), (200, 150)], [(200, 150)], []])
+ def test_list_returns_1hw_items(self, device, dtype, sizes):
+ self._skip_float64_on_mps(device, dtype)
+ model = DepthEstimation(_stand_in_graph(), pre_processor=None)
+ images = [torch.rand(3, h, w, device=device, dtype=dtype) for h, w in sizes]
+
+ depths = model(images)
+
+ assert isinstance(depths, list)
+ assert [tuple(d.shape) for d in depths] == [(1, h, w) for h, w in sizes]
+ for depth, image in zip(depths, images):
+ self.assert_close(depth, image.float().mean(0, keepdim=True).to(dtype))
+
+ @pytest.mark.parametrize("as_list", [False, True])
+ def test_graph_returning_b1hw_keeps_its_layout(self, device, dtype, as_list):
+ # a graph that already returns (B, 1, H, W) gives the same layout as Depth-Anything's (B, H, W) graph
+ self._skip_float64_on_mps(device, dtype)
+ model = DepthEstimation(_stand_in_graph(keepdims=True), pre_processor=None)
+ images = torch.rand(2, 3, 300, 400, device=device, dtype=dtype)
+
+ depth = model(list(images) if as_list else images)
+
+ if as_list:
+ assert [tuple(d.shape) for d in depth] == [(1, 300, 400), (1, 300, 400)]
+ depth = torch.stack(depth)
+ assert depth.shape == (2, 1, 300, 400)
+ self.assert_close(depth, images.float().mean(1, keepdim=True).to(dtype))
+
+ @pytest.mark.parametrize("as_list", [False, True])
+ def test_visualize_and_save_take_a_tensor_batch(self, device, dtype, as_list, tmp_path):
+ self._skip_float64_on_mps(device, dtype)
+ model = DepthEstimation(_stand_in_graph(), pre_processor=None)
+ images = torch.rand(2, 3, 300, 400, device=device, dtype=dtype)
+ if as_list:
+ images = list(images)
+
+ views = model.visualize(images)
+
+ assert [tuple(v.shape) for v in views] == [(3, 300, 400), (3, 300, 400)]
+ # relative depth: each map divided by its maximum, repeated over three channels
+ depth = images[0].float().mean(0, keepdim=True).to(dtype)
+ self.assert_close(views[0], (depth / depth.max()).expand(3, -1, -1))
+
+ model.save(images, directory=str(tmp_path))
+
+ names = sorted(p.name for p in tmp_path.iterdir())
+ assert len(names) == 4
+ assert sum("_src_" in n for n in names) == 2
+ assert sum("_depth_" in n for n in names) == 2
+
+ def test_any_float_dtype(self, device, dtype):
+ self._skip_float64_on_mps(device, dtype)
+ model = DepthEstimation(_stand_in_graph(), pre_processor=None)
+ images = torch.rand(2, 3, 30, 40, device=device, dtype=dtype)
+
+ depth = model(images)
+ (item,) = model([images[0]])
+
+ for out in (depth, item):
+ assert out.dtype == dtype
+ assert out.device == images.device
+ assert torch.isfinite(out).all()
+ # ONNX Runtime computes in float32, and the depth is cast to the input dtype at the end
+ self.assert_close(depth, images.float().mean(1, keepdim=True).to(dtype))
+ self.assert_close(item, depth[0])
+
+ @pytest.mark.parametrize("as_list", [False, True])
+ @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int64])
+ def test_integer_images_raise(self, device, as_list, int_dtype):
+ # the float32 cast must not hand the graph a [0, 255] image as if it were a [0, 1] one
+ from kornia.core.exceptions import BaseError
+
+ model = DepthEstimation(_stand_in_graph(), pre_processor=None)
+ images = torch.randint(0, 256, (1, 3, 30, 40), device=device, dtype=int_dtype)
+
+ with pytest.raises(BaseError, match="floating dtype"):
+ model(list(images) if as_list else images)
+
+ def test_graph_sees_the_dpt_size(self, device):
+ # the resize runs on the CPU whatever the image's device, with the filter of transformers' DPT image processor
+ model = DepthEstimation(_stand_in_graph(), pre_processor=None, resize=_depth_anything_resize())
+ spy = _spy_on(model)
+ images = torch.rand(2, 3, 300, 400, device=device)
+
+ depth = model(images)
+
+ assert [tuple(x.shape) for x in spy.inputs] == [(2, 3, 392, 518)]
+ assert depth.shape == (2, 1, 300, 400)
+ assert depth.device == images.device
+ expected = torch.nn.functional.interpolate(
+ images.cpu(), size=(392, 518), mode="bicubic", align_corners=False, antialias=True
+ )
+ self.assert_close(torch.from_numpy(spy.inputs[0]), expected, rtol=0.0, atol=0.0)
+
+ def test_depth_is_resized_back_bicubically(self, device):
+ # as transformers' DPT post_process_depth_estimation does: interpolate(depth[None, None], size=target_size,
+ # mode="bicubic", align_corners=False), here on the CPU in float32
+ model = DepthEstimation(_stand_in_graph(), pre_processor=None, resize=_depth_anything_resize())
+ spy = _spy_on(model)
+ images = torch.rand(2, 3, 300, 400, device=device)
+
+ depth = model(images)
+
+ assert [x.shape for x in spy.outputs] == [(2, 392, 518)]
+ expected = torch.nn.functional.interpolate(
+ torch.from_numpy(spy.outputs[0])[:, None], size=(300, 400), mode="bicubic", align_corners=False
+ )
+ self.assert_close(depth.cpu(), expected, rtol=0.0, atol=0.0)
+
+ def test_graph_sees_the_dpt_size_of_each_list_item(self, device):
+ model = DepthEstimation(_stand_in_graph(), pre_processor=None, resize=_depth_anything_resize())
+ spy = _spy_on(model)
+ # 200x150: 518/200 = 2.59 beats 518/150 = 3.45, so W = round(150 * 2.59 / 14) * 14 = round(27.75) * 14 = 392
+ images = [torch.rand(3, 300, 400, device=device), torch.rand(3, 200, 150, device=device)]
+
+ depths = model(images)
+
+ assert [tuple(x.shape) for x in spy.inputs] == [(1, 3, 392, 518), (1, 3, 518, 392)]
+ assert [tuple(d.shape) for d in depths] == [(1, 300, 400), (1, 200, 150)]
+
+ def test_resize_runs_in_float32(self, device, dtype):
+ # the resize runs in float32 whatever the input dtype, so the depth of a half image is the depth of the same
+ # values in float32, cast at the end
+ self._skip_float64_on_mps(device, dtype)
+ model = DepthEstimation(_stand_in_graph(), pre_processor=None, resize=_depth_anything_resize())
+ images = torch.rand(1, 3, 60, 80, device=device, dtype=dtype)
+
+ depth = model(images)
+
+ assert depth.dtype == dtype
+ self.assert_close(depth, model(images.float()).to(dtype), rtol=0.0, atol=0.0)
+
+
+def test_to_onnx_graph_takes_a_resized_image():
+ from kornia.core import ImageSequential
+ from kornia.enhance import Normalize, Rescale
+
+ mean, std = torch.tensor([[0.485, 0.456, 0.406]]), torch.tensor([[0.229, 0.224, 0.225]])
+ pre = ImageSequential(Rescale(2.0), Normalize(mean=mean, std=std)).to_onnx(save=False)
+ model = DepthEstimation(_stand_in_graph(), pre_processor=pre, resize=_depth_anything_resize())
+ spy = _spy_on(model)
+ image = torch.rand(1, 3, 300, 400)
+ model(image) # the depth the model computes before resizing it back to 300x400
+
+ combined = model.to_onnx(include_pre_and_post_processor=True, save=False)
+
+ import onnxruntime as ort
+
+ session = ort.InferenceSession(combined.SerializeToString(), providers=["CPUExecutionProvider"])
+ resized = model.resize(image)
+ assert resized.shape == (1, 3, 392, 518)
+ (depth,) = session.run(None, {session.get_inputs()[0].name: resized.numpy()})
+ assert depth.shape == (1, 392, 518)
+ BaseTester.assert_close(torch.from_numpy(depth), torch.from_numpy(spy.outputs[0]))
+ expected = ((resized * 2.0 - mean[..., None, None]) / std[..., None, None]).mean(1)
+ BaseTester.assert_close(torch.from_numpy(depth), expected)
+
+
+def test_builder_resizes_in_torch_before_the_graph(monkeypatch):
+ # DepthAnythingONNXBuilder.build with the loader's downloads replaced by the stand-in graph and the
+ # depth-anything-v2-small config: the DPT resize runs in torch and the exported preprocessing graph keeps the rest
+ from kornia.models._hf_models import HFONNXComunnityModelLoader
+ from kornia.models._hf_models.preprocessor import PreprocessingLoader, _DPTResize
+ from kornia.models.depth_estimation import DepthAnythingONNXBuilder
+
+ monkeypatch.setattr(HFONNXComunnityModelLoader, "load_model", lambda self, **kwargs: _stand_in_graph())
+ monkeypatch.setattr(
+ HFONNXComunnityModelLoader,
+ "load_preprocessing",
+ lambda self: PreprocessingLoader.from_json(dict(_DEPTH_ANYTHING_V2_SMALL_CONFIG)),
+ )
+
+ model = DepthAnythingONNXBuilder.build()
+
+ assert isinstance(model.resize, _DPTResize)
+ assert model.resize.interpolation == "bicubic"
+ spy = _spy_on(model)
+ depth = model(torch.rand(1, 3, 300, 400))
+ assert [tuple(x.shape) for x in spy.inputs] == [(1, 3, 392, 518)]
+ assert depth.shape == (1, 1, 300, 400)