# DepthPro

## 概要

DepthProモデルは、Aleksei Bochkovskii、Amaël Delaunoy、Hugo Germain、Marcel Santos、Yichao Zhou、Stephan R. Richter、Vladlen Koltun による [Depth Pro: Sharp Monocular Metric Depth in Less Than a Second](https://huggingface.co/papers/2410.02073) で提案されました。

DepthProは、ゼロショットのメトリック単眼深度推定のための基盤モデルであり、顕著なシャープネスと細粒度の詳細を備えた高解像度の深度マップを生成するように設計されています。マルチスケールのVision Transformer (ViT)ベースのアーキテクチャを採用しており、画像はダウンサンプリングされ、パッチに分割された後、共有Dinov2エンコーダーによって処理されます。抽出されたパッチレベルの特徴量はマージされ、アップサンプリングおよびDPT類似の融合ステージによって洗練されることで、正確な深度推定を可能にします。

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

*ゼロショットのメトリック単眼深度推定のための基盤モデルを提示します。当社のモデル Depth Pro は、比類なきシャープネスと高周波数のディテールを備えた高解像度の深度マップを合成します。予測はメトリックであり、絶対スケールを持ち、カメラの内部パラメータなどのメタデータの可用性に依存しません。また、モデルは高速で、標準的な GPU 上で 0.3 秒で 2.25 メガピクセルの深度マップを生成します。これらの特性は、高密度予測のための効率的なマルチスケールビジョントランスフォーマー、高精度なメトリック精度と精密な境界追跡を同時に実現するために実データセットと合成データセットを組み合わせるトレーニングプロトコル、推定深度マップにおける境界精度のための専用評価指標、そして単一画像からの最先端の焦点距離推定など、いくつかの技術的貢献によって実現されています。広範な実験により、特定の設計選択が分析され、Depth Pro が複数の次元において先行研究を上回ることが示されています。*

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

 DepthPro の出力。公式コードから引用。

このモデルは [geetu040](https://github.com/geetu040) によって提供されました。元のコードは [こちら](https://github.com/apple/ml-depth-pro) で確認できます。

## 使用のコツ

DepthProモデルは、入力画像をまず複数のスケールでダウンサンプリングし、各スケールバージョンをパッチに分割して処理します。これらのパッチは、共有されるVision Transformer (ViT)ベースのDinov2パッチエンコーダーによってエンコードされ、一方、フルサイズ画像は別の画像エンコーダーによって処理されます。抽出されたパッチ特徴量は特徴量マップにマージされ、アップサンプリングおよびDPT類似のデコーダーによる融合を経て、最終的な深度推定が生成されます。有効化されている場合、追加のField of View (FOV)エンコーダーが画像を処理してカメラの視野を推定し、深度の精度向上に貢献します。

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

from transformers import DepthProForDepthEstimation, DepthProImageProcessor

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

image_processor = DepthProImageProcessor.from_pretrained("apple/DepthPro-hf")
model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", device_map="auto")

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)],
)

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

### アーキテクチャと設定

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

 DepthProのアーキテクチャ。元の論文から引用。

`DepthProForDepthEstimation` モデルは、入力画像をエンコードするための `DepthProEncoder` と、エンコーダーからの出力特徴量を融合するための `FeatureFusionStage` を使用します。

`DepthProEncoder`はさらに2つのエンコーダーを使用します:

- `patch_encoder`
  - 入力画像は、`scaled_images_ratios`設定で指定された複数の比率でスケーリングされます。
  - 各スケーリング済み画像は、`scaled_images_overlap_ratios`によって決定される重複領域を有する、サイズ`patch_size`のより小さな**パッチ**に分割されます。
  - これらのパッチは、**`patch_encoder`**によって処理されます。
- `image_encoder`
  - 入力画像も`patch_size`にリサイズされ、**`image_encoder`**によって処理されます。

これらのエンコーダーは、それぞれ `patch_model_config` および `image_model_config` を通じて設定でき、デフォルトでは両方とも独立した `Dinov2Model` です。

両方のエンコーダーの出力(`last_hidden_state`)と、**`patch_encoder`**から選択された中間状態(`hidden_states`)は、深度推定のために`DPT`ベースの`FeatureFusionStage`によって融合されます。

### 視野（FOV）の予測

ネットワークには、焦点距離推定ヘッドが追加されています。小型の畳み込みヘッドは、深度推定ネットワーク由来の凍結された特徴量と、別個のViT画像エンコーダー由来のタスク固有の特徴量を取得し、水平方向の視野角を予測します。

