Transformers 文档
Depth Anything
并获得增强的文档体验
开始使用
Depth Anything
Depth Anything 旨在成为单目深度估计 (MDE) 的基础模型。它在有标签和约 6200 万无标签图像上联合训练,以增强数据集。它使用预训练的 DINOv2 模型作为图像编码器,以继承其现有的丰富语义先验,并使用 DPT 作为解码器。一个教师模型在无标签图像上进行训练以创建伪标签。学生模型在伪标签和有标签图像的组合上进行训练。为了提高学生模型的性能,对无标签图像添加了强烈的扰动,以挑战学生模型从图像中学习更多的视觉知识。
您可以在 Depth Anything 集合中找到所有原始的 Depth Anything 检查点。
点击右侧边栏中的 Depth Anything 模型,了解更多关于如何将 Depth Anything 应用于不同视觉任务的示例。
以下示例演示了如何使用 Pipeline 或 AutoModel 类获取深度图。
import torch
from transformers import pipeline
pipe = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf", torch_dtype=torch.bfloat16, device=0)
pipe("http://images.cocodataset.org/val2017/000000039769.jpg")["depth"]
注意事项
- DepthAnythingV2 于 2024 年 6 月发布,采用与 Depth Anything 相同的架构,并与所有代码示例和现有工作流程兼容。它使用合成数据和更大容量的教师模型,以实现更精细、更鲁棒的深度预测。
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]
, 可选) — 骨干模型的配置。仅在is_hybrid
为True
或您希望利用 AutoBackbone API 时使用。 - backbone (
str
, 可选) — 当backbone_config
为None
时使用的骨干名称。如果use_pretrained_backbone
为True
,这将从 timm 或 transformers 库中加载相应的预训练权重。如果use_pretrained_backbone
为False
,这将加载骨干的配置并用于使用随机权重初始化骨干。 - use_pretrained_backbone (
bool
, 可选, 默认为False
) — 是否为骨干使用预训练权重。 - use_timm_backbone (
bool
, 可选, 默认为False
) — 是否为骨干使用timm
库。如果设置为False
,将使用 AutoBackbone API。 - backbone_kwargs (
dict
, 可选) — 加载检查点时传递给 AutoBackbone 的关键字参数,例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则不能指定。 - patch_size (
int
, 可选, 默认为 14) — 从骨干特征中提取的补丁大小。 - 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”深度估计,此值被忽略。
这是一个配置类,用于存储 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
DepthAnythingForDepthEstimation
class transformers.DepthAnythingForDepthEstimation
< 来源 >( config )
参数
- config (DepthAnythingForDepthEstimation) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法以加载模型权重。
Depth Anything 模型,顶部带有一个深度估计头部(由 3 个卷积层组成),例如用于 KITTI、NYUv2。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 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.DepthEstimatorOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
,形状为(batch_size, num_channels, image_size, image_size)
) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参见{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - labels (
torch.LongTensor
,形状为(batch_size, height, width)
,可选) — 用于计算损失的真实深度估计图。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是纯元组。
返回
transformers.modeling_outputs.DepthEstimatorOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.DepthEstimatorOutput 或 torch.FloatTensor
的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置 (DepthAnythingConfig) 和输入而异的各种元素。
-
loss (形状为
(1,)
的torch.FloatTensor
,可选,当提供labels
时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 -
predicted_depth (
torch.FloatTensor
,形状为(batch_size, height, width)
) — 每个像素的预测深度。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组(一个用于嵌入层输出,如果模型有嵌入层,+一个用于每个层输出),形状为(batch_size, num_channels, height, width)
。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递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"))