Transformers 文档
ZoeDepth
并获得增强的文档体验
开始使用
ZoeDepth
概述
ZoeDepth 模型在 ZoeDepth: Zero-shot Transfer by Combining Relative and Metric Depth 中提出,作者是 Shariq Farooq Bhat, Reiner Birkl, Diana Wofk, Peter Wonka, Matthias Müller。ZoeDepth 扩展了 DPT 框架,用于度量(也称为绝对)深度估计。ZoeDepth 在 12 个数据集上使用相对深度进行预训练,并在两个领域(NYU 和 KITTI)上使用度量深度进行微调。每个领域都使用一个轻量级头部和一个名为度量 bin 模块的新型 bin 调整设计。在推理过程中,每个输入图像都使用潜在分类器自动路由到相应的头部。
论文摘要如下
本文探讨了从单张图像进行深度估计的问题。现有工作要么侧重于泛化性能,而忽略度量尺度,即相对深度估计;要么侧重于特定数据集上的最先进结果,即度量深度估计。我们提出了第一种结合两个世界的方法,从而产生一个具有出色泛化性能同时保持度量尺度的模型。我们的旗舰模型 ZoeD-M12-NK 在 12 个数据集上使用相对深度进行预训练,并在两个数据集上使用度量深度进行微调。我们为每个领域使用了一个轻量级头部和一个名为度量 bin 模块的新型 bin 调整设计。在推理过程中,每个输入图像都使用潜在分类器自动路由到相应的头部。我们的框架允许根据用于相对深度预训练和度量微调的数据集进行多种配置。在没有预训练的情况下,我们已经可以显著提高 NYU Depth v2 室内数据集上的最先进水平 (SOTA)。在十二个数据集上进行预训练,并在 NYU Depth v2 室内数据集上进行微调,我们可以进一步提高 SOTA,相对绝对误差 (REL) 总共提高了 21%。最后,ZoeD-M12-NK 是第一个可以联合在多个数据集(NYU Depth v2 和 KITTI)上训练而性能没有显著下降的模型,并在室内和室外领域的八个未见数据集上实现了前所未有的零样本泛化性能。

