Transformers 文档
Depth Anything
并获取增强的文档体验
开始使用
Depth Anything
概述
Depth Anything 模型在 Depth Anything: Unleashing the Power of Large-Scale Unlabeled Data 中被提出,作者为 Lihe Yang、Bingyi Kang、Zilong Huang、Xiaogang Xu、Jiashi Feng、Hengshuang Zhao。Depth Anything 基于 DPT 架构,使用约 6200 万张图像进行训练,在相对和绝对深度估计方面均获得了最先进的结果。
Depth Anything V2 于 2024 年 6 月发布。它使用与 Depth Anything 相同的架构,因此与所有代码示例和现有工作流程兼容。但是,它利用合成数据和更大容量的教师模型来实现更精细和鲁棒的深度预测。
以下是论文的摘要
这项工作提出了 Depth Anything,这是一种用于稳健的单目深度估计的高度实用的解决方案。我们不追求新颖的技术模块,而是旨在构建一个简单而强大的基础模型,以应对任何情况下的任何图像。为此,我们通过设计一个数据引擎来收集和自动注释大规模未标记数据(约 62M)来扩大数据集,这显着扩大了数据覆盖范围,从而能够减少泛化误差。我们研究了两种简单而有效的策略,这些策略使数据规模扩大变得有希望。首先,通过利用数据增强工具创建更具挑战性的优化目标。它迫使模型主动寻找额外的视觉知识并获得鲁棒的表示。其次,开发了一种辅助监督,以强制模型从预训练的编码器继承丰富的语义先验。我们广泛评估了它的零样本能力,包括六个公共数据集和随机捕获的照片。它展示了令人印象深刻的泛化能力。此外,通过使用 NYUv2 和 KITTI 中的度量深度信息对其进行微调,设置了新的 SOTA。我们更好的深度模型也带来了更好的深度条件 ControlNet。

使用示例
使用 Depth Anything 主要有两种方式:要么使用 pipeline API,它可以为您抽象化所有复杂性,要么自己使用 DepthAnythingForDepthEstimation
类。
Pipeline API
pipeline 允许在几行代码中使用模型
>>> from transformers import pipeline
>>> from PIL import Image
>>> import requests
>>> # load pipe
>>> pipe = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-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("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 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。
- 单目深度估计任务指南
- 一个展示如何使用 DepthAnythingForDepthEstimation 进行推理的 notebook 可以在这里找到。 🌎
如果您有兴趣提交要包含在此处的资源,请随时打开 Pull Request,我们将对其进行审核!该资源最好能展示一些新的东西,而不是重复现有资源。
DepthAnythingConfig
class transformers.DepthAnythingConfig
< source >( 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_hybrid
为True
或您想利用 AutoBackbone API 的情况下使用。 - backbone (
str
, 可选) — 当backbone_config
为None
时,要使用的 backbone 的名称。如果use_pretrained_backbone
为True
,这将从 timm 或 transformers 库加载相应的预训练权重。如果use_pretrained_backbone
为False
,这将加载 backbone 的配置并使用它来初始化具有随机权重的 backbone。 - use_pretrained_backbone (
bool
, 可选,默认为False
) — 是否对 backbone 使用预训练权重。 - use_timm_backbone (
bool
, 可选,默认为False
) — 是否对 backbone 使用timm
库。如果设置为False
,将使用 AutoBackbone API。 - backbone_kwargs (
dict
, 可选) — 从检查点加载时要传递给 AutoBackbone 的关键字参数,例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则无法指定。 - patch_size (
int
, 可选,默认为 14) — 从 backbone 特征中提取的 patch 的大小。 - 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]
) — 用于 backbone 的特征图投影到的隐藏层大小。 - 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
将此实例序列化为 Python 字典。覆盖默认的 to_dict()。 返回: Dict[str, any]
: 构成此配置实例的所有属性的字典,
DepthAnythingForDepthEstimation
class transformers.DepthAnythingForDepthEstimation
< source >( config )
参数
- config (DepthAnythingConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
带有置于顶部的深度估计头(由 3 个卷积层组成)的 Depth Anything 模型,例如用于 KITTI、NYUv2。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。
forward
< source >( 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.DepthEstimatorOutput 或 tuple(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.DepthEstimatorOutput 或 tuple(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__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在之后调用 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"))