Transformers documentation
Depth Anything
このモデルは2024年1月19日にHF papersで公開され、2024年1月25日にHugging Face Transformersに貢献されました。
Depth Anything
Depth Anythingは、単眼深度推定(MDE)の基盤モデルとして設計されています。ラベル付き画像と約6,200万枚のラベルなし画像を同時に学習することで、データセットを強化しています。画像エンコーダーには事前学習済みのDINOv2モデルを使用し、既存の豊富なセマンティックな事前知識を継承するとともに、デコーダーにはDPTを使用しています。教師モデルはラベルなし画像で学習され、疑似ラベルを生成します。生徒モデルは、疑似ラベルとラベル付き画像の組み合わせで学習されます。生徒モデルの性能を向上させるため、ラベルなし画像には強力な摂動が加えられ、生徒モデルが画像からより多くの視覚的知識を学習するように促します。
すべての Depth Anything のオリジナルチェックポイントは、Depth Anythingコレクション内で確認できます。
右側のサイドバーにある Depth Anything モデルをクリックすると、Depth Anything をさまざまなビジョンタスクに適用する方法の例をさらに確認できます。
以下の例では、PipelineまたはAutoModelクラスを使用して深度マップを取得する方法を示しています。
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"]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 と同じアーキテクチャを採用しており、すべてのコード例や既存のワークフローと互換性があります。合成データとより大容量の教師モデルを用いることで、より細かくかつ頑健な深度予測を実現しています。
DepthAnythingConfig
クラス transformers.DepthAnythingConfig
< source >( 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.configDepthAnythingForDepthEstimation
class transformers.DepthAnythingForDepthEstimation
< source >( config: DepthAnythingConfig )
パラメータ
- config (DepthAnythingConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
Depth Anythingモデルの上部に深度推定ヘッド(3つの畳み込み層で構成)を備えたもの。例えばKITTIやNYUv2向け。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( 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"))