使用技巧
- ZoeDepth 是一种绝对(也称为度量)深度估计模型,与 DPT 这种相对深度估计模型不同。这意味着 ZoeDepth 能够以米等度量单位估计深度。
使用 ZoeDepth 进行推理的最简单方法是利用 pipeline API
>>> from transformers import pipeline
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> pipe = pipeline(task="depth-estimation", model="Intel/zoedepth-nyu-kitti")
>>> result = pipe(image)
>>> depth = result["depth"]
或者,也可以使用类执行推理
>>> from transformers import AutoImageProcessor, ZoeDepthForDepthEstimation
>>> 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("Intel/zoedepth-nyu-kitti")
>>> model = ZoeDepthForDepthEstimation.from_pretrained("Intel/zoedepth-nyu-kitti")
>>> # 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
>>> ## ZoeDepth dynamically pads the input image. Thus we pass the original image size as argument
>>> ## to `post_process_depth_estimation` to remove the padding and resize to original dimensions.
>>> post_processed_output = image_processor.post_process_depth_estimation(
... outputs,
... source_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"))
在 原始实现 中,ZoeDepth 模型对原始图像和翻转图像都执行推理,并对结果取平均值。`post_process_depth_estimation` 函数可以通过将翻转的输出传递给可选的 `outputs_flipped` 参数来为我们处理这个问题
>>> with torch.no_grad():
... outputs = model(pixel_values)
... outputs_flipped = model(pixel_values=torch.flip(inputs.pixel_values, dims=[3]))
>>> post_processed_output = image_processor.post_process_depth_estimation(
... outputs,
... source_sizes=[(image.height, image.width)],
... outputs_flipped=outputs_flipped,
... )
资源
以下是官方 Hugging Face 和社区 (🌎) 资源列表,可帮助您开始使用 ZoeDepth。
- 关于使用 ZoeDepth 模型进行推理的演示 notebook 可以在这里找到。 🌎
ZoeDepthConfig
class transformers.ZoeDepthConfig
< 源代码 >( backbone_config = None backbone = None use_pretrained_backbone = False backbone_kwargs = None hidden_act = 'gelu' initializer_range = 0.02 batch_norm_eps = 1e-05 readout_type = 'project' reassemble_factors = [4, 2, 1, 0.5] neck_hidden_sizes = [96, 192, 384, 768] fusion_hidden_size = 256 head_in_index = -1 use_batch_norm_in_fusion_residual = False use_bias_in_fusion_residual = None num_relative_features = 32 add_projection = False bottleneck_features = 256 num_attractors = [16, 8, 4, 1] bin_embedding_dim = 128 attractor_alpha = 1000 attractor_gamma = 2 attractor_kind = 'mean' min_temp = 0.0212 max_temp = 50.0 bin_centers_type = 'softplus' bin_configurations = [{'n_bins': 64, 'min_depth': 0.001, 'max_depth': 10.0}] num_patch_transformer_layers = None patch_transformer_hidden_size = None patch_transformer_intermediate_size = None patch_transformer_num_attention_heads = None **kwargs )
参数
- backbone_config (
Union[Dict[str, Any], PretrainedConfig]
, 可选, 默认为BeitConfig()
) — backbone 模型的配置。 - backbone (
str
, 可选) — 当backbone_config
为None
时,要使用的 backbone 名称。如果use_pretrained_backbone
为True
,则将从 timm 或 transformers 库加载相应的预训练权重。如果use_pretrained_backbone
为False
,则加载 backbone 的配置并使用它来初始化具有随机权重的 backbone。 - use_pretrained_backbone (
bool
, optional, defaults toFalse
) — 是否使用预训练权重作为backbone。 - backbone_kwargs (
dict
, optional) — 从检查点加载时传递给 AutoBackbone 的关键字参数,例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则不能指定此项。 - hidden_act (
str
orfunction
, optional, defaults to"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - initializer_range (
float
, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - batch_norm_eps (
float
, optional, defaults to 1e-05) — 批归一化层使用的 epsilon 值。 - readout_type (
str
, optional, defaults to"project"
) — 处理 ViT backbone 中间隐藏状态的 readout token (CLS token) 时使用的 readout 类型。可以是 ["ignore"
,"add"
,"project"
] 之一。- “ignore” 简单地忽略 CLS token。
- “add” 通过添加表示将 CLS token 中的信息传递给所有其他 token。
- “project” 通过在将表示投影到原始特征维度 D 之前,将 readout 连接到所有其他 token,从而将信息传递给其他 token,使用线性层,然后是 GELU 非线性激活函数。
- reassemble_factors (
List[int]
, optional, defaults to[4, 2, 1, 0.5]
) — 重新组装层的上/下采样因子。 - neck_hidden_sizes (
List[str]
, optional, defaults to[96, 192, 384, 768]
) — backbone 的特征图要投影到的隐藏层大小。 - fusion_hidden_size (
int
, optional, defaults to 256) — 融合之前的通道数。 - head_in_index (
int
, optional, defaults to -1) — 在 head 中使用的特征的索引。 - use_batch_norm_in_fusion_residual (
bool
, optional, defaults toFalse
) — 是否在融合块的预激活残差单元中使用批归一化。 - use_bias_in_fusion_residual (
bool
, optional, defaults toTrue
) — 是否在融合块的预激活残差单元中使用偏置。 - num_relative_features (
int
, optional, defaults to 32) — 相对深度估计 head 中使用的特征数量。 - add_projection (
bool
, optional, defaults toFalse
) — 是否在深度估计 head 之前添加一个投影层。 - bottleneck_features (
int
, optional, defaults to 256) — 瓶颈层中的特征数量。 - num_attractors (
List[int]
, optional, defaults to[16, 8, 4, 1]
) — 每个阶段中使用的 attractor 的数量。 - bin_embedding_dim (
int
, optional, defaults to 128) — bin 嵌入的维度。 - attractor_alpha (
int
, optional, defaults to 1000) — 在 attractor 中使用的 alpha 值。 - attractor_gamma (
int
, optional, defaults to 2) — 在 attractor 中使用的 gamma 值。 - attractor_kind (
str
, optional, defaults to"mean"
) — 要使用的 attractor 的种类。可以是 ["mean"
,"sum"
] 之一。 - min_temp (
float
, optional, defaults to 0.0212) — 要考虑的最小温度值。 - max_temp (
float
, optional, defaults to 50.0) — 要考虑的最大温度值。 - bin_centers_type (
str
, optional, defaults to"softplus"
) — 用于 bin 中心的激活类型。可以是 “normed” 或 “softplus”。对于 “normed” bin 中心,应用线性归一化技巧。这导致有界的 bin 中心。对于 “softplus”,使用 softplus 激活,因此是无界的。 - bin_configurations (
List[dict]
, optional, defaults to[{'n_bins' -- 64, 'min_depth': 0.001, 'max_depth': 10.0}]
): 每个 bin head 的配置。每个配置应包含以下键:- name (
str
): bin head 的名称 - 仅在多个 bin 配置的情况下需要。 n_bins
(int
): 要使用的 bin 的数量。min_depth
(float
): 要考虑的最小深度值。max_depth
(float
): 要考虑的最大深度值。如果仅传递单个配置,则模型将使用具有指定配置的单个 head。如果传递多个配置,则模型将使用具有指定配置的多个 head。
- name (
- num_patch_transformer_layers (
int
, optional) — 在 patch transformer 中使用的 transformer 层数。仅在多个 bin 配置的情况下使用。 - patch_transformer_hidden_size (
int
, optional) — 在 patch transformer 中使用的隐藏层大小。仅在多个 bin 配置的情况下使用。 - patch_transformer_intermediate_size (
int
, optional) — 在 patch transformer 中使用的中间层大小。仅在多个 bin 配置的情况下使用。 - patch_transformer_num_attention_heads (
int
, optional) — 在 patch transformer 中使用的注意力头的数量。仅在存在多个 bin 配置的情况下使用。
这是用于存储 ZoeDepthForDepthEstimation 配置的配置类。 它用于根据指定的参数实例化 ZoeDepth 模型,定义模型架构。使用默认值实例化配置将产生与 ZoeDepth Intel/zoedepth-nyu 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。 有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import ZoeDepthConfig, ZoeDepthForDepthEstimation
>>> # Initializing a ZoeDepth zoedepth-large style configuration
>>> configuration = ZoeDepthConfig()
>>> # Initializing a model from the zoedepth-large style configuration
>>> model = ZoeDepthForDepthEstimation(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
ZoeDepthImageProcessor
class transformers.ZoeDepthImageProcessor
< source >( do_pad: bool = True do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BILINEAR: 2> keep_aspect_ratio: bool = True ensure_multiple_of: int = 32 **kwargs )
参数
- do_pad (
bool
, optional, defaults toTrue
) — 是否应用 padding 到输入。 - do_rescale (
bool
, optional, defaults toTrue
) — 是否通过指定的比例rescale_factor
重新缩放图像。可以被preprocess
中的do_rescale
覆盖。 - rescale_factor (
int
或float
, optional, defaults to1/255
) — 如果重新缩放图像,则使用的缩放因子。可以被preprocess
中的rescale_factor
覆盖。 - do_normalize (
bool
, optional, defaults toTrue
) — 是否标准化图像。可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, optional, defaults toIMAGENET_STANDARD_MEAN
) — 如果标准化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, optional, defaults toIMAGENET_STANDARD_STD
) — 如果标准化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_std
参数覆盖。 - do_resize (
bool
, optional, defaults toTrue
) — 是否调整图像 (高度, 宽度) 尺寸。可以被preprocess
中的do_resize
覆盖。 - size (
Dict[str, int]
optional, defaults to{"height" -- 384, "width": 512}
): 调整大小后图像的尺寸。调整大小后图像的尺寸。如果keep_aspect_ratio
为True
,则通过选择高度和宽度缩放因子中较小的一个并将其用于两个维度来调整图像大小。如果还设置了ensure_multiple_of
,则进一步调整图像大小,使其尺寸为此值的倍数。可以被preprocess
中的size
覆盖。 - resample (
PILImageResampling
, optional, defaults toResampling.BILINEAR
) — 定义如果调整图像大小时要使用的重采样过滤器。可以被preprocess
中的resample
覆盖。 - keep_aspect_ratio (
bool
, optional, defaults toTrue
) — 如果为True
,则通过选择高度和宽度缩放因子中较小的一个并将其用于两个维度来调整图像大小。这确保了图像在尽可能少地缩小的情况下仍能适应所需的输出尺寸。如果还设置了ensure_multiple_of
,则通过将高度和宽度向下取整到最接近的该值的倍数,进一步调整图像大小,使其尺寸为此值的倍数。可以被preprocess
中的keep_aspect_ratio
覆盖。 - ensure_multiple_of (
int
, optional, defaults to 32) — 如果do_resize
为True
,则将图像大小调整为该值的倍数。通过将高度和宽度向下取整到最接近的该值的倍数来工作。无论是否将
keep_aspect_ratio
设置为True
均可工作。可以被preprocess
中的ensure_multiple_of
覆盖。
构建 ZoeDepth 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_pad: bool = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_resize: bool = None size: int = None keep_aspect_ratio: bool = None ensure_multiple_of: int = None resample: Resampling = 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
。 - do_pad (
bool
, optional, defaults toself.do_pad
) — 是否 padding 输入图像。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的缩放因子。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否标准化图像。 - image_mean (
float
或List[float]
, optional, defaults toself.image_mean
) — 图像均值。 - image_std (
float
或List[float]
, optional, defaults toself.image_std
) — 图像标准差。 - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, optional, defaults toself.size
) — 调整大小后图像的尺寸。如果keep_aspect_ratio
为True
,则通过选择高度和宽度缩放因子中较小的一个并将其用于两个维度来调整图像大小。如果还设置了ensure_multiple_of
,则进一步调整图像大小,使其尺寸为此值的倍数。 - keep_aspect_ratio (
bool
, optional, defaults toself.keep_aspect_ratio
) — 如果为True
且do_resize=True
,则通过选择高度和宽度缩放因子中较小的一个,并将其用于两个维度来调整图像大小。 这确保了图像在尽可能小的范围内缩小,同时仍适合所需的输出大小。 如果还设置了ensure_multiple_of
,则图像将进一步调整大小,使其尺寸成为该值的倍数,方法是将高度和宽度向下取整到最接近该值的倍数。 - ensure_multiple_of (
int
, optional, defaults toself.ensure_multiple_of
) — 如果do_resize
为True
,则图像将被调整为该值的倍数的大小。 通过将高度和宽度向下取整到最接近该值的倍数来工作。无论是否将
keep_aspect_ratio
设置为True
,都可以工作。 可以被preprocess
中的ensure_multiple_of
覆盖。 - resample (
int
, optional, defaults toself.resample
) — 如果调整图像大小,则使用的重采样过滤器。 这可以是枚举PILImageResampling
之一,仅当do_resize
设置为True
时才有效。 - return_tensors (
str
orTensorType
, optional) — 要返回的张量类型。 可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
:返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
:返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
:返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
:返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, optional, defaults toChannelDimension.FIRST
) — 输出图像的通道维度格式。 可以是以下之一:ChannelDimension.FIRST
:(num_channels, height, width) 格式的图像。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) 格式的图像。
预处理图像或批量图像。
ZoeDepthForDepthEstimation
class transformers.ZoeDepthForDepthEstimation
< source >( config )
参数
- config (ViTConfig) — 具有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
ZoeDepth 模型,顶部带有一个或多个度量深度估计头。
此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。
forward
< source >( 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, height, width)
) — 像素值。 像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参见 DPTImageProcessor.call()。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是普通元组。 - labels (
torch.LongTensor
,形状为(batch_size, height, width)
, optional) — 用于计算损失的真实深度估计图。
返回
transformers.modeling_outputs.DepthEstimatorOutput 或 tuple(torch.FloatTensor)
transformers.modeling_outputs.DepthEstimatorOutput 或 torch.FloatTensor
元组(如果传递 return_dict=False
或当 config.return_dict=False
时),包括各种元素,具体取决于配置 (ZoeDepthConfig) 和输入。
-
loss (
torch.FloatTensor
,形状为(1,)
, optional, 当提供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
时返回) —torch.FloatTensor
元组(每层一个),形状为(batch_size, num_heads, patch_size, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
ZoeDepthForDepthEstimation forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则会默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, ZoeDepthForDepthEstimation
>>> 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("Intel/zoedepth-nyu-kitti")
>>> model = ZoeDepthForDepthEstimation.from_pretrained("Intel/zoedepth-nyu-kitti")
>>> # 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,
... source_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"))