Transformers 文档
DepthPro
并获得增强的文档体验
开始使用
DepthPro
概述
DepthPro 模型由 Aleksei Bochkovskii、Amaël Delaunoy、Hugo Germain、Marcel Santos、Yichao Zhou、Stephan R. Richter 和 Vladlen Koltun 在 Depth Pro: Sharp Monocular Metric Depth in Less Than a Second 中提出。
DepthPro 是一种用于零样本度量单目深度估计的基础模型,旨在生成具有卓越清晰度和精细细节的高分辨率深度图。它采用多尺度 Vision Transformer (ViT) 架构,其中图像被下采样,分成块,并使用共享的 Dinov2 编码器进行处理。提取的块级特征被合并、上采样,并使用 DPT 类似的融合阶段进行细化,从而实现精确的深度估计。
论文摘要如下:
我们提出了一种用于零样本度量单目深度估计的基础模型。我们的模型 Depth Pro 合成高分辨率深度图,具有无与伦比的清晰度和高频细节。预测是度量的,具有绝对尺度,不依赖于相机内参等元数据的可用性。该模型速度快,可在标准 GPU 上在 0.3 秒内生成 2.25 兆像素的深度图。这些特性得益于多项技术贡献,包括用于密集预测的高效多尺度视觉 Transformer、结合真实和合成数据集以实现高度量精度和精细边界追踪的训练协议、用于估计深度图中边界精度的专用评估指标,以及从单张图像进行最先进焦距估计。大量的实验分析了具体的D设计选择,并证明 Depth Pro 在多个维度上优于现有工作。

