# Depth Anything V2

## 概要

Depth Anything V2 was introduced in [the paper of the same name](https://huggingface.co/papers/2406.09414) by Lihe Yang et al. It uses the same architecture as the original [Depth Anything model](depth_anything), but uses synthetic data and a larger capacity teacher model to achieve much finer and robust depth predictions.

論文の抄録は以下の通りです。

*本稿では、Depth Anything V2 を紹介します。派手な手法を追求するのではなく、強力な単眼深度推定モデルの構築に向けた道を開くために、重要な知見を明らかにすることを目的としています。特に、V1 と比較して、本バージョンでは以下の 3 つの重要な取り組みにより、はるかに細かく、かつ頑健な深度予測を実現しています：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 を使用する主な方法は 2 つあります。複雑さをすべて抽象化してくれる 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"))
```

## リソース

Depth Anything の入門を支援するための、Hugging Face 公式およびコミュニティ（🌎 で示されます）のリソースのリストです。

- [単眼深度推定タスクガイド](../tasks/monocular_depth_estimation)
- [Depth Anything V2 デモ](https://huggingface.co/spaces/depth-anything/Depth-Anything-V2)。
- [DepthAnythingForDepthEstimation](/docs/transformers/main/ja/model_doc/depth_anything#transformers.DepthAnythingForDepthEstimation) を用いた推論を紹介するノートブックは、[こちら](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Depth%20Anything/Predicting_depth_in_an_image_with_Depth_Anything.ipynb)で確認できます。🌎
- [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/main/src/transformers/models/depth_anything/configuration_depth_anything.py#L25)

**パラメータ:**

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`、*optional*) : バックボーンモデルの設定です。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`14`) : 各パッチのサイズ（解像度）。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

reassemble_hidden_size (`int`、*任意*、デフォルトは 384) : reassemble レイヤーの入力チャネル数です。

reassemble_factors (`list[int]`、*optional*、デフォルトは`[4, 2, 1, 0.5]`) : reassemble レイヤーのアップ/ダウンサンプリング係数です。

neck_hidden_sizes (`list[str]`、*optional*、デフォルトは `[48, 96, 192, 384]`) : バックボーンのフィーチャマップを投影するための隠れ層サイズ。

fusion_hidden_size (`int`、*任意*、デフォルトは 64) : フュージョン前のチャネル数。

head_in_index (`int`, *optional*, デフォルトは -1) : 深度推定ヘッドで使用する特徴のインデックス。

head_hidden_size (`int`, *任意*, デフォルトは 32) : 深度推定ヘッドの2番目の畳み込みにおける出力チャネル数。

depth_estimation_type (`str`、*任意*、デフォルトは `"relative"`) : 使用する深度推定のタイプ。`["relative", "metric"]` のいずれかです。

max_depth (`float`, *省略可*) : "metric"深度推定ヘッドに使用する最大深度。屋内モデルには20、屋外モデルには80を使用してください。"relative"深度推定の場合、この値は無視されます。

This is the configuration class to store the configuration of a Depth AnythingModel. It is used to instantiate a Depth Anything model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [LiheYoung/depth-anything-small-hf](https://huggingface.co/LiheYoung/depth-anything-small-hf)

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/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/main/src/transformers/models/depth_anything/modeling_depth_anything.py#L316)

**パラメータ:**

config ([DepthAnythingConfig](/docs/transformers/main/ja/model_doc/depth_anything#transformers.DepthAnythingConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを参照してください。

Depth Anythingモデルの上部に深度推定ヘッド（3つの畳み込み層で構成）を備えたもの。例えばKITTIやNYUv2向け。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/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: FloatTensor, 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/main/src/transformers/models/depth_anything/modeling_depth_anything.py#L327)

**パラメータ:**

pixel_values (`torch.FloatTensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [DPTImageProcessor](/docs/transformers/main/ja/model_doc/dpt#transformers.DPTImageProcessor) を使用して取得できます。詳細は [DPTImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [DPTImageProcessor](/docs/transformers/main/ja/model_doc/dpt#transformers.DPTImageProcessor) を使用します）。

labels (`torch.LongTensor`、形状 `(batch_size, height, width)`、*任意*) : ロスの計算に使用する正解の深度推定マップ。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** [DepthEstimatorOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput) または `tuple(torch.FloatTensor)`

[DepthAnythingConfig](/docs/transformers/main/ja/model_doc/depth_anything#transformers.DepthAnythingConfig) や入力に応じて、さまざまな要素で構成される [DepthEstimatorOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput)、または `torch.FloatTensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。

[DepthAnythingForDepthEstimation](/docs/transformers/main/ja/model_doc/depth_anything#transformers.DepthAnythingForDepthEstimation)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 分類（または config.num_labels==1 の場合は回帰）の損失。
- **predicted_depth** (`torch.FloatTensor`、shape `(batch_size, height, width)`) -- 各ピクセルの予測深度。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（モデルに埋め込み層がある場合はその出力用 + 各層の出力用）で、形状は `(batch_size, num_channels, height, width)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）、形状は `(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"))
```

