Transformers documentation

MaskFormer

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2021-07-13 在 HF papers 上发布,并于 2022-03-02 贡献至 Hugging Face Transformers。

MaskFormer

这是一个近期推出的模型,因此其 API 尚未经过充分测试。未来可能会修复一些 bug 或轻微的破坏性变更。如果您发现任何异常,请提交一个 Github Issue。

概述

The MaskFormer model was proposed in Per-Pixel Classification is Not All You Need for Semantic Segmentation by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov. MaskFormer addresses semantic segmentation with a mask classification paradigm instead of performing classic pixel-level classification.

该论文的摘要如下:

现代方法通常将语义分割表述为逐像素分类任务,而实例级分割则通过另一种掩码分类来处理。我们的核心洞察是:掩码分类具有足够的通用性,能够使用完全相同的模型、损失函数和训练流程,以统一的方式同时解决语义级和实例级分割任务。基于这一观察,我们提出了 MaskFormer,一个简单的掩码分类模型,它预测一组二值掩码,每个掩码都关联一个全局类别标签预测。总体而言,所提出的基于掩码分类的方法简化了语义分割和全景分割任务中有效方法的格局,并展示了出色的实证结果。特别是,我们观察到,当类别数量较大时,MaskFormer 的表现优于逐像素分类基线。我们的基于掩码分类的方法在语义分割(ADE20K 上 55.6 mIoU)和全景分割(COCO 上 52.7 PQ)两方面均超越了当前最先进的模型。

下图展示了 MaskFormer 的架构。摘自原始论文。

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

使用技巧

  • MaskFormer 的 Transformer 解码器与 DETR 的解码器完全相同。在训练过程中,DETR 的作者发现使用辅助损失很有帮助,尤其是帮助模型输出每个类别的正确对象数量。如果将 MaskFormerConfig 的参数 use_auxiliary_loss 设置为 True,则会在每个解码器层之后添加预测前馈神经网络和匈牙利损失(这些 FFN 共享参数)。
  • 如果要在跨多个节点的分布式环境中训练模型,则应更新 modeling_maskformer.py 中 MaskFormerLoss 类内的 get_num_masks 函数。在多节点训练时,该值应设置为所有节点上目标掩码数量的平均值,具体可参见原始实现中的此处。
  • 可以使用 MaskFormerImageProcessor 为模型准备图像以及可选的目标。
  • 要获取最终的分割结果,根据任务的不同,您可以调用 post_process_semantic_segmentation() 或 post_process_panoptic_segmentation()。这两项任务都可以使用 MaskFormerForInstanceSegmentation 的输出来解决,其中全景分割接受一个可选的 label_ids_to_fuse 参数,用于将目标对象(例如天空)的实例融合在一起。

资源

Image Segmentation
  • 所有演示如何使用 MaskFormer 进行推理以及在自定义数据上进行微调的笔记本均可在此处找到。

MaskFormer 特定输出

类 transformers.models.maskformer.modeling_maskformer.MaskFormerModelOutput

< >

( encoder_last_hidden_state: typing.Optional[torch.Tensor] = Nonepixel_decoder_last_hidden_state: typing.Optional[torch.Tensor] = Nonetransformer_decoder_last_hidden_state: typing.Optional[torch.Tensor] = Noneencoder_hidden_states: tuple[torch.Tensor] | None = Nonepixel_decoder_hidden_states: tuple[torch.Tensor] | None = Nonetransformer_decoder_hidden_states: tuple[torch.Tensor] | None = Nonehidden_states: tuple[torch.Tensor] | None = Noneattentions: tuple[torch.Tensor] | None = None )

参数

  • encoder_last_hidden_state (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 编码器模型(backbone)最后阶段的最后隐藏状态(最终特征图)。
  • pixel_decoder_last_hidden_state (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 像素解码器模型(FPN)最后阶段的最后隐藏状态(最终特征图)。
  • transformer_decoder_last_hidden_state (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size)) — 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 解码器在每个阶段输出处的隐藏状态(也称为特征图)。
  • hidden_states tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 包含 encoder_hidden_states、pixel_decoder_hidden_states 和 decoder_hidden_states 的 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[torch.Tensor], 可选, 在传入 output_attentions=True 或 config.output_attentions=True) — 的元组 torch.Tensor ((每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length).

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

MaskFormerModel 的输出类。该类返回计算 logits 所需的所有隐藏状态。

类 transformers.models.maskformer.modeling_maskformer.MaskFormerForInstanceSegmentationOutput

< >

( loss: typing.Optional[torch.Tensor] = Noneclass_queries_logits: typing.Optional[torch.Tensor] = Nonemasks_queries_logits: typing.Optional[torch.Tensor] = Noneauxiliary_logits: typing.Optional[torch.Tensor] = Noneencoder_last_hidden_state: typing.Optional[torch.Tensor] = Nonepixel_decoder_last_hidden_state: typing.Optional[torch.Tensor] = Nonetransformer_decoder_last_hidden_state: typing.Optional[torch.Tensor] = Noneencoder_hidden_states: tuple[torch.Tensor] | None = Nonepixel_decoder_hidden_states: tuple[torch.Tensor] | None = Nonetransformer_decoder_hidden_states: tuple[torch.Tensor] | None = Nonehidden_states: tuple[torch.Tensor] | None = Noneattentions: tuple[torch.Tensor] | None = None )

参数

  • 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_logits (Dict[str, torch.Tensor],可选,当 output_auxiliary_logits=True 时返回) — 当启用辅助损失时,包含每个解码器层辅助预测的字典。
  • encoder_last_hidden_state (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 编码器模型(backbone)最后阶段的最后隐藏状态(最终特征图)。
  • pixel_decoder_last_hidden_state (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 像素解码器模型(FPN)最后阶段的最后隐藏状态(最终特征图)。
  • transformer_decoder_last_hidden_state (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size)) — 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 解码器在每个阶段输出处的隐藏状态。
  • hidden_states tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 包含 encoder_hidden_states、pixel_decoder_hidden_states 和 decoder_hidden_states 的 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[torch.Tensor], 可选, 在传入 output_attentions=True 或 config.output_attentions=True) — 的元组 torch.Tensor ((每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length).

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

MaskFormerForInstanceSegmentation 的输出类。

该输出可以直接传递给 post_process_semantic_segmentation() 或 post_process_instance_segmentation() 或 post_process_panoptic_segmentation(),具体取决于任务。有关用法的详细信息,请参阅 [`~MaskFormerImageProcessor]。

MaskFormerDetrConfig

类 transformers.MaskFormerDetrConfig

< >

( 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 = 0id2label: 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 = Noneis_encoder_decoder: bool = Truebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonenum_channels: int = 3num_queries: int = 100encoder_layers: int = 6encoder_ffn_dim: int = 2048encoder_attention_heads: int = 8decoder_layers: int = 6decoder_ffn_dim: int = 2048decoder_attention_heads: int = 8encoder_layerdrop: float | int = 0.0decoder_layerdrop: float | int = 0.0activation_function: str = 'relu'd_model: int = 256dropout: float | int = 0.1attention_dropout: float | int = 0.0activation_dropout: float | int = 0.0init_std: float = 0.02init_xavier_std: float = 1.0auxiliary_loss: bool = Falseposition_embedding_type: str = 'sine'dilation: bool = Falseclass_cost: int = 1bbox_cost: int = 5giou_cost: int = 2mask_loss_coefficient: int = 1dice_loss_coefficient: int = 1bbox_loss_coefficient: int = 5giou_loss_coefficient: int = 2eos_coefficient: float = 0.1 )

参数

  • is_encoder_decoder (bool,可选,默认为 True) — 指示该模型是否用作编码器/解码器。
  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • num_queries (int, 可选,默认为 100) — 对象查询的数量,即检测槽位。这是 ConditionalDetrModel 在单张图像中可检测到的最大对象数量。对于 COCO,我们建议使用 100 个查询。
  • encoder_layers (int,可选,默认为 6) — Transformer 编码器中的隐藏层数量。如果未设置,将使用与 num_layers 相同的值。
  • encoder_ffn_dim (int,可选,默认为 2048) — 编码器中“中间”(通常称为前馈)层的维度。
  • encoder_attention_heads (int,可选,默认为 8) — Transformer 编码器中每个注意力层的注意力头数量。
  • decoder_layers (int, 可选,默认为 6) — Transformer 解码器中的隐藏层数量。如果未设置,将使用与 num_layers 相同的值。
  • decoder_ffn_dim (int,可选,默认为 2048) — 解码器中“中间”(通常称为前馈)层的维度。
  • decoder_attention_heads (int,可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • encoder_layerdrop (Union[float, int],可选,默认值为 0.0) — 编码器的 LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。
  • decoder_layerdrop (Union[float, int],可选,默认为 0.0) — 解码器的 LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。
  • activation_function (str,可选,默认为 relu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu" 等。
  • d_model (int,可选,默认为 256) — 编码器层和池化层的维度大小。
  • dropout (Union[float, int],可选,默认为 0.1) — 所有 dropout 层的比率。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • activation_dropout (Union[float, int],可选,默认为 0.0) — 全连接层中激活值的 dropout 比率。
  • init_std (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • init_xavier_std (float,可选,默认为 1.0) — 用于交叉注意力权重 Xavier 初始化的缩放因子。
  • auxiliary_loss (bool,可选,默认为 False) — 是否使用辅助解码损失(即每个解码器层的损失)。
  • position_embedding_type (str,可选,默认为 "sine") — 用于叠加在图像特征之上的位置嵌入类型。取值为 "sine" 或 "learned" 之一。
  • dilation (bool,可选,默认为 False) — 是否将最后一个卷积块(DC5)中的 stride 替换为 dilation。仅在 use_timm_backbone = True 时支持。
  • class_cost (int,可选,默认为 1) — 匈牙利匹配代价中分类误差的相对权重。
  • bbox_cost (int,可选,默认为 5) — 匈牙利匹配代价中 L1 边界框误差的相对权重。
  • giou_cost (int,可选,默认为 2) — 匈牙利匹配代价中广义 IoU 损失的相对权重。
  • mask_loss_coefficient (int,可选,默认为 1) — 全景分割损失中焦点损失的相对权重。
  • dice_loss_coefficient (int,可选,默认为 1) — 在全景分割损失中,Dice 损失的相对权重。
  • bbox_loss_coefficient (int,可选,默认为 5) — 全景分割损失中 L1 边界框损失的相对权重。
  • giou_loss_coefficient (int,可选,默认值为 2) — 全景分割损失中广义 IoU 损失的相对权重。
  • eos_coefficient (float,可选,默认为 0.1) — 目标检测损失中“无目标”类别的相对分类权重。

这是用于存储 MaskFormerModel 配置的类。它根据指定的参数实例化 Maskformer 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/maskformer-swin-base-ade 类似的配置。

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

示例:

>>> from transformers import MaskFormerDetrConfig, MaskFormerDetrModel

>>> # Initializing a MASK_FORMER_DETR facebook/mask_former_detr-resnet-50 style configuration
>>> configuration = MaskFormerDetrConfig()

>>> # Initializing a model (with random weights) from the facebook/mask_former_detr-resnet-50 style configuration
>>> model = MaskFormerDetrModel(configuration)

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

MaskFormerConfig

class transformers.MaskFormerConfig

< >

( 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 = Nonefpn_feature_size: int = 256mask_feature_size: int = 256no_object_weight: float = 0.1use_auxiliary_loss: bool = Falsebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonedecoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinit_std: float = 0.02init_xavier_std: float = 1.0dice_weight: float = 1.0cross_entropy_weight: float = 1.0mask_weight: float = 20.0output_auxiliary_logits: bool | None = None )

参数

  • fpn_feature_size (int, 可选,默认为 256) — 特征金字塔网络(Feature Pyramid Network)的特征尺寸。
  • mask_feature_size (int,可选,默认为 256) — 掩码的特征尺寸,该值同时用于指定特征金字塔网络(Feature Pyramid Network)特征的尺寸。
  • no_object_weight (float, 可选,默认为 0.1) — 目标检测损失中无目标类别的相对分类权重。
  • use_auxiliary_loss (bool,可选,默认为 False) — 是否使用 transformer decoder 的中间预测来计算损失。
  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。
  • decoder_config (Dict, 可选) — 传递给 transformer 解码器模型的配置。如果未设置,将使用 detr-resnet-50 的基础配置。
  • init_std (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • init_xavier_std (float,可选,默认为 1.0) — 用于交叉注意力权重 Xavier 初始化的缩放因子。
  • dice_weight (float, 可选,默认为 1.0) — 全景分割损失中 dice 损失的相对权重。
  • cross_entropy_weight (float,可选,默认为 1.0) — 交叉熵损失的权重。
  • mask_weight (float, 可选,默认为 20.0) — 全景分割损失中焦点损失的相对权重。
  • output_auxiliary_logits (bool, 可选) — 是否让模型输出其 auxiliary_logits。

引发

ValueError

  • ValueError — 如果所选的骨干网络模型类型不在 ["swin"] 中,或所选的解码器模型类型不在 ["detr"] 中,则引发此错误

这是用于存储 MaskFormerModel 配置的类。它根据指定的参数实例化 Maskformer 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/maskformer-swin-base-ade 类似的配置。

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

示例:

>>> from transformers import MaskFormerConfig, MaskFormerModel

>>> # Initializing a MaskFormer facebook/maskformer-swin-base-ade configuration
>>> configuration = MaskFormerConfig()

>>> # Initializing a model (with random weights) from the facebook/maskformer-swin-base-ade style configuration
>>> model = MaskFormerModel(configuration)

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

MaskFormerImageProcessor

class transformers.MaskFormerImageProcessor

< >

( **kwargs: *<class 'transformers.models.maskformer.image_processing_maskformer.MaskFormerImageProcessorKwargs'> )

参数

  • 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' -- 800, 'longest_edge': 1333}): 描述输入到模型的最大尺寸。
  • 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, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (SizeDict, kwargs, 可选) — 用于填充图像的目标尺寸。必须大于预处理中提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ignore_index (int, kwargs, 可选) — 分配给分割图中背景像素的标签。如果提供,分割图中标记为 0(背景)的像素将被替换为 ignore_index。
  • do_reduce_labels (bool,kwargs,可选,默认为 False) — 是否将所有分割图标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 ignore_index。
  • num_labels (int,kwargs,可选) — 分割图中的标签数量。
  • size_divisor (int,kwargs,可选,默认值为 32) — 某些骨干网络要求图像尺寸能被特定数值整除。如果未传入该参数,则默认使用 Swin Transformer 中的值。

构建一个 MaskFormerImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Noneinstance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None**kwargs: *<class 'transformers.models.maskformer.image_processing_maskformer.MaskFormerImageProcessorKwargs'> ) → ~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 (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 为整数时,是否在调整大小时默认使用正方形图像。
  • 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 (SizeDict, kwargs, 可选) — 用于填充图像的目标尺寸。必须大于预处理中提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ignore_index (int, kwargs, 可选) — 分配给分割图中背景像素的标签。如果提供,分割图中标记为 0(背景)的像素将被替换为 ignore_index。
  • do_reduce_labels (bool,kwargs,可选,默认为 False) — 是否将所有分割图标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 ignore_index。
  • num_labels (int,kwargs,可选) — 分割图中的标签数量。
  • size_divisor (int,kwargs,可选,默认值为 32) — 某些骨干网络要求图像尺寸能被特定数值整除。如果未传入该参数,则默认使用 Swin Transformer 中的值。

返回值

~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: list[tuple[int, int]] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]

参数

  • outputs (MaskFormerForInstanceSegmentation) — 模型的原始输出。
  • 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)。

将 MaskFormerForInstanceSegmentation 的输出转换为语义分割图。仅支持 PyTorch。

post_process_instance_segmentation

< >

( outputsthreshold: float = 0.5mask_threshold: float = 0.5overlap_mask_area_threshold: float = 0.8target_sizes: list[tuple[int, int]] | None = Nonereturn_coco_annotation: bool | None = Falsereturn_binary_maps: bool | None = False ) → list[Dict]

参数

  • outputs (MaskFormerForInstanceSegmentation) — 模型的原始输出。
  • 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) — 如果设置为 True,分割图将以 COCO 游程编码(RLE)格式返回。
  • return_binary_maps (bool,可选,默认为 False) — 如果设置为 True,分割图将以二值分割图拼接张量的形式返回(每个检测到的实例对应一张)。

返回值

list[Dict]

一个字典列表,每张图片对应一个字典,每个字典包含两个键:

  • segmentation — 形状为 (height, width) 的张量,其中每个像素代表一个 segment_id;或者,如果 return_coco_annotation 设置为 True,则为分割图的 list[List] 游程编码(RLE);或者,如果 return_binary_maps 设置为 True,则为形状为 (num_instances, height, width) 的张量。如果未找到高于 threshold 的掩码,则设置为 None。
  • segments_info — 一个包含每个片段附加信息的字典。
    • id — 表示 segment_id 的整数。
    • label_id — 一个整数,表示与 segment_id 对应的标签/语义类别 ID。
    • score — 具有 segment_id 的片段的预测分数。

将 MaskFormerForInstanceSegmentationOutput 的输出转换为实例分割预测。仅支持 PyTorch。如果实例可能重叠,请将 return_coco_annotation 或 return_binary_maps 设置为 True,以获取正确的分割结果。

post_process_panoptic_segmentation

< >

( outputsthreshold: float = 0.5mask_threshold: float = 0.5overlap_mask_area_threshold: float = 0.8label_ids_to_fuse: set[int] | None = Nonetarget_sizes: list[tuple[int, int]] | None = None ) → list[Dict]

参数

  • outputs (MaskFormerForInstanceSegmentationOutput) — 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。

MaskFormerImageProcessorPil

class transformers.MaskFormerImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.maskformer.image_processing_pil_maskformer.MaskFormerImageProcessorKwargs'> )

参数

  • 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' -- 800, 'longest_edge': 1333}): 描述输入到模型的最大尺寸。
  • 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, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (SizeDict, kwargs, 可选) — 用于填充图像的目标尺寸。必须大于预处理中提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ignore_index (int, kwargs, 可选) — 分配给分割图中背景像素的标签。如果提供,分割图中标记为 0(背景)的像素将被替换为 ignore_index。
  • do_reduce_labels (bool,kwargs,可选,默认为 False) — 是否将所有分割图标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 ignore_index。
  • num_labels (int,kwargs,可选) — 分割图中的标签数量。
  • size_divisor (int,kwargs,可选,默认值为 32) — 某些骨干网络要求图像尺寸能被特定数值整除。如果未传入该参数,则默认使用 Swin Transformer 中的值。

构建一个 MaskFormerImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Noneinstance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None**kwargs: *<class 'transformers.models.maskformer.image_processing_pil_maskformer.MaskFormerImageProcessorKwargs'> ) → ~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 (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 为整数时,是否在调整大小时默认使用正方形图像。
  • 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 (SizeDict, kwargs, 可选) — 用于填充图像的目标尺寸。必须大于预处理中提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ignore_index (int, kwargs, 可选) — 分配给分割图中背景像素的标签。如果提供,分割图中标记为 0(背景)的像素将被替换为 ignore_index。
  • do_reduce_labels (bool,kwargs,可选,默认为 False) — 是否将所有分割图标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 ignore_index。
  • num_labels (int,kwargs,可选) — 分割图中的标签数量。
  • size_divisor (int,kwargs,可选,默认值为 32) — 某些骨干网络要求图像尺寸能被特定数值整除。如果未传入该参数,则默认使用 Swin Transformer 中的值。

返回值

~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: list[tuple[int, int]] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]

参数

  • outputs (MaskFormerForInstanceSegmentation) — 模型的原始输出。
  • 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)。

将 MaskFormerForInstanceSegmentation 的输出转换为语义分割图。仅支持 PyTorch。

post_process_instance_segmentation

< >

( outputsthreshold: float = 0.5mask_threshold: float = 0.5overlap_mask_area_threshold: float = 0.8target_sizes: list[tuple[int, int]] | None = Nonereturn_coco_annotation: bool | None = Falsereturn_binary_maps: bool | None = False ) → list[Dict]

参数

  • outputs (MaskFormerForInstanceSegmentation) — 模型的原始输出。
  • 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) — 如果设置为 True,分割图将以 COCO 游程编码(RLE)格式返回。
  • return_binary_maps (bool,可选,默认为 False) — 如果设置为 True,分割图将以二值分割图拼接张量的形式返回(每个检测到的实例对应一张)。

返回值

list[Dict]

一个字典列表,每张图片对应一个字典,每个字典包含两个键:

  • segmentation — 形状为 (height, width) 的张量,其中每个像素代表一个 segment_id;或者,如果 return_coco_annotation 设置为 True,则为分割图的 list[List] 游程编码(RLE);或者,如果 return_binary_maps 设置为 True,则为形状为 (num_instances, height, width) 的张量。如果未找到高于 threshold 的掩码,则设置为 None。
  • segments_info — 一个包含每个片段附加信息的字典。
    • id — 表示 segment_id 的整数。
    • label_id — 一个整数,表示与 segment_id 对应的标签/语义类别 ID。
    • score — 具有 segment_id 的片段的预测分数。

将 MaskFormerForInstanceSegmentationOutput 的输出转换为实例分割预测。仅支持 PyTorch。如果实例可能重叠,请将 return_coco_annotation 或 return_binary_maps 设置为 True,以获取正确的分割结果。

post_process_panoptic_segmentation

< >

( outputsthreshold: float = 0.5mask_threshold: float = 0.5overlap_mask_area_threshold: float = 0.8label_ids_to_fuse: set[int] | None = Nonetarget_sizes: list[tuple[int, int]] | None = None ) → list[Dict]

参数

  • outputs (MaskFormerForInstanceSegmentationOutput) — 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。

MaskFormerModel

class transformers.MaskFormerModel

< >

( config: MaskFormerConfig )

参数

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

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

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

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

forward

< >

( pixel_values: Tensorpixel_mask: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Noneoutput_attentions: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → MaskFormerModelOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 MaskFormerImageProcessor 获取像素值。有关详细信息,请参阅 MaskFormerImageProcessor.call()(processor_class 使用 MaskFormerImageProcessor 处理图像)。
  • pixel_mask (torch.Tensor 形状为 (batch_size, height, width), 可选) — 用于避免对填充像素值执行注意力的掩码。掩码值取自 [0, 1]:
    • 对于真实的像素(即未被掩码的像素),值为 1,
    • 对于填充像素(即 被屏蔽 的像素),值为 0。

    什么是注意力掩码?

  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

MaskFormerModelOutput 或 tuple(torch.Tensor)

一个 MaskFormerModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(MaskFormerConfig)和输入。

MaskFormerModel 的 forward 方法重写了 __call__ 特殊方法。

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

  • encoder_last_hidden_state (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 编码器模型(backbone)最后阶段的最后隐藏状态(最终特征图)。

  • pixel_decoder_last_hidden_state (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 像素解码器模型(FPN)最后阶段的最后隐藏状态(最终特征图)。

  • transformer_decoder_last_hidden_state (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size)) — 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 解码器在每个阶段输出处的隐藏状态(也称为特征图)。 hidden_states tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回: 由 torch.Tensor 组成的元组,包含 encoder_hidden_states、pixel_decoder_hidden_states 和 decoder_hidden_states

  • hidden_states (tuple[torch.Tensor],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

示例:

>>> from transformers import AutoImageProcessor, MaskFormerModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> # load MaskFormer fine-tuned on ADE20k semantic segmentation
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/maskformer-swin-base-ade")
>>> model = MaskFormerModel.from_pretrained("facebook/maskformer-swin-base-ade")

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

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

>>> # forward pass
>>> outputs = model(**inputs)

>>> # the decoder of MaskFormer outputs hidden states of shape (batch_size, num_queries, hidden_size)
>>> transformer_decoder_last_hidden_state = outputs.transformer_decoder_last_hidden_state
>>> list(transformer_decoder_last_hidden_state.shape)
[1, 100, 256]

MaskFormerForInstanceSegmentation

class transformers.MaskFormerForInstanceSegmentation

< >

( config: MaskFormerConfig )

forward

< >

( pixel_values: Tensormask_labels: list[torch.Tensor] | None = Noneclass_labels: list[torch.Tensor] | None = Nonepixel_mask: typing.Optional[torch.Tensor] = Noneoutput_auxiliary_logits: bool | None = Noneoutput_hidden_states: bool | None = Noneoutput_attentions: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → MaskFormerForInstanceSegmentationOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 MaskFormerImageProcessor 获取像素值。有关详细信息,请参阅 MaskFormerImageProcessor.call()(processor_class 使用 MaskFormerImageProcessor 处理图像)。
  • 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。

    什么是注意力掩码?

  • output_auxiliary_logits (bool, 可选) — 是否输出辅助 logits。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

MaskFormerForInstanceSegmentationOutput 或 tuple(torch.Tensor)

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

MaskFormerForInstanceSegmentation 的 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_logits (Dict[str, torch.Tensor],可选,当 output_auxiliary_logits=True 时返回) — 当启用辅助损失时,包含每个解码器层辅助预测的字典。

  • encoder_last_hidden_state (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 编码器模型(backbone)最后阶段的最后隐藏状态(最终特征图)。

  • pixel_decoder_last_hidden_state (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 像素解码器模型(FPN)最后阶段的最后隐藏状态(最终特征图)。

  • transformer_decoder_last_hidden_state (torch.Tensor,形状为 (batch_size, sequence_length, hidden_size)) — 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 解码器在每个阶段输出处的隐藏状态。 hidden_states tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回: 由 torch.Tensor 组成的元组,包含 encoder_hidden_states、pixel_decoder_hidden_states 和 decoder_hidden_states。

  • hidden_states (tuple[torch.Tensor],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple[torch.Tensor],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

示例:

语义分割示例:

>>> from transformers import AutoImageProcessor, MaskFormerForInstanceSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> # load MaskFormer fine-tuned on ADE20k semantic segmentation
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/maskformer-swin-base-ade")
>>> model = MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-base-ade")

>>> 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()))
>>> inputs = image_processor(images=image, return_tensors="pt")

>>> 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 image_processor for postprocessing
>>> predicted_semantic_map = image_processor.post_process_semantic_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]

>>> # we refer to the demo notebooks for visualization (see "Resources" section in the MaskFormer docs)
>>> list(predicted_semantic_map.shape)
[512, 683]

全景分割示例:

>>> from transformers import AutoImageProcessor, MaskFormerForInstanceSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> # load MaskFormer fine-tuned on COCO panoptic segmentation
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/maskformer-swin-base-coco")
>>> model = MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-base-coco")

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

>>> 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 image_processor for postprocessing
>>> result = image_processor.post_process_panoptic_segmentation(outputs, target_sizes=[(image.height, image.width)])[0]

>>> # we refer to the demo notebooks for visualization (see "Resources" section in the MaskFormer docs)
>>> predicted_panoptic_map = result["segmentation"]
>>> list(predicted_panoptic_map.shape)
[480, 640]
Update on GitHub