`DepthProConfig` の `use_fov_model` パラメータは、**FOV 予測**を有効にするかどうかを制御します。デフォルトでは、メモリと計算量を節約するために `False` に設定されています。有効にすると、`fov_model_config` パラメータに基づいて **FOV エンコーダー**がインスタンス化されます。このパラメータのデフォルト値は `Dinov2Model` です。`use_fov_model` パラメータは、`DepthProForDepthEstimation` モデルを初期化する際にも渡すことができます。

チェックポイント `apple/DepthPro-hf` の事前学習済みモデルは、FOV エンコーダーを使用しています。FOV エンコーダーを使わずに事前学習済みモデルを使用するには、モデルの読み込み時に `use_fov_model=False` を設定してください。これにより計算量を削減できます。

```python
from transformers import DepthProForDepthEstimation

model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", use_fov_model=False, device_map="auto")
```

FOVエンコーダー付きの新しいモデルをインスタンス化するには、設定で`use_fov_model=True`を設定します。

```python
from transformers import DepthProConfig, DepthProForDepthEstimation

config = DepthProConfig(use_fov_model=True)
model = DepthProForDepthEstimation(config)
```

モデルの初期化時に`use_fov_model=True`を設定すると、config内の値が上書きされます。

```python
from transformers import DepthProConfig, DepthProForDepthEstimation

config = DepthProConfig()
model = DepthProForDepthEstimation(config, use_fov_model=True)
```

### Scaled Dot Product Attention (SDPA) の使用

PyTorchには、`torch.nn.functional`の一部として、ネイティブなスケーリングドットプロダクトアテンション（SDPA）オペレーターが含まれています。この関数は、入力や使用しているハードウェアに応じて適用できる複数の実装を備えています。詳細については、[公式ドキュメント](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html)または[GPU推論](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention)ページを参照してください。

`torch>=2.1.1` の場合、実装が利用可能な場合はデフォルトで SDPA が使用されますが、`from_pretrained()` で `attn_implementation="sdpa"` を設定することで、SDPA の使用を明示的に指定することもできます。

```python
from transformers import DepthProForDepthEstimation

model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", attn_implementation="sdpa", device_map="auto")
```

最大限の高速化を実現するには、モデルを半精度（例: `torch.float16` または `torch.bfloat16`）で読み込むことをお勧めします。

ローカル環境でのベンチマーク（A100-40GB、PyTorch 2.3.0、OS Ubuntu 22.04）において、`float32` と `google/vit-base-patch16-224` モデルを使用した場合、推論時に以下の速度向上を確認しました。

|   バッチサイズ |   平均推論時間 (ms)、eager モード |   平均推論時間 (ms)、sdpa モデル |   Speed up, Sdpa / Eager (x) |
|--------------|-------------------------------------------|-------------------------------------------|------------------------------|
|            1 |                                         7 |                                         6 |                      1.17 |
|            2 |                                         8 |                                         6 |                      1.33 |
|            4 |                                         8 |                                         6 |                      1.33 |
|            8 |                                         8 |                                         6 |                      1.33 |

## リソース

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

