Transformers 文档
ZoeDepth
并获得增强的文档体验
开始使用
ZoeDepth
ZoeDepth 是一个深度估算模型,它结合了相对深度估算(物体彼此之间的距离)和度量深度估算(在度量尺度上精确测量深度)的泛化性能,两者都来自单张图像。它在 12 个数据集上使用相对深度进行预训练,并在 2 个数据集(NYU Depth v2 和 KITTI)上进行度量准确性训练。为每个域使用一个带有度量 bin 模块的轻量级头部,在推理过程中,它通过一个潜在分类器自动为每个输入图像选择合适的头部。

你可以在 Intel 组织下找到所有原始的 ZoeDepth 检查点。
下面的示例演示了如何使用 Pipeline 或 AutoModel 类来估算深度。
import requests
import torch
from transformers import pipeline
from PIL import Image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
pipeline = pipeline(
task="depth-estimation",
model="Intel/zoedepth-nyu-kitti",
torch_dtype=torch.float16,
device=0
)
results = pipeline(image)
results["depth"]
注意
- 在原始实现中,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, )
资源
- 有关推理示例,请参阅此 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 (
str
, 可选) — 当backbone_config
为None
时使用的主干名称。如果 `use_pretrained_backbone` 为True
,将从 timm 或 transformers 库加载相应的预训练权重。如果use_pretrained_backbone
为False
,将加载主干的配置并用其初始化主干的随机权重。 - use_pretrained_backbone (
bool
, 可选, 默认为False
) — 是否为主干使用预训练权重。 - backbone_kwargs (
dict
, 可选) — 在从检查点加载时传递给 AutoBackbone 的关键字参数,例如 `{'out_indices': (0, 1, 2, 3)}`。如果设置了 `backbone_config`,则不能指定此项。 - hidden_act (
str
orfunction
, 可选, 默认为"gelu"
) — 编码器和池化层中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - batch_norm_eps (
float
, 可选, 默认为 1e-05) — 批量归一化层使用的 epsilon。 - readout_type (
str
, 可选, 默认为"project"
) — 在处理 ViT 主干中间隐藏状态的读出令牌(CLS 令牌)时使用的读出类型。可以是 ["ignore"
、"add"
、"project"
] 中的一个。- “ignore” 简单地忽略 CLS 令牌。
- “add” 通过添加表示将 CLS 令牌的信息传递给所有其他令牌。
- “project” 通过将读出连接到所有其他令牌,然后使用线性层和 GELU 非线性将表示投影到原始特征维度 D,从而将信息传递给其他令牌。
- reassemble_factors (
list[int]
, 可选, 默认为[4, 2, 1, 0.5]
) — 重组层的上/下采样因子。 - neck_hidden_sizes (
list[str]
, 可选, 默认为[96, 192, 384, 768]
) — 用于主干特征图投影的隐藏大小。 - fusion_hidden_size (
int
, 可选, 默认为 256) — 融合前的通道数。 - head_in_index (
int
, 可选, 默认为 -1) — 在头部中使用的特征索引。 - use_batch_norm_in_fusion_residual (
bool
, 可选, 默认为False
) — 是否在融合块的预激活残差单元中使用批量归一化。 - use_bias_in_fusion_residual (
bool
, 可选, 默认为True
) — 是否在融合块的预激活残差单元中使用偏置。 - num_relative_features (
int
, 可选, 默认为 32) — 相对深度估计头中使用的特征数量。 - add_projection (
bool
, 可选, 默认为False
) — 是否在深度估计头之前添加投影层。 - bottleneck_features (
int
, 可选, 默认为 256) — 瓶颈层中的特征数量。 - num_attractors (
list[int], *可选*, 默认为
[16, 8, 4, 1]`) — 每个阶段中使用的吸引子数量。 - bin_embedding_dim (
int
, 可选, 默认为 128) — bin 嵌入的维度。 - attractor_alpha (
int
, 可选, 默认为 1000) — 在吸引子中使用的 alpha 值。 - attractor_gamma (
int
, 可选, 默认为 2) — 在吸引子中使用的 gamma 值。 - attractor_kind (
str
, 可选, 默认为"mean"
) — 使用的吸引子类型。可以是 ["mean"
,"sum"
] 中的一个。 - min_temp (
float
, 可选, 默认为 0.0212) — 考虑的最小温度值。 - max_temp (
float
, 可选, 默认为 50.0) — 考虑的最大温度值。 - bin_centers_type (
str
, 可选, 默认为"softplus"
) — 用于 bin 中心的激活类型。可以是“normed”或“softplus”。对于“normed” bin 中心,应用线性归一化技巧。这导致有界的 bin 中心。对于“softplus”,使用 softplus 激活,因此是无界的。 - bin_configurations (
list[dict]
, 可选, 默认为[{'n_bins' -- 64, 'min_depth': 0.001, 'max_depth': 10.0}]
):每个 bin 头部的配置。每个配置应包含以下键:- name (
str
):bin 头部的名称——仅在有多个 bin 配置时需要。 - `n_bins` (
int
):要使用的 bin 数量。 - `min_depth` (
float
):要考虑的最小深度值。 - `max_depth` (
float
):要考虑的最大深度值。如果只传递一个配置,模型将使用具有指定配置的单个头部。如果传递多个配置,模型将使用具有指定配置的多个头部。
- name (
- num_patch_transformer_layers (
int
, 可选) — 补丁转换器中使用的 transformer 层数。仅在有多个 bin 配置时使用。 - patch_transformer_hidden_size (
int
, 可选) — 补丁转换器中使用的隐藏大小。仅在有多个 bin 配置时使用。 - patch_transformer_intermediate_size (
int
, 可选) — 补丁转换器中使用的中间大小。仅在有多个 bin 配置时使用。 - patch_transformer_num_attention_heads (
int
, 可选) — 补丁转换器中使用的注意力头数量。仅在有多个 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
< 源代码 >( 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, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> keep_aspect_ratio: bool = True ensure_multiple_of: int = 32 **kwargs )
参数
- do_pad (
bool
, 可选, 默认为True
) — 是否对输入进行填充。 - 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_resize (
bool
, 可选, 默认为True
) — 是否调整图像的 (height, width) 尺寸。可在preprocess
中通过do_resize
参数覆盖。 - size (
dict[str, int]
可选, 默认为{"height" -- 384, "width": 512}
): 调整大小后图像的尺寸。如果keep_aspect_ratio
为True
,则通过选择高度和宽度缩放因子中较小的一个,并将其用于两个维度来调整图像大小。如果还设置了ensure_multiple_of
,则图像将进一步调整为该值的倍数。可在preprocess
中通过size
参数覆盖。 - resample (
PILImageResampling
, 可选, 默认为Resampling.BILINEAR
) — 定义调整图像大小时使用的重采样滤波器。可在preprocess
中通过resample
参数覆盖。 - keep_aspect_ratio (
bool
, 可选, 默认为True
) — 如果为True
,则通过选择高度和宽度缩放因子中较小的一个,并将其用于两个维度来调整图像大小。这确保了图像在尽可能少地缩小的同时仍能适应期望的输出尺寸。如果还设置了ensure_multiple_of
,则通过将高度和宽度向下取整到该值的最近倍数,进一步将图像调整为该值的倍数。可在preprocess
中通过keep_aspect_ratio
参数覆盖。 - ensure_multiple_of (
int
, 可选, 默认为 32) — 如果do_resize
为True
,则将图像大小调整为此值的倍数。通过将高度和宽度向下取整到该值的最近倍数来实现。无论
keep_aspect_ratio
是否设置为True
,此参数都有效。可在preprocess
中通过ensure_multiple_of
参数覆盖。
构建一个 ZoeDepth 图像处理器。
preprocess
< 来源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_pad: typing.Optional[bool] = 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_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: Resampling = None return_tensors: typing.Union[transformers.utils.generic.TensorType, str, 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
, 可选, 默认为self.do_pad
) — 是否对输入图像进行填充。 - 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
) — 图像标准差。 - 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
) — 如果为True
且do_resize=True
,则通过选择高度和宽度缩放因子中较小的一个,并将其用于两个维度来调整图像大小。这确保了图像在尽可能少地缩小的同时仍能适应期望的输出尺寸。如果还设置了ensure_multiple_of
,则通过将高度和宽度向下取整到该值的最近倍数,进一步将图像调整为该值的倍数。 - ensure_multiple_of (
int
, 可选, 默认为self.ensure_multiple_of
) — 如果do_resize
为True
,则将图像大小调整为此值的倍数。通过将高度和宽度向下取整到该值的最近倍数来实现。无论
keep_aspect_ratio
是否设置为True
,此参数都有效。可在preprocess
中通过ensure_multiple_of
参数覆盖。 - resample (
int
, 可选, 默认为self.resample
) — 调整图像大小时使用的重采样滤波器。可以是PILImageResampling
枚举之一,仅在do_resize
设置为True
时生效。 - 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)。
预处理一张或一批图像。
ZoeDepthImageProcessorFast
class transformers.ZoeDepthImageProcessorFast
< 来源 >( **kwargs: typing_extensions.Unpack[transformers.models.zoedepth.image_processing_zoedepth_fast.ZoeDepthFastImageProcessorKwargs] )
构建一个快速的 Zoedepth 图像处理器。
preprocess
< 来源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.zoedepth.image_processing_zoedepth_fast.ZoeDepthFastImageProcessorKwargs] ) → <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
, 可选) — 是否调整图像大小。 - size (
dict[str, int]
, 可选) — 描述模型的最大输入尺寸。 - default_to_square (
bool
, 可选) — 在调整大小时,如果尺寸是整数,是否默认为方形图像。 - resample (
Union[PILImageResampling, F.InterpolationMode, NoneType]
) — 调整图像大小时使用的重采样滤波器。可以是PILImageResampling
枚举之一。仅在do_resize
设置为True
时生效。 - do_center_crop (
bool
, 可选) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, 可选) — 应用center_crop
后输出图像的尺寸。 - do_rescale (
bool
, 可选) — 是否重新缩放图像。 - rescale_factor (
Union[int, float, NoneType]
) — 如果do_rescale
设置为True
,则用于重新缩放图像的因子。 - do_normalize (
bool
, 可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], NoneType]
) — 用于归一化的图像均值。仅在do_normalize
设置为True
时生效。 - image_std (
Union[float, list[float], NoneType]
) — 用于归一化的图像标准差。仅在do_normalize
设置为True
时生效。 - do_convert_rgb (
bool
, 可选) — 是否将图像转换为 RGB。 - return_tensors (
Union[str, ~utils.generic.TensorType, NoneType]
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
~image_utils.ChannelDimension
, 可选) — 仅支持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
, 可选) — 处理图像的设备。如果未设置,将从输入图像中推断设备。 - disable_grouping (
bool
, 可选) — 是否禁用按尺寸分组图像,以便单独处理而不是分批处理。如果为 None,则如果图像在 CPU 上,则设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - do_pad (
bool
, 可选, 默认为True
) — 是否对输入应用填充。 - keep_aspect_ratio (
bool
, 可选, 默认为True
) — 如果为True
,则通过选择高度和宽度缩放因子中较小的一个,并将其用于两个维度来调整图像大小。这确保了图像在缩小的同时尽可能少地失真,并且仍然能适应期望的输出尺寸。如果同时设置了ensure_multiple_of
,图像将进一步调整大小,使其尺寸是该值的倍数,方法是将高度和宽度向下取整到最接近该值的倍数。该参数可在preprocess
中被keep_aspect_ratio
覆盖。 - ensure_multiple_of (
int
, 可选, 默认为 32) — 如果do_resize
为True
,则图像将被调整为该值的倍数。其工作原理是将高度和宽度向下取整到最接近该值的倍数。无论keep_aspect_ratio
是否设置为True
,此参数都有效。该参数可在preprocess
中被ensure_multiple_of
覆盖。
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType]
, 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。
ZoeDepthForDepthEstimation
class transformers.ZoeDepthForDepthEstimation
< source >( config )
参数
- config (ZoeDepthForDepthEstimation) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
ZoeDepth 模型,其顶部带有一个或多个度量深度估计头。
该模型继承自 PreTrainedModel。请查阅超类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是 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, image_size, image_size)
) — 与输入图像对应的张量。像素值可以使用{image_processor_class}
获得。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
来处理图像)。 - labels (
torch.LongTensor
,形状为(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
),包含根据配置(ZoeDepthConfig)和输入的不同元素。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
ZoeDepthForDepthEstimation 的 forward 方法会覆盖 __call__
特殊方法。
尽管前向传播的流程需要在此函数中定义,但之后应该调用 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"))