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

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。
- 单目深度估计任务指南
- Depth Anything V2 演示.
- 展示 DepthAnythingForDepthEstimation 推理的 Jupyter Notebook 可在此处找到。🌎
- 用于 Apple Silicon 的
small
变体的 Core ML 转换.
如果您有兴趣在此处提交资源,请随时开启 Pull Request,我们将对其进行审查!该资源最好能展示一些新内容,而不是重复现有资源。
DepthAnythingConfig
类 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) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。 - 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
, 可选) — 用于“度量”深度估计头部的最大深度。室内模型应使用 20,室外模型应使用 80。对于“相对”深度估计,此值将被忽略。
这是用于存储 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
类 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"))