Transformers documentation

Depth Anything V2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

このモデルは2024年6月13日にHF papersで公開され、2024年7月5日にHugging Face Transformersに貢献されました。

Depth Anything V2

概要

Depth Anything V2 was introduced in the paper of the same name by Lihe Yang et al. It uses the same architecture as the original Depth Anything model, 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 パラメータ)のモデルを提供しています。これらのモデルは強力な汎化能力を備えているため、メトリック深度ラベルを用いてファインチューニングを行い、メトリック深度モデルを取得しています。また、当社のモデルに加え、現在のテストセットには多様性が限られておりノイズが頻繁に発生する点に鑑み、将来の研究を促進するために、正確なアノテーションと多様なシーンを含む汎用的な評価ベンチマークを構築しました。

drawing Depth Anything overview. Taken from the original paper.

Depth Anything モデルは nielsr によって提供されました。 元のコードは こちら で確認できます。

使用例

Depth Anything V2 を使用する主な方法は 2 つあります。複雑さをすべて抽象化してくれる pipeline API を使う方法と、DepthAnythingForDepthEstimation クラスを直接自分で使う方法です。

Pipeline API

pipelineを使用すると、わずか数行のコードでモデルを利用できます。

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"]

モデルを自分で使用する

前処理と後処理を自分で行いたい場合は、次のようにしてください。

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 公式およびコミュニティ(🌎 で示されます)のリソースのリストです。

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

DepthAnythingConfig

クラス transformers.DepthAnythingConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepatch_size: int | list[int] | tuple[int, int] = 14initializer_range: float = 0.02reassemble_hidden_size: int = 384reassemble_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 = 64head_in_index: int = -1head_hidden_size: int = 32depth_estimation_type: str = 'relative'max_depth: int | None = 1 )

パラメータ

  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig], 任意) — バックボーンモデルの設定です。
  • 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]、任意、デフォルトは [4, 2, 1, 0.5]) — reassemble レイヤーの上/下サンプリング係数です。
  • neck_hidden_sizes (list[str]、任意、デフォルトは [48, 96, 192, 384]) — バックボーンのフィーチャマップを投影するための隠れ層サイズです。
  • fusion_hidden_size (int、任意、デフォルトは 64) — 融合前のチャネル数です。
  • head_in_index (int、任意、デフォルトは -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 と同様の設定が得られます。

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

例:

>>> 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

class transformers.DepthAnythingForDepthEstimation

< >

( config: DepthAnythingConfig )

パラメータ

  • config (DepthAnythingConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。

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

このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

forward

< >

( pixel_values: FloatTensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → DepthEstimatorOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.FloatTensor、shape (batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値は DPTImageProcessor を使用して取得できます。詳細については DPTImageProcessor.call() を参照してください(processor_class は画像の処理に DPTImageProcessor を使用します)。
  • labels (torch.LongTensor、形状 (batch_size, height, width)、任意) — 損失の計算に使用する正解の深度推定マップです。
  • output_attentions (bool, 省略可) — すべてのアテンション層のアテンションテンソルを返すかどうかを指定します。詳細は、返されるテンソルの attentions を参照してください。
  • output_hidden_states (bool, 省略可) — すべての層の hidden states を返すかどうかを指定します。詳細は、返されるテンソルの hidden_states を参照してください。
  • return_dict (bool, 任意) — プレーンなタプルではなく ModelOutput を返すかどうか。

戻り値

DepthEstimatorOutput または tuple(torch.FloatTensor)

torch.FloatTensor のタプル、または return_dict=False が渡された場合、または config.return_dict=False の場合は torch.FloatTensor のタプル、または DepthEstimatorOutput。設定 (DepthAnythingConfig) と入力に応じて、さまざまな要素で構成されます。

DepthAnythingForDepthEstimationのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

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

  • loss (torch.FloatTensor、shape (1,)、optional、labels が指定された場合に返されます) — 分類損失(config.num_labels==1 の場合は回帰損失)。

  • predicted_depth (torch.FloatTensor、形状 (batch_size, height, width)) — 各ピクセルの予測深度。

  • hidden_states (tuple(torch.FloatTensor)、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返される) — torch.FloatTensor のタプル(埋め込み層を持つモデルの場合、埋め込みの出力が 1 つ、各層の出力がそれぞれ 1 つずつ)で、形状は (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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

>>> 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"))
Update on GitHub