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中提出。 GLPN结合了SegFormer的分层混合Transformer与轻量级解码器,用于单目深度估计。所提出的解码器在性能上优于之前提出的解码器,且计算复杂度显著降低。
论文的摘要如下:
从单张图像进行深度估计是一个重要的任务,可以应用于计算机视觉的各个领域,并且随着卷积神经网络的发展迅速增长。在本文中,我们提出了一种新颖的结构和训练策略,用于单目深度估计,以进一步提高网络的预测精度。我们部署了一个分层变压器编码器来捕捉和传递全局上下文,并设计了一个轻量级但功能强大的解码器,以生成估计的深度图,同时考虑局部连通性。通过在我们提出的选择性特征融合模块中构建多尺度局部特征与全局解码流之间的连接路径,网络可以整合这两种表示并恢复精细细节。此外,所提出的解码器比之前提出的解码器表现出更好的性能,且计算复杂度显著降低。此外,我们通过利用深度估计中的一个重要观察结果来改进深度特定的增强方法,以增强模型。我们的网络在具有挑战性的深度数据集NYU Depth V2上实现了最先进的性能。进行了大量实验以验证并展示所提出方法的有效性。最后,我们的模型显示出比其他比较模型更好的泛化能力和鲁棒性。
![drawing](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/glpn_architecture.jpg)
资源
一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用GLPN。
- GLPNForDepthEstimation的演示笔记本可以在这里找到。
- 单目深度估计任务指南
GLPNConfig
类 transformers.GLPNConfig
< source >( 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
, optional, 默认为 3) — 输入通道的数量。 - num_encoder_blocks (
int
, optional, 默认为 4) — 编码器块的数量(即 Mix Transformer 编码器中的阶段数)。 - depths (
List[int]
, optional, 默认为[2, 2, 2, 2]
) — 每个编码器块中的层数。 - sr_ratios (
List[int]
, 可选, 默认为[8, 4, 2, 1]
) — 每个编码器块中的序列缩减比率。 - hidden_sizes (
List[int]
, optional, 默认为[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]
) — 编码器块中Mix FFNs的隐藏层大小与输入层大小的比率。 - hidden_act (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, optional, 默认为 0.0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, optional, 默认为 0.0) — 注意力概率的丢弃比例。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。 - drop_path_rate (
float
, optional, 默认为 0.1) — 用于 Transformer 编码器块中的随机深度的丢弃概率。 - layer_norm_eps (
float
, optional, defaults to 1e-06) — 层归一化层使用的epsilon值。 - decoder_hidden_size (
int
, optional, defaults to 64) — 解码器的维度。 - max_depth (
int
, optional, 默认为 10) — 解码器的最大深度。 - head_in_index (
int
, optional, 默认为 -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
类 transformers.GLPNImageProcessor
< source >( do_resize: bool = True size_divisor: int = 32 resample =
参数
- 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图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), transformers.utils.generic.TensorType, typing.List[ForwardRef('PIL.Image.Image')], typing.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 =
参数
- 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
, optional, defaults toself.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
类 transformers.GLPNModel
< source >( config )
参数
- config (GLPNConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的GLPN编码器(Mix-Transformer)输出原始隐藏状态,顶部没有任何特定的头部。 该模型是PyTorch torch.nn.Module 的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< 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 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。默认情况下,如果您提供了填充,它将被忽略。可以使用 AutoImageProcessor获取像素值。有关详细信息,请参见GLPNImageProcessor.call(). - 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 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoImageProcessor, GLPNModel
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("vinvino02/glpn-kitti")
>>> model = GLPNModel.from_pretrained("vinvino02/glpn-kitti")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 512, 15, 20]
GLPN深度估计
类 transformers.GLPNForDepthEstimation
< source >( config )
参数
- config (GLPNConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
GLPN模型转换器,顶部带有轻量级深度估计头,例如用于KITTI、NYUv2。 该模型是PyTorch torch.nn.Module的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< 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 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。默认情况下,如果您提供了填充,它将被忽略。可以使用 AutoImageProcessor获取像素值。详情请参见GLPNImageProcessor.call(). - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
torch.FloatTensor
of shape(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
时),包含各种
元素,具体取决于配置(GLPNConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供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 的前向方法,重写了 __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"))