Transformers documentation
Mask2Former
该模型于 2021-12-02 在 HF papers 上发表,并于 2023-01-16 贡献至 Hugging Face Transformers。
Mask2Former
概述
Mask2Former 模型由 Bowen Cheng、Ishan Misra、Alexander G. Schwing、Alexander Kirillov 和 Rohit Girdhar 在 Masked-attention Mask Transformer for Universal Image Segmentation 中提出。Mask2Former 是一个用于全景分割、实例分割和语义分割的统一框架,相较于 MaskFormer,它在性能和效率方面均有显著提升。
该论文的摘要如下:
图像分割将具有不同语义(例如类别或实例归属)的像素进行分组。每种语义的选择都定义了一个任务。尽管各任务之间仅语义不同,但当前的研究重点在于为每个任务设计专门的架构。我们提出了 Masked-attention Mask Transformer(Mask2Former),这是一种能够处理任意图像分割任务(全景、实例或语义)的新架构。其关键组件包括 masked attention,它通过限制交叉注意力在预测的掩码区域内,来提取局部化特征。除了将研究工作量至少减少三倍之外,它在四个流行数据集上以显著优势超越了最佳的专用架构。最值得注意的是,Mask2Former 在全景分割(COCO 上 57.8 PQ)、实例分割(COCO 上 50.1 AP)和语义分割(ADE20K 上 57.7 mIoU)方面均达到了新的最先进水平。
Mask2Former architecture. Taken from the original paper. 该模型由 Shivalika Singh 和 Alara Dirik 贡献。原始代码可在此处找到。
使用技巧
- Mask2Former 使用与 MaskFormer 相同的预处理和后处理步骤。使用 Mask2FormerImageProcessor 或 AutoImageProcessor 为模型准备图像和可选的目标。
- 要获取最终的分割结果,根据任务的不同,您可以调用 post_process_semantic_segmentation() 或 post_process_instance_segmentation() 或 post_process_panoptic_segmentation()。这三种任务都可以使用 Mask2FormerForUniversalSegmentation 的输出来解决,其中全景分割接受一个可选的
label_ids_to_fuse参数,用于将目标对象(例如天空)的实例融合在一起。
资源
以下是来自 Hugging Face 官方和社区(以 🌎 标识)的资源列表,可帮助您快速上手 Mask2Former。
- 有关在自定义数据上进行推理和微调 Mask2Former 的演示笔记本,可在此处找到。
如果您有兴趣提交资源以收录在此处,请随时发起 Pull Request,我们将对其进行审核。 该资源最好能展示一些新内容,而不是重复已有的资源。
Mask2FormerConfig
class transformers.Mask2FormerConfig
< source >( 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 = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonefeature_size: int = 256mask_feature_size: int = 256hidden_dim: int = 256encoder_feedforward_dim: int = 1024activation_function: str = 'relu'encoder_layers: int = 6decoder_layers: int = 10num_attention_heads: int = 8dropout: float | int = 0.0dim_feedforward: int = 2048pre_norm: bool = Falseenforce_input_projection: bool = Falsecommon_stride: int = 4ignore_value: int = 255num_queries: int = 100no_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.75init_std: float = 0.02init_xavier_std: float = 1.0use_auxiliary_loss: bool = Truefeature_strides: list[int] | tuple[int, ...] = (4, 8, 16, 32)output_auxiliary_logits: bool | None = None )
参数
- backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。 - feature_size (
int,可选,默认为 256) — 生成的特征图的通道数。 - mask_feature_size (
int,可选,默认为 256) — 掩码的特征尺寸,该值同时用于指定特征金字塔网络(Feature Pyramid Network)特征的尺寸。 - hidden_dim (
int,可选,默认为256) — 隐藏表示的维度。 - encoder_feedforward_dim (
int,可选,默认值为 1024) — 作为像素解码器一部分的 deformable detr 编码器中前馈网络的维度。 - activation_function (
str,可选,默认为relu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - encoder_layers (
int,可选,默认为6) — Transformer 编码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - decoder_layers (
int,可选,默认为10) — Transformer 解码器中的隐藏层数。如果未设置,将使用与num_layers相同的值。 - num_attention_heads (
int,可选,默认为8) — Transformer 解码器中每个注意力层的注意力头数量。 - dropout (
Union[float, int],可选,默认为0.0) — 所有 dropout 层的比率。 - dim_feedforward (
int,可选,默认为 2048) — Transformer 解码器中前馈网络的特征维度。 - pre_norm (
bool,可选,默认为False) — 是否对 transformer decoder 使用 pre-LayerNorm。 - enforce_input_projection (
bool, 可选,默认为False) — 即使 Transformer 解码器中的输入通道数与隐藏维度相同,是否仍添加 1x1 输入投影卷积。 - common_stride (
int,可选,默认为 4) — 用于确定作为像素解码器一部分的 FPN 层数的参数。 - ignore_value (
int,可选,默认为 255) — 训练期间需要忽略的类别 ID。 - num_queries (
int, 可选,默认为 100) — 解码器的查询数量。 - 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(
str或function,可选,默认值为 12544)— 在计算损失时用于采样的点数。 - oversample_ratio (
float,可选,默认值为 3.0) — 用于计算采样点数量的过采样参数 - importance_sample_ratio (
float,可选,默认值为 0.75) — 通过重要性采样采样的点的比例。 - init_std (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - init_xavier_std (
float,可选,默认为1.0) — 用于交叉注意力权重 Xavier 初始化的缩放因子。 - use_auxiliary_loss (
bool,可选,默认为True) — 是否使用 transformer decoder 的中间预测值来计算损失。 - feature_strides (
list[int],可选,默认为[4, 8, 16, 32]) — 与骨干网络生成的特征相对应的特征步幅。 - output_auxiliary_logits (
bool, 可选) — 是否让模型输出其auxiliary_logits。
这是用于存储 Mask2FormerModel 配置的类。它根据指定的参数实例化 Mask2Former 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/mask2former-swin-small-coco-instance
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import Mask2FormerConfig, Mask2FormerModel
>>> # Initializing a Mask2Former facebook/mask2former-swin-small-coco-instance configuration
>>> configuration = Mask2FormerConfig()
>>> # Initializing a model (with random weights) from the facebook/mask2former-swin-small-coco-instance style configuration
>>> model = Mask2FormerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configMaskFormer 特定输出
class transformers.models.mask2former.modeling_mask2former.Mask2FormerModelOutput
< source >( 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 = Nonetransformer_decoder_intermediate_states: tuple[torch.Tensor] | None = Nonemasks_queries_logits: tuple[torch.Tensor] | None = Noneattentions: tuple[torch.Tensor] | None = None )
参数
- encoder_last_hidden_state (
torch.Tensor,形状为(batch_size, num_channels, height, width),可选) — 编码器模型(backbone)最后阶段的最后隐藏状态(最终特征图)。当传入output_hidden_states=True时返回。 - pixel_decoder_last_hidden_state (
torch.Tensor,形状为(batch_size, num_channels, height, width),可选) — 像素解码器模型最后阶段的最后隐藏状态(最终特征图)。 - transformer_decoder_last_hidden_state (
tuple(torch.Tensor)) — transformer decoder 的最终输出(batch_size, sequence_length, hidden_size)。 - encoder_hidden_states (
tuple(torch.Tensor), 可选) —torch.Tensor的元组(一个用于嵌入的输出,一个用于每个阶段的输出),形状为(batch_size, num_channels, height, width)。编码器模型在每个阶段输出处的隐藏状态(也称为特征图)。当传入output_hidden_states=True时返回。 - pixel_decoder_hidden_states (
tuple(torch.Tensor), , 可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) —torch.Tensor的元组(包含嵌入层输出以及每个阶段输出的各一个张量),形状为(batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出处的隐藏状态(也称为特征图)。在传入output_hidden_states=True时返回。 - transformer_decoder_hidden_states (
tuple(torch.Tensor), 可选) —torch.Tensor的元组(一个用于嵌入的输出,一个用于每个阶段的输出),形状为(batch_size, sequence_length, hidden_size)。Transformer 解码器在每个阶段输出处的隐藏状态(也称为特征图)。当传入output_hidden_states=True时返回。 - transformer_decoder_intermediate_states (
tuple(torch.Tensor),形状为(num_queries, 1, hidden_size)) — 解码器的中间激活值,即每个解码器层的输出,且每个输出都经过了一次层归一化(layernorm)。 - masks_queries_logits (
tuple(torch.Tensor),形状为(batch_size, num_queries, height, width)) — Transformer 解码器每一层输出的掩码预测。 - attentions (
tuple(tuple(torch.Tensor)),可选,在传入output_attentions=True时返回) —tuple(torch.Tensor)的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力权重。 - attentions (
tuple[torch.Tensor], 可选, 在传入output_attentions=True或config.output_attentions=True) — 的元组torch.Tensor((每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length).注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
Mask2FormerModel 的输出类。该类返回计算 logits 所需的所有隐藏状态。
class transformers.models.mask2former.modeling_mask2former.Mask2FormerForUniversalSegmentationOutput
< source >( loss: typing.Optional[torch.Tensor] = Noneclass_queries_logits: typing.Optional[torch.Tensor] = Nonemasks_queries_logits: typing.Optional[torch.Tensor] = Noneauxiliary_logits: list[dict[str, torch.Tensor]] | None = 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: typing.Optional[torch.Tensor] = 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 (
list[Dict(str, torch.Tensor)],可选) — Transformer 解码器每一层的类别和掩码预测列表。 - 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)) — 像素解码器模型最后阶段的最后隐藏状态(最终特征图)。 - transformer_decoder_last_hidden_state (
tuple(torch.Tensor)) — transformer decoder 的最终输出(batch_size, sequence_length, hidden_size)。 - 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 解码器在每个阶段输出处的隐藏状态(也称为特征图)。 - attentions (
tuple(tuple(torch.Tensor)),可选,在传入output_attentions=True或config.output_attentions=True时返回) —tuple(torch.Tensor)的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力和交叉注意力权重。
Mask2FormerForUniversalSegmentationOutput 的输出类。
该输出可以直接传递给 post_process_semantic_segmentation() 或 post_process_instance_segmentation() 或 post_process_panoptic_segmentation() 以计算最终的分割图。有关用法的详细信息,请参阅 [`~Mask2FormerImageProcessor]。
Mask2FormerModel
类 transformers.Mask2FormerModel
< source >( config: Mask2FormerConfig )
参数
- config (Mask2FormerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Mask2Former 模型,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensorpixel_mask: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Noneoutput_attentions: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → Mask2FormerModelOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Mask2FormerImageProcessor 获取像素值。有关详细信息,请参阅 Mask2FormerImageProcessor.call()(processor_class使用 Mask2FormerImageProcessor 处理图像)。 - 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 而不是普通元组。
返回值
Mask2FormerModelOutput 或 tuple(torch.Tensor)
一个 Mask2FormerModelOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Mask2FormerConfig)和输入。
Mask2FormerModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
encoder_last_hidden_state (
torch.Tensor,形状为(batch_size, num_channels, height, width),可选) — 编码器模型(backbone)最后阶段的最后隐藏状态(最终特征图)。当传入output_hidden_states=True时返回。pixel_decoder_last_hidden_state (
torch.Tensor,形状为(batch_size, num_channels, height, width),可选) — 像素解码器模型最后阶段的最后隐藏状态(最终特征图)。transformer_decoder_last_hidden_state (
tuple(torch.Tensor)) — Transformer 解码器的最终输出(batch_size, sequence_length, hidden_size)。encoder_hidden_states (
tuple(torch.Tensor), 可选) — 一个torch.Tensor元组(包含一个嵌入层输出张量和每个阶段的一个输出张量),形状为(batch_size, num_channels, height, width)。编码器模型在每个阶段输出处的隐藏状态(也称为特征图)。当传入output_hidden_states=True时返回。pixel_decoder_hidden_states (
tuple(torch.Tensor), , 可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(包含嵌入层输出以及每个阶段的输出各一个),形状为(batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出处的隐藏状态(也称为特征图)。当传入output_hidden_states=True时返回。transformer_decoder_hidden_states (
tuple(torch.Tensor), 可选) — 一个torch.Tensor元组(包含一个嵌入层输出张量和每个阶段的输出张量),形状为(batch_size, sequence_length, hidden_size)。Transformer 解码器在每个阶段输出处的隐藏状态(也称为特征图)。当传入output_hidden_states=True时返回。transformer_decoder_intermediate_states (
tuple(torch.Tensor),形状为(num_queries, 1, hidden_size)) — 解码器的中间激活值,即每个解码器层的输出,且每个输出都经过了一次层归一化(layernorm)。masks_queries_logits (
tuple(torch.Tensor),形状为(batch_size, num_queries, height, width)) Transformer 解码器中每一层的掩码预测。 attentions (tuple(tuple(torch.Tensor)),可选,在传入output_attentions=True时返回) —tuple(torch.Tensor)的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。Transformer 解码器中的自注意力权重。attentions (
tuple[torch.Tensor],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
Mask2FormerForUniversalSegmentation
class transformers.Mask2FormerForUniversalSegmentation
< source >( config: Mask2FormerConfig )
参数
- config (Mask2FormerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
带有用于实例/语义/全景分割的头部结构的 Mask2Former 模型。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensormask_labels: list[torch.Tensor] | None = Noneclass_labels: list[torch.Tensor] | None = Nonepixel_mask: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Noneoutput_auxiliary_logits: bool | None = Noneoutput_attentions: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → Mask2FormerForUniversalSegmentationOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Mask2FormerImageProcessor 获取像素值。有关详细信息,请参阅 Mask2FormerImageProcessor.call()(processor_class使用 Mask2FormerImageProcessor 处理图像)。 - 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_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - output_auxiliary_logits (
bool, 可选) — 是否输出辅助 logits。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
Mask2FormerForUniversalSegmentationOutput 或 tuple(torch.Tensor)
一个 Mask2FormerForUniversalSegmentationOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Mask2FormerConfig)和输入。
Mask2FormerForUniversalSegmentation 的 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 (
list[Dict(str, torch.Tensor)],可选) — 来自 transformer 解码器每一层的类别和掩码预测列表。 - encoder_last_hidden_state (
torch.Tensor,形状为(batch_size, num_channels, height, width)) — 编码器模型(backbone)最后阶段的最后隐藏状态(最终特征图)。 - pixel_decoder_last_hidden_state(形状为
(batch_size, num_channels, height, width)的torch.Tensor)— 像素解码器模型最后阶段的最后隐藏状态(最终特征图)。 - transformer_decoder_last_hidden_state (
tuple(torch.Tensor)) — Transformer 解码器的最终输出(batch_size, sequence_length, hidden_size)。 - 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 解码器在每个阶段输出处的隐藏状态(也称为特征图)。 - attentions (
tuple(tuple(torch.Tensor)),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个tuple(torch.Tensor)元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力和交叉注意力权重。
示例:
实例分割示例:
>>> from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch
>>> # Load Mask2Former trained on COCO instance segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-coco-instance")
>>> model = Mask2FormerForUniversalSegmentation.from_pretrained(
... "facebook/mask2former-swin-small-coco-instance"
... )
>>> 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")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits
>>> # Perform post-processing to get instance segmentation map
>>> pred_instance_map = image_processor.post_process_instance_segmentation(
... outputs, target_sizes=[(image.height, image.width)]
... )[0]
>>> print(pred_instance_map.shape)
torch.Size([480, 640])语义分割示例:
>>> from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch
>>> # Load Mask2Former trained on ADE20k semantic segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-ade-semantic")
>>> model = Mask2FormerForUniversalSegmentation.from_pretrained("facebook/mask2former-swin-small-ade-semantic")
>>> 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(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits
>>> # Perform post-processing to get semantic segmentation map
>>> pred_semantic_map = image_processor.post_process_semantic_segmentation(
... outputs, target_sizes=[(image.height, image.width)]
... )[0]
>>> print(pred_semantic_map.shape)
torch.Size([512, 683])全景分割示例:
>>> from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch
>>> # Load Mask2Former trained on CityScapes panoptic segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-cityscapes-panoptic")
>>> model = Mask2FormerForUniversalSegmentation.from_pretrained(
... "facebook/mask2former-swin-small-cityscapes-panoptic"
... )
>>> url = "/static-proxy?url=https%3A%2F%2Fcdn-media.huggingface.co%2FInference-API%2FSample-results-on-the-Cityscapes-dataset-The-above-images-show-how-our-method-can-handle.png%26quot%3B%3C%2Fspan%3E
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits
>>> # Perform post-processing to get panoptic segmentation map
>>> pred_panoptic_map = image_processor.post_process_panoptic_segmentation(
... outputs, target_sizes=[(image.height, image.width)]
... )[0]["segmentation"]
>>> print(pred_panoptic_map.shape)
torch.Size([338, 676])Mask2FormerImageProcessor
class transformers.Mask2FormerImageProcessor
< source >( **kwargs: *<class 'transformers.models.mask2former.image_processing_mask2former.Mask2FormerImageProcessorKwargs'> )
参数
- 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 中的值。
构建一个 Mask2FormerImageProcessor 图像处理器。
预处理
< source >( 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.mask2former.image_processing_mask2former.Mask2FormerImageProcessorKwargs'> ) → ~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
< source >( outputstarget_sizes: list[tuple[int, int]] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]
参数
- outputs (Mask2FormerForUniversalSegmentation) — 模型的原始输出。
- 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)。
将 Mask2FormerForUniversalSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
post_process_instance_segmentation
< source >( 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 (Mask2FormerForUniversalSegmentation) — 模型的原始输出。
- 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的片段的预测分数。
- id — 表示
将 Mask2FormerForUniversalSegmentationOutput 的输出转换为实例分割预测。
仅支持 PyTorch。如果实例可能重叠,请将 return_coco_annotation 或 return_binary_maps 设置为 True,以获取正确的分割结果。
post_process_panoptic_segmentation
< source >( 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 (
Mask2FormerForUniversalSegmentationOutput) — Mask2FormerForUniversalSegmentation 的输出。 - 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的片段的预测分数。
- id — 一个表示
将 Mask2FormerForUniversalSegmentationOutput 的输出转换为图像全景分割预测。仅支持 PyTorch。
Mask2FormerImageProcessorPil
class transformers.Mask2FormerImageProcessorPil
< source >( **kwargs: *<class 'transformers.models.mask2former.image_processing_pil_mask2former.Mask2FormerImageProcessorKwargs'> )
预处理
< source >( 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.mask2former.image_processing_pil_mask2former.Mask2FormerImageProcessorKwargs'> ) → ~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
< source >( outputstarget_sizes: list[tuple[int, int]] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]
参数
- outputs (Mask2FormerForUniversalSegmentation) — 模型的原始输出。
- 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)。
将 Mask2FormerForUniversalSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
post_process_instance_segmentation
< source >( 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 (Mask2FormerForUniversalSegmentation) — 模型的原始输出。
- 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的片段的预测分数。
- id — 表示
将 Mask2FormerForUniversalSegmentationOutput 的输出转换为实例分割预测。
仅支持 PyTorch。如果实例可能重叠,请将 return_coco_annotation 或 return_binary_maps 设置为 True,以获取正确的分割结果。
post_process_panoptic_segmentation
< source >( 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 (
Mask2FormerForUniversalSegmentationOutput) — Mask2FormerForUniversalSegmentation 的输出。 - 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的片段的预测分数。
- id — 一个表示
将 Mask2FormerForUniversalSegmentationOutput 的输出转换为图像全景分割预测。仅支持 PyTorch。