# Depth Anything V2

## 概述

Depth Anything V2 由 Lihe Yang 等人在[同名论文](https://huggingface.co/papers/2406.09414)中提出。它采用了与原始[Depth Anything 模型](depth_anything)相同的架构，但通过使用合成数据和更大容量的教师模型，实现了更精细且更鲁棒的深度预测。

该论文的摘要如下：

*本工作提出了 Depth Anything V2。我们并未追求花哨的技术，而是旨在揭示关键发现，为构建强大的单目深度估计模型铺平道路。值得注意的是，与 V1 相比，该版本通过三项关键实践，生成了更精细且更鲁棒的深度预测：1) 用合成图像替换所有带标注的真实图像；2) 扩大教师模型的容量；3) 通过大规模伪标注真实图像作为桥梁来训练学生模型。与基于 Stable Diffusion 构建的最新模型相比，我们的模型效率显著提升（速度快 10 倍以上）且精度更高。我们提供了不同规模的模型（参数量从 25M 到 1.3B 不等），以支持广泛的应用场景。得益于其强大的泛化能力，我们使用度量深度标签对其进行微调，从而获得了度量深度模型。除了我们的模型之外，考虑到当前测试集多样性有限且噪声频繁，我们构建了一个具有精确标注和多样化场景的通用评估基准，以促进未来的研究。*

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/depth_anything_overview.jpg"
alt="drawing" width="600"/>

 Depth Anything 概览。摘自原始论文。