使用技巧
DepthPro 模型通过首先在多个尺度上对输入图像进行下采样,并将每个缩放版本分成块来处理。然后使用共享的基于 Vision Transformer (ViT) 的 Dinov2 块编码器对这些块进行编码,同时使用单独的图像编码器处理完整图像。提取的块特征被合并到特征图中,上采样,并使用 DPT 类似的解码器进行融合,以生成最终的深度估计。如果启用,额外的视野 (FOV) 编码器会处理图像以估计相机的视野,从而有助于提高深度精度。
>>> import requests
>>> from PIL import Image
>>> import torch
>>> from transformers import DepthProImageProcessorFast, DepthProForDepthEstimation
>>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
>>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = DepthProImageProcessorFast.from_pretrained("apple/DepthPro-hf")
>>> model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf").to(device)
>>> inputs = image_processor(images=image, return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> post_processed_output = image_processor.post_process_depth_estimation(
... outputs, target_sizes=[(image.height, image.width)],
... )
>>> field_of_view = post_processed_output[0]["field_of_view"]
>>> focal_length = post_processed_output[0]["focal_length"]
>>> depth = post_processed_output[0]["predicted_depth"]
>>> depth = (depth - depth.min()) / depth.max()
>>> depth = depth * 255.
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint8"))
架构和配置

DepthProForDepthEstimation
模型使用 DepthProEncoder
来编码输入图像,并使用 FeatureFusionStage
来融合编码器的输出特征。
DepthProEncoder
进一步使用两个编码器:
patch_encoder(补丁编码器)
- 输入图像以多种比例进行缩放,具体由
scaled_images_ratios
配置指定。 - 每个缩放后的图像都被分成大小为
patch_size
的小补丁,其重叠区域由scaled_images_overlap_ratios
确定。 - 这些补丁由
patch_encoder
处理。
- 输入图像以多种比例进行缩放,具体由
image_encoder(图像编码器)
- 输入图像也会被重新缩放到
patch_size
并由image_encoder
处理。
- 输入图像也会被重新缩放到
这两个编码器都可以通过 patch_model_config
和 image_model_config
进行配置,两者默认都为独立的 Dinov2Model
。
来自两个编码器(last_hidden_state
)的输出以及来自patch_encoder
的选定中间状态(hidden_states
)由基于 DPT
的 FeatureFusionStage
进行融合,以进行深度估计。
视野 (FOV) 预测
该网络补充了一个焦距估算头。一个小型卷积头接收来自深度估算网络的冻结特征和来自独立 ViT 图像编码器的任务特定特征,以预测水平视角。
DepthProConfig
中的 use_fov_model
参数控制是否启用 FOV 预测。默认情况下,它设置为 False
以节省内存和计算。启用时,FOV 编码器根据 fov_model_config
参数实例化,该参数默认为 Dinov2Model
。初始化 DepthProForDepthEstimation
模型时也可以传递 use_fov_model
参数。
检查点 apple/DepthPro-hf
处的预训练模型使用 FOV 编码器。要在不使用 FOV 编码器的情况下使用预训练模型,请在加载模型时将 use_fov_model=False
设置为 False
,这可以节省计算量。
>>> from transformers import DepthProForDepthEstimation
>>> model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", use_fov_model=False)
要实例化一个带有 FOV 编码器的新模型,请在配置中设置 use_fov_model=True
。
>>> from transformers import DepthProConfig, DepthProForDepthEstimation
>>> config = DepthProConfig(use_fov_model=True)
>>> model = DepthProForDepthEstimation(config)
或者在初始化模型时设置 use_fov_model=True
,这会覆盖配置中的值。
>>> from transformers import DepthProConfig, DepthProForDepthEstimation
>>> config = DepthProConfig()
>>> model = DepthProForDepthEstimation(config, use_fov_model=True)
使用缩放点积注意力 (SDPA)
PyTorch 包含一个原生缩放点积注意力 (SDPA) 运算符,作为 torch.nn.functional
的一部分。此函数包含几种实现,可根据输入和所使用的硬件进行应用。有关更多信息,请参阅 官方文档 或 GPU 推理 页面。
当实现可用时,SDPA 默认用于 `torch>=2.1.1`,但你也可以在 `from_pretrained()` 中设置 `attn_implementation="sdpa"` 来明确请求使用 SDPA。
from transformers import DepthProForDepthEstimation
model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", attn_implementation="sdpa", torch_dtype=torch.float16)
为了获得最佳加速效果,我们建议以半精度(例如 `torch.float16` 或 `torch.bfloat16`)加载模型。
在本地基准测试中(A100-40GB,PyTorch 2.3.0,操作系统 Ubuntu 22.04),使用 float32
和 google/vit-base-patch16-224
模型,我们在推理过程中观察到以下加速。
批次大小 | 平均推理时间(毫秒),eager 模式 | 平均推理时间(毫秒),sdpa 模型 | 加速,Sdpa / Eager (x) |
---|---|---|---|
1 | 7 | 6 | 1.17 |
2 | 8 | 6 | 1.33 |
4 | 8 | 6 | 1.33 |
8 | 8 | 6 | 1.33 |
资源
Hugging Face 官方和社区(🌎 表示)资源列表,帮助您开始使用 DepthPro
- 研究论文:Depth Pro: Sharp Monocular Metric Depth in Less Than a Second
- 官方实现:apple/ml-depth-pro
- DepthPro 推理 Notebook:DepthPro 推理
- DepthPro 用于超分辨率和图像分割
- 阅读 Medium 博客:Depth Pro: Beyond Depth
- GitHub 上的代码:geetu040/depthpro-beyond-depth
如果您有兴趣在此处提交资源,请随时开启 Pull Request,我们将对其进行审查!该资源最好能展示一些新内容,而不是重复现有资源。
DepthProConfig
类 transformers.DepthProConfig
< 来源 >( fusion_hidden_size = 256 patch_size = 384 initializer_range = 0.02 intermediate_hook_ids = [11, 5] intermediate_feature_dims = [256, 256] scaled_images_ratios = [0.25, 0.5, 1] scaled_images_overlap_ratios = [0.0, 0.5, 0.25] scaled_images_feature_dims = [1024, 1024, 512] merge_padding_value = 3 use_batch_norm_in_fusion_residual = False use_bias_in_fusion_residual = True use_fov_model = False num_fov_head_layers = 2 image_model_config = None patch_model_config = None fov_model_config = None **kwargs )
参数
- fusion_hidden_size (
int
, 可选, 默认为 256) — 融合前的通道数。 - patch_size (
int
, 可选, 默认为 384) — 每个补丁的大小(分辨率)。这也是骨干模型的图像大小。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - intermediate_hook_ids (
list[int]
, 可选, 默认为[11, 5]
) — 用于融合的补丁编码器中间隐藏状态的索引。 - intermediate_feature_dims (
list[int]
, 可选, 默认为[256, 256]
) —intermediate_hook_ids
中每个中间隐藏状态在上采样时的隐藏状态维度。 - scaled_images_ratios (
list[float]
, 可选, 默认为[0.25, 0.5, 1]
) — 补丁编码器使用的缩放图像比例。 - scaled_images_overlap_ratios (
list[float]
, 可选, 默认为[0.0, 0.5, 0.25]
) —scaled_images_ratios
中每个缩放图像的补丁之间的重叠比例。 - scaled_images_feature_dims (
list[int]
, 可选, 默认为[1024, 1024, 512]
) —scaled_images_ratios
中每个缩放图像在上采样时的隐藏状态维度。 - merge_padding_value (
int
, 可选, 默认为 3) — 将较小的补丁合并回图像大小时,会移除此大小的重叠部分。 - use_batch_norm_in_fusion_residual (
bool
, 可选, 默认为False
) — 是否在融合块的预激活残差单元中使用批量归一化。 - use_bias_in_fusion_residual (
bool
, 可选, 默认为True
) — 是否在融合块的预激活残差单元中使用偏置。 - use_fov_model (
bool
, 可选, 默认为False
) — 是否使用DepthProFovModel
生成视野。 - num_fov_head_layers (
int
, 可选, 默认为 2) —DepthProFovModel
头部的卷积层数量。 - image_model_config (
Union[dict[str, Any], PretrainedConfig]
, 可选) — 图像编码器模型的配置,该模型使用 AutoModel API 加载。默认情况下,Dinov2 模型用作骨干。 - patch_model_config (
Union[dict[str, Any], PretrainedConfig]
, 可选) — 补丁编码器模型的配置,该模型使用 AutoModel API 加载。默认情况下,Dinov2 模型用作骨干。 - fov_model_config (
Union[dict[str, Any], PretrainedConfig]
, 可选) — fov 编码器模型的配置,该模型使用 AutoModel API 加载。默认情况下,Dinov2 模型用作骨干。
这是用于存储 DepthProModel 配置的配置类。它用于根据指定参数实例化 DepthPro 模型,定义模型架构。使用默认值实例化配置将产生与 DepthPro apple/DepthPro 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import DepthProConfig, DepthProModel
>>> # Initializing a DepthPro apple/DepthPro style configuration
>>> configuration = DepthProConfig()
>>> # Initializing a model (with random weights) from the apple/DepthPro style configuration
>>> model = DepthProModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
DepthProImageProcessor
类 transformers.DepthProImageProcessor
< 来源 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> 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 **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的 (height, width) 维度调整为指定的(size["height"], size["width"])
。可以通过preprocess
方法中的do_resize
参数覆盖。 - size (
dict
, 可选, 默认为{"height": 1536, "width": 1536}
):调整大小后输出图像的大小。可以通过preprocess
方法中的size
参数覆盖。 - resample (
PILImageResampling
, 可选, 默认为Resampling.BILINEAR
) — 如果调整图像大小,使用的重采样过滤器。可以通过preprocess
方法中的resample
参数覆盖。 - do_rescale (
bool
, 可选, 默认为True
) — 是否将图像值缩放到 [0 - 1] 之间。可以通过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
参数覆盖。
构造一个 DepthPro 图像处理器。
预处理
< 来源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, 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 return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.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
。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
dict[str, int]
, 可选, 默认为self.size
) — 字典格式{"height": h, "width": w}
,指定调整大小后输出图像的大小。可以通过preprocess
方法中的size
参数覆盖。 - resample (
PILImageResampling
过滤器, 可选, 默认为self.resample
) — 如果调整图像大小,使用的PILImageResampling
过滤器,例如PILImageResampling.BILINEAR
。仅当do_resize
设置为True
时有效。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否将图像值缩放到 [0 - 1] 之间。 - rescale_factor (
float
, optional, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,用于缩放图像的缩放因子。 - do_normalize (
bool
, optional, 默认为self.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
或list[float]
, optional, 默认为self.image_mean
) — 如果do_normalize
设置为True
,要使用的图像均值。 - image_std (
float
或list[float]
, optional, 默认为self.image_std
) — 如果do_normalize
设置为True
,要使用的图像标准差。 - return_tensors (
str
或TensorType
, optional) — 要返回的张量类型。可以是以下之一:- 未设置:返回
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
, optional, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像为 (num_channels, height, width) 格式。"channels_last"
或ChannelDimension.LAST
:图像为 (height, width, num_channels) 格式。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, optional) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像为 (num_channels, height, width) 格式。"channels_last"
或ChannelDimension.LAST
:图像为 (height, width, num_channels) 格式。"none"
或ChannelDimension.NONE
:图像为 (height, width) 格式。
预处理一张或一批图像。
后处理深度估计
< source >( outputs: DepthProDepthEstimatorOutput target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple[int, int]], NoneType] = None ) → list[dict[str, TensorType]]
参数
- outputs (
DepthProDepthEstimatorOutput
) — 模型的原始输出。 - target_sizes (
Optional[Union[TensorType, list[tuple[int, int]], None]]
, optional, 默认为None
) — 调整深度预测目标大小。可以是形状为(batch_size, 2)
的张量,也可以是批次中每个图像的元组(height, width)
列表。如果为None
,则不执行大小调整。
返回
list[dict[str, TensorType]]
张量字典列表,表示已处理的深度预测,如果 outputs
中给出了 field_of_view
,则还包括视野(度)和焦距(像素)。
引发
ValueError
ValueError
— 如果predicted_depths
、fovs
或target_sizes
的长度不匹配。
对模型的原始深度预测进行后处理,以生成最终的深度预测,如果提供了视野,则使用视野进行校准,如果提供了目标大小,则调整到指定的目标大小。
DepthProImageProcessorFast
class transformers.DepthProImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
构造一个快速的 Depth Pro 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] ) → <class 'transformers.image_processing_base.BatchFeature'>
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]
) — 要预处理的图像。期望单个或批次图像的像素值范围为 0 到 255。如果传入像素值在 0 到 1 之间的图像,请设置do_rescale=False
。 - do_resize (
bool
, optional) — 是否调整图像大小。 - size (
dict[str, int]
, optional) — 描述模型最大输入维度。 - default_to_square (
bool
, optional) — 当调整大小且大小为整数时,是否默认为正方形图像。 - resample (
Union[PILImageResampling, F.InterpolationMode, NoneType]
) — 如果调整图像大小,要使用的重采样滤镜。这可以是枚举PILImageResampling
之一。仅在do_resize
设置为True
时有效。 - do_center_crop (
bool
, optional) — 是否中心裁剪图像。 - crop_size (
dict[str, int]
, optional) — 应用center_crop
后输出图像的大小。 - do_rescale (
bool
, optional) — 是否缩放图像。 - rescale_factor (
Union[int, float, NoneType]
) — 如果do_rescale
设置为True
,用于缩放图像的缩放因子。 - do_normalize (
bool
, optional) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], NoneType]
) — 用于归一化的图像均值。仅在do_normalize
设置为True
时有效。 - image_std (
Union[float, list[float], NoneType]
) — 用于归一化的图像标准差。仅在do_normalize
设置为True
时有效。 - do_convert_rgb (
bool
, optional) — 是否将图像转换为 RGB。 - return_tensors (
Union[str, ~utils.generic.TensorType, NoneType]
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
~image_utils.ChannelDimension
, optional) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]
) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像为 (num_channels, height, width) 格式。"channels_last"
或ChannelDimension.LAST
:图像为 (height, width, num_channels) 格式。"none"
或ChannelDimension.NONE
:图像为 (height, width) 格式。
- device (
torch.device
, optional) — 处理图像的设备。如果未设置,则从输入图像推断设备。 - disable_grouping (
bool
, optional) — 是否禁用按大小对图像进行分组以单独处理而不是批量处理。如果为 None,则如果图像在 CPU 上,将设置为 True,否则设置为 False。此选择基于经验观察,详情见此:https://github.com/huggingface/transformers/pull/38157
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType]
, 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。
后处理深度估计
< source >( outputs: DepthProDepthEstimatorOutput target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple[int, int]], NoneType] = None ) → list[dict[str, TensorType]]
参数
- outputs (
DepthProDepthEstimatorOutput
) — 模型的原始输出。 - target_sizes (
Optional[Union[TensorType, list[tuple[int, int]], None]]
, optional, 默认为None
) — 调整深度预测目标大小。可以是形状为(batch_size, 2)
的张量,也可以是批次中每个图像的元组(height, width)
列表。如果为None
,则不执行大小调整。
返回
list[dict[str, TensorType]]
张量字典列表,表示已处理的深度预测,如果 outputs
中给出了 field_of_view
,则还包括视野(度)和焦距(像素)。
引发
ValueError
ValueError
— 如果predicted_depths
、fovs
或target_sizes
的长度不匹配。
对模型的原始深度预测进行后处理,以生成最终的深度预测,如果提供了视野,则使用视野进行校准,如果提供了目标大小,则调整到指定的目标大小。
DepthProModel
class transformers.DepthProModel
< source >( config )
参数
- config (DepthProModel) — 具有模型所有参数的模型配置类。使用配置文件初始化不加载与模型关联的权重,只加载配置。查看 from_pretrained() 方法以加载模型权重。
裸 Depth Pro 模型,输出原始隐藏状态,顶部没有任何特定头部。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中与通用用法和行为相关的所有事项。
forward
< source >( pixel_values: FloatTensor head_mask: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.depth_pro.modeling_depth_pro.DepthProOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获得。有关详细信息,请参见{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的torch.FloatTensor
, optional) — 用于使自注意力模块的选定头部无效的掩码。在[0, 1]
中选择掩码值:- 1 表示头部未被遮蔽,
- 0 表示头部被遮蔽。
- output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是普通元组。
返回
transformers.models.depth_pro.modeling_depth_pro.DepthProOutput
或 tuple(torch.FloatTensor)
transformers.models.depth_pro.modeling_depth_pro.DepthProOutput
或 torch.FloatTensor
的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置 (DepthProConfig) 和输入的不同元素。
-
last_hidden_state (形状为
(batch_size, n_patches_per_batch, sequence_length, hidden_size)
的torch.FloatTensor
) — 模型最后一层输出的隐藏状态序列。 -
features (
Union[torch.FloatTensor, List[torch.FloatTensor]]
, optional) — 编码器的特征。可以是单个特征或特征列表。 -
hidden_states (
tuple[torch.FloatTensor, ...]
, optional, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(如果模型具有嵌入层,则为一个嵌入层输出,加上每个层的一个输出)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple[torch.FloatTensor, ...]
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的torch.FloatTensor
元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
DepthProModel 前向方法,覆盖 __call__
特殊方法。
尽管前向传播的配方需要在此函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, DepthProModel
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> checkpoint = "apple/DepthPro-hf"
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> model = DepthProModel.from_pretrained(checkpoint)
>>> # prepare image for the model
>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.no_grad():
... output = model(**inputs)
>>> output.last_hidden_state.shape
torch.Size([1, 35, 577, 1024])
DepthProForDepthEstimation
class transformers.DepthProForDepthEstimation
< source >( config use_fov_model = None )
参数
- config (DepthProForDepthEstimation) — 具有模型所有参数的模型配置类。使用配置文件初始化不加载与模型关联的权重,只加载配置。查看 from_pretrained() 方法以加载模型权重。
- use_fov_model (
bool
, optional) — 是否使用视野模型。
带有顶部深度估计头(由 3 个卷积层组成)的 DepthPro 模型。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中与通用用法和行为相关的所有事项。
forward
< source >( pixel_values: FloatTensor head_mask: 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.models.depth_pro.modeling_depth_pro.DepthProDepthEstimatorOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获得。有关详细信息,请参见{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的torch.FloatTensor
, optional) — 用于使自注意力模块的选定头部无效的掩码。在[0, 1]
中选择掩码值:- 1 表示头部未被遮蔽,
- 0 表示头部被遮蔽。
- labels (形状为
(batch_size, height, width)
的torch.LongTensor
, optional) — 用于计算损失的真实深度估计图。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是普通元组。
返回
transformers.models.depth_pro.modeling_depth_pro.DepthProDepthEstimatorOutput
或 tuple(torch.FloatTensor)
transformers.models.depth_pro.modeling_depth_pro.DepthProDepthEstimatorOutput
或 torch.FloatTensor
的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置 (DepthProConfig) 和输入的不同元素。
-
loss (形状为
(1,)
的torch.FloatTensor
,可选,当提供labels
时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 -
predicted_depth (形状为
(batch_size, height, width)
的torch.FloatTensor
, optional, 默认为None
) — 每个像素的预测深度。 -
field_of_view (形状为
(batch_size,)
的torch.FloatTensor
, optional, 当提供use_fov_model
时返回) — 视野缩放器。 -
hidden_states (
tuple[torch.FloatTensor, ...]
, optional, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(如果模型具有嵌入层,则为一个嵌入层输出,加上每个层的一个输出)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple[torch.FloatTensor, ...]
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的torch.FloatTensor
元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
DepthProForDepthEstimation 前向方法,覆盖 __call__
特殊方法。
尽管前向传播的配方需要在此函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, DepthProForDepthEstimation
>>> import torch
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> checkpoint = "apple/DepthPro-hf"
>>> processor = AutoImageProcessor.from_pretrained(checkpoint)
>>> model = DepthProForDepthEstimation.from_pretrained(checkpoint)
>>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
>>> model.to(device)
>>> # prepare image for the model
>>> inputs = processor(images=image, return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # interpolate to original size
>>> post_processed_output = processor.post_process_depth_estimation(
... outputs, target_sizes=[(image.height, image.width)],
... )
>>> # get the field of view (fov) predictions
>>> field_of_view = post_processed_output[0]["field_of_view"]
>>> focal_length = post_processed_output[0]["focal_length"]
>>> # 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"))