Transformers 文档
GLPN
并获得增强的文档体验
开始使用
GLPN
这是一个最近推出的模型,因此 API 尚未经过广泛测试。未来可能会有一些错误或微小的重大变更来修复它。如果您发现任何异常,请提交 Github Issue。
概述
GLPN 模型由 Doyeon Kim、Woonghyun Ga、Pyungwhan Ahn、Donggyu Joo、Sehwan Chun 和 Junmo Kim 在论文 《Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth》(用于单目深度估计的全局-局部路径网络与垂直 CutDepth) 中提出。GLPN 将 SegFormer 的分层混合 Transformer 与一个轻量级解码器相结合,用于单目深度估计。所提出的解码器比之前提出的解码器表现出更好的性能,且计算复杂性要低得多。
论文摘要如下:
从单张图像估计深度是计算机视觉中一项重要任务,可应用于各个领域,并且随着卷积神经网络的发展而迅速成长。在本文中,我们提出了一种用于单目深度估计的新颖结构和训练策略,以进一步提高网络的预测精度。我们部署了一个分层 Transformer 编码器来捕获和传递全局上下文,并设计了一个轻量级但功能强大的解码器来生成估计的深度图,同时考虑局部连通性。通过我们提出的选择性特征融合模块,在多尺度局部特征和全局解码流之间构建连接路径,网络可以整合两种表示并恢复精细细节。此外,所提出的解码器比之前提出的解码器表现出更好的性能,且计算复杂性要低得多。此外,我们利用深度估计中的一个重要观察,改进了特定于深度的增强方法,以增强模型性能。我们的网络在具有挑战性的 NYU Depth V2 深度数据集上达到了最先进的性能。我们进行了广泛的实验来验证并展示所提出方法的有效性。最后,我们的模型比其他对比模型显示出更好的泛化能力和鲁棒性。

