Transformers 文档
Prompt Depth Anything
并获得增强的文档体验
开始使用
Prompt Depth Anything
概述
Prompt Depth Anything 模型由 Haotong Lin, Sida Peng, Jingxiao Chen, Songyou Peng, Jiaming Sun, Minghuan Liu, Hujun Bao, Jiashi Feng, Xiaowei Zhou, Bingyi Kang 在 Prompting Depth Anything for 4K Resolution Accurate Metric Depth Estimation 中提出。
论文摘要如下:
提示在释放语言和视觉基础模型在特定任务上的力量方面起着关键作用。我们首次将提示引入深度基础模型,为度量深度估计创建了一个新的范式,称为 Prompt Depth Anything。具体来说,我们使用低成本的 LiDAR 作为提示来指导 Depth Anything 模型进行精确的度量深度输出,实现高达 4K 分辨率。我们的方法以简洁的提示融合设计为中心,该设计在深度解码器内以多尺度集成 LiDAR。为了解决包含 LiDAR 深度和精确 GT 深度的数据集有限带来的训练挑战,我们提出了一种可扩展的数据管道,包括合成数据 LiDAR 模拟和真实数据伪 GT 深度生成。我们的方法在 ARKitScenes 和 ScanNet++ 数据集上取得了新的最先进水平,并受益于下游应用,包括 3D 重建和广义机器人抓取。

