Transformers 文档

Depth Anything V2

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

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 概述。摘自原始论文

Depth Anything 模型由 nielsr 贡献。原始代码可以在这里找到。

使用示例

使用 Depth Anything V2 主要有两种方式:使用 pipeline API,它为您抽象了所有复杂性;或者自己使用 DepthAnythingForDepthEstimation 类。

Pipeline API

该 pipeline 允许使用几行代码即可使用该模型

>>> from transformers import pipeline
>>> from PIL import Image
>>> import requests

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

自己使用模型

如果您想自己进行预处理和后处理,以下是如何操作的方法

>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> import requests

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

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

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

< >

( backbone_config = None backbone = None use_pretrained_backbone = False use_timm_backbone = False backbone_kwargs = None patch_size = 14 initializer_range = 0.02 reassemble_hidden_size = 384 reassemble_factors = [4, 2, 1, 0.5] neck_hidden_sizes = [48, 96, 192, 384] fusion_hidden_size = 64 head_in_index = -1 head_hidden_size = 32 depth_estimation_type = 'relative' max_depth = None **kwargs )

参数

  • backbone_config (Union[Dict[str, Any], PretrainedConfig], 可选) — backbone 模型的配置。仅在 is_hybridTrue 或您想利用 AutoBackbone API 的情况下使用。
  • backbone (str, 可选) — 当 backbone_configNone 时要使用的 backbone 名称。如果 use_pretrained_backboneTrue,这将从 timm 或 transformers 库加载相应的预训练权重。如果 use_pretrained_backboneFalse,这将加载 backbone 的配置并使用它来初始化具有随机权重的 backbone。
  • use_pretrained_backbone (bool, 可选, 默认为 False) — 是否对 backbone 使用预训练权重。
  • use_timm_backbone (bool, optional, defaults to False) — 是否使用 timm 库作为骨干网络。如果设置为 False,将使用 AutoBackbone API。
  • backbone_kwargs (dict, optional) — 从检查点加载时传递给 AutoBackbone 的关键字参数,例如 {'out_indices': (0, 1, 2, 3)}。如果设置了 backbone_config,则不能指定此项。
  • patch_size (int, optional, defaults to 14) — 从骨干网络特征中提取的图像块的大小。
  • initializer_range (float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • reassemble_hidden_size (int, optional, defaults to 384) — 重组层的输入通道数。
  • reassemble_factors (List[int], optional, defaults to [4, 2, 1, 0.5]) — 重组层的上/下采样因子。
  • neck_hidden_sizes (List[str], optional, defaults to [48, 96, 192, 384]) — 用于骨干网络特征图的投影隐藏层大小。
  • fusion_hidden_size (int, optional, defaults to 64) — 融合之前的通道数。
  • head_in_index (int, optional, defaults to -1) — 在深度估计头中使用的特征索引。
  • head_hidden_size (int, optional, defaults to 32) — 深度估计头的第二个卷积层中的输出通道数。
  • depth_estimation_type (str, optional, defaults to "relative") — 要使用的深度估计类型。可以是 ["relative", "metric"] 之一。
  • max_depth (float, optional) — 用于 “metric” 深度估计头的最大深度。室内模型应使用 20,室外模型应使用 80。“relative” 深度估计会忽略此值。

这是用于存储 DepthAnythingModel 配置的配置类。它用于根据指定的参数实例化 DepthAnything 模型,定义模型架构。使用默认值实例化配置将产生与 DepthAnything 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

to_dict

< >

( )

将此实例序列化为 Python 字典。覆盖默认的 to_dict()。 返回值: Dict[str, any]: 构成此配置实例的所有属性的字典。

DepthAnythingForDepthEstimation

class transformers.DepthAnythingForDepthEstimation

< >

( config )

参数

  • config (DepthAnythingConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。

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

此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: FloatTensor labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.DepthEstimatorOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 DPTImageProcessor.call()
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通元组。
  • labels (torch.LongTensor,形状为 (batch_size, height, width), optional) — 用于计算损失的地面实况深度估计图。

返回值

transformers.modeling_outputs.DepthEstimatorOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.DepthEstimatorOutput 或一个 torch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),其中包含各种元素,具体取决于配置 (DepthAnythingConfig) 和输入。

  • loss (torch.FloatTensor,形状为 (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 的元组(如果模型具有嵌入层,则为嵌入输出的元组 + 每层输出的元组),形状为 (batch_size, num_channels, height, width)

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

  • attentions (tuple(torch.FloatTensor), optional, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每层一个),形状为 (batch_size, num_heads, patch_size, sequence_length)

    注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。

DepthAnythingForDepthEstimation forward 方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> import requests

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

>>> 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"))
< > GitHub 更新