Transformers documentation

EoMT

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2025-03-24 在 HF papers 上发布,并于 2025-06-27 贡献至 Hugging Face Transformers。

EoMT

概述

仅编码器掩码 Transformer(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 中提出。 EoMT 表明,Vision Transformer 无需任务特定组件即可高效执行图像分割。

该论文的摘要如下:

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

该模型由 Yaswanth Gali 贡献。 原始代码可在此处找到。

架构信息

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

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

drawing

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

使用示例

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

语义分割

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

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

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}
对于实例分割和全景分割,输入图像将被缩放并填充至该目标尺寸。

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、类别标签和置信度分数等分割元数据。

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

class transformers.EomtImageProcessor

< >

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

参数

  • 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 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.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 图像处理器。

预处理

< >

( 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 = Noneinstance_id_to_semantic_id: dict[int, int] | None = None**kwargs: *<class 'transformers.models.eomt.image_processing_eomt.EomtImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • 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 为整数时,是否在调整大小时默认使用正方形图像。
  • 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

< >

( outputstarget_sizes: listsize: dict[str, int] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]

参数

  • outputs (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 的输出转换为语义分割图。

post_process_instance_segmentation

< >

( outputstarget_sizes: listthreshold: float = 0.8size: dict[str, int] | None = None )

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

post_process_panoptic_segmentation

< >

( outputstarget_sizes: listthreshold: float = 0.8mask_threshold: float = 0.5overlap_mask_area_threshold: float = 0.8stuff_classes: list[int] | None = Nonesize: dict[str, int] | None = None )

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

EomtImageProcessorPil

class transformers.EomtImageProcessorPil

< >

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

参数

  • 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 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.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 图像处理器。

预处理

< >

( 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 = Noneinstance_id_to_semantic_id: dict[int, int] | None = None**kwargs: *<class 'transformers.models.eomt.image_processing_pil_eomt.EomtImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
  • 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 为整数时,是否在调整大小时默认使用正方形图像。
  • 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

< >

( outputstarget_sizes: listsize: dict[str, int] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]

参数

  • outputs (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 的输出转换为语义分割图。

post_process_instance_segmentation

< >

( outputstarget_sizes: listthreshold: float = 0.8size: dict[str, int] | None = None )

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

post_process_panoptic_segmentation

< >

( outputstarget_sizes: listthreshold: float = 0.8mask_threshold: float = 0.5overlap_mask_area_threshold: float = 0.8stuff_classes: list[int] | None = Nonesize: dict[str, int] | None = None )

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

EomtConfig

class transformers.EomtConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1024num_hidden_layers: int = 24num_attention_heads: int = 16hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06image_size: int | list[int] | tuple[int, int] = 640patch_size: int | list[int] | tuple[int, int] = 16num_channels: int = 3mlp_ratio: int = 4layerscale_value: float = 1.0drop_path_rate: float | int = 0.0num_upscale_blocks: int = 2attention_dropout: float | int = 0.0use_swiglu_ffn: bool = Falsenum_blocks: int = 4no_object_weight: float = 0.1class_weight: float = 2.0mask_weight: float = 5.0dice_weight: float = 5.0train_num_points: int = 12544oversample_ratio: float = 3.0importance_sample_ratio: float = 0.75num_queries: int = 200num_register_tokens: int = 4 )

参数

  • 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 fusion 的 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 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import EomtConfig, EomtForUniversalSegmentation

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

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

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

EomtForUniversalSegmentation

class transformers.EomtForUniversalSegmentation

< >

( config: EomtConfig )

参数

  • config (EomtConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensormask_labels: list[torch.Tensor] | None = Noneclass_labels: list[torch.Tensor] | None = Nonepatch_offsets: list[torch.Tensor] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → EomtForUniversalSegmentationOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 EomtImageProcessor 获取像素值。有关详细信息,请参阅 EomtImageProcessor.call()(processor_class 使用 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],可选) — 一个元组列表,指示用于语义分割的图像索引以及 patch 的起始和结束位置。

返回值

EomtForUniversalSegmentationOutput 或 tuple(torch.Tensor)

EomtForUniversalSegmentationOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(EomtConfig)和输入。

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],可选) — 一个元组列表,指示用于语义分割的图像索引以及 patch 的起始和结束位置。
Update on GitHub