资源
一份官方 Hugging Face 和社区(由 🌎 标志表示)资源列表,帮助您开始使用 GLPN。
- GLPNForDepthEstimation 的演示笔记本可以在这里找到。
- 单目深度估计任务指南
GLPNConfig
class transformers.GLPNConfig
< 源代码 >( num_channels = 3 num_encoder_blocks = 4 depths = [2, 2, 2, 2] sr_ratios = [8, 4, 2, 1] hidden_sizes = [32, 64, 160, 256] patch_sizes = [7, 3, 3, 3] strides = [4, 2, 2, 2] num_attention_heads = [1, 2, 5, 8] mlp_ratios = [4, 4, 4, 4] hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 drop_path_rate = 0.1 layer_norm_eps = 1e-06 decoder_hidden_size = 64 max_depth = 10 head_in_index = -1 **kwargs )
参数
- num_channels (
int
, 可选, 默认为 3) — 输入通道的数量。 - num_encoder_blocks (
int
, 可选, 默认为 4) — 编码器块的数量(即混合 Transformer 编码器中的阶段数)。 - depths (
list[int]
, 可选, 默认为 `[2, 2, 2, 2]`) — 每个编码器块中的层数。 - sr_ratios (
list[int]
, 可选, 默认为 `[8, 4, 2, 1]`) — 每个编码器块中的序列缩减比率。 - hidden_sizes (
list[int]
, 可选, 默认为 `[32, 64, 160, 256]`) — 每个编码器块的维度。 - patch_sizes (
list[int]
, 可选, 默认为 `[7, 3, 3, 3]`) — 每个编码器块前的补丁大小。 - strides (
list[int]
, 可选, 默认为 `[4, 2, 2, 2]`) — 每个编码器块前的步幅。 - num_attention_heads (
list[int]
, 可选, 默认为 `[1, 2, 5, 8]`) — Transformer 编码器中每个块的每个注意力层的注意力头数。 - mlp_ratios (
list[int]
, 可选, 默认为 `[4, 4, 4, 4]`) — 编码器块中混合 FFNs 隐藏层大小与输入层大小的比率。 - hidden_act (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,支持"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, 可选, 默认为 0.0) — 嵌入、编码器和池化器中所有全连接层的丢弃概率。 - attention_probs_dropout_prob (
float
, 可选, 默认为 0.0) — 注意力概率的丢弃率。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - drop_path_rate (
float
, 可选, 默认为 0.1) — 随机深度的丢弃概率,用于 Transformer 编码器的块中。 - layer_norm_eps (
float
, 可选, 默认为 1e-06) — 层归一化层使用的 epsilon。 - decoder_hidden_size (
int
, 可选, 默认为 64) — 解码器的维度。 - max_depth (
int
, 可选, 默认为 10) — 解码器的最大深度。 - head_in_index (
int
, 可选, 默认为 -1) — 在头部中使用的特征索引。
这是用于存储 GLPNModel 配置的配置类。它用于根据指定的参数实例化一个 GLPN 模型,定义模型架构。使用默认值实例化配置将产生与 GLPN vinvino02/glpn-kitti 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import GLPNModel, GLPNConfig
>>> # Initializing a GLPN vinvino02/glpn-kitti style configuration
>>> configuration = GLPNConfig()
>>> # Initializing a model from the vinvino02/glpn-kitti style configuration
>>> model = GLPNModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
GLPNFeatureExtractor
预处理单张或批量图像。
GLPNImageProcessor
class transformers.GLPNImageProcessor
< 源代码 >( do_resize: bool = True size_divisor: int = 32 resample = <Resampling.BILINEAR: 2> do_rescale: bool = True **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否调整图像的(高、宽)尺寸,将其向下取整到最接近的size_divisor
的倍数。可在 `preprocess` 中通过 `do_resize` 覆盖。 - size_divisor (
int
, 可选, 默认为 32) — 当 `do_resize` 为 `True` 时,图像会被调整大小,使其高度和宽度向下取整到最接近的 `size_divisor` 的倍数。可在 `preprocess` 中通过 `size_divisor` 覆盖。 - resample (`PIL.Image` 重采样过滤器, 可选, 默认为 `Resampling.BILINEAR`) — 如果调整图像大小,使用的重采样过滤器。可在 `preprocess` 中通过 `resample` 覆盖。
- do_rescale (
bool
, 可选, 默认为True
) — 是否应用缩放因子(使像素值为 0 到 1 之间的浮点数)。可在 `preprocess` 中通过 `do_rescale` 覆盖。
构建一个 GLPN 图像处理器。
preprocess
< 源代码 >( images: typing.Union[ForwardRef('PIL.Image.Image'), transformers.utils.generic.TensorType, list['PIL.Image.Image'], list[transformers.utils.generic.TensorType]] do_resize: typing.Optional[bool] = None size_divisor: typing.Optional[int] = None resample = None do_rescale: typing.Optional[bool] = 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 (
PIL.Image.Image
或TensorType
或list[np.ndarray]
或list[TensorType]
) — 要预处理的图像。期望单个或一批图像,其像素值范围为 0 到 255。如果传入像素值在 0 到 1 之间的图像,请设置 `do_normalize=False`。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整输入大小,使其(高、宽)尺寸为 `size_divisor` 的倍数。 - size_divisor (
int
, 可选, 默认为self.size_divisor
) — 当 `do_resize` 为 `True` 时,图像会被调整大小,使其高度和宽度向下取整到最接近的 `size_divisor` 的倍数。 - resample (`PIL.Image` 重采样过滤器, 可选, 默认为
self.resample
) — 如果调整图像大小,使用的 `PIL.Image` 重采样过滤器,例如 `PILImageResampling.BILINEAR`。仅当 `do_resize` 设置为 `True` 时生效。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否应用缩放因子(使像素值为 0 到 1 之间的浮点数)。 - return_tensors (
str
或TensorType
, 可选) — 要返回的张量类型。可以是以下之一:None
: 返回一个 `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)。
预处理给定的图像。
GLPNModel
class transformers.GLPNModel
< source >( config )
参数
- config (GLPNModel) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
基础的 Glpn 模型,输出原始的隐藏状态,顶部没有任何特定的头(head)。
该模型继承自 PreTrainedModel。请查阅超类的文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是 PyTorch torch.nn.Module 的子类。可以像使用常规 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与常规用法和行为相关的事项。
forward
< source >( pixel_values: FloatTensor output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutput or 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}
处理图像)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。更多细节请参阅返回张量下的 `attentions`。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。更多细节请参阅返回张量下的 `hidden_states`。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutput 或一个 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置 (GLPNConfig) 和输入而定的各种元素。
-
last_hidden_state (
torch.FloatTensor
, 形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组 (一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
GLPNModel 的 forward 方法重写了 `__call__` 特殊方法。
虽然前向传播的逻辑需要在此函数中定义,但之后应该调用 `Module` 实例而不是这个函数,因为前者会处理预处理和后处理步骤,而后者会默默地忽略它们。
GLPNForDepthEstimation
class transformers.GLPNForDepthEstimation
< source >( config )
参数
- config (GLPNForDepthEstimation) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
GLPN Transformer 模型,顶部带有一个轻量级的深度估计头,例如用于 KITTI、NYUv2 数据集。
该模型继承自 PreTrainedModel。请查阅超类的文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是 PyTorch torch.nn.Module 的子类。可以像使用常规 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与常规用法和行为相关的事项。
forward
< source >( pixel_values: FloatTensor labels: 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.modeling_outputs.DepthEstimatorOutput or 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.FloatTensor
,形状为(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
时),包含根据配置 (GLPNConfig) 和输入而定的各种元素。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
GLPNForDepthEstimation 的 forward 方法重写了 `__call__` 特殊方法。
虽然前向传播的逻辑需要在此函数中定义,但之后应该调用 `Module` 实例而不是这个函数,因为前者会处理预处理和后处理步骤,而后者会默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, GLPNForDepthEstimation
>>> 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("vinvino02/glpn-kitti")
>>> model = GLPNForDepthEstimation.from_pretrained("vinvino02/glpn-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,
... 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"))