# DPT

## 概述

DPT 模型由 René Ranftl、Alexey Bochkovskiy 和 Vladlen Koltun 在 [Vision Transformers for Dense Prediction](https://huggingface.co/papers/2103.13413) 中提出。DPT 是一种利用 [Vision Transformer (ViT)](vit) 作为骨干网络，用于语义分割和深度估计等密集预测任务的模型。

该论文的摘要如下：

*我们提出了稠密视觉 Transformer（dense vision transformers），这是一种以视觉 Transformer 取代卷积网络作为稠密预测任务骨干网络的架构。我们将视觉 Transformer 各个阶段的 token 组装成不同分辨率的类图像表示，并通过卷积解码器逐步将其融合为全分辨率的预测结果。Transformer 骨干网络在恒定且相对较高的分辨率下处理表示，并且在每个阶段都具有全局感受野。这些特性使得稠密视觉 Transformer 相较于全卷积网络，能够提供更细粒度且全局一致性更强的预测。我们的实验表明，该架构在稠密预测任务上带来了显著提升，尤其是在拥有大量训练数据的情况下。在单目深度估计任务中，与最先进的全卷积网络相比，我们观察到相对性能最高提升了 28%。当应用于语义分割时，稠密视觉 Transformer 在 ADE20K 数据集上以 49.02% 的 mIoU 刷新了最先进水平。我们进一步表明，该架构可以在 NYUv2、KITTI 和 Pascal Context 等较小的数据集上进行微调，并在这些数据集上同样刷新了最先进水平。*

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/dpt_architecture.jpg"
alt="drawing" width="600"/>

 DPT 架构。摘自原始论文。

该模型由 [nielsr](https://huggingface.co/nielsr) 贡献。原始代码可在[此处](https://github.com/isl-org/DPT)找到。

## 使用技巧

DPT 与 [AutoBackbone](/docs/transformers/v5.23.0/zh/main_classes/backbones#transformers.AutoBackbone) 类兼容。这使得您可以使用 DPT 框架搭配库中可用的各种计算机视觉骨干网络，例如 `VitDetBackbone` 或 `Dinov2Backbone`。创建方式如下：

```python
from transformers import Dinov2Config, DPTConfig, DPTForDepthEstimation

# initialize with a Transformer-based backbone such as DINOv2
# in that case, we also specify `reshape_hidden_states=False` to get feature maps of shape (batch_size, num_channels, height, width)
backbone_config = Dinov2Config.from_pretrained("facebook/dinov2-base", out_features=["stage1", "stage2", "stage3", "stage4"], reshape_hidden_states=False)

config = DPTConfig(backbone_config=backbone_config)
model = DPTForDepthEstimation(config=config)
```

## 资源

一份来自 Hugging Face 官方和社区（以 🌎 标识）的资源列表，帮助你快速上手 DPT。

- [DPTForDepthEstimation](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTForDepthEstimation) 的演示笔记本可在[此处](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/DPT)找到。

- [语义分割任务指南](../tasks/semantic_segmentation)
- [单目深度估计任务指南](../tasks/monocular_depth_estimation)

如果您有兴趣提交资源以收录在此处，请随时发起 Pull Request，我们将对其进行审核！理想情况下，该资源应展示一些新内容，而不是重复现有资源。

## DPTConfig[[transformers.DPTConfig]]

#### transformers.DPTConfig[[transformers.DPTConfig]]

```python
transformers.DPTConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 768, num_hidden_layers: None | int = 12, num_attention_heads: int | None = 12, intermediate_size: int | None = 3072, hidden_act: str = 'gelu', hidden_dropout_prob: float | int | None = 0.0, attention_probs_dropout_prob: float | int | None = 0.0, initializer_range: float = 0.02, layer_norm_eps: float | None = 1e-12, image_size: int | list[int] | tuple[int, int] | None = 384, patch_size: int | list[int] | tuple[int, int] | None = 16, num_channels: int | None = 3, is_hybrid: bool = False, qkv_bias: bool | None = True, backbone_out_indices: list[int] | tuple[int, ...] | None = (2, 5, 8, 11), readout_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 = 256, head_in_index: int = -1, use_batch_norm_in_fusion_residual: bool | None = False, use_bias_in_fusion_residual: bool | None = None, add_projection: bool = False, use_auxiliary_head: bool | None = True, auxiliary_loss_weight: float = 0.4, semantic_loss_ignore_index: int = 255, semantic_classifier_dropout: float | int = 0.1, backbone_featmap_shape: list[int] | tuple[int, ...] | None = (1, 1024, 24, 24), neck_ignore_stages: list[int] | tuple[int, ...] = (0, 1), backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, pooler_output_size: int | None = None, pooler_act: str = 'tanh')
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/configuration_dpt.py#L27)

**参数：**

hidden_size (`int`，*可选*，默认为 `768`)：隐藏表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `12`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `12`)：Transformer 解码器中每个注意力层的注意力头数量。

intermediate_size (`int`，*可选*，默认值为 `3072`)：MLP 表示的维度。

hidden_act (`str`，*可选*，默认为 `gelu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

hidden_dropout_prob (`Union[float, int]`，*可选*，默认值为 `0.0`)：嵌入层、编码器和池化器中所有全连接层的 dropout 概率。

attention_probs_dropout_prob (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

layer_norm_eps (`float`, *可选*，默认为 `1e-12`)：层归一化层所使用的 epsilon。

image_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `384`)：每张图片的尺寸（分辨率）。

patch_size (`Union[int, list[int], tuple[int, int]]`，*可选*，默认为 `16`)：每个 patch 的大小（分辨率）。

num_channels (`int`，*可选*，默认为 `3`)：输入通道数。

is_hybrid (`bool`, *可选*, 默认为 `False`) : 是否使用混合骨干网络。在加载 DPT-Hybrid 模型时很有用。

qkv_bias (`bool`，*可选*，默认为 `True`)：是否向查询、键和值添加偏置。

backbone_out_indices (`list[int]`，*可选*，默认为 `[2, 5, 8, 11]`)：从 backbone 中使用的中间隐藏状态的索引。

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)：在 heads 中使用的特征索引。

use_batch_norm_in_fusion_residual (`bool`，*可选*，默认为 `False`)：是否在融合块的预激活残差单元中使用批归一化。

use_bias_in_fusion_residual (`bool`，*可选*，默认为 `True`)：是否在融合块的前激活残差单元中使用偏置。

add_projection (`bool`，*可选*，默认为 `False`)：是否在深度估计头之前添加投影层。

use_auxiliary_head (`bool`, *可选*, 默认为 `True`) : 是否在训练期间使用辅助头。

auxiliary_loss_weight (`float`, *可选*, 默认值为 0.4) : 辅助头交叉熵损失的权重。

semantic_loss_ignore_index (`int`，*可选*，默认为 `255`)：语义分割模型的损失函数所忽略的索引。

semantic_classifier_dropout (`float`, *可选*，默认为 0.1)：语义分类头的 dropout 比率。

backbone_featmap_shape (`list[int]`，*可选*，默认为 `[1, 1024, 24, 24]`)：仅用于 `hybrid` 嵌入类型。主干网络的特征图形状。

neck_ignore_stages (`list[int]`，*可选*，默认为 `[0, 1]`)：仅用于 `hybrid` 嵌入类型。要忽略的读出层阶段。

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：骨干模型的配置。

pooler_output_size (`int`, *可选*) : 池化层的维度。如果为 None，则默认为 `hidden_size`。

pooler_act (`str`，*可选*，默认为 `"tanh"`)：池化器所使用的激活函数。

这是用于存储 DPTModel 配置的类。它根据指定的参数实例化 Dpt 模型，并定义模型架构。使用默认值实例化配置将生成与 [Intel/dpt-large](https://huggingface.co/Intel/dpt-large) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import DPTModel, DPTConfig

>>> # Initializing a DPT dpt-large style configuration
>>> configuration = DPTConfig()

>>> # Initializing a model from the dpt-large style configuration
>>> model = DPTModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## DPTImageProcessor[[transformers.DPTImageProcessor]]

#### transformers.DPTImageProcessor[[transformers.DPTImageProcessor]]

```python
transformers.DPTImageProcessor(**kwargs: *<class 'transformers.models.dpt.image_processing_dpt.DPTImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_dpt.py#L110)

**参数：**

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': 384}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `None`) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `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*, *可选*，默认为 `False`) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

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*, *可选*，默认为 `None`) : 是否对图像进行居中裁剪。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

ensure_multiple_of (`int`, *kwargs*, *可选*，默认为 1) : 如果 `do_resize` 为 `True`，图像将被调整为此值整数倍的尺寸。可通过 `preprocess` 中的 `ensure_multiple_of` 进行覆盖。

size_divisor (`int`, *kwargs*) : 确保高度和宽度都能被整除的尺寸。

keep_aspect_ratio (`bool`, *kwargs*, *可选*，默认为 `False`) : 如果为 `True`，图像将被调整为保持宽高比的最大可能尺寸。可通过 `preprocess` 中的 `keep_aspect_ratio` 进行覆盖。

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `self.do_reduce_labels`) : 是否将所有分割图的标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集（例如 ADE20k）。背景标签将被替换为 255。