使用示例
Transformers 库允许您仅用几行代码使用该模型:
>>> import torch
>>> import requests
>>> import numpy as np
>>> from PIL import Image
>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
>>> url = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/image.jpg?raw=true"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("depth-anything/prompt-depth-anything-vits-hf")
>>> model = AutoModelForDepthEstimation.from_pretrained("depth-anything/prompt-depth-anything-vits-hf")
>>> prompt_depth_url = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/arkit_depth.png?raw=true"
>>> prompt_depth = Image.open(requests.get(prompt_depth_url, stream=True).raw)
>>> # the prompt depth can be None, and the model will output a monocular relative depth.
>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt", prompt_depth=prompt_depth)
>>> 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 * 1000
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint16")) # mm
资源
官方 Hugging Face 和社区(用 🌎 表示)资源列表,可帮助您开始使用 Prompt Depth Anything。
如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审查!理想情况下,该资源应展示一些新内容,而不是重复现有资源。
PromptDepthAnythingConfig
class transformers.PromptDepthAnythingConfig
< 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]
, optional) — 主干模型的配置。仅在is_hybrid
为True
或您想利用 AutoBackbone API 时使用。 - backbone (
str
, optional) — 当backbone_config
为None
时使用的主干模型名称。如果use_pretrained_backbone
为True
,这将从 timm 或 transformers 库加载相应的预训练权重。如果use_pretrained_backbone
为False
,这将加载主干模型的配置并使用它来初始化具有随机权重的主干模型。 - use_pretrained_backbone (
bool
, optional, 默认为False
) — 是否使用主干模型的预训练权重。 - use_timm_backbone (
bool
, optional, 默认为False
) — 是否使用timm
库作为主干模型。如果设置为False
,将使用 AutoBackbone API。 - backbone_kwargs (
dict
, optional) — 从检查点加载时传递给 AutoBackbone 的关键字参数,例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则不能指定此参数。 - patch_size (
int
, optional, 默认为 14) — 从主干模型特征中提取的补丁大小。 - initializer_range (
float
, optional, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。 - reassemble_hidden_size (
int
, optional, 默认为 384) — 重组层的输入通道数。 - reassemble_factors (
list[int]
, optional, 默认为[4, 2, 1, 0.5]
) — 重组层的上/下采样因子。 - neck_hidden_sizes (
list[str]
, optional, 默认为[48, 96, 192, 384]
) — 主干模型特征图的投影隐藏大小。 - fusion_hidden_size (
int
, optional, 默认为 64) — 融合前的通道数。 - head_in_index (
int
, optional, 默认为 -1) — 在深度估计头部中使用的特征索引。 - head_hidden_size (
int
, optional, 默认为 32) — 深度估计头部中第二个卷积层的输出通道数。 - depth_estimation_type (
str
, optional, 默认为"relative"
) — 要使用的深度估计类型。可以是["relative", "metric"]
之一。 - max_depth (
float
, optional) — “度量”深度估计头部要使用的最大深度。室内模型应使用 20,室外模型应使用 80。对于“相对”深度估计,此值将被忽略。
这是用于存储 PromptDepthAnythingModel
配置的配置类。它用于根据指定的参数实例化 PromptDepthAnything 模型,定义模型架构。使用默认值实例化配置将产生类似于 PromptDepthAnything LiheYoung/depth-anything-small-hf 架构的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import PromptDepthAnythingConfig, PromptDepthAnythingForDepthEstimation
>>> # Initializing a PromptDepthAnything small style configuration
>>> configuration = PromptDepthAnythingConfig()
>>> # Initializing a model from the PromptDepthAnything small style configuration
>>> model = PromptDepthAnythingForDepthEstimation(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
PromptDepthAnythingForDepthEstimation
class transformers.PromptDepthAnythingForDepthEstimation
< 源 >( config )
参数
- config (PromptDepthAnythingForDepthEstimation) — 包含模型所有参数的模型配置类。使用配置文件初始化不加载与模型关联的权重,只加载配置。请查阅 from_pretrained() 方法以加载模型权重。
Prompt Depth Anything 模型,顶部带有一个深度估计头(由 3 个卷积层组成),例如用于 KITTI、NYUv2。
此模型继承自 PreTrainedModel。请查阅超类文档以了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参阅 PyTorch 文档以了解与一般使用和行为相关的所有事项。
forward
< 源 >( pixel_values: FloatTensor prompt_depth: typing.Optional[torch.FloatTensor] = None 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}
处理图像)。 - prompt_depth (
torch.FloatTensor
,形状为(batch_size, 1, height, width)
, 可选) — 提示深度是从多视角几何或低分辨率深度传感器获得的稀疏或低分辨率深度。它通常具有 (height, width) 的形状,其中 height 和 width 可以小于图像的 height 和 width。它是可选的,可以为 None,这意味着将不使用提示深度。如果为 None,输出将是单目相对深度。建议值以米为单位,但这并非必需。 - labels (
torch.LongTensor
,形状为(batch_size, sequence_length)
, 可选) — 用于计算掩码语言建模损失的标签。索引应位于[0, ..., config.vocab_size]
或 -100(参阅input_ids
文档字符串)中。索引设置为-100
的标记将被忽略(掩码),损失仅针对标签位于[0, ..., config.vocab_size]
中的标记计算。 - 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
),包含根据配置(PromptDepthAnythingConfig)和输入而变化的不同元素。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
此 PromptDepthAnythingForDepthEstimation forward 方法会覆盖 __call__
特殊方法。
尽管前向传播的实现需要在该函数中定义,但之后应调用 Module
实例,而不是该函数,因为前者会处理运行前处理和后处理步骤,而后者会默默忽略它们。
示例
>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> import requests
>>> url = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/image.jpg?raw=true"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("depth-anything/prompt-depth-anything-vits-hf")
>>> model = AutoModelForDepthEstimation.from_pretrained("depth-anything/prompt-depth-anything-vits-hf")
>>> prompt_depth_url = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/arkit_depth.png?raw=true"
>>> prompt_depth = Image.open(requests.get(prompt_depth_url, stream=True).raw)
>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt", prompt_depth=prompt_depth)
>>> 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 * 1000.
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint16")) # mm
PromptDepthAnythingImageProcessor
class transformers.PromptDepthAnythingImageProcessor
< 源 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BICUBIC: 3> keep_aspect_ratio: bool = False ensure_multiple_of: int = 1 do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_pad: bool = False size_divisor: typing.Optional[int] = None prompt_scale_to_meter: float = 0.001 **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否调整图像的(高度,宽度)尺寸。可以通过preprocess
中的do_resize
覆盖。 - size (
dict[str, int]
可选, 默认为{"height" -- 384, "width": 384}
): 调整大小后的图像尺寸。可以通过preprocess
中的size
覆盖。 - resample (
PILImageResampling
, 可选, 默认为Resampling.BICUBIC
) — 定义如果调整图像大小要使用的重采样滤镜。可以通过preprocess
中的resample
覆盖。 - keep_aspect_ratio (
bool
, 可选, 默认为False
) — 如果为True
,图像将调整为尽可能大的尺寸,以保持宽高比。可以通过preprocess
中的keep_aspect_ratio
覆盖。 - ensure_multiple_of (
int
, 可选, 默认为 1) — 如果do_resize
为True
,图像将调整为该值的倍数。可以通过preprocess
中的ensure_multiple_of
覆盖。 - do_rescale (
bool
, 可选, 默认为True
) — 是否按指定比例rescale_factor
重新缩放图像。可以通过preprocess
中的do_rescale
覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果重新缩放图像,要使用的比例因子。可以通过preprocess
中的rescale_factor
覆盖。 - do_normalize (
bool
, 可选, 默认为True
) — 是否归一化图像。可以通过preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或list[float]
, 可选, 默认为IMAGENET_STANDARD_MEAN
) — 如果归一化图像,要使用的均值。这是一个浮点数或长度等于图像通道数的浮点数列表。可以通过preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或list[float]
, 可选, 默认为IMAGENET_STANDARD_STD
) — 如果归一化图像,要使用的标准差。这是一个浮点数或长度等于图像通道数的浮点数列表。可以通过preprocess
方法中的image_std
参数覆盖。 - do_pad (
bool
, 可选, 默认为False
) — 是否应用中心填充。这是 DINOv2 论文中引入的,它将模型与 DPT 结合使用。 - size_divisor (
int
, 可选) — 如果do_pad
为True
,将图像尺寸填充到可被此值整除。这是 DINOv2 论文中引入的,它将模型与 DPT 结合使用。 - prompt_scale_to_meter (
float
, 可选, 默认为 0.001) — 用于将提示深度转换为米的比例因子。
构造一个 PromptDepthAnything 图像处理器。
预处理
< 来源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] prompt_depth: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None do_resize: typing.Optional[bool] = None size: typing.Optional[int] = None keep_aspect_ratio: typing.Optional[bool] = None ensure_multiple_of: typing.Optional[int] = None resample: typing.Optional[PIL.Image.Resampling] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_pad: typing.Optional[bool] = None size_divisor: typing.Optional[int] = None prompt_scale_to_meter: typing.Optional[float] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )
参数
- images (
ImageInput
) — 要预处理的图像。期望是像素值范围为 0 到 255 的单张或批量图像。如果传入像素值在 0 到 1 之间的图像,请设置do_rescale=False
。 - prompt_depth (
ImageInput
, 可选) — 要预处理的提示深度,可以是来自多视图几何的稀疏深度,也可以是来自深度传感器的低分辨率深度。通常形状为 (高度,宽度),其中高度和宽度可以小于图像的尺寸。它是可选的,可以为 None,这意味着不使用提示深度。如果为 None,则输出深度将为单目相对深度。建议提供prompt_scale_to_meter
值,即用于将提示深度转换为米的比例因子。当提示深度不以米为单位时,这很有用。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
dict[str, int]
, 可选, 默认为self.size
) — 调整大小后的图像尺寸。如果keep_aspect_ratio
为True
,图像将调整为尽可能大的尺寸,以保持宽高比。如果设置了ensure_multiple_of
,图像将调整为该值的倍数。 - keep_aspect_ratio (
bool
, 可选, 默认为self.keep_aspect_ratio
) — 是否保持图像的宽高比。如果为 False,图像将调整为 (size, size)。如果为 True,图像将调整大小以保持宽高比,并且尺寸将是最大可能尺寸。 - ensure_multiple_of (
int
, 可选, 默认为self.ensure_multiple_of
) — 确保图像尺寸是此值的倍数。 - resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,要使用的重采样滤镜。这可以是枚举PILImageResampling
之一。仅在do_resize
设置为True
时有效。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的比例因子。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否归一化图像。 - image_mean (
float
或list[float]
, 可选, 默认为self.image_mean
) — 图像均值。 - image_std (
float
或list[float]
, 可选, 默认为self.image_std
) — 图像标准差。 - prompt_scale_to_meter (
float
, 可选, 默认为self.prompt_scale_to_meter
) — 用于将提示深度转换为米的比例因子。 - return_tensors (
str
或TensorType
, 可选) — 要返回的张量类型。可以是以下之一:- 未设置:返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
:返回tf.Tensor
批次。TensorType.PYTORCH
或'pt'
:返回torch.Tensor
批次。TensorType.NUMPY
或'np'
:返回np.ndarray
批次。TensorType.JAX
或'jax'
:返回jax.numpy.ndarray
批次。
- 未设置:返回
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
预处理一张或一批图像。
后处理深度估计
< 来源 >( outputs: DepthEstimatorOutput target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple[int, int]], NoneType] = None ) → list[dict[str, TensorType]]
将 DepthEstimatorOutput
的原始输出转换为最终的深度预测和深度 PIL 图像。仅支持 PyTorch。