# OneFormer

## 概述

OneFormer 模型由 Jitesh Jain、Jiachen Li、MangTik Chiu、Ali Hassani、Nikita Orlov 和 Humphrey Shi 在 [OneFormer: One Transformer to Rule Universal Image Segmentation](https://huggingface.co/papers/2211.06220) 中提出。OneFormer 是一个通用图像分割框架，可以在单个全景数据集上进行训练，以执行语义分割、实例分割和全景分割任务。OneFormer 使用任务 token 来使模型适应当前关注的任务，从而使架构在训练时具有任务引导性，在推理时具有任务动态性。

该论文的摘要如下：

*通用图像分割并非一个新概念。过去几十年中，统一图像分割的尝试包括场景解析、全景分割，以及更近期的新型全景分割架构。然而，这些全景分割架构并未真正实现图像分割的统一，因为它们需要针对语义分割、实例分割或全景分割分别进行训练，才能达到最佳性能。理想情况下，一个真正通用的框架应只需训练一次，即可在所有三种图像分割任务上取得 SOTA 性能。为此，我们提出了 OneFormer，一个通过多任务“一次训练”设计来统一分割的通用图像分割框架。首先，我们提出了一种任务条件联合训练策略，使得在单一的多任务训练过程中，能够基于每个领域（语义分割、实例分割和全景分割）的真值进行训练。其次，我们引入了任务 token，使模型能够根据当前任务进行条件化，从而使模型具备任务动态性，以支持多任务训练和推理。第三，我们提出在训练过程中使用查询-文本对比损失，以建立更好的任务间和类别间区分度。值得注意的是，尽管 Mask2Former 针对三个任务分别进行了训练，且使用了三倍的资源，但我们的单一 OneFormer 模型在 ADE20k、CityScapes 和 COCO 上的所有三种分割任务上均优于专门的 Mask2Former 模型。使用新的 ConvNeXt 和 DiNAT 骨干网络后，我们观察到性能进一步提升。我们认为 OneFormer 是使图像分割更加通用和易于获取的重要一步。*

下图展示了 OneFormer 的架构。摘自[原始论文](https://huggingface.co/papers/2211.06220)。

该模型由 [Jitesh Jain](https://huggingface.co/praeclarumjj3) 贡献。原始代码可在 [此处](https://github.com/SHI-Labs/OneFormer) 找到。

## 使用技巧

- OneFormer 在推理时需要两个输入：*image* 和 *task token*。
- 在训练过程中，OneFormer 仅使用全景分割标注。
- 如果要在跨多个节点的分布式环境中训练模型，则应更新 `modeling_oneformer.py` 中 `OneFormerLoss` 类内的 `get_num_masks` 函数。在多节点训练时，该值应设置为所有节点上目标掩码数量的平均值，具体可参见原始实现中的 [此处](https://github.com/SHI-Labs/OneFormer/blob/33ebb56ed34f970a30ae103e786c0cb64c653d9a/oneformer/modeling/criterion.py#L287)。
- 可以使用 [OneFormerProcessor](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerProcessor) 为模型准备输入图像和任务输入，以及可选的模型目标。[OneFormerProcessor](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerProcessor) 将 [OneFormerImageProcessor](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerImageProcessor) 和 [CLIPTokenizer](/docs/transformers/main/zh/model_doc/clip#transformers.CLIPTokenizer) 封装为单一实例，以同时完成图像准备和任务输入编码。
- 要获取最终的分割结果，根据任务的不同，你可以调用 `post_process_semantic_segmentation()` 或 [post_process_instance_segmentation()](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_instance_segmentation) 或 [post_process_panoptic_segmentation()](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_panoptic_segmentation)。这三种任务都可以使用 [OneFormerForUniversalSegmentation](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation) 的输出来解决，全景分割接受一个可选的 `label_ids_to_fuse` 参数，用于将目标对象（例如天空）的实例融合在一起。

## 资源

以下是来自 Hugging Face 官方和社区（以 🌎 标识）的资源列表，可帮助您快速上手 OneFormer。

- 有关在自定义数据上进行推理 + 微调的演示笔记本可在[此处](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/OneFormer)找到。

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

## OneFormer 特定输出[[transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput]]

#### transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput[[transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput]]

```python
transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput(encoder_hidden_states: tuple[torch.Tensor] | None = None, pixel_decoder_hidden_states: tuple[torch.Tensor] | None = None, transformer_decoder_hidden_states: typing.Optional[torch.Tensor] = None, transformer_decoder_object_queries: typing.Optional[torch.Tensor] = None, transformer_decoder_contrastive_queries: typing.Optional[torch.Tensor] = None, transformer_decoder_mask_predictions: typing.Optional[torch.Tensor] = None, transformer_decoder_class_predictions: typing.Optional[torch.Tensor] = None, transformer_decoder_auxiliary_predictions: tuple[dict[str, torch.Tensor]] | None = None, text_queries: typing.Optional[torch.Tensor] = None, task_token: typing.Optional[torch.Tensor] = None, attentions: tuple[torch.Tensor] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L829)

**参数：**

encoder_hidden_states (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回)：一个 `torch.Tensor` 元组（包含一个嵌入层输出和每个阶段的输出），形状为 `(batch_size, num_channels, height, width)`。编码器模型在每个阶段输出处的隐藏状态（也称为特征图）。

pixel_decoder_hidden_states (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回)：一个 `torch.Tensor` 元组（包含一个嵌入层输出和每个阶段的输出），形状为 `(batch_size, num_channels, height, width)`。像素解码器模型在每个阶段输出处的隐藏状态（也称为特征图）。

transformer_decoder_hidden_states (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回)：一个 `torch.Tensor` 元组（包含嵌入层输出的一个张量以及每个阶段输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。Transformer 解码器在每个阶段输出处的隐藏状态（也称为特征图）。

transformer_decoder_object_queries (`torch.Tensor`，形状为 `(batch_size, num_queries, hidden_dim)`)：Transformer 解码器最后一层输出的对象查询。

transformer_decoder_contrastive_queries (`torch.Tensor`，形状为 `(batch_size, num_queries, hidden_dim)`)：来自 Transformer 解码器的对比查询。

transformer_decoder_mask_predictions (`torch.Tensor`，形状为 `(batch_size, num_queries, height, width)`)：Transformer 解码器最后一层输出的掩码预测。

transformer_decoder_class_predictions (`torch.Tensor`，形状为 `(batch_size, num_queries, num_classes+1)`)：Transformer 解码器最后一层的类别预测。

transformer_decoder_auxiliary_predictions (`Tuple` of Dict of `str, torch.Tensor`, *可选*) : 来自 transformer 解码器每一层的类别和掩码预测的元组。

text_queries (`torch.Tensor`，*可选*，形状为 `(batch_size, num_queries, hidden_dim)`)：从输入文本列表派生的文本查询，用于在训练期间计算对比损失。

task_token (`torch.Tensor`，形状为 `(batch_size, hidden_dim)`)：用于条件化查询的 1D 任务 token。

attentions (`tuple(tuple(torch.Tensor))`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回)：一个 `tuple(torch.Tensor)` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。来自 transformer 解码器的自注意力和交叉注意力权重。

[OneFormerModel](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerModel) 的输出类。该类返回计算 logits 所需的所有隐藏状态。

#### transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput[[transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput]]

```python
transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput(loss: typing.Optional[torch.Tensor] = None, class_queries_logits: typing.Optional[torch.Tensor] = None, masks_queries_logits: typing.Optional[torch.Tensor] = None, auxiliary_predictions: list = None, encoder_hidden_states: tuple[torch.Tensor] | None = None, pixel_decoder_hidden_states: list[torch.Tensor] | None = None, transformer_decoder_hidden_states: typing.Optional[torch.Tensor] = None, transformer_decoder_object_queries: typing.Optional[torch.Tensor] = None, transformer_decoder_contrastive_queries: typing.Optional[torch.Tensor] = None, transformer_decoder_mask_predictions: typing.Optional[torch.Tensor] = None, transformer_decoder_class_predictions: typing.Optional[torch.Tensor] = None, transformer_decoder_auxiliary_predictions: list[dict[str, torch.Tensor]] | None = None, text_queries: typing.Optional[torch.Tensor] = None, task_token: typing.Optional[torch.Tensor] = None, attentions: tuple[tuple[torch.Tensor]] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L886)

**参数：**

loss (`torch.Tensor`, *可选*) : 计算得到的损失，在存在标签时返回。

class_queries_logits (`torch.Tensor`, *可选*) : 形状为 `(batch_size, num_queries, num_labels + 1)` 的张量，表示每个查询所提议的类别。请注意，`+ 1` 是必需的，因为我们纳入了空类别。

masks_queries_logits (`torch.Tensor`, *可选*) : 形状为 `(batch_size, num_queries, height, width)` 的张量，表示每个查询对应的提议掩码。

auxiliary_predictions (`List` of Dict of `str, torch.Tensor`, *可选*) : 来自 transformer 解码器每一层的类别和掩码预测列表。

encoder_hidden_states (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回)：一个 `torch.Tensor` 元组（包含一个嵌入层输出和每个阶段的输出），形状为 `(batch_size, num_channels, height, width)`。编码器模型在每个阶段输出处的隐藏状态（也称为特征图）。

pixel_decoder_hidden_states (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回)：一个 `torch.Tensor` 元组（包含一个嵌入层输出和每个阶段的输出），形状为 `(batch_size, num_channels, height, width)`。像素解码器模型在每个阶段输出处的隐藏状态（也称为特征图）。

transformer_decoder_hidden_states (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回)：一个 `torch.Tensor` 元组（包含嵌入层输出的一个张量以及每个阶段输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。Transformer 解码器在每个阶段输出处的隐藏状态（也称为特征图）。

transformer_decoder_object_queries (`torch.Tensor`，形状为 `(batch_size, num_queries, hidden_dim)`)：Transformer 解码器最后一层输出的对象查询。

transformer_decoder_contrastive_queries (`torch.Tensor`，形状为 `(batch_size, num_queries, hidden_dim)`)：来自 Transformer 解码器的对比查询。

transformer_decoder_mask_predictions (`torch.Tensor`，形状为 `(batch_size, num_queries, height, width)`)：Transformer 解码器最后一层输出的掩码预测。

transformer_decoder_class_predictions (`torch.Tensor`，形状为 `(batch_size, num_queries, num_classes+1)`)：Transformer 解码器最后一层的类别预测。

transformer_decoder_auxiliary_predictions (`List` of Dict of `str, torch.Tensor`, *可选*) : 来自 transformer 解码器每一层的类别和掩码预测列表。

text_queries (`torch.Tensor`，*可选*，形状为 `(batch_size, num_queries, hidden_dim)`)：从输入文本列表派生的文本查询，用于在训练期间计算对比损失。

task_token (`torch.Tensor`，形状为 `(batch_size, hidden_dim)`)：用于条件化查询的 1D 任务 token。

attentions (`tuple(tuple(torch.Tensor))`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回)：一个 `tuple(torch.Tensor)` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。来自 transformer 解码器的自注意力和交叉注意力权重。

`OneFormerForUniversalSegmentationOutput` 的输出类。

该输出可以直接传递给 [post_process_semantic_segmentation()](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_semantic_segmentation) 或 [post_process_instance_segmentation()](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_instance_segmentation) 或 [post_process_panoptic_segmentation()](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_panoptic_segmentation)，具体取决于任务。有关使用详情，请参阅 [`~OneFormerImageProcessor]。

## OneFormerConfig[[transformers.OneFormerConfig]]

#### transformers.OneFormerConfig[[transformers.OneFormerConfig]]

```python
transformers.OneFormerConfig(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, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, ignore_value: int = 255, num_queries: int = 150, no_object_weight: float = 0.1, class_weight: float = 2.0, mask_weight: float = 5.0, dice_weight: float = 5.0, contrastive_weight: float = 0.5, contrastive_temperature: float = 0.07, train_num_points: int = 12544, oversample_ratio: float = 3.0, importance_sample_ratio: float = 0.75, init_std: float = 0.02, init_xavier_std: float = 1.0, layer_norm_eps: float = 1e-05, is_training: bool = False, use_auxiliary_loss: bool = True, output_auxiliary_logits: bool = True, strides: list[int] | tuple[int, ...] = (4, 8, 16, 32), task_seq_len: int = 77, text_encoder_width: int = 256, text_encoder_context_length: int = 77, text_encoder_num_layers: int = 6, text_encoder_vocab_size: int = 49408, text_encoder_proj_layers: int = 2, text_encoder_n_ctx: int = 16, conv_dim: int = 256, mask_dim: int = 256, hidden_dim: int = 256, encoder_feedforward_dim: int = 1024, norm: str = 'GN', encoder_layers: int = 6, decoder_layers: int = 10, use_task_norm: bool = True, num_attention_heads: int = 8, dropout: float | int = 0.1, dim_feedforward: int = 2048, pre_norm: bool = False, enforce_input_proj: bool = False, query_dec_layers: int = 2, common_stride: int = 4)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/configuration_oneformer.py#L25)

**参数：**

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

ignore_value (`int`，*可选*，默认为 255)：在计算损失时，GT 标签中需要忽略的值。

num_queries (`int`，*可选*，默认为 150)：对象查询的数量。

no_object_weight (`float`, *可选*, 默认为 `0.1`) : 目标检测损失中无目标类别的相对分类权重。

class_weight (`float`, *可选*, 默认为 `2.0`) : 匈牙利匹配代价中分类误差的相对权重。

mask_weight (`float`, *可选*，默认为 `5.0`)：全景分割损失中焦点损失的相对权重。

dice_weight (`float`, *可选*, 默认为 `5.0`) : 全景分割损失中 dice 损失的相对权重。

contrastive_weight (`float`, *可选*, 默认值为 0.5) : 对比损失的权重。

contrastive_temperature (`float`, *可选*，默认为 0.07) : 用于缩放对比 logits 的初始值。

train_num_points (`int`, *可选*, 默认为 12544) : 在计算掩码预测的损失时采样的点数。

oversample_ratio (`float`, *可选*，默认为 3.0)：用于决定超采样点数的比例。

importance_sample_ratio (`float`, *可选*，默认为 0.75)：通过重要性采样采样的点的比例。

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

init_xavier_std (`float`, *可选*，默认为 `1.0`) : 用于交叉注意力权重 Xavier 初始化的缩放因子。

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

is_training (`bool`，*可选*，默认为 `False`)：是否以训练模式或推理模式运行。

use_auxiliary_loss (`bool`, *可选*, 默认为 `True`) : 是否使用 transformer decoder 的中间预测值来计算损失。

output_auxiliary_logits (`bool`, *可选*, 默认为 `True`) : 是否返回 transformer decoder 的中间预测结果。

strides (`list`，*可选*，默认为 `[4, 8, 16, 32]`)：包含编码器中特征图步长的列表。

task_seq_len (`int`，*可选*，默认为 77)：用于对文本列表输入进行分词的序列长度。

text_encoder_width (`int`，*可选*，默认为 256)：文本编码器的隐藏层大小。

text_encoder_context_length (`int`，*可选*，默认为 77)：文本编码器的输入序列长度。

text_encoder_num_layers (`int`, *可选*, 默认为 6) : 文本编码器中 transformer 的层数。

text_encoder_vocab_size (`int`，*可选*，默认为 49408)：分词器的词汇表大小。

text_encoder_proj_layers (`int`, *可选*, 默认为 2) : 用于投影文本查询的 MLP 层数。

text_encoder_n_ctx (`int`，*可选*，默认为 16)：可学习文本上下文查询的数量。

conv_dim (`int`，*可选*，默认为 256)：用于将主干网络输出映射的特征图维度。

mask_dim (`int`，*可选*，默认为 256)：像素解码器中特征图的维度。

hidden_dim (`int`，*可选*，默认为 256)：Transformer 解码器中隐藏状态的维度。

encoder_feedforward_dim (`int`, *可选*，默认为 1024)：像素解码器中 FFN 层的维度。

norm (`str`，*可选*，默认为 `"GN"`)：归一化的类型。

encoder_layers (`int`，*可选*，默认为 `6`)：Transformer 编码器中的隐藏层数。如果未设置，将使用与 `num_layers` 相同的值。

decoder_layers (`int`，*可选*，默认为 `10`)：Transformer 解码器中的隐藏层数。如果未设置，将使用与 `num_layers` 相同的值。

use_task_norm (`bool`, *可选*, 默认为 `True`) : 是否对任务标记进行归一化。

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

dropout (`Union[float, int]`，*可选*，默认为 `0.1`)：所有 dropout 层的比率。

dim_feedforward (`int`，*可选*，默认为 2048)：Transformer 解码器中 FFN 层的维度。

pre_norm (`bool`, *可选*, 默认为 `False`) : 是否在 Transformer 解码器的注意力层之前对隐藏状态进行归一化。

enforce_input_proj (`bool`, *可选*, 默认为 `False`) : 是否对 transformer 解码器中的隐藏状态进行投影。

query_dec_layers (`int`，*可选*，默认为 2)：查询 Transformer 的层数。

common_stride (`int`，*可选*，默认为 4)：像素解码器中特征常用的步长。

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

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

示例：
```python
>>> from transformers import OneFormerConfig, OneFormerModel

>>> # Initializing a OneFormer shi-labs/oneformer_ade20k_swin_tiny configuration
>>> configuration = OneFormerConfig()
>>> # Initializing a model (with random weights) from the shi-labs/oneformer_ade20k_swin_tiny style configuration
>>> model = OneFormerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```

## OneFormerImageProcessor[[transformers.OneFormerImageProcessor]]

#### transformers.OneFormerImageProcessor[[transformers.OneFormerImageProcessor]]

```python
transformers.OneFormerImageProcessor(**kwargs: *<class 'transformers.models.oneformer.image_processing_oneformer.OneFormerImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L275)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `True`)：是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'shortest_edge' : 800, 'longest_edge': 1333}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 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*，默认为 `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.485, 0.456, 0.406]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.229, 0.224, 0.225]`) : 用于归一化的图像标准差。仅当 `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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

repo_path (`str`, *kwargs*, *可选*，默认为 `shi-labs/oneformer_demo`)：包含模型元数据的本地目录或 HuggingFace Hub 仓库的路径。

class_info_file (`str`, *kwargs*, *可选*) : 仓库中包含类元数据的 JSON 文件的路径。

num_text (`int`, *kwargs*, *可选*) : 文本编码器使用的文本查询数量，用作任务引导提示。

num_labels (`int`, *kwargs*, *可选*) : 用于分割的语义类别数量，决定输出层的大小。

ignore_index (`int`, *kwargs*, *可选*) : 在分割图中需要忽略的标签，通常用于填充。

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否将所有标签值减 1，将背景类映射到 `ignore_index`。

构建一个 OneFormerImageProcessor 图像处理器。

#### preprocess[[transformers.OneFormerImageProcessor.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']], task_inputs: list[str] | None = None, 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, instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None, **kwargs: *<class 'transformers.models.oneformer.image_processing_oneformer.OneFormerImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L300)

**参数：**

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

task_inputs (`list[str]`, *可选*) : 批次中每张图片的任务列表（`"panoptic"`、`"instance"`、`"semantic"`）。

segmentation_maps (`ImageInput`，*可选*)：分割图。

instance_id_to_semantic_id (`Union[list[dict[int, int]], dict[int, int]]`, *可选*) : 从实例 ID 到语义 ID 的映射。

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

repo_path (`str`, *kwargs*, *可选*，默认为 `shi-labs/oneformer_demo`)：包含模型元数据的本地目录或 HuggingFace Hub 仓库的路径。

class_info_file (`str`, *kwargs*, *可选*) : 仓库中包含类元数据的 JSON 文件的路径。

num_text (`int`, *kwargs*, *可选*) : 文本编码器使用的文本查询数量，用作任务引导提示。

num_labels (`int`, *kwargs*, *可选*) : 用于分割的语义类别数量，决定输出层的大小。

ignore_index (`int`, *kwargs*, *可选*) : 在分割图中需要忽略的标签，通常用于填充。

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否将所有标签值减 1，将背景类映射到 `ignore_index`。

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

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

#### post_process_semantic_segmentation[[transformers.OneFormerImageProcessor.post_process_semantic_segmentation]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L690)

**参数：**

outputs ([OneFormerForUniversalSegmentation](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation))：模型的原始输出。

target_sizes (`list[tuple[int, int]]`, *可选*) : 长度为 (batch_size) 的列表，其中每个列表项 (`Tuple[int, int]]`) 对应每个预测所需的最终尺寸（高度、宽度）。如果设置为 None，则不会调整预测结果的尺寸。

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

将 [OneFormerForUniversalSegmentation](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation) 的输出转换为语义分割图。仅支持 PyTorch。

#### post_process_instance_segmentation[[transformers.OneFormerImageProcessor.post_process_instance_segmentation]]

```python
post_process_instance_segmentation(outputs, task_type: str = 'instance', is_demo: bool = True, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, target_sizes: list[tuple[int, int]] | None = None, return_coco_annotation: bool | None = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L766)

**参数：**

outputs (`OneFormerForUniversalSegmentationOutput`) : `OneFormerForUniversalSegmentationOutput` 的输出。

task_type (`str`, *可选*, 默认为 "instance") : 后处理取决于任务标记输入。如果 `task_type` 为 "panoptic"，则需要忽略 stuff 预测。

is_demo (`bool`, *可选*, 默认为 `True`) : 模型是否处于演示模式。如果为 true，则使用阈值来预测最终掩码。

threshold (`float`, *可选*，默认为 0.5)：用于保留预测实例掩码的概率分数阈值。

mask_threshold (`float`，*可选*，默认值为 0.5)：将预测掩码转换为二值时使用的阈值。

overlap_mask_area_threshold (`float`, *可选*，默认为 0.8)：用于合并或丢弃每个二值实例掩码内部小的不连通部分的重叠掩码面积阈值。

target_sizes (`List[Tuple]`, *可选*) : 长度为 (batch_size) 的列表，其中每个列表项 (`Tuple[int, int]]`) 对应批处理中每个预测所需的最终尺寸（高度、宽度）。如果设置为 None，则不会调整预测结果的尺寸。

return_coco_annotation (`bool`，*可选*，默认为 `False`)：是否以 COCO 格式返回预测结果。

**返回：** `List[Dict]`

一个字典列表，每张图片对应一个字典，每个字典包含两个键：
- **segmentation** -- 形状为 `(height, width)` 的张量，其中每个像素代表一个 `segment_id`，如果未找到高于 `threshold` 的掩码，则设置为 `None`。如果指定了 `target_sizes`，则 segmentation 会被调整大小以对应 `target_sizes` 中的相应条目。
- **segments_info** -- 一个包含每个片段附加信息的字典。
  - **id** -- 一个表示 `segment_id` 的整数。
  - **label_id** -- 一个整数，表示与 `segment_id` 对应的标签/语义类别 ID。
  - **was_fused** -- 一个布尔值，如果 `label_id` 在 `label_ids_to_fuse` 中，则为 `True`，否则为 `False`。同一类别/标签的多个实例已被融合，并被分配了单一的 `segment_id`。
  - **score** -- 具有 `segment_id` 的片段的预测分数。

将 `OneFormerForUniversalSegmentationOutput` 的输出转换为图像实例分割预测。仅支持 PyTorch。

#### post_process_panoptic_segmentation[[transformers.OneFormerImageProcessor.post_process_panoptic_segmentation]]

```python
post_process_panoptic_segmentation(outputs, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, label_ids_to_fuse: set[int] | None = None, target_sizes: list[tuple[int, int]] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L886)

**参数：**

outputs (`MaskFormerForInstanceSegmentationOutput`) : [MaskFormerForInstanceSegmentation](/docs/transformers/main/zh/model_doc/maskformer#transformers.MaskFormerForInstanceSegmentation) 的输出。

threshold (`float`, *可选*，默认为 0.5)：用于保留预测实例掩码的概率分数阈值。

mask_threshold (`float`，*可选*，默认值为 0.5)：将预测掩码转换为二值时使用的阈值。

overlap_mask_area_threshold (`float`, *可选*，默认为 0.8)：用于合并或丢弃每个二值实例掩码内部小的不连通部分的重叠掩码面积阈值。

label_ids_to_fuse (`Set[int]`, *可选*) : 在此状态下，标签的所有实例将被融合在一起。例如，我们可以说一张图像中只能有一个天空，但可以有多个行人，因此天空的标签 ID 会包含在该集合中，而行人的标签 ID 则不会。

target_sizes (`list[Tuple]`，*可选*)：长度为 (batch_size) 的列表，其中每个列表项 (`tuple[int, int]]`) 对应批处理中每个预测所需的最终尺寸（高度、宽度）。如果设为 None，则不会调整预测结果的尺寸。

**返回：** `list[Dict]`

一个字典列表，每张图片对应一个字典，每个字典包含两个键：
- **segmentation** -- 形状为 `(height, width)` 的张量，其中每个像素代表一个 `segment_id`，如果未找到高于 `threshold` 的掩码，则设置为 `None`。如果指定了 `target_sizes`，则 segmentation 会被调整大小以对应 `target_sizes` 中的相应条目。
- **segments_info** -- 一个包含每个片段附加信息的字典。
  - **id** -- 一个表示 `segment_id` 的整数。
  - **label_id** -- 一个整数，表示与 `segment_id` 对应的标签/语义类别 ID。
  - **was_fused** -- 一个布尔值，如果 `label_id` 在 `label_ids_to_fuse` 中，则为 `True`，否则为 `False`。同一类别/标签的多个实例已被融合，并被分配了单一的 `segment_id`。
  - **score** -- 具有 `segment_id` 的片段的预测分数。

将 `MaskFormerForInstanceSegmentationOutput` 的输出转换为图像全景分割预测。仅支持 PyTorch。

## OneFormerImageProcessorPil[[transformers.OneFormerImageProcessorPil]]

#### transformers.OneFormerImageProcessorPil[[transformers.OneFormerImageProcessorPil]]

```python
transformers.OneFormerImageProcessorPil(**kwargs: *<class 'transformers.models.oneformer.image_processing_pil_oneformer.OneFormerImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L293)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `True`)：是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'shortest_edge' : 800, 'longest_edge': 1333}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 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*，默认为 `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.485, 0.456, 0.406]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.229, 0.224, 0.225]`) : 用于归一化的图像标准差。仅当 `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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

repo_path (`str`, *kwargs*, *可选*，默认为 `shi-labs/oneformer_demo`)：包含模型元数据的本地目录或 HuggingFace Hub 仓库的路径。

class_info_file (`str`, *kwargs*, *可选*) : 仓库中包含类元数据的 JSON 文件的路径。

num_text (`int`, *kwargs*, *可选*) : 文本编码器使用的文本查询数量，用作任务引导提示。

num_labels (`int`, *kwargs*, *可选*) : 用于分割的语义类别数量，决定输出层的大小。

ignore_index (`int`, *kwargs*, *可选*) : 在分割图中需要忽略的标签，通常用于填充。

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否将所有标签值减 1，将背景类映射到 `ignore_index`。

构建一个 OneFormerImageProcessor 图像处理器。

#### preprocess[[transformers.OneFormerImageProcessorPil.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']], task_inputs: list[str] | None = None, 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, instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None, **kwargs: *<class 'transformers.models.oneformer.image_processing_pil_oneformer.OneFormerImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L318)

**参数：**

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

task_inputs (`list[str]`, *可选*) : 批次中每张图片的任务列表（`"panoptic"`、`"instance"`、`"semantic"`）。

segmentation_maps (`ImageInput`，*可选*)：分割图。

instance_id_to_semantic_id (`Union[list[dict[int, int]], dict[int, int]]`, *可选*) : 从实例 ID 到语义 ID 的映射。

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

repo_path (`str`, *kwargs*, *可选*，默认为 `shi-labs/oneformer_demo`)：包含模型元数据的本地目录或 HuggingFace Hub 仓库的路径。

class_info_file (`str`, *kwargs*, *可选*) : 仓库中包含类元数据的 JSON 文件的路径。

num_text (`int`, *kwargs*, *可选*) : 文本编码器使用的文本查询数量，用作任务引导提示。

num_labels (`int`, *kwargs*, *可选*) : 用于分割的语义类别数量，决定输出层的大小。

ignore_index (`int`, *kwargs*, *可选*) : 在分割图中需要忽略的标签，通常用于填充。

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否将所有标签值减 1，将背景类映射到 `ignore_index`。

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

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

#### post_process_semantic_segmentation[[transformers.OneFormerImageProcessorPil.post_process_semantic_segmentation]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L746)

**参数：**

outputs ([OneFormerForUniversalSegmentation](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation))：模型的原始输出。

target_sizes (`list[tuple[int, int]]`, *可选*) : 长度为 (batch_size) 的列表，其中每个列表项 (`Tuple[int, int]]`) 对应每个预测所需的最终尺寸（高度、宽度）。如果设置为 None，则不会调整预测结果的尺寸。

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

将 [OneFormerForUniversalSegmentation](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation) 的输出转换为语义分割图。仅支持 PyTorch。

#### post_process_instance_segmentation[[transformers.OneFormerImageProcessorPil.post_process_instance_segmentation]]

```python
post_process_instance_segmentation(outputs, task_type: str = 'instance', is_demo: bool = True, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, target_sizes: list[tuple[int, int]] | None = None, return_coco_annotation: bool | None = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L820)

**参数：**

outputs (`OneFormerForUniversalSegmentationOutput`) : `OneFormerForUniversalSegmentationOutput` 的输出。

task_type (`str`, *可选*, 默认为 "instance") : 后处理取决于任务标记输入。如果 `task_type` 为 "panoptic"，则需要忽略 stuff 预测。

is_demo (`bool`, *可选*, 默认为 `True`) : 模型是否处于演示模式。如果为 true，则使用阈值来预测最终掩码。

threshold (`float`, *可选*，默认为 0.5)：用于保留预测实例掩码的概率分数阈值。

mask_threshold (`float`，*可选*，默认值为 0.5)：将预测掩码转换为二值时使用的阈值。

overlap_mask_area_threshold (`float`, *可选*，默认为 0.8)：用于合并或丢弃每个二值实例掩码内部小的不连通部分的重叠掩码面积阈值。

target_sizes (`List[Tuple]`, *可选*) : 长度为 (batch_size) 的列表，其中每个列表项 (`Tuple[int, int]]`) 对应批处理中每个预测所需的最终尺寸（高度、宽度）。如果设置为 None，则不会调整预测结果的尺寸。

return_coco_annotation (`bool`，*可选*，默认为 `False`)：是否以 COCO 格式返回预测结果。

**返回：** `List[Dict]`

一个字典列表，每张图片对应一个字典，每个字典包含两个键：
- **segmentation** -- 形状为 `(height, width)` 的张量，其中每个像素代表一个 `segment_id`，如果未找到高于 `threshold` 的掩码，则设置为 `None`。如果指定了 `target_sizes`，则 segmentation 会被调整大小以对应 `target_sizes` 中的相应条目。
- **segments_info** -- 一个包含每个片段附加信息的字典。
  - **id** -- 一个表示 `segment_id` 的整数。
  - **label_id** -- 一个整数，表示与 `segment_id` 对应的标签/语义类别 ID。
  - **was_fused** -- 一个布尔值，如果 `label_id` 在 `label_ids_to_fuse` 中，则为 `True`，否则为 `False`。同一类别/标签的多个实例已被融合，并被分配了单一的 `segment_id`。
  - **score** -- 具有 `segment_id` 的片段的预测分数。

将 `OneFormerForUniversalSegmentationOutput` 的输出转换为图像实例分割预测。仅支持 PyTorch。

#### post_process_panoptic_segmentation[[transformers.OneFormerImageProcessorPil.post_process_panoptic_segmentation]]

```python
post_process_panoptic_segmentation(outputs, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, label_ids_to_fuse: set[int] | None = None, target_sizes: list[tuple[int, int]] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L940)

**参数：**

outputs (`MaskFormerForInstanceSegmentationOutput`) : [MaskFormerForInstanceSegmentation](/docs/transformers/main/zh/model_doc/maskformer#transformers.MaskFormerForInstanceSegmentation) 的输出。

threshold (`float`, *可选*，默认为 0.5)：用于保留预测实例掩码的概率分数阈值。

mask_threshold (`float`，*可选*，默认值为 0.5)：将预测掩码转换为二值时使用的阈值。

overlap_mask_area_threshold (`float`, *可选*，默认为 0.8)：用于合并或丢弃每个二值实例掩码内部小的不连通部分的重叠掩码面积阈值。

label_ids_to_fuse (`Set[int]`, *可选*) : 在此状态下，标签的所有实例将被融合在一起。例如，我们可以说一张图像中只能有一个天空，但可以有多个行人，因此天空的标签 ID 会包含在该集合中，而行人的标签 ID 则不会。

target_sizes (`list[Tuple]`，*可选*)：长度为 (batch_size) 的列表，其中每个列表项 (`tuple[int, int]]`) 对应批处理中每个预测所需的最终尺寸（高度、宽度）。如果设为 None，则不会调整预测结果的尺寸。

**返回：** `list[Dict]`

一个字典列表，每张图片对应一个字典，每个字典包含两个键：
- **segmentation** -- 形状为 `(height, width)` 的张量，其中每个像素代表一个 `segment_id`，如果未找到高于 `threshold` 的掩码，则设置为 `None`。如果指定了 `target_sizes`，则 segmentation 会被调整大小以对应 `target_sizes` 中的相应条目。
- **segments_info** -- 一个包含每个片段附加信息的字典。
  - **id** -- 一个表示 `segment_id` 的整数。
  - **label_id** -- 一个整数，表示与 `segment_id` 对应的标签/语义类别 ID。
  - **was_fused** -- 一个布尔值，如果 `label_id` 在 `label_ids_to_fuse` 中，则为 `True`，否则为 `False`。同一类别/标签的多个实例已被融合，并被分配了单一的 `segment_id`。
  - **score** -- 具有 `segment_id` 的片段的预测分数。

将 `MaskFormerForInstanceSegmentationOutput` 的输出转换为图像全景分割预测。仅支持 PyTorch。

## OneFormerProcessor[[transformers.OneFormerProcessor]]

#### transformers.OneFormerProcessor[[transformers.OneFormerProcessor]]

```python
transformers.OneFormerProcessor(image_processor = None, tokenizer = None, max_seq_length: int = 77, task_seq_length: int = 77, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/processing_oneformer.py#L27)

**参数：**

image_processor (`OneFormerImageProcessor`)：图像处理器是必需的输入。

tokenizer (`CLIPTokenizer`)：分词器是必需的输入。

max_seq_length (`int`，*可选*，默认为 `77`)：用于编码类名和文本输入的最大序列长度。此参数控制在对类名和其他文本输入进行分词时，模型所使用的最大 token 数量。

task_seq_length (`int`, *可选*，默认为 `77`) : 专门用于编码任务描述的最大序列长度。任务描述（例如“the task is semantic”）将在此长度限制下进行分词，该限制可能与通用文本的序列长度不同。

构建一个 OneFormerProcessor，它将图像处理器和分词器封装为单个处理器。

[OneFormerProcessor](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerProcessor) 提供了 [OneFormerImageProcessor](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerImageProcessor) 和 [CLIPTokenizer](/docs/transformers/main/zh/model_doc/clip#transformers.CLIPTokenizer) 的所有功能。有关更多信息，请参阅 [~OneFormerImageProcessor](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerImageProcessor) 和 [~CLIPTokenizer](/docs/transformers/main/zh/model_doc/clip#transformers.CLIPTokenizer)。

#### __调用__[[transformers.OneFormerProcessor.__call__]]

```python
__call__(images = None, task_inputs = None, segmentation_maps = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/processing_oneformer.py#L61)

**参数：**

images (``) : Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.

task_inputs (`str` 或 `list[str]`，*必需*)：分割的任务类型。必须是 `"semantic"`、`"instance"` 或 `"panoptic"` 中的一个或多个。对于单张图像，可以是单个字符串；对于批量处理，可以是字符串列表（每张图像对应一个）。任务类型决定了模型将在输入图像上执行哪种类型的分割。

segmentation_maps (`ImageInput`，*可选*)：对应的语义分割图，包含逐像素的标注。 (`bool`，*可选*，默认为 `True`)：是否将图像填充至批次中最大图像的尺寸并创建像素掩码。 如果保留默认值，将返回一个像素掩码，其中： - 真实像素（即 **未掩码**）的值为 1， - 填充像素（即 **已掩码**）的值为 0。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

**返回：** [BatchFeature](/docs/transformers/main/zh/main_classes/feature_extractor#transformers.BatchFeature)

一个包含以下字段的 [BatchFeature](/docs/transformers/main/zh/main_classes/feature_extractor#transformers.BatchFeature)：
- **task_inputs** -- 要输入模型的 token id 列表。当 `text` 不为 `None` 时返回。
- **pixel_values** -- 输入模型的像素值。当 `images` 不为 `None` 时返回。

## OneFormerModel[[transformers.OneFormerModel]]

#### transformers.OneFormerModel[[transformers.OneFormerModel]]

```python
transformers.OneFormerModel(config: OneFormerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L2855)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.OneFormerModel.forward]]

```python
forward(pixel_values: Tensor, task_inputs: Tensor, text_inputs: typing.Optional[torch.Tensor] = None, pixel_mask: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, output_attentions: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L2872)

**参数：**

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

task_inputs (`torch.Tensor`，形状为 `(batch_size, sequence_length)`)：任务输入。可以使用 [AutoImageProcessor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoImageProcessor) 获取任务输入。有关详细信息，请参阅 [OneFormerProcessor.__call__()](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerProcessor.__call__)。

text_inputs (`list[torch.Tensor]`, *可选*) : 形状为 `(num_queries, sequence_length)` 的张量，用于输入模型

pixel_mask (`torch.Tensor`，形状为 `(batch_size, height, width)`，*可选*)：用于避免对填充像素值执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 1 表示真实像素（即 **未掩码**）， - 0 表示填充像素（即 **已掩码**）。 [什么是注意力掩码？](../glossary#attention-mask)

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** [OneFormerModelOutput](/docs/transformers/main/zh/model_doc/oneformer#transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput) 或 `tuple(torch.Tensor)`

一个 [OneFormerModelOutput](/docs/transformers/main/zh/model_doc/oneformer#transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[OneFormerConfig](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerConfig)）和输入。

[OneFormerModel](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerModel) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **encoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层的输出以及每个阶段的输出），形状为 `(batch_size, num_channels, height, width)`。编码器模型在每个阶段输出处的隐藏状态（也称为特征图）。
- **pixel_decoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层输出以及每个阶段的输出各一个），形状为 `(batch_size, num_channels, height, width)`。像素解码器模型在每个阶段输出处的隐藏状态（也称为特征图）。
- **transformer_decoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层的输出以及每个阶段的输出），形状为 `(batch_size, sequence_length, hidden_size)`。Transformer 解码器在每个阶段输出处的隐藏状态（也称为特征图）。
- **transformer_decoder_object_queries**（形状为 `(batch_size, num_queries, hidden_dim)` 的 `torch.Tensor`）-- 来自 Transformer 解码器最后一层的输出对象查询。
- **transformer_decoder_contrastive_queries**（形状为 `(batch_size, num_queries, hidden_dim)` 的 `torch.Tensor`）-- 来自 transformer decoder 的对比查询。
- **transformer_decoder_mask_predictions**（形状为 `(batch_size, num_queries, height, width)` 的 `torch.Tensor`）-- 来自 Transformer 解码器最后一层的掩码预测。
- **transformer_decoder_class_predictions**（形状为 `(batch_size, num_queries, num_classes+1)` 的 `torch.Tensor`）-- 来自 Transformer 解码器最后一层的类别预测。
- **transformer_decoder_auxiliary_predictions**（`Tuple`，Dict of `str, torch.Tensor`，*可选*）-- 来自 transformer 解码器每一层的类别和掩码预测的元组。
- **text_queries**（`torch.Tensor`，*可选*，形状为 `(batch_size, num_queries, hidden_dim)`）-- 从输入文本列表派生的文本查询，用于在训练期间计算对比损失。
- **task_token**（形状为 `(batch_size, hidden_dim)` 的 `torch.Tensor`）-- 用于条件化查询的一维任务标记。
- **attentions** (`tuple(tuple(torch.Tensor))`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `tuple(torch.Tensor)` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。来自 transformer 解码器的自注意力和交叉注意力权重。

示例：

```python
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import OneFormerProcessor, OneFormerModel

>>> # download test image
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> # load processor for preprocessing the inputs
>>> processor = OneFormerProcessor.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
>>> model = OneFormerModel.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
>>> inputs = processor(image, ["semantic"], return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> mask_predictions = outputs.transformer_decoder_mask_predictions
>>> class_predictions = outputs.transformer_decoder_class_predictions

>>> f"👉 Mask Predictions Shape: {list(mask_predictions.shape)}, Class Predictions Shape: {list(class_predictions.shape)}"
'👉 Mask Predictions Shape: [1, 150, 128, 171], Class Predictions Shape: [1, 150, 151]'
```

## OneFormerForUniversalSegmentation[[transformers.OneFormerForUniversalSegmentation]]

#### transformers.OneFormerForUniversalSegmentation[[transformers.OneFormerForUniversalSegmentation]]

```python
transformers.OneFormerForUniversalSegmentation(config: OneFormerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L2991)

**参数：**

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

OneFormer 模型，用于实例分割、语义分割和全景分割。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.OneFormerForUniversalSegmentation.forward]]

```python
forward(pixel_values: Tensor, task_inputs: Tensor, text_inputs: typing.Optional[torch.Tensor] = None, mask_labels: list[torch.Tensor] | None = None, class_labels: list[torch.Tensor] | None = None, pixel_mask: typing.Optional[torch.Tensor] = None, output_auxiliary_logits: bool | None = None, output_hidden_states: bool | None = None, output_attentions: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L3058)

**参数：**

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

task_inputs (`torch.Tensor`，形状为 `(batch_size, sequence_length)`)：任务输入。可以使用 [AutoImageProcessor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoImageProcessor) 获取任务输入。有关详细信息，请参阅 [OneFormerProcessor.__call__()](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerProcessor.__call__)。

text_inputs (`list[torch.Tensor]`, *可选*) : 形状为 `(num_queries, sequence_length)` 的张量，用于输入模型

mask_labels (`list[torch.Tensor]`, *可选*) : 要输入到模型中的掩码标签列表，形状为 `(num_labels, height, width)`

class_labels (`list[torch.LongTensor]`, *可选*) : 要输入模型的形状为 `(num_labels, height, width)` 的目标类别标签列表。它们标识 `mask_labels` 的标签，例如，当 `class_labels[i][j]` 时，`mask_labels[i][j]` 的标签。

pixel_mask (`torch.Tensor`，形状为 `(batch_size, height, width)`，*可选*)：用于避免对填充像素值执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 1 表示真实像素（即 **未掩码**）， - 0 表示填充像素（即 **已掩码**）。 [什么是注意力掩码？](../glossary#attention-mask)

output_auxiliary_logits (`bool`, *可选*) : 是否输出辅助 logits。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** [OneFormerForUniversalSegmentationOutput](/docs/transformers/main/zh/model_doc/oneformer#transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput) 或 `tuple(torch.Tensor)`

一个 [OneFormerForUniversalSegmentationOutput](/docs/transformers/main/zh/model_doc/oneformer#transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[OneFormerConfig](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerConfig)）和输入。

[OneFormerForUniversalSegmentation](/docs/transformers/main/zh/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`, *可选*) -- 计算得到的损失，当存在标签时返回。
- **class_queries_logits** (`torch.Tensor`, *可选*) -- 形状为 `(batch_size, num_queries, num_labels + 1)` 的张量，表示每个查询所提议的类别。请注意，`+ 1` 是必需的，因为我们纳入了空类别。
- **masks_queries_logits** (`torch.Tensor`, *可选*) -- 形状为 `(batch_size, num_queries, height, width)` 的张量，表示每个查询对应的预测掩码。
- **auxiliary_predictions** (`List` of Dict of `str, torch.Tensor`, *optional*) -- List of class and mask predictions from each layer of the transformer decoder.
- **encoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层的输出以及每个阶段的输出），形状为 `(batch_size, num_channels, height, width)`。编码器模型在每个阶段输出处的隐藏状态（也称为特征图）。
- **pixel_decoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层输出以及每个阶段的输出各一个），形状为 `(batch_size, num_channels, height, width)`。像素解码器模型在每个阶段输出处的隐藏状态（也称为特征图）。
- **transformer_decoder_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层的输出以及每个阶段的输出），形状为 `(batch_size, sequence_length, hidden_size)`。Transformer 解码器在每个阶段输出处的隐藏状态（也称为特征图）。
- **transformer_decoder_object_queries**（形状为 `(batch_size, num_queries, hidden_dim)` 的 `torch.Tensor`）-- 来自 Transformer 解码器最后一层的输出对象查询。
- **transformer_decoder_contrastive_queries**（形状为 `(batch_size, num_queries, hidden_dim)` 的 `torch.Tensor`）-- 来自 transformer decoder 的对比查询。
- **transformer_decoder_mask_predictions**（形状为 `(batch_size, num_queries, height, width)` 的 `torch.Tensor`）-- 来自 Transformer 解码器最后一层的掩码预测。
- **transformer_decoder_class_predictions**（形状为 `(batch_size, num_queries, num_classes+1)` 的 `torch.Tensor`）-- 来自 Transformer 解码器最后一层的类别预测。
- **transformer_decoder_auxiliary_predictions** (`List` of Dict of `str, torch.Tensor`, *optional*) -- List of class and mask predictions from each layer of the transformer decoder.
- **text_queries**（`torch.Tensor`，*可选*，形状为 `(batch_size, num_queries, hidden_dim)`）-- 从输入文本列表派生的文本查询，用于在训练期间计算对比损失。
- **task_token**（形状为 `(batch_size, hidden_dim)` 的 `torch.Tensor`）-- 用于条件化查询的一维任务标记。
- **attentions** (`tuple(tuple(torch.Tensor))`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `tuple(torch.Tensor)` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。来自 transformer 解码器的自注意力和交叉注意力权重。

示例：

通用分割示例：

```python
>>> from transformers import OneFormerProcessor, OneFormerForUniversalSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch

>>> # load OneFormer fine-tuned on ADE20k for universal segmentation
>>> processor = OneFormerProcessor.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
>>> model = OneFormerForUniversalSegmentation.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")

>>> url = (
...     "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
... )
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> # Semantic Segmentation
>>> inputs = processor(image, ["semantic"], return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> # model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits

>>> # you can pass them to processor for semantic postprocessing
>>> predicted_semantic_map = processor.post_process_semantic_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]
>>> f"👉 Semantic Predictions Shape: {list(predicted_semantic_map.shape)}"
'👉 Semantic Predictions Shape: [512, 683]'

>>> # Instance Segmentation
>>> inputs = processor(image, ["instance"], return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> # model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits

>>> # you can pass them to processor for instance postprocessing
>>> predicted_instance_map = processor.post_process_instance_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]["segmentation"]
>>> f"👉 Instance Predictions Shape: {list(predicted_instance_map.shape)}"
'👉 Instance Predictions Shape: [512, 683]'

>>> # Panoptic Segmentation
>>> inputs = processor(image, ["panoptic"], return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> # model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits

>>> # you can pass them to processor for panoptic postprocessing
>>> predicted_panoptic_map = processor.post_process_panoptic_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]["segmentation"]
>>> f"👉 Panoptic Predictions Shape: {list(predicted_panoptic_map.shape)}"
'👉 Panoptic Predictions Shape: [512, 683]'
```