Depth Anything 模型由 [nielsr](https://huggingface.co/nielsr) 贡献。原始代码可在[此处](https://github.com/DepthAnything/Depth-Anything-V2)找到。

## 使用示例

使用 Depth Anything V2 主要有两种方式：使用 pipeline API，它会为你抽象掉所有复杂性；或者直接使用 `DepthAnythingForDepthEstimation` 类。

### Pipeline API

Pipeline 允许您用几行代码来使用模型：

```python
import requests
from PIL import Image

from transformers import pipeline

# load pipe
pipe = pipeline(task="depth-estimation", model="depth-anything/Depth-Anything-V2-Small-hf")

# load image
url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)

# inference
depth = pipe(image)["depth"]
```

### 自行使用模型

如果您想自行完成预处理和后处理，以下是具体方法：

```python
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForDepthEstimation

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)

image_processor = AutoImageProcessor.from_pretrained("depth-anything/Depth-Anything-V2-Small-hf")
model = AutoModelForDepthEstimation.from_pretrained("depth-anything/Depth-Anything-V2-Small-hf", device_map="auto")

# prepare image for the model
inputs = image_processor(images=image, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)

# interpolate to original size and visualize the prediction
post_processed_output = image_processor.post_process_depth_estimation(
    outputs,
    target_sizes=[(image.height, image.width)],
)

predicted_depth = post_processed_output[0]["predicted_depth"]
depth = (predicted_depth - predicted_depth.min()) / (predicted_depth.max() - predicted_depth.min())
depth = depth.detach().cpu().numpy() * 255
depth = Image.fromarray(depth.astype("uint8"))
```

## 资源

官方 Hugging Face 和社区（以 🌎 标识）资源列表，帮助你快速上手 Depth Anything。

- [单目深度估计任务指南](../tasks/monocular_depth_estimation)
- [Depth Anything V2 演示](https://huggingface.co/spaces/depth-anything/Depth-Anything-V2)。
- 您可以在[此处](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Depth%20Anything/Predicting_depth_in_an_image_with_Depth_Anything.ipynb)找到一个展示使用[DepthAnythingForDepthEstimation](/docs/transformers/v5.23.0/zh/model_doc/depth_anything#transformers.DepthAnythingForDepthEstimation)进行推理的笔记本。🌎
- [用于在 Apple Silicon 上运行的 `small` 变体的 Core ML 转换](https://huggingface.co/apple/coreml-depth-anything-v2-small)。

如果您有兴趣提交资源以收录在此处，请随时发起 Pull Request，我们将对其进行审核！理想情况下，该资源应展示一些新内容，而不是重复现有资源。

## DepthAnythingConfig[[transformers.DepthAnythingConfig]]

#### transformers.DepthAnythingConfig[[transformers.DepthAnythingConfig]]

```python
transformers.DepthAnythingConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, patch_size: int | list[int] | tuple[int, int] = 14, initializer_range: float = 0.02, reassemble_hidden_size: int = 384, reassemble_factors: list[int | float] | tuple[int | float, ...] = (4, 2, 1, 0.5), neck_hidden_sizes: list[int] | tuple[int, ...] = (48, 96, 192, 384), fusion_hidden_size: int = 64, head_in_index: int = -1, head_hidden_size: int = 32, depth_estimation_type: str = 'relative', max_depth: int | None = 1)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/depth_anything/configuration_depth_anything.py#L25)

**参数：**

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：骨干模型的配置。

patch_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `14`)：每个 patch 的大小（分辨率）。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

reassemble_hidden_size (`int`, *可选*，默认为 384)：重组层的输入通道数。

reassemble_factors (`list[int]`，*可选*，默认为 `[4, 2, 1, 0.5]`)：重组层的上/下采样因子。

neck_hidden_sizes (`list[str]`, *可选*, 默认为 `[48, 96, 192, 384]`) : 用于将骨干网络的特征图投影到的隐藏层大小。

fusion_hidden_size (`int`，*可选*，默认为 64)：融合前的通道数。

head_in_index (`int`，*可选*，默认为 -1)：在深度估计头中使用的特征索引。

head_hidden_size (`int`, *可选*，默认为 32)：深度估计头中第二个卷积的输出通道数。

depth_estimation_type (`str`，*可选*，默认为 `"relative"`)：要使用的深度估计类型。可以是 `["relative", "metric"]` 之一。

max_depth (`float`, *可选*) : “metric”深度估计头使用的最大深度。室内模型应使用 20，室外模型应使用 80。对于“relative”深度估计，此值将被忽略。

这是用于存储 Depth AnythingModel 配置的类。它根据指定的参数实例化 Depth Anything 模型，并定义模型架构。使用默认值实例化配置将得到与 [LiheYoung/depth-anything-small-hf](https://huggingface.co/LiheYoung/depth-anything-small-hf) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import DepthAnythingConfig, DepthAnythingForDepthEstimation

>>> # Initializing a DepthAnything small style configuration
>>> configuration = DepthAnythingConfig()

>>> # Initializing a model from the DepthAnything small style configuration
>>> model = DepthAnythingForDepthEstimation(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## DepthAnythingForDepthEstimation[[transformers.DepthAnythingForDepthEstimation]]

#### transformers.DepthAnythingForDepthEstimation[[transformers.DepthAnythingForDepthEstimation]]

```python
transformers.DepthAnythingForDepthEstimation(config: DepthAnythingConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/depth_anything/modeling_depth_anything.py#L316)

**参数：**

config ([DepthAnythingConfig](/docs/transformers/v5.23.0/zh/model_doc/depth_anything#transformers.DepthAnythingConfig))：模型配置类，包含模型的所有参数。使用配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

带有深度估计头（由 3 个卷积层组成）的 Depth Anything 模型，例如用于 KITTI、NYUv2。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.DepthAnythingForDepthEstimation.forward]]

```python
forward(pixel_values: Tensor, labels: typing.Optional[torch.LongTensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/depth_anything/modeling_depth_anything.py#L327)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [DPTImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTImageProcessor) 获取像素值。有关详细信息，请参阅 [DPTImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [DPTImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTImageProcessor) 处理图像）。

labels (`torch.LongTensor`，形状为 `(batch_size, height, width)`，*可选*)：用于计算损失的真实深度估计图。

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** [DepthEstimatorOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput) 或 `tuple(torch.Tensor)`

一个 [DepthEstimatorOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[DepthAnythingConfig](/docs/transformers/v5.23.0/zh/model_doc/depth_anything#transformers.DepthAnythingConfig)）和输入。

[DepthAnythingForDepthEstimation](/docs/transformers/v5.23.0/zh/model_doc/depth_anything#transformers.DepthAnythingForDepthEstimation) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **predicted_depth**（形状为 `(batch_size, height, width)` 的 `torch.Tensor`）-- 每个像素的预测深度。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, num_channels, height, width)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, patch_size, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：
```python
>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
>>> model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf")

>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # interpolate to original size
>>> post_processed_output = image_processor.post_process_depth_estimation(
...     outputs,
...     target_sizes=[(image.height, image.width)],
... )

>>> # visualize the prediction
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
>>> depth = predicted_depth * 255 / predicted_depth.max()
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint8"))
```

