# ZoeDepth

[ZoeDepth](https://huggingface.co/papers/2302.12288)は、単一の画像から相対深度推定（オブジェクト間の相対的な距離）とメトリック深度推定（メトリックスケールでの正確な深度測定）の汎化性能を組み合わせる深度推定モデルです。12のデータセットで相対深度、2つのデータセット（NYU Depth v2とKITTI）でメトリック精度について事前学習されています。各ドメイン用のメトリックビンモジュールを備えた軽量なヘッドが使用され、推論時には潜在分類器によって各入力画像に適したヘッドが自動的に選択されます。

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

すべてのオリジナルのZoeDepthチェックポイントは、[Intel](https://huggingface.co/Intel?search=zoedepth)組織の下で見つけることができます。

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

```python
import requests
from PIL import Image

from transformers import pipeline

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
pipeline = pipeline(
    task="depth-estimation",
    model="Intel/zoedepth-nyu-kitti",
    device=0
)
results = pipeline(image)
results["depth"]
```

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

from transformers import AutoImageProcessor, AutoModelForDepthEstimation

image_processor = AutoImageProcessor.from_pretrained(
    "Intel/zoedepth-nyu-kitti"
)
model = AutoModelForDepthEstimation.from_pretrained(
    "Intel/zoedepth-nyu-kitti",
    device_map="auto"
)
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = image_processor(image, return_tensors="pt").to(model.device)

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

# interpolate to original size and visualize the prediction
## ZoeDepth dynamically pads the input image, so pass the original image size as argument
## to `post_process_depth_estimation` to remove the padding and resize to original dimensions.
post_processed_output = image_processor.post_process_depth_estimation(
    outputs,
    source_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"))
```

## 注記

- [元の実装](https://github.com/isl-org/ZoeDepth/blob/edb6daf45458569e24f50250ef1ed08c015f17a7/zoedepth/models/depth_model.py#L131)では、ZoeDepth は元画像と反転画像の両方で推論を実行し、その結果を平均化します。`post_process_depth_estimation` 関数は、以下に示すように、反転された出力を任意の `outputs_flipped` 引数に渡すことで、この処理を処理します。

   ```py
    with torch.no_grad():
        outputs = model(pixel_values)
        outputs_flipped = model(pixel_values=torch.flip(inputs.pixel_values, dims=[3]))
        post_processed_output = image_processor.post_process_depth_estimation(
            outputs,
            source_sizes=[(image.height, image.width)],
            outputs_flipped=outputs_flipped,
        )
   ```

## リソース

- 推論の例については、この[ノートブック](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/ZoeDepth)を参照してください。

## ZoeDepthConfig[[transformers.ZoeDepthConfig]]

#### transformers.ZoeDepthConfig[[transformers.ZoeDepthConfig]]

```python
transformers.ZoeDepthConfig(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, hidden_act: str = 'gelu', initializer_range: float = 0.02, batch_norm_eps: float = 1e-05, readout_type: typing.Literal['ignore', 'add', 'project'] = 'project', reassemble_factors: list[int | float] | tuple[int | float, ...] = (4, 2, 1, 0.5), neck_hidden_sizes: list[int] | tuple[int, ...] = (96, 192, 384, 768), fusion_hidden_size: int = 256, head_in_index: int = -1, use_batch_norm_in_fusion_residual: bool = False, use_bias_in_fusion_residual: bool | None = None, num_relative_features: int = 32, add_projection: bool = False, bottleneck_features: int = 256, num_attractors: list[int] | tuple[int, ...] = (16, 8, 4, 1), bin_embedding_dim: int = 128, attractor_alpha: int = 1000, attractor_gamma: int = 2, attractor_kind: typing.Literal['mean', 'sum'] = 'mean', min_temp: float = 0.0212, max_temp: float = 50.0, bin_centers_type: str = 'softplus', bin_configurations: list[dict] | None = None, num_patch_transformer_layers: int | None = None, patch_transformer_hidden_size: int | None = None, patch_transformer_intermediate_size: int | None = None, patch_transformer_num_attention_heads: int | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/zoedepth/configuration_zoedepth.py#L32)

**パラメータ:**

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

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

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

batch_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : バッチ正規化レイヤーで使用するepsilonです。

readout_type (`str`、*optional*、デフォルトは`"project"`) : ViTバックボーンの中間隠れ状態のリードアウトトークン（CLSトークン）を処理する際に使用するリードアウトタイプ。`"ignore"`、`"add"`、`"project"`のいずれかになります。 - "ignore"はCLSトークンを単に無視します。 - "add"は表現を足し合わせることで、CLSトークンの情報を他のすべてのトークンに伝達します。 - "project"は、他のすべてのトークンにリードアウトを連結してから、線形層とGELU非線形性を適用して元のフィーチャ次元Dに射影することで、他のトークンに情報を伝達します。

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

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

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

head_in_index (`int`、*任意*、デフォルトは -1) : ヘッドで使用する特徴のインデックス。

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

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

num_relative_features (`int`、*optional*、デフォルトは 32) : 相対深度推定ヘッドで使用する特徴量の数。

add_projection (`bool`, *任意*, デフォルトは `False`) : 深度推定ヘッドの前に投影層を追加するかどうか。

bottleneck_features (`int`、*任意*、デフォルトは 256) : ボトルネック層のフィーチャ数。

num_attractors (`list[int], *optional*, defaults to `[16, 8, 4, 1]`) : 各ステージで使用するアトラクターの数。

bin_embedding_dim (`int`, *optional*, デフォルトは 128) : バイン埋め込みの次元数。

attractor_alpha (`int`、*optional*、デフォルトは 1000) : アトラクターで使用する alpha 値。

attractor_gamma (`int`、*optional*、デフォルトは 2) : アトラクターで使用する gamma 値。

attractor_kind (`str`、*任意*、デフォルトは`"mean"`) : 使用するアトラクターの種類。`"mean"`または`"sum"`のいずれかです。

min_temp (`float`、*任意*、デフォルト値は 0.0212) : 考慮する最小の温度値。

max_temp (`float`、*任意*、デフォルト値は 50.0) : 考慮する温度の最大値。

bin_centers_type (`str`、*任意*、デフォルトは`"softplus"`) : バインの中心に使用される活性化の種類です。"normed"または"softplus"を指定できます。"normed"のバイン中心では、線形正規化のトリックが適用されます。これにより、バインの中心は有界になります。"softplus"では、softplus活性化が使用されるため、バインの中心は無界になります。

bin_configurations (`list[dict]`、*任意*、デフォルトは`[{'n_bins' : 64, 'min_depth': 0.001, 'max_depth': 10.0}]`): 各 bin head の設定です。各設定には、以下のキーが含まれる必要があります: - name (`str`): bin head の名前 - 複数の bin 設定がある場合のみ必須です。 - `n_bins` (`int`): 使用する bin の数。 - `min_depth` (`float`): 考慮する最小の深度値。 - `max_depth` (`float`): 考慮する最大の深度値。 単一の設定のみが渡された場合、モデルは指定された設定を持つ単一の head を使用します。複数の設定が渡された場合、モデルは指定された設定を持つ複数の head を使用します。

num_patch_transformer_layers (`int`, *optional*) : パッチトランスフォーマーで使用するトランスフォーマー層の数。複数のビン構成の場合にのみ使用されます。

patch_transformer_hidden_size (`int`, *optional*) : パッチトランスフォーマーで使用する隠れ層サイズ。複数のビン構成の場合にのみ使用されます。

patch_transformer_intermediate_size (`int`, *optional*) : パッチトランスフォーマーで使用する中間サイズ。複数のビン構成の場合にのみ使用されます。

patch_transformer_num_attention_heads (`int`, *optional*) : パッチトランスフォーマーで使用するアテンションヘッドの数。複数のビン構成の場合にのみ使用されます。

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

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

例:

```python
>>> from transformers import ZoeDepthConfig, ZoeDepthForDepthEstimation

>>> # Initializing a ZoeDepth zoedepth-large style configuration
>>> configuration = ZoeDepthConfig()

>>> # Initializing a model from the zoedepth-large style configuration
>>> model = ZoeDepthForDepthEstimation(configuration)

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

## ZoeDepthImageProcessor[[transformers.ZoeDepthImageProcessor]]

#### transformers.ZoeDepthImageProcessor[[transformers.ZoeDepthImageProcessor]]

```python
transformers.ZoeDepthImageProcessor(**kwargs: *<class 'transformers.models.zoedepth.image_processing_zoedepth.ZoeDepthImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/zoedepth/image_processing_zoedepth.py#L105)

**パラメータ:**

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' : 384, 'width': 512}`): モデルへの最大入力次元を記述します。

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*, *optional*, デフォルトは `True`) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

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

keep_aspect_ratio (`bool`, *kwargs*, *optional*, デフォルトは `self.keep_aspect_ratio`) : `True` の場合、高さと幅のスケール係数のうち小さい方を選択し、両方の次元に適用して画像をリサイズします。これにより、望ましい出力サイズ内に収まるようにしながらも、画像が可能な限り小さく縮小されないようにします。`ensure_multiple_of` も設定されている場合、高さと幅をこの値の最も近い倍数に切り捨てて、この値の倍数であるサイズにさらにリサイズされます。`preprocess` の `keep_aspect_ratio` によって上書きできます。

ensure_multiple_of (`int`, *kwargs*, *optional*, デフォルトは `self.ensure_multiple_of`) : `do_resize` が `True` の場合、画像はこの値の倍数となるサイズにリサイズされます。高さと幅をこの値の最も近い倍数に切り下げることで動作します。`keep_aspect_ratio` が `True` に設定されている場合でも、設定されていない場合でも動作します。`preprocess` 内の `ensure_multiple_of` によって上書きできます。

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

#### preprocess[[transformers.ZoeDepthImageProcessor.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']], **kwargs: *<class 'transformers.models.zoedepth.image_processing_zoedepth.ZoeDepthImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/zoedepth/image_processing_zoedepth.py#L121)

**パラメータ:**

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` を設定してください。

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

keep_aspect_ratio (`bool`, *kwargs*, *optional*, デフォルトは `self.keep_aspect_ratio`) : `True` の場合、高さと幅のスケール係数のうち小さい方を選択し、両方の次元に適用して画像をリサイズします。これにより、望ましい出力サイズ内に収まるようにしながらも、画像が可能な限り小さく縮小されないようにします。`ensure_multiple_of` も設定されている場合、高さと幅をこの値の最も近い倍数に切り捨てて、この値の倍数であるサイズにさらにリサイズされます。`preprocess` の `keep_aspect_ratio` によって上書きできます。

ensure_multiple_of (`int`, *kwargs*, *optional*, デフォルトは `self.ensure_multiple_of`) : `do_resize` が `True` の場合、画像はこの値の倍数となるサイズにリサイズされます。高さと幅をこの値の最も近い倍数に切り下げることで動作します。`keep_aspect_ratio` が `True` に設定されている場合でも、設定されていない場合でも動作します。`preprocess` 内の `ensure_multiple_of` によって上書きできます。

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

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

## ZoeDepthImageProcessorPil[[transformers.ZoeDepthImageProcessorPil]]

#### transformers.ZoeDepthImageProcessorPil[[transformers.ZoeDepthImageProcessorPil]]

```python
transformers.ZoeDepthImageProcessorPil(**kwargs: *<class 'transformers.models.zoedepth.image_processing_pil_zoedepth.ZoeDepthImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/zoedepth/image_processing_pil_zoedepth.py#L113)

**パラメータ:**

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' : 384, 'width': 512}`): モデルへの最大入力次元を記述します。

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*, *optional*, デフォルトは `True`) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

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

keep_aspect_ratio (`bool`, *kwargs*, *optional*, デフォルトは `self.keep_aspect_ratio`) : `True` の場合、高さと幅のスケール係数のうち小さい方を選択し、両方の次元に適用して画像をリサイズします。これにより、望ましい出力サイズ内に収まるようにしながらも、画像が可能な限り小さく縮小されないようにします。`ensure_multiple_of` も設定されている場合、高さと幅をこの値の最も近い倍数に切り捨てて、この値の倍数であるサイズにさらにリサイズされます。`preprocess` の `keep_aspect_ratio` によって上書きできます。

ensure_multiple_of (`int`, *kwargs*, *optional*, デフォルトは `self.ensure_multiple_of`) : `do_resize` が `True` の場合、画像はこの値の倍数となるサイズにリサイズされます。高さと幅をこの値の最も近い倍数に切り下げることで動作します。`keep_aspect_ratio` が `True` に設定されている場合でも、設定されていない場合でも動作します。`preprocess` 内の `ensure_multiple_of` によって上書きできます。

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

#### preprocess[[transformers.ZoeDepthImageProcessorPil.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']], **kwargs: *<class 'transformers.models.zoedepth.image_processing_pil_zoedepth.ZoeDepthImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/zoedepth/image_processing_pil_zoedepth.py#L129)

**パラメータ:**

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` を設定してください。

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

keep_aspect_ratio (`bool`, *kwargs*, *optional*, デフォルトは `self.keep_aspect_ratio`) : `True` の場合、高さと幅のスケール係数のうち小さい方を選択し、両方の次元に適用して画像をリサイズします。これにより、望ましい出力サイズ内に収まるようにしながらも、画像が可能な限り小さく縮小されないようにします。`ensure_multiple_of` も設定されている場合、高さと幅をこの値の最も近い倍数に切り捨てて、この値の倍数であるサイズにさらにリサイズされます。`preprocess` の `keep_aspect_ratio` によって上書きできます。

ensure_multiple_of (`int`, *kwargs*, *optional*, デフォルトは `self.ensure_multiple_of`) : `do_resize` が `True` の場合、画像はこの値の倍数となるサイズにリサイズされます。高さと幅をこの値の最も近い倍数に切り下げることで動作します。`keep_aspect_ratio` が `True` に設定されている場合でも、設定されていない場合でも動作します。`preprocess` 内の `ensure_multiple_of` によって上書きできます。

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

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

## ZoeDepthForDepthEstimation[[transformers.ZoeDepthForDepthEstimation]]

#### transformers.ZoeDepthForDepthEstimation[[transformers.ZoeDepthForDepthEstimation]]

```python
transformers.ZoeDepthForDepthEstimation(config: ZoeDepthConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.0/src/transformers/models/zoedepth/modeling_zoedepth.py#L1224)

**パラメータ:**

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

ZoeDepthモデルは、その上に1つまたは複数のメトリック深度推定ヘッドを備えています。

このモデルは [PreTrainedModel](/docs/transformers/v5.24.0/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.ZoeDepthForDepthEstimation.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.24.0/src/transformers/models/zoedepth/modeling_zoedepth.py#L1250)

**パラメータ:**

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

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/v5.24.0/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

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

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

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

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

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

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

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

例:
```python
>>> from transformers import AutoImageProcessor, ZoeDepthForDepthEstimation
>>> 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("Intel/zoedepth-nyu-kitti")
>>> model = ZoeDepthForDepthEstimation.from_pretrained("Intel/zoedepth-nyu-kitti")

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

