# Depth Anything

[Depth Anything](https://huggingface.co/papers/2401.10891)は、単眼深度推定（MDE）のための基盤モデルとして設計されています。ラベル付きデータと約6,200万枚のラベルなし画像を併用して共同学習を行い、データセットを強化しています。画像エンコーダーには事前学習済みの[DINOv2](./dinov2)モデルを使用し、既存の豊富なセマンティックな事前知識を継承するとともに、デコーダーには[DPT](./dpt)を使用しています。教師モデルはラベルなし画像で学習され、疑似ラベルを生成します。生徒モデルは、この疑似ラベルとラベル付き画像の組み合わせで学習されます。生徒モデルの性能を向上させるため、ラベルなし画像には強力な摂動が加えられ、生徒モデルが画像からより多くの視覚的知識を学習するように促します。

すべての Depth Anything のオリジナルチェックポイントは、[Depth Anything](https://huggingface.co/collections/LiheYoung/depth-anything-release-65b317de04eec72abf6b55aa)コレクション内で確認できます。

> [!TIP]
> 右側のサイドバーにある Depth Anything モデルをクリックすると、Depth Anything をさまざまなビジョンタスクに適用する方法の例をさらに確認できます。

以下の例では、[Pipeline](/docs/transformers/main/ja/main_classes/pipelines#transformers.Pipeline)または[AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)クラスを使用して深度マップを取得する方法を示しています。

```python
from transformers import pipeline

pipe = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf", device=0)
pipe("http://images.cocodataset.org/val2017/000000039769.jpg")["depth"]
```

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

from transformers import AutoImageProcessor, AutoModelForDepthEstimation

image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-base-hf")
model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-base-hf", device_map="auto")
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = image_processor(images=image, return_tensors="pt").to(model.device)

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

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
Image.fromarray(depth.astype("uint8"))
```

## 注記

- 2024年6月にリリースされた[DepthAnythingV2](./depth_anything_v2)は、Depth Anything と同じアーキテクチャを採用しており、すべてのコード例や既存のワークフローと互換性があります。合成データとより大容量の教師モデルを用いることで、より細かくかつ頑健な深度予測を実現しています。

## 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"深度推定の場合、この値は無視されます。

これはDepth AnythingModelの設定を保存するための設定クラスです。指定された引数に基づいてDepth Anythingモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[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"))
```

