Transformers documentation

Depth Anything V2

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2024-06-13 在 HF papers 上发布,并于 2024-07-05 贡献至 Hugging Face Transformers。

Depth Anything V2

概述

Depth Anything V2 由 Lihe Yang 等人在同名论文中提出。它采用了与原始Depth Anything 模型相同的架构,但通过使用合成数据和更大容量的教师模型,实现了更精细且更鲁棒的深度预测。

该论文的摘要如下:

本工作提出了 Depth Anything V2。我们并未追求花哨的技术,而是旨在揭示关键发现,为构建强大的单目深度估计模型铺平道路。值得注意的是,与 V1 相比,该版本通过三项关键实践,生成了更精细且更鲁棒的深度预测:1) 用合成图像替换所有带标注的真实图像;2) 扩大教师模型的容量;3) 通过大规模伪标注真实图像作为桥梁来训练学生模型。与基于 Stable Diffusion 构建的最新模型相比,我们的模型效率显著提升(速度快 10 倍以上)且精度更高。我们提供了不同规模的模型(参数量从 25M 到 1.3B 不等),以支持广泛的应用场景。得益于其强大的泛化能力,我们使用度量深度标签对其进行微调,从而获得了度量深度模型。除了我们的模型之外,考虑到当前测试集多样性有限且噪声频繁,我们构建了一个具有精确标注和多样化场景的通用评估基准,以促进未来的研究。

drawing Depth Anything overview. Taken from the original paper.

Depth Anything 模型由 nielsr 贡献。 原始代码可在此处找到。

使用示例

使用 Depth Anything V2 主要有两种方式:使用 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"))

资源

官方 Hugging Face 和社区(以 🌎 标识)资源列表,帮助你快速上手 Depth Anything。

如果您有兴趣提交资源以收录在此处,请随时发起 Pull Request,我们将对其进行审核!理想情况下,该资源应展示一些新内容,而不是重复现有资源。

DepthAnythingConfig

class 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) — 每个 patch 的大小(分辨率)。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • reassemble_hidden_size (int, 可选,默认为 384) — 重组层的输入通道数。
  • reassemble_factors (list[int],可选,默认为 [4, 2, 1, 0.5]) — 重组层的上采样/下采样因子。
  • neck_hidden_sizes (list[str],可选,默认为 [48, 96, 192, 384]) — 用于将主干网络的特征图投影到的隐藏层大小。
  • fusion_hidden_size (int,可选,默认为 64) — 融合前的通道数。
  • head_in_index (int,可选,默认为 -1) — 深度估计头中要使用的特征的索引。
  • head_hidden_size (int, 可选,默认为 32) — 深度估计头中第二个卷积层的输出通道数。
  • 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() 方法以加载模型权重。

带有深度估计头(由 3 个卷积层组成)的 Depth Anything 模型,例如用于 KITTI、NYUv2。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

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

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 DPTImageProcessor 获取像素值。有关详细信息,请参阅 DPTImageProcessor.call()(processor_class 使用 DPTImageProcessor 处理图像)。
  • labels(形状为 (batch_size, height, width) 的 torch.LongTensor,可选) — 用于计算损失的真实深度估计图。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

DepthEstimatorOutput 或 tuple(torch.Tensor)

DepthEstimatorOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(DepthAnythingConfig)和输入。

DepthAnythingForDepthEstimation 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。

  • predicted_depth(形状为 (batch_size, height, width) 的 torch.Tensor)— 每个像素的预测深度。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, num_channels, height, width)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (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