Transformers 文档
Depth Anything
并获得增强的文档体验
开始使用
该模型于 2024 年 1 月 19 日在 HF 论文中发表,并于 2024 年 1 月 25 日贡献给 Hugging Face Transformers。
Depth Anything
Depth Anything 旨在成为单目深度估计 (MDE) 的基础模型。它联合使用标注数据和约 6200 万张未标注图像进行训练,以扩充数据集。它使用预训练的 DINOv2 模型作为图像编码器,以继承其现有的丰富语义先验,并使用 DPT 作为解码器。教师模型在未标注图像上进行训练以生成伪标签。学生模型则在伪标签和标注图像的组合上进行训练。为了提高学生模型的性能,会对未标注图像添加强扰动,以激励学生模型从图像中学习到更多的视觉知识。
你可以在 Depth Anything 合集中找到所有原始的 Depth Anything 检查点。
点击右侧侧边栏中的 Depth Anything 模型,查看如何将 Depth Anything 应用于不同视觉任务的更多示例。
下面的示例演示了如何使用 Pipeline 或 AutoModel 类获取深度图。
from transformers import pipeline
pipe = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf", device=0)
pipe("http://images.cocodataset.org/val2017/000000039769.jpg")["depth"]注意事项
- DepthAnythingV2 于 2024 年 6 月发布,它使用了与 Depth Anything 相同的架构,并兼容所有代码示例和现有工作流。它使用合成数据和容量更大的教师模型,以实现更精细、更稳健的深度预测。
DepthAnythingConfig
class transformers.DepthAnythingConfig
< 源码 >( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None patch_size: int | list[int] | tuple[int, int] = 14 initializer_range: float = 0.02 reassemble_hidden_size: int = 384 reassemble_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 = 64 head_in_index: int = -1 head_hidden_size: int = 32 depth_estimation_type: str = 'relative' max_depth: int | None = None )
参数
- backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig], 可选) — 骨干模型的配置。 - patch_size (
Union[int, list[int], tuple[int, int]], 可选, 默认为14) — 每个块(patch)的大小(分辨率)。 - initializer_range (
float, 可选, 默认为0.02) — 用于初始化所有权重矩阵的截断正态分布初始化器的标准差。 - reassemble_hidden_size (
int, 可选, 默认为 384) — 重组层(reassemble layers)的输入通道数。 - 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.configDepthAnythingForDepthEstimation
class transformers.DepthAnythingForDepthEstimation
< 源码 >( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )
参数
- config (DepthAnythingForDepthEstimation) — 具有所有模型参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
Depth Anything 模型,顶部带有一个深度估计头部(由 3 个卷积层组成),例如用于 KITTI、NYUv2。
该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< 源码 >( pixel_values: FloatTensor labels: torch.LongTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) → DepthEstimatorOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor, 形状为(batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。像素值可以使用 DPTImageProcessor 获取。详情请参阅DPTImageProcessor.__call__()(processor_class使用 DPTImageProcessor 进行图像处理)。 - labels (
torch.LongTensor, 形状为(batch_size, height, width), 可选) — 用于计算损失的真实深度估计图。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的attentions。 - output_hidden_states (
bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回
DepthEstimatorOutput 或 tuple(torch.FloatTensor)
一个 DepthEstimatorOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置(DepthAnythingConfig)和输入,包含各种元素。
DepthAnythingForDepthEstimation 的 forward 方法重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
loss (形状为
(1,)的torch.FloatTensor,可选,当提供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时返回) — 形状为(batch_size, num_heads, patch_size, sequence_length)的torch.FloatTensor元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
示例
>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> 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"))