构建 DPTImageProcessor 图像处理器。

#### preprocess[[transformers.DPTImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.dpt.image_processing_dpt.DPTImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_dpt.py#L135)

**参数：**

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`。

segmentation_maps (`ImageInput`，*可选*)：要预处理的分割图。

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 为 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*) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

ensure_multiple_of (`int`, *kwargs*, *可选*，默认为 1) : 如果 `do_resize` 为 `True`，图像将被调整为此值整数倍的尺寸。可通过 `preprocess` 中的 `ensure_multiple_of` 进行覆盖。

size_divisor (`int`, *kwargs*) : 确保高度和宽度都能被整除的尺寸。

keep_aspect_ratio (`bool`, *kwargs*, *可选*，默认为 `False`) : 如果为 `True`，图像将被调整为保持宽高比的最大可能尺寸。可通过 `preprocess` 中的 `keep_aspect_ratio` 进行覆盖。

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `self.do_reduce_labels`) : 是否将所有分割图的标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集（例如 ADE20k）。背景标签将被替换为 255。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

## DPTImageProcessorPil[[transformers.DPTImageProcessorPil]]

#### transformers.DPTImageProcessorPil[[transformers.DPTImageProcessorPil]]

```python
transformers.DPTImageProcessorPil(**kwargs: *<class 'transformers.models.dpt.image_processing_pil_dpt.DPTImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_pil_dpt.py#L110)

**参数：**

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': 384}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 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*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `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*, *可选*，默认为 `False`) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

ensure_multiple_of (`int`, *kwargs*, *可选*，默认为 1) : 如果 `do_resize` 为 `True`，图像将被调整为此值整数倍的尺寸。可通过 `preprocess` 中的 `ensure_multiple_of` 进行覆盖。

size_divisor (`int`, *kwargs*) : 确保高度和宽度都能被整除的尺寸。

keep_aspect_ratio (`bool`, *kwargs*, *可选*，默认为 `False`) : 如果为 `True`，图像将被调整为保持宽高比的最大可能尺寸。可通过 `preprocess` 中的 `keep_aspect_ratio` 进行覆盖。

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `self.do_reduce_labels`) : 是否将所有分割图的标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集（例如 ADE20k）。背景标签将被替换为 255。

构建 DPTImageProcessor 图像处理器。

#### preprocess[[transformers.DPTImageProcessorPil.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.dpt.image_processing_pil_dpt.DPTImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_pil_dpt.py#L131)

**参数：**

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`。

segmentation_maps (`ImageInput`，*可选*)：要预处理的分割图。

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 为 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*) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

ensure_multiple_of (`int`, *kwargs*, *可选*，默认为 1) : 如果 `do_resize` 为 `True`，图像将被调整为此值整数倍的尺寸。可通过 `preprocess` 中的 `ensure_multiple_of` 进行覆盖。

size_divisor (`int`, *kwargs*) : 确保高度和宽度都能被整除的尺寸。

keep_aspect_ratio (`bool`, *kwargs*, *可选*，默认为 `False`) : 如果为 `True`，图像将被调整为保持宽高比的最大可能尺寸。可通过 `preprocess` 中的 `keep_aspect_ratio` 进行覆盖。

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `self.do_reduce_labels`) : 是否将所有分割图的标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集（例如 ADE20k）。背景标签将被替换为 255。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

#### post_process_semantic_segmentation[[transformers.DPTImageProcessorPil.post_process_semantic_segmentation]]

```python
post_process_semantic_segmentation(outputs, target_sizes: list[tuple] | None = None, return_segmentation_scores: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_pil_dpt.py#L268)

**参数：**

outputs ([DPTForSemanticSegmentation](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTForSemanticSegmentation))：模型的原始输出。

target_sizes (`list[tuple]`, *可选*) : 一个元组列表（`tuple[int, int]`），包含批次中每张图片的目标尺寸（高度、宽度）。如果未设置，预测结果将不会被调整大小。

return_segmentation_scores (`bool`，*可选*，默认为 `False`)：是否同时返回分割分数和分割图。当为 `True` 时，返回列表中的每个元素都是一个 `SemanticSegmentationPostProcessorOutput`，包含字段 `segmentation`（类别 ID，形状为 `(height, width)`）和 `segmentation_scores`（形状为 `(num_classes, height, width)`）。

**返回：** `list[torch.Tensor]` 或 `list[SemanticSegmentationPostProcessorOutput]`

当 `return_segmentation_scores=False`（默认值）时，返回一个长度为 `batch_size` 的列表，其中每个元素都是形状为 `(height, width)` 且包含类别 ID 的分割图。当 `return_segmentation_scores=True` 时，返回一个 `SemanticSegmentationPostProcessorOutput` 列表，包含字段 `segmentation`（类别 ID，形状为 `(height, width)`）和 `segmentation_scores`（形状为 `(num_classes, height, width)`）。在这两种情况下，`(height, width)` 均对应目标尺寸（如果指定了 `target_sizes`）。

将 [DPTForSemanticSegmentation](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTForSemanticSegmentation) 的输出转换为语义分割图。

#### post_process_depth_estimation[[transformers.DPTImageProcessorPil.post_process_depth_estimation]]

```python
post_process_depth_estimation(outputs: DepthEstimatorOutput, target_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/image_processing_pil_dpt.py#L331)

将 `DepthEstimatorOutput` 的原始输出转换为最终的深度预测结果。

## DPTModel[[transformers.DPTModel]]

#### transformers.DPTModel[[transformers.DPTModel]]

```python
transformers.DPTModel(config: DPTConfig, add_pooling_layer: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L752)

**参数：**

config ([DPTConfig](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTConfig))：模型配置类，包含模型的所有参数。使用配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

add_pooling_layer (`bool`，*可选*，默认为 `True`)：是否添加池化层

未添加任何特定头部的裸 Dpt 模型，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.DPTModel.forward]]

