Transformers documentation
ZoeDepth
该模型于 2023-02-23 在 HF papers 上发布,并于 2024-07-08 贡献至 Hugging Face Transformers。
ZoeDepth
ZoeDepth 是一种深度估计模型,它从单张图像中同时结合了相对深度估计(物体之间的相对距离)和度量深度估计(以度量单位进行的精确深度测量)的泛化性能。该模型在 12 个数据集上使用相对深度进行预训练,并在 2 个数据集(NYU Depth v2 和 KITTI)上针对度量精度进行训练。模型采用了一个轻量级头部,其中包含针对每个领域的度量分箱模块;在推理阶段,它会通过一个潜在分类器为每张输入图像自动选择相应的头部。
您可以在 Intel 组织下找到所有原始的 ZoeDepth 检查点。
以下示例演示了如何使用 Pipeline 或 AutoModel 类来估计深度。
import requests
from PIL import Image
from transformers import pipeline
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",
device=0
)
results = pipeline(image)
results["depth"]import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForDepthEstimation
image_processor = AutoImageProcessor.from_pretrained(
"Intel/zoedepth-nyu-kitti"
)
model = AutoModelForDepthEstimation.from_pretrained(
"Intel/zoedepth-nyu-kitti",
device_map="auto"
)
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(inputs)
# interpolate to original size and visualize the prediction
## ZoeDepth dynamically pads the input image, so 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
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, )
资源
- 请参阅此 notebook 以获取推理示例。
ZoeDepthConfig
class transformers.ZoeDepthConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonehidden_act: str = 'gelu'initializer_range: float = 0.02batch_norm_eps: float = 1e-05readout_type: typing.Literal['ignore', 'add', 'project'] = 'project'reassemble_factors: list[int | float] | tuple[int | float, ...] = (4, 2, 1, 0.5)neck_hidden_sizes: list[int] | tuple[int, ...] = (96, 192, 384, 768)fusion_hidden_size: int = 256head_in_index: int = -1use_batch_norm_in_fusion_residual: bool = Falseuse_bias_in_fusion_residual: bool | None = Nonenum_relative_features: int = 32add_projection: bool = Falsebottleneck_features: int = 256num_attractors: list[int] | tuple[int, ...] = (16, 8, 4, 1)bin_embedding_dim: int = 128attractor_alpha: int = 1000attractor_gamma: int = 2attractor_kind: typing.Literal['mean', 'sum'] = 'mean'min_temp: float = 0.0212max_temp: float = 50.0bin_centers_type: str = 'softplus'bin_configurations: list[dict] | None = Nonenum_patch_transformer_layers: int | None = Nonepatch_transformer_hidden_size: int | None = Nonepatch_transformer_intermediate_size: int | None = Nonepatch_transformer_num_attention_heads: int | None = None )
参数
- backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - batch_norm_eps (
float,可选,默认为1e-05) — 批归一化层使用的 epsilon 值。 - readout_type (
str, 可选, 默认为"project") — 处理 ViT 主干网络中间隐藏状态的读出 token(CLS token)时使用的读出类型。可以是 ["ignore", "add", "project"] 之一。“ignore” 直接忽略 CLS token。“add” 通过相加表示将 CLS token 的信息传递给所有其他 token。“project” 通过将读出与所有其他 token 拼接,然后使用线性层后接 GELU 非线性函数将表示投影回原始特征维度 D,从而将信息传递给其他 token。"ignore","add","project"].- “ignore” 简单地忽略 CLS token。
- “add” 通过相加表示的方式,将 CLS token 的信息传递给所有其他 token。
- “project” 通过将 readout 拼接(concatenating)到所有其他 token 上来向其他 token 传递信息,然后使用一个线性层后接 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) — 在 heads 中使用的特征的索引。 - 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], *optional*, defaults to[16, 8, 4, 1]`) — 每个阶段中使用的吸引子数量。 - bin_embedding_dim (
int, 可选,默认为 128) — bin 嵌入的维度。 - attractor_alpha (
int,可选,默认值为 1000) — 在 attractor 中使用的 alpha 值。 - attractor_gamma (
int,可选,默认值为 2) — 在 attractor 中使用的 gamma 值。 - attractor_kind (
str,可选,默认为"mean") — 要使用的吸引子类型。可以是 ["mean","sum"] 之一。 - min_temp(
float,可选,默认值为 0.0212)— 需要考虑的最低温度值。 - max_temp(
float,可选,默认值为 50.0)— 要考量的最高温度值。 - bin_centers_type (
str,可选,默认为"softplus") — 用于 bin centers 的激活类型。可以是 “normed” 或 “softplus”。对于 “normed” bin centers,会应用线性归一化技巧,从而使 bin centers 有界。对于 “softplus”,使用 softplus 激活,因此 bin centers 无界。 - bin_configurations (
list[dict], 可选, 默认为[{'n_bins' -- 64, 'min_depth': 0.001, 'max_depth': 10.0}]): 每个 bin head 的配置。 每个配置应包含以下键:- name (
str): 分箱头的名称 - 仅在存在多个分箱配置时需要。 n_bins(int): 要使用的分箱数量。min_depth(float):要考量的最小深度值。max_depth(float):要考量的最大深度值。 如果仅传入单个配置,模型将使用具有该指定配置的单个头。 如果传入多个配置,模型将使用具有这些指定配置的多个头。
- name (
- num_patch_transformer_layers (
int, 可选) — patch transformer 中使用的 transformer 层数。仅在存在多个 bin 配置时使用。 - patch_transformer_hidden_size (
int, 可选) — patch transformer 中使用的隐藏层大小。仅在存在多个 bin 配置时使用。 - patch_transformer_intermediate_size (
int, 可选) — patch transformer 中使用的中间层大小。仅在存在多个 bin 配置时使用。 - patch_transformer_num_attention_heads (
int, 可选) — patch transformer 中使用的注意力头数量。仅在存在多个 bin 配置时使用。
这是用于存储 ZoedepthModel 配置的类。它根据指定的参数实例化 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.configZoeDepthImageProcessor
class transformers.ZoeDepthImageProcessor
< source >( **kwargs: *<class 'transformers.models.zoedepth.image_processing_zoedepth.ZoeDepthImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'height' -- 384, 'width': 512}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool,kwargs,可选,默认为True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - keep_aspect_ratio (
bool,kwargs,可选,默认为self.keep_aspect_ratio) — 如果为True,则通过选择高度和宽度缩放因子中较小的一个,并将其同时应用于两个维度来调整图像大小。这可以确保图像在尽可能少缩小的同时,仍然适应所需的输出尺寸。如果同时设置了ensure_multiple_of,则图像会进一步调整大小,使其高度和宽度向下取整为该值的最近倍数,从而得到一个该值整数倍的尺寸。可以通过preprocess中的keep_aspect_ratio进行覆盖。 - ensure_multiple_of (
int,kwargs,可选,默认为self.ensure_multiple_of) — 如果do_resize为True,图像将被调整为此值整数倍的尺寸。其实现方式是将高度和宽度向下取整到该值最近的整数倍。 无论keep_aspect_ratio是否设置为True,该参数均有效。 可通过preprocess中的ensure_multiple_of进行覆盖。
构建 ZoeDepthImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.zoedepth.image_processing_zoedepth.ZoeDepthImageProcessorKwargs'> ) → ~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_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - keep_aspect_ratio (
bool,kwargs,可选,默认为self.keep_aspect_ratio) — 如果为True,则通过选择高度和宽度缩放因子中较小的一个,并将其同时应用于两个维度来调整图像大小。这可以确保图像在尽可能少缩小的同时,仍然适应所需的输出尺寸。如果同时设置了ensure_multiple_of,则会将图像进一步调整为该值倍数的尺寸,方法是将高度和宽度向下取整到该值最近的倍数。可以通过preprocess中的keep_aspect_ratio进行覆盖。 - ensure_multiple_of (
int,kwargs,可选,默认为self.ensure_multiple_of) — 如果do_resize为True,图像将被调整为此值整数倍的尺寸。其实现方式是将高度和宽度向下取整到该值最近的整数倍。 无论keep_aspect_ratio是否设置为True,该参数均有效。 可通过preprocess中的ensure_multiple_of进行覆盖。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
ZoeDepthImageProcessorPil
class transformers.ZoeDepthImageProcessorPil
< source >( **kwargs: *<class 'transformers.models.zoedepth.image_processing_pil_zoedepth.ZoeDepthImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'height' -- 384, 'width': 512}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool,kwargs,可选,默认为True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - keep_aspect_ratio (
bool,kwargs,可选,默认为self.keep_aspect_ratio) — 如果为True,则通过选择高度和宽度缩放因子中较小的一个,并将其应用于两个维度来调整图像大小。这可以确保图像在尽可能少缩小的同时,仍然适合所需的输出尺寸。如果同时设置了ensure_multiple_of,则会将图像进一步调整为该值倍数的尺寸,方法是将高度和宽度向下取整到该值最近的倍数。可以通过preprocess中的keep_aspect_ratio进行覆盖。 - ensure_multiple_of (
int,kwargs,可选,默认值为self.ensure_multiple_of) — 如果do_resize为True,图像将被调整为此值整数倍的尺寸。其实现方式是将高度和宽度向下取整到该值最近的整数倍。 无论keep_aspect_ratio是否设置为True,该参数均有效。 可通过preprocess中的ensure_multiple_of进行覆盖。
构建 ZoeDepthImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.zoedepth.image_processing_pil_zoedepth.ZoeDepthImageProcessorKwargs'> ) → ~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_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - keep_aspect_ratio (
bool,kwargs,可选,默认为self.keep_aspect_ratio) — 如果为True,则通过选择高度和宽度缩放因子中较小的一个,并将其同时应用于两个维度来调整图像大小。这可以确保图像在尽可能少缩小的同时,仍然适应所需的输出尺寸。如果同时设置了ensure_multiple_of,则图像会进一步调整大小,使其高度和宽度向下取整为该值的最近倍数,从而得到一个该值整数倍的尺寸。可以通过preprocess中的keep_aspect_ratio进行覆盖。 - ensure_multiple_of (
int,kwargs,可选,默认值为self.ensure_multiple_of) — 如果do_resize为True,图像将被调整为此值整数倍的尺寸。其实现方式是将高度和宽度向下取整到该值最近的整数倍。 无论keep_aspect_ratio是否设置为True,该参数均有效。 可通过preprocess中的ensure_multiple_of进行覆盖。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
ZoeDepthForDepthEstimation
class transformers.ZoeDepthForDepthEstimation
< source >( config: ZoeDepthConfig )
参数
- config (ZoeDepthConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
在顶部添加一个或多个度量深度估计头的 ZoeDepth 模型。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: FloatTensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → DepthEstimatorOutput or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 ZoeDepthImageProcessor 获取像素值。有关详细信息,请参阅 ZoeDepthImageProcessor.call()(processor_class使用 ZoeDepthImageProcessor 处理图像)。 - labels(形状为
(batch_size, height, width)的torch.LongTensor,可选) — 用于计算损失的真实深度估计图。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
DepthEstimatorOutput 或 tuple(torch.FloatTensor)
DepthEstimatorOutput 或 torch.FloatTensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(ZoeDepthConfig)和输入。
ZoeDepthForDepthEstimation 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.FloatTensor,形状为(1,),可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。predicted_depth(形状为
(batch_size, height, width)的torch.FloatTensor)— 每个像素的预测深度。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 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from transformers import AutoImageProcessor, ZoeDepthForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> 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"))