# EoMT

## 概述

[仅编码器掩码 Transformer](https://www.tue-mps.org/eomt)（EoMT）模型由 Tommie Kerssies、Niccolò Cavagnero、Alexander Hermans、Narges Norouzi、Giuseppe Averta、Bastian Leibe、Gijs Dubbelman 和 Daan de Geus 在 CVPR 2025 高亮论文 *[Your ViT is Secretly an Image Segmentation Model](https://huggingface.co/papers/2503.19108)* 中提出。EoMT 揭示了 Vision Transformers 无需任务特定组件即可高效执行图像分割。

该论文的摘要如下：

*视觉 Transformer（ViT）在多种计算机视觉任务中展现出卓越的性能和可扩展性。为了将单尺度 ViT 应用于图像分割，现有方法采用卷积适配器生成多尺度特征，使用像素解码器融合这些特征，并借助 Transformer 解码器利用融合后的特征进行预测。本文表明，在模型规模足够大且经过充分预训练的前提下，这些任务特定组件所引入的归纳偏置可以由 ViT 自身学习获得。基于这一发现，我们提出了仅编码器掩码 Transformer（EoMT），它重新利用纯 ViT 架构来执行图像分割。借助大规模模型和预训练，EoMT 取得了与使用任务特定组件的最先进模型相当的分割精度。与此同时，得益于其架构的简洁性，EoMT 的速度显著快于这些方法，例如在使用 ViT-L 时速度最高可达 4 倍。在多种模型规模下，EoMT 在分割精度与预测速度之间实现了最佳平衡，这表明将计算资源用于扩展 ViT 本身，而非增加架构复杂度，是更优的选择。*

该模型由 [Yaswanth Gali](https://huggingface.co/yaswanthgali) 贡献。原始代码可在[此处](https://github.com/tue-mps/eomt)找到。

## 架构信息

`EoMT` 模型使用经过 DINOv2 预训练的、带有 **register tokens** 的 Vision Transformer 作为其骨干网络。EoMT 通过仅依赖编码器来简化分割流程，从而消除了先前方法中常用的任务特定解码器。

在架构上，EoMT 引入了一组小型的 **可学习查询** 和一个轻量级的 **掩码预测模块**。这些查询被注入到编码器的最后几个块中，从而实现图像块与对象查询之间的 **联合注意力**。在训练过程中，应用 **掩码注意力** 以约束每个查询专注于其对应的区域——这有效地模拟了交叉注意力。通过 **掩码退火策略** 逐步移除该约束，从而在不牺牲分割性能的前提下，实现 **高效且无需解码器的推理**。

  <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/eomt_architecture.png"
       alt="drawing" width="500"/>

该模型采用统一架构，并结合针对特定任务的后期处理，支持语义分割、实例分割和全景分割。

## 使用示例

使用 Hugging Face 的 EoMT 实现，对预训练模型进行推理。

### 语义分割

EoMT 模型使用滑动窗口推理来执行语义分割。输入图像会被调整大小，使其较短的一边与目标输入尺寸匹配，然后被分割成重叠的裁剪块。随后，每个裁剪块被送入模型进行推理。推理完成后，将每个裁剪块预测的 logits 重新拼接，并缩放回原始图像尺寸，从而得到最终的分割掩码。

> **注意：**   如果您希望为 **语义分割** 使用自定义目标尺寸，请按以下格式指定：`{"shortest_edge": 512}` 请注意，此处未提供 `longest_edge` —— 这是有意为之。对于语义分割，图像通常会被 **缩放，使得最短边大于或等于目标尺寸**，因此无需指定 longest_edge。

```python
import matplotlib.pyplot as plt
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, EomtForUniversalSegmentation

model_id = "tue-mps/ade20k_semantic_eomt_large_512"
processor = AutoImageProcessor.from_pretrained(model_id)
model = EomtForUniversalSegmentation.from_pretrained(model_id, device_map="auto")

image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)

inputs = processor(
    images=image,
    return_tensors="pt",
)

with torch.inference_mode():
    outputs = model(**inputs)

# Prepare the original image size in the format (height, width)
target_sizes = [(image.height, image.width)]

# Post-process the model outputs to get final segmentation prediction
preds = processor.post_process_semantic_segmentation(
    outputs,
    target_sizes=target_sizes,
)

# Visualize the segmentation mask
plt.imshow(preds[0])
plt.axis("off")
plt.title("Semantic Segmentation")
plt.show()
```

### 实例分割

EoMT 模型使用填充推理（padded inference）来执行实例分割。输入图像会被调整大小，使其较长的一边与目标输入尺寸匹配，较短的一边则通过零填充（zero-padding）形成正方形。随后，生成的掩码（mask）和类别 logits 会经过后处理（改编自 Mask2Former）进行整合，从而生成统一的实例分割图，并附带分割元数据，例如分割 ID、类别标签和置信度分数。

> **注意：**   若要使用自定义目标尺寸，请以字典形式指定尺寸，格式如下：`{"shortest_edge": 512, "longest_edge": 512}` 对于实例分割和全景分割，输入图像将被**缩放并填充**至该目标尺寸。

```python
import matplotlib.pyplot as plt
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, EomtForUniversalSegmentation

model_id = "tue-mps/coco_instance_eomt_large_640"
processor = AutoImageProcessor.from_pretrained(model_id)
model = EomtForUniversalSegmentation.from_pretrained(model_id, device_map="auto")

image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)

inputs = processor(
    images=image,
    return_tensors="pt",
)

with torch.inference_mode():
    outputs = model(**inputs)

# Prepare the original image size in the format (height, width)
target_sizes = [(image.height, image.width)]

# Post-process the model outputs to get final segmentation prediction
preds = processor.post_process_instance_segmentation(
    outputs,
    target_sizes=target_sizes,
)

# Visualize the segmentation mask
plt.imshow(preds[0]["segmentation"])
plt.axis("off")
plt.title("Instance Segmentation")
plt.show()
```

### 全景分割

EoMT 模型采用与实例分割相同的填充推理策略来执行全景分割。在填充和归一化之后，模型同时预测 thing（实例）和 stuff（无定形区域）类别。通过后处理（改编自 Mask2Former）将生成的掩码和类别 logits 进行组合，从而生成统一的全景分割图，以及诸如 segment id、类别标签和置信度分数等分割元数据。

```python
import matplotlib.pyplot as plt
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, EomtForUniversalSegmentation

model_id = "tue-mps/coco_panoptic_eomt_large_640"
processor = AutoImageProcessor.from_pretrained(model_id)
model = EomtForUniversalSegmentation.from_pretrained(model_id, device_map="auto")

image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)

inputs = processor(
    images=image,
    return_tensors="pt",
)

with torch.inference_mode():
    outputs = model(**inputs)

# Prepare the original image size in the format (height, width)
target_sizes = [(image.height, image.width)]

# Post-process the model outputs to get final segmentation prediction
preds = processor.post_process_panoptic_segmentation(
    outputs,
    target_sizes=target_sizes,
)

# Visualize the panoptic segmentation mask
plt.imshow(preds[0]["segmentation"])
plt.axis("off")
plt.title("Panoptic Segmentation")
plt.show()
```

## EomtImageProcessor[[transformers.EomtImageProcessor]]

#### transformers.EomtImageProcessor[[transformers.EomtImageProcessor]]

```python
transformers.EomtImageProcessor(**kwargs: *<class 'transformers.models.eomt.image_processing_eomt.EomtImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_eomt.py#L214)

**参数：**

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

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

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

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

do_split_image (`bool`, *kwargs*, *可选*，默认为 `self.do_split_image`) : 是否将输入图像分割为重叠的补丁以用于语义分割。如果设置为 `True`，输入图像将被分割为大小为 `size["shortest_edge"]` 的补丁，且补丁之间存在重叠。否则，输入图像将被填充至目标大小。

ignore_index (`int`, *kwargs*, *可选*，默认为 `self.ignore_index`) : 分配给分割图中背景像素的标签。如果提供，分割图中标记为 0（背景）的像素将被替换为 `ignore_index`。

构造一个 EomtImageProcessor 图像处理器。

#### preprocess[[transformers.EomtImageProcessor.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: list[torch.Tensor] | None = None, instance_id_to_semantic_id: dict[int, int] | None = None, **kwargs: *<class 'transformers.models.eomt.image_processing_eomt.EomtImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_eomt.py#L273)

**参数：**

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`，*可选*)：用于预处理对应图像的分割图。

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

do_split_image (`bool`, *kwargs*, *可选*，默认为 `self.do_split_image`) : 是否将输入图像分割为重叠的补丁以用于语义分割。如果设置为 `True`，输入图像将被分割为大小为 `size["shortest_edge"]` 的补丁，且补丁之间存在重叠。否则，输入图像将被填充至目标大小。

ignore_index (`int`, *kwargs*, *可选*，默认为 `self.ignore_index`) : 分配给分割图中背景像素的标签。如果提供，分割图中标记为 0（背景）的像素将被替换为 `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.EomtImageProcessor.post_process_semantic_segmentation]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_eomt.py#L502)

**参数：**

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

target_sizes (`list[tuple[int, int]]`) : 一个元组列表（`tuple[int, int]`），包含批次中每张图片的目标尺寸（高度，宽度）。

size (`dict[str, int]`, *可选*) : 中间掩码被插值到的尺寸。默认为 `self.size`。

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)` 均对应目标尺寸。

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

#### post_process_instance_segmentation[[transformers.EomtImageProcessor.post_process_instance_segmentation]]

```python
post_process_instance_segmentation(outputs, target_sizes: list[tuple[int, int]], threshold: float = 0.8, size: dict[str, int] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_eomt.py#L635)

将模型输出后处理为实例分割预测结果。

#### post_process_panoptic_segmentation[[transformers.EomtImageProcessor.post_process_panoptic_segmentation]]

```python
post_process_panoptic_segmentation(outputs, target_sizes: list[tuple[int, int]], threshold: float = 0.8, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, stuff_classes: list[int] | None = None, size: dict[str, int] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_eomt.py#L578)

将模型输出后处理为最终的全景分割预测。

## EomtImageProcessorPil[[transformers.EomtImageProcessorPil]]

#### transformers.EomtImageProcessorPil[[transformers.EomtImageProcessorPil]]

```python
transformers.EomtImageProcessorPil(**kwargs: *<class 'transformers.models.eomt.image_processing_pil_eomt.EomtImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_pil_eomt.py#L215)

**参数：**

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

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

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

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

do_split_image (`bool`, *kwargs*, *可选*，默认为 `self.do_split_image`) : 是否将输入图像分割为重叠的补丁以用于语义分割。如果设置为 `True`，输入图像将被分割为大小为 `size["shortest_edge"]` 的补丁，且补丁之间存在重叠。否则，输入图像将被填充至目标大小。

ignore_index (`int`, *kwargs*, *可选*，默认为 `self.ignore_index`) : 分配给分割图中背景像素的标签。如果提供，分割图中标记为 0（背景）的像素将被替换为 `ignore_index`。

构造一个 EomtImageProcessor 图像处理器。

#### preprocess[[transformers.EomtImageProcessorPil.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: list[torch.Tensor] | None = None, instance_id_to_semantic_id: dict[int, int] | None = None, **kwargs: *<class 'transformers.models.eomt.image_processing_pil_eomt.EomtImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_pil_eomt.py#L281)

**参数：**

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`，*可选*)：用于预处理对应图像的分割图。

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

do_split_image (`bool`, *kwargs*, *可选*，默认为 `self.do_split_image`) : 是否将输入图像分割为重叠的补丁以用于语义分割。如果设置为 `True`，输入图像将被分割为大小为 `size["shortest_edge"]` 的补丁，且补丁之间存在重叠。否则，输入图像将被填充至目标大小。

ignore_index (`int`, *kwargs*, *可选*，默认为 `self.ignore_index`) : 分配给分割图中背景像素的标签。如果提供，分割图中标记为 0（背景）的像素将被替换为 `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.EomtImageProcessorPil.post_process_semantic_segmentation]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_pil_eomt.py#L495)

**参数：**

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

target_sizes (`list[tuple[int, int]]`) : 一个元组列表（`tuple[int, int]`），包含批次中每张图片的目标尺寸（高度，宽度）。

size (`dict[str, int]`, *可选*) : 中间掩码被插值到的尺寸。默认为 `self.size`。

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)` 均对应目标尺寸。

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

#### post_process_instance_segmentation[[transformers.EomtImageProcessorPil.post_process_instance_segmentation]]

```python
post_process_instance_segmentation(outputs, target_sizes: list[tuple[int, int]], threshold: float = 0.8, size: dict[str, int] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_pil_eomt.py#L620)

将模型输出后处理为实例分割预测结果。

#### post_process_panoptic_segmentation[[transformers.EomtImageProcessorPil.post_process_panoptic_segmentation]]

```python
post_process_panoptic_segmentation(outputs, target_sizes: list[tuple[int, int]], threshold: float = 0.8, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, stuff_classes: list[int] | None = None, size: dict[str, int] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/image_processing_pil_eomt.py#L567)

将模型输出后处理为最终的全景分割预测。

## EomtConfig[[transformers.EomtConfig]]

#### transformers.EomtConfig[[transformers.EomtConfig]]

```python
transformers.EomtConfig(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 = 1024, num_hidden_layers: int = 24, num_attention_heads: int = 16, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, image_size: int | list[int] | tuple[int, int] = 640, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, mlp_ratio: int = 4, layerscale_value: float = 1.0, drop_path_rate: float | int = 0.0, num_upscale_blocks: int = 2, attention_dropout: float | int = 0.0, use_swiglu_ffn: bool = False, num_blocks: int = 4, no_object_weight: float = 0.1, class_weight: float = 2.0, mask_weight: float = 5.0, dice_weight: float = 5.0, train_num_points: int = 12544, oversample_ratio: float = 3.0, importance_sample_ratio: float = 0.75, num_queries: int = 200, num_register_tokens: int = 4)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/configuration_eomt.py#L28)

**参数：**

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

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

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

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

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

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

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

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

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

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

mlp_ratio (`int`，*可选*，默认为 `4`)：MLP 隐藏维度与嵌入维度的比率。

layerscale_value (`float`, *可选*，默认为 1.0) : LayerScale 参数的初始值。

drop_path_rate (`Union[float, int]`，*可选*，默认为 `0.0`)：用于 patch 融合的 drop path 比率。

num_upscale_blocks (`int`, *可选*，默认为 2)：解码器或分割头中使用的上采样块数量。

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

use_swiglu_ffn (`bool`, *可选*, 默认为 `False`) : 是否使用 SwiGLU 前馈神经网络。

num_blocks (`int`，*可选*，默认为 4)：架构中特征块或阶段的数量。

no_object_weight (`float`, *可选*，默认为 0.1)：全景/实例分割中“无目标”类别的损失权重。

class_weight (`float`, *可选*, 默认值为 2.0) : 分类目标的损失权重。

mask_weight (`float`, *可选*, 默认值为 5.0) : 掩码预测的损失权重。

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

train_num_points (`int`, *可选*, 默认为 12544) : 训练期间用于计算掩码损失的采样点数。

oversample_ratio (`float`, *可选*，默认为 3.0)：在掩码训练的点采样中使用的过采样率。

importance_sample_ratio (`float`, *可选*, 默认值为 0.75) : 训练期间基于重要性采样的点比例。

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

num_register_tokens (`int`，*可选*，默认为 4)：添加到 Transformer 输入中的可学习寄存器 token 数量。

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

配置对象继承自 [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 EomtConfig, EomtForUniversalSegmentation

>>> # Initialize configuration
>>> config = EomtConfig()

>>> # Initialize model
>>> model = EomtForUniversalSegmentation(config)

>>> # Access config
>>> config = model.config
```

## EomtForUniversalSegmentation[[transformers.EomtForUniversalSegmentation]]

#### transformers.EomtForUniversalSegmentation[[transformers.EomtForUniversalSegmentation]]

```python
transformers.EomtForUniversalSegmentation(config: EomtConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/modeling_eomt.py#L1016)

**参数：**

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

用于实例/语义/全景分割的 EoMT 模型，其顶部带有 head。

该模型继承自 [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.EomtForUniversalSegmentation.forward]]

```python
forward(pixel_values: Tensor, mask_labels: list[torch.Tensor] | None = None, class_labels: list[torch.Tensor] | None = None, patch_offsets: list[torch.Tensor] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/eomt/modeling_eomt.py#L1074)

**参数：**

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

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]` 的标签。

patch_offsets (`list[torch.Tensor]`, *可选*) : 一个元组列表，指示用于语义分割的图像索引以及补丁的起始和结束位置。

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

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

[EomtForUniversalSegmentation](/docs/transformers/v5.23.0/zh/model_doc/eomt#transformers.EomtForUniversalSegmentation) 的 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)` 的张量，表示每个查询对应的预测掩码。
- **last_hidden_state**（形状为 `(batch_size, num_channels, height, width)` 的 `torch.Tensor`）-- 最后一层的最后隐藏状态（最终特征图）。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层的输出以及每个阶段的输出），形状为 `(batch_size, sequence_length, hidden_size)`。模型所有层的隐藏状态。
- **attentions** (`tuple(tuple(torch.Tensor))`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `tuple(torch.Tensor)` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。来自 transformer 解码器的自注意力和交叉注意力权重。
- **patch_offsets** (`list[torch.Tensor]`，*可选*) -- 一个元组列表，指示用于语义分割的图像索引以及补丁的起始和结束位置。