```python
forward(pixel_values: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L780)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [DPTImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTImageProcessor) 获取像素值。有关详细信息，请参阅 [DPTImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [DPTImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTImageProcessor) 处理图像）。

**返回：** `BaseModelOutputWithPoolingAndIntermediateActivations` 或 `tuple(torch.Tensor)`

`BaseModelOutputWithPoolingAndIntermediateActivations` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[DPTConfig](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTConfig)）和输入。

[DPTModel](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple[torch.Tensor, ...]`，*可选*，当传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple[torch.Tensor, ...]`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **intermediate_activations** (`tuple(torch.Tensor)`，*可选*) -- 可用于计算模型各层隐藏状态的中间激活值。

示例：

```python
```

## DPTForDepthEstimation[[transformers.DPTForDepthEstimation]]

#### transformers.DPTForDepthEstimation[[transformers.DPTForDepthEstimation]]

```python
transformers.DPTForDepthEstimation(config: DPTConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L923)

**参数：**

config ([DPTConfig](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTConfig))：模型配置类，包含模型的所有参数。使用配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

带有深度估计头（由 3 个卷积层组成）的 DPT 模型，例如用于 KITTI、NYUv2。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.DPTForDepthEstimation.forward]]

```python
forward(pixel_values: Tensor, labels: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L942)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(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)`，*可选*)：用于计算损失的真实深度估计图。

**返回：** [DepthEstimatorOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput) 或 `tuple(torch.Tensor)`

一个 [DepthEstimatorOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[DPTForDepthEstimation](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTForDepthEstimation) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **predicted_depth**（形状为 `(batch_size, height, width)` 的 `torch.Tensor`）-- 每个像素的预测深度。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, num_channels, height, width)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, patch_size, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：
```python
>>> from transformers import AutoImageProcessor, DPTForDepthEstimation
>>> 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/dpt-large")
>>> model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")

>>> # 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"))
```

## DPTForSemanticSegmentation[[transformers.DPTForSemanticSegmentation]]

#### transformers.DPTForSemanticSegmentation[[transformers.DPTForSemanticSegmentation]]

```python
transformers.DPTForSemanticSegmentation(config: DPTConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L1070)

**参数：**

config ([DPTConfig](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTConfig))：模型配置类，包含模型的所有参数。使用配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

带有语义分割头的 Dpt 模型，例如用于 ADE20K、CityScapes。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.DPTForSemanticSegmentation.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/dpt/modeling_dpt.py#L1086)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(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)`，*可选*) : 用于计算损失的真实语义分割图。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `config.num_labels > 1`，则计算分类损失（交叉熵）。

**返回：** [SemanticSegmenterOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 或 `tuple(torch.Tensor)`

一个 [SemanticSegmenterOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[DPTForSemanticSegmentation](/docs/transformers/v5.23.0/zh/model_doc/dpt#transformers.DPTForSemanticSegmentation) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **logits**（形状为 `(batch_size, config.num_labels, logits_height, logits_width)` 的 `torch.Tensor`）-- 每个像素的分类分数。

  

  返回的 logits 大小不一定与作为输入传入的 `pixel_values` 相同。这样设计是为了避免进行两次插值，从而在用户需要将 logits 调整为原始图像尺寸作为后处理时损失部分质量。您应始终检查 logits 的形状，并根据需要进行调整。

  
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, patch_size, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, patch_size, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：
```python
>>> from transformers import AutoImageProcessor, DPTForSemanticSegmentation
>>> 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/dpt-large-ade")
>>> model = DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade")

>>> inputs = image_processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)
>>> logits = outputs.logits
```