- 研究論文: [Depth Pro: Sharp Monocular Metric Depth in Less Than a Second](https://huggingface.co/papers/2410.02073)
- 公式実装: [apple/ml-depth-pro](https://github.com/apple/ml-depth-pro)
- DepthPro 推論ノートブック: [DepthPro 推論](https://github.com/qubvel/transformers-notebooks/blob/main/notebooks/DepthPro_inference.ipynb)
- Super Resolution と Image Segmentation 向けの DepthPro
  - Mediumのブログを読む: [Depth Pro: Beyond Depth](https://medium.com/@raoarmaghanshakir040/depth-pro-beyond-depth-9d822fc557ba)
  - Github上のコード: [geetu040/depthpro-beyond-depth](https://github.com/geetu040/depthpro-beyond-depth)

ここにリソースを掲載していただくことを希望される場合は、Pull Request を開いてください。レビューいたします。リソースは、既存のリソースと重複するのではなく、新しいものを示すことが望ましいです。

## DepthProConfig[[transformers.DepthProConfig]]

#### transformers.DepthProConfig[[transformers.DepthProConfig]]

```python
transformers.DepthProConfig(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, fusion_hidden_size: int = 256, patch_size: int | list[int] | tuple[int, int] = 384, initializer_range: float = 0.02, intermediate_hook_ids: list[int] | tuple[int, ...] = (11, 5), intermediate_feature_dims: list[int] | tuple[int, ...] = (256, 256), scaled_images_ratios: list[int | float] | tuple[int | float, ...] = (0.25, 0.5, 1), scaled_images_overlap_ratios: list[float] | tuple[float, ...] = (0.0, 0.5, 0.25), scaled_images_feature_dims: list[int] | tuple[int, ...] = (1024, 1024, 512), merge_padding_value: int = 3, use_batch_norm_in_fusion_residual: bool = False, use_bias_in_fusion_residual: bool = True, use_fov_model: bool = False, num_fov_head_layers: int = 2, image_model_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, patch_model_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, fov_model_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/depth_pro/configuration_depth_pro.py#L28)

**パラメータ:**

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

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

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

intermediate_hook_ids (`list[int]`、*optional*、デフォルトは `[11, 5]`) : パッチエンコーダーから融合に使用する中間隠れ状態のインデックス。

intermediate_feature_dims (`list[int]`、*optional*、デフォルトは`[256, 256]`) : `intermediate_hook_ids`内の各中間隠れ状態におけるアップサンプリング時の隠れ状態の次元数。

scaled_images_ratios (`list[float]`、*optional*、デフォルトは`[0.25, 0.5, 1]`) : patch encoder が使用する、スケーリングされた画像の比率。

scaled_images_overlap_ratios (`list[float]`、*optional*、デフォルトは`[0.0, 0.5, 0.25]`) : `scaled_images_ratios`内の各スケーリング済み画像における、パッチ間の重複率です。

scaled_images_feature_dims (`list[int]`、*optional*、デフォルトは `[1024, 1024, 512]`) : `scaled_images_ratios` 内の各スケーリング済み画像のアップサンプリング時の隠れ状態の次元数。

merge_padding_value (`int`、*optional*、デフォルトは 3) : 小さいパッチを元の画像サイズにマージする際に、このサイズの重複するセクションが削除されます。

use_batch_norm_in_fusion_residual (`bool`, *任意*, デフォルトは `False`) : フュージョンブロックのプレアクティベーション残差ユニットでバッチ正規化を使用するかどうか。

use_bias_in_fusion_residual (`bool`、*任意*、デフォルトは`True`) : フュージョンブロックのpre-activate residualユニットでバイアスを使用するかどうか。

use_fov_model (`bool`、*任意*、デフォルトは`False`) : `DepthProFovModel`を使用して視野角を生成するかどうか。

num_fov_head_layers (`int`、*任意*、デフォルトは 2) : `DepthProFovModel` のヘッドにある畳み込み層の数。

image_model_config (`Union[dict[str, Any], PreTrainedConfig]`、*任意*) : [AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel) API を使用して読み込まれる、画像エンコーダーモデルの設定です。デフォルトでは、Dinov2 モデルがバックボーンとして使用されます。

patch_model_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*) : パッチエンコーダーモデルの設定です。[AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel) API を使用して読み込まれます。デフォルトでは、Dinov2 モデルがバックボーンとして使用されます。

fov_model_config (`Union[dict[str, Any], PreTrainedConfig]`、*optional*) : fov エンコーダーモデルの設定です。[AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel) API を使用して読み込まれます。デフォルトでは、Dinov2 モデルがバックボーンとして使用されます。

これはDepthProModelの設定を保存するための設定クラスです。指定された引数に基づいてDepth Proモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[apple/DepthPro](https://huggingface.co/apple/DepthPro)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> from transformers import DepthProConfig, DepthProModel

>>> # Initializing a DepthPro apple/DepthPro style configuration
>>> configuration = DepthProConfig()

>>> # Initializing a model (with random weights) from the apple/DepthPro style configuration
>>> model = DepthProModel(configuration)

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

## DepthProImageProcessor[[transformers.DepthProImageProcessor]]

#### transformers.DepthProImageProcessor[[transformers.DepthProImageProcessor]]

```python
transformers.DepthProImageProcessor(**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/depth_pro/image_processing_depth_pro.py#L45)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は `{'height' : 1536, 'width': 1536}`): モデルへの最大入力サイズを指定します。

default_to_square (`bool`, *kwargs*, *任意*、デフォルトは `True`) : size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *optional*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。`'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

`'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。 --

DepthProの画像プロセッサを構築します。

disable_grouping (`bool`, *kwargs*, *任意*): 画像をサイズごとにグループ化してバッチ処理する機能を無効にし、個別に処理するかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、ここ https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。 image_seq_length (`int`, *kwargs*, *任意*): 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

#### preprocess[[transformers.DepthProImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], *args, image_like_kwargs: dict[str, typing.Any] | None = None, **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/image_processing_utils.py#L382)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 前処理対象の画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

image_like_kwargs (`dict[str, Any]`、*省略可*) : 追加の画像類似の入力も前処理対象にするための開発者向けフラグです。引数として kwarg を渡す方法が機能しない場合のみ使用してください。例えば、`preprocess(images, masks=masks)` が推奨される方法ですが、一部のモデルでは引数の優先順位の問題が発生します。そのような場合は、代わりに `preprocess(images, image_like_inputs={"masks": masks})` を使用できます。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

画像または画像のバッチを前処理します。

#### post_process_depth_estimation[[transformers.DepthProImageProcessor.post_process_depth_estimation]]

```python
post_process_depth_estimation(outputs: DepthProDepthEstimatorOutput, target_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/depth_pro/image_processing_depth_pro.py#L84)

モデルからの生深度予測を後処理します。

## DepthProModel[[transformers.DepthProModel]]

#### transformers.DepthProModel[[transformers.DepthProModel]]

```python
transformers.DepthProModel(config: DepthProConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/depth_pro/modeling_depth_pro.py#L624)

**パラメータ:**

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

特定のヘッドを付加せずに、生の隠れ状態を出力する素の Depth Pro Model。

このモデルは [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.DepthProModel.forward]]

```python
forward(pixel_values: FloatTensor, 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_pro/modeling_depth_pro.py#L636)

**パラメータ:**

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

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) を返すかどうか。

**戻り値:** `DepthProOutput` または `tuple(torch.FloatTensor)`

`DepthProOutput`、または`torch.FloatTensor`のタプル(`return_dict=False`が渡された場合、または`config.return_dict=False`の場合)。設定([DepthProConfig](/docs/transformers/main/ja/model_doc/depth_pro#transformers.DepthProConfig))や入力に応じて、さまざまな要素で構成されます。

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

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, n_patches_per_batch, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **features** (`Union[torch.FloatTensor, List[torch.FloatTensor]]`、*任意*) -- エンコーダーからの特徴量。単一の特徴量または特徴量のリストを指定できます。
- **hidden_states** (`tuple[torch.FloatTensor, ...]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

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

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, DepthProModel

>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> checkpoint = "apple/DepthPro-hf"
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> model = DepthProModel.from_pretrained(checkpoint)

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

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

>>> output.last_hidden_state.shape
torch.Size([1, 35, 577, 1024])
```

## DepthProForDepthEstimation[[transformers.DepthProForDepthEstimation]]

#### transformers.DepthProForDepthEstimation[[transformers.DepthProForDepthEstimation]]

```python
transformers.DepthProForDepthEstimation(config: DepthProConfig, use_fov_model = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/depth_pro/modeling_depth_pro.py#L995)

**パラメータ:**

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

use_fov_model (`bool`, *任意*) : 視野角モデルを使用するかどうか。

深度推定ヘッド（3つの畳み込み層で構成）を上部に備えたDepthProモデル。

このモデルは [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.DepthProForDepthEstimation.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_pro/modeling_depth_pro.py#L1020)

**パラメータ:**

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

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) を返すかどうか。

**戻り値:** `DepthProDepthEstimatorOutput` または `tuple(torch.FloatTensor)`

`DepthProDepthEstimatorOutput`、または`torch.FloatTensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[DepthProConfig](/docs/transformers/main/ja/model_doc/depth_pro#transformers.DepthProConfig)）や入力に応じて、さまざまな要素で構成されます。

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

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

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 分類（または config.num_labels==1 の場合は回帰）の損失。
- **predicted_depth** (`torch.FloatTensor`、形状 `(batch_size, height, width)`、*任意*) -- 各ピクセルの予測深度。
- **field_of_view** (`torch.FloatTensor`、shape `(batch_size,)`、*任意*、`use_fov_model` が指定された場合に返されます) -- 視野角スケーラー。
- **hidden_states** (`tuple[torch.FloatTensor, ...]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

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

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
>>> from transformers import AutoImageProcessor, DepthProForDepthEstimation
>>> import torch
>>> 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()))

>>> checkpoint = "apple/DepthPro-hf"
>>> processor = AutoImageProcessor.from_pretrained(checkpoint)
>>> model = DepthProForDepthEstimation.from_pretrained(checkpoint)

>>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
>>> model.to(device)

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

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

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

>>> # get the field of view (fov) predictions
>>> field_of_view = post_processed_output[0]["field_of_view"]
>>> focal_length = post_processed_output[0]["focal_length"]

>>> # 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"))
```

