Transformers 文档

OneFormer

Hugging Face's logo
加入 Hugging Face 社区

并访问增强的文档体验

开始使用

OneFormer

PyTorch

概述

OneFormer 模型由 Jitesh Jain、Jiachen Li、MangTik Chiu、Ali Hassani、Nikita Orlov、Humphrey Shi 在 OneFormer: One Transformer to Rule Universal Image Segmentation 中提出。 OneFormer 是一个通用图像分割框架,可以在单个全景数据集上进行训练,以执行语义分割、实例分割和全景分割任务。 OneFormer 使用任务令牌来调节模型关注的任务,使架构在训练时以任务为导向,在推理时以任务为动态。

论文摘要如下

通用图像分割并不是一个新概念。过去几十年统一图像分割的尝试包括场景解析、全景分割,以及最近出现的新全景架构。然而,这种全景架构并没有真正统一图像分割,因为它们需要分别在语义分割、实例分割或全景分割上进行训练才能获得最佳性能。理想情况下,一个真正的通用框架应该只训练一次,并在所有三个图像分割任务中都达到 SOTA 性能。为此,我们提出了 OneFormer,这是一个通用图像分割框架,它通过多任务一次性训练设计统一了分割。我们首先提出了一种任务条件联合训练策略,该策略支持在单个多任务训练过程中对每个领域(语义分割、实例分割和全景分割)的真实标签进行训练。其次,我们引入了一个任务令牌来调节我们的模型以适应手头的任务,使我们的模型具有任务动态性,以支持多任务训练和推理。第三,我们建议在训练期间使用查询-文本对比损失,以建立更好的任务间和类间区分。值得注意的是,我们单个 OneFormer 模型在 ADE20k、CityScapes 和 COCO 上的所有三个分割任务中都优于专门的 Mask2Former 模型,尽管后者在三个任务中的每一个上都单独训练,资源是其三倍。借助新的 ConvNeXt 和 DiNAT 主干网络,我们观察到性能甚至得到更大的提升。我们相信 OneFormer 是朝着使图像分割更通用和可访问迈出的重要一步。

下图说明了 OneFormer 的架构。取自原始论文

此模型由 Jitesh Jain 贡献。 原始代码可以在这里找到。

使用技巧

资源

官方 Hugging Face 和社区(🌎 表示)资源列表,可帮助您开始使用 OneFormer。

  • 有关推理 + 在自定义数据上微调的演示 notebook 可以在此处找到。

如果您有兴趣提交要在此处包含的资源,请随时打开 Pull Request,我们将对其进行审核。 该资源最好能展示一些新的东西,而不是重复现有的资源。

OneFormer 特定输出

class transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput

< >

( encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None pixel_decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None transformer_decoder_hidden_states: typing.Optional[torch.FloatTensor] = None transformer_decoder_object_queries: FloatTensor = None transformer_decoder_contrastive_queries: typing.Optional[torch.FloatTensor] = None transformer_decoder_mask_predictions: FloatTensor = None transformer_decoder_class_predictions: FloatTensor = None transformer_decoder_auxiliary_predictions: typing.Optional[typing.Tuple[typing.Dict[str, torch.FloatTensor]]] = None text_queries: typing.Optional[torch.FloatTensor] = None task_token: FloatTensor = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

参数

  • encoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, num_channels, height, width)torch.FloatTensor 元组(每个嵌入输出一个,每个阶段输出一个)。 编码器模型在每个阶段输出端的隐藏状态(也称为特征图)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, num_channels, height, width)torch.FloatTensor 元组(每个嵌入输出一个,每个阶段输出一个)。 像素解码器模型在每个阶段输出端的隐藏状态(也称为特征图)。
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元组(每个嵌入输出一个,每个阶段输出一个)。 transformer 解码器在每个阶段输出端的隐藏状态(也称为特征图)。
  • transformer_decoder_object_queries (形状为 (batch_size, num_queries, hidden_dim)torch.FloatTensor) — 来自 transformer 解码器最后一层的输出对象查询。
  • transformer_decoder_contrastive_queries (形状为 (batch_size, num_queries, hidden_dim)torch.FloatTensor) — 来自 transformer 解码器的对比查询。
  • transformer_decoder_mask_predictions (torch.FloatTensor,形状为 (batch_size, num_queries, height, width)) — 来自 transformer 解码器最后一层的掩码预测。
  • transformer_decoder_class_predictions (torch.FloatTensor,形状为 (batch_size, num_queries, num_classes+1)) — 来自 transformer 解码器最后一层的类别预测。
  • transformer_decoder_auxiliary_predictions (Dict[str, torch.FloatTensor] 的元组, 可选) — 来自 transformer 解码器每一层的类别和掩码预测的元组。
  • text_queries (torch.FloatTensor, 可选,形状为 (batch_size, num_queries, hidden_dim)) — 从输入文本列表派生的文本查询,用于计算训练期间的对比损失。
  • task_token (torch.FloatTensor,形状为 (batch_size, hidden_dim)) — 用于调节查询的 1D 任务令牌。
  • attentions (tuple(tuple(torch.FloatTensor)), 可选,当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — tuple(torch.FloatTensor) 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力和交叉注意力权重。

用于 OneFormerModel 输出的类。此类返回计算 logits 所需的所有隐藏状态。

class transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput

< >

( loss: typing.Optional[torch.FloatTensor] = None class_queries_logits: FloatTensor = None masks_queries_logits: FloatTensor = None auxiliary_predictions: typing.List[typing.Dict[str, torch.FloatTensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None pixel_decoder_hidden_states: typing.Optional[typing.List[torch.FloatTensor]] = None transformer_decoder_hidden_states: typing.Optional[torch.FloatTensor] = None transformer_decoder_object_queries: FloatTensor = None transformer_decoder_contrastive_queries: typing.Optional[torch.FloatTensor] = None transformer_decoder_mask_predictions: FloatTensor = None transformer_decoder_class_predictions: FloatTensor = None transformer_decoder_auxiliary_predictions: typing.Optional[typing.List[typing.Dict[str, torch.FloatTensor]]] = None text_queries: typing.Optional[torch.FloatTensor] = None task_token: FloatTensor = None attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )

参数

  • loss (torch.Tensor, 可选) — 计算出的损失值,当存在标签时返回。
  • class_queries_logits (torch.FloatTensor) — 形状为 (batch_size, num_queries, num_labels + 1) 的张量,表示每个查询的提议类别。请注意,由于我们加入了空类别,因此需要 + 1
  • masks_queries_logits (torch.FloatTensor) — 形状为 (batch_size, num_queries, height, width) 的张量,表示每个查询的提议掩码。
  • auxiliary_predictions (Dict[str, torch.FloatTensor] 的列表, 可选) — 来自 transformer 解码器每一层的类别和掩码预测的列表。
  • encoder_hidden_states (tuple(torch.FloatTensor), 可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(每个阶段的输出一个,加上嵌入的输出),形状为 (batch_size, num_channels, height, width)。编码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor), 可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(每个阶段的输出一个,加上嵌入的输出),形状为 (batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(每个阶段的输出一个,加上嵌入的输出),形状为 (batch_size, sequence_length, hidden_size)。transformer 解码器在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_object_queries (torch.FloatTensor,形状为 (batch_size, num_queries, hidden_dim)) — 来自 transformer 解码器最后一层的输出对象查询。
  • transformer_decoder_contrastive_queries (torch.FloatTensor,形状为 (batch_size, num_queries, hidden_dim)) — 来自 transformer 解码器的对比查询。
  • transformer_decoder_mask_predictions (torch.FloatTensor,形状为 (batch_size, num_queries, height, width)) — 来自 transformer 解码器最后一层的掩码预测。
  • transformer_decoder_class_predictions (torch.FloatTensor,形状为 (batch_size, num_queries, num_classes+1)) — 来自 transformer 解码器最后一层的类别预测。
  • transformer_decoder_auxiliary_predictions (Dict[str, torch.FloatTensor] 的列表, 可选) — 来自 transformer 解码器每一层的类别和掩码预测的列表。
  • text_queries (torch.FloatTensor, 可选,形状为 (batch_size, num_queries, hidden_dim)) — 从输入文本列表导出的文本查询,用于计算训练期间的对比损失。
  • task_token (torch.FloatTensor,形状为 (batch_size, hidden_dim)) — 用于调节查询的 1D 任务令牌。
  • attentions (tuple(tuple(torch.FloatTensor)), 可选,当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — tuple(torch.FloatTensor) 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力和交叉注意力权重。

用于 OneFormerForUniversalSegmentationOutput 输出的类。

此输出可以直接传递给 post_process_semantic_segmentation()post_process_instance_segmentation()post_process_panoptic_segmentation(),具体取决于任务。 有关使用详情,请参阅 [`~OneFormerImageProcessor]。

OneFormerConfig

class transformers.OneFormerConfig

< >

( backbone_config: typing.Optional[typing.Dict] = None backbone: typing.Optional[str] = None use_pretrained_backbone: bool = False use_timm_backbone: bool = False backbone_kwargs: typing.Optional[typing.Dict] = None ignore_value: int = 255 num_queries: int = 150 no_object_weight: int = 0.1 class_weight: float = 2.0 mask_weight: float = 5.0 dice_weight: float = 5.0 contrastive_weight: float = 0.5 contrastive_temperature: float = 0.07 train_num_points: int = 12544 oversample_ratio: float = 3.0 importance_sample_ratio: float = 0.75 init_std: float = 0.02 init_xavier_std: float = 1.0 layer_norm_eps: float = 1e-05 is_training: bool = False use_auxiliary_loss: bool = True output_auxiliary_logits: bool = True strides: typing.Optional[list] = [4, 8, 16, 32] task_seq_len: int = 77 text_encoder_width: int = 256 text_encoder_context_length: int = 77 text_encoder_num_layers: int = 6 text_encoder_vocab_size: int = 49408 text_encoder_proj_layers: int = 2 text_encoder_n_ctx: int = 16 conv_dim: int = 256 mask_dim: int = 256 hidden_dim: int = 256 encoder_feedforward_dim: int = 1024 norm: str = 'GN' encoder_layers: int = 6 decoder_layers: int = 10 use_task_norm: bool = True num_attention_heads: int = 8 dropout: float = 0.1 dim_feedforward: int = 2048 pre_norm: bool = False enforce_input_proj: bool = False query_dec_layers: int = 2 common_stride: int = 4 **kwargs )

参数

  • backbone_config (PretrainedConfig, optional, defaults to SwinConfig) — 骨干模型的配置。 (可选, 默认为 SwinConfig)
  • backbone (str, optional) — 当 backbone_configNone 时,要使用的骨干网络的名称。如果 use_pretrained_backboneTrue,这将从 timm 或 transformers 库加载相应的预训练权重。如果 use_pretrained_backboneFalse,这将加载骨干网络的配置,并使用该配置以随机权重初始化骨干网络。 (可选)
  • use_pretrained_backbone (bool, optional, defaults to False) — 是否对骨干网络使用预训练权重。 (可选, 默认为 False)
  • use_timm_backbone (bool, optional, defaults to False) — 是否从 timm 库加载 backbone。如果为 False,则从 transformers 库加载骨干网络。 (可选, 默认为 False)
  • backbone_kwargs (dict, optional) — 从检查点加载时要传递给 AutoBackbone 的关键字参数,例如 {'out_indices': (0, 1, 2, 3)}。如果设置了 backbone_config,则不能指定此项。 (可选)
  • ignore_value (int, optional, defaults to 255) — 在计算损失时要忽略的 GT 标签中的值。 (可选, 默认为 255)
  • num_queries (int, optional, defaults to 150) — 对象查询的数量。 (可选, 默认为 150)
  • no_object_weight (float, optional, defaults to 0.1) — 无对象类别预测的权重。 (可选, 默认为 0.1)
  • class_weight (float, optional, defaults to 2.0) — 分类交叉熵损失的权重。 (可选, 默认为 2.0)
  • mask_weight (float, optional, defaults to 5.0) — 二元交叉熵损失的权重。 (可选, 默认为 5.0)
  • dice_weight (float, optional, defaults to 5.0) — Dice 损失的权重。 (可选, 默认为 5.0)
  • contrastive_weight (float, optional, defaults to 0.5) — 对比损失的权重。 (可选, 默认为 0.5)
  • contrastive_temperature (float, optional, defaults to 0.07) — 用于缩放对比 logits 的初始值。 (可选, 默认为 0.07)
  • train_num_points (int, optional, defaults to 12544) — 在计算掩码预测的损失时要采样的点数。 (可选, 默认为 12544)
  • oversample_ratio (float, optional, defaults to 3.0) — 决定要过采样多少点的比率。 (可选, 默认为 3.0)
  • importance_sample_ratio (float, optional, defaults to 0.75) — 通过重要性采样采样的点的比例。 (可选, 默认为 0.75)
  • init_std (float, optional, defaults to 0.02) — 正态初始化的标准差。 (可选, 默认为 0.02)
  • init_xavier_std (float, optional, defaults to 1.0) — Xavier 均匀初始化的标准差。 (可选, 默认为 1.0)
  • layer_norm_eps (float, optional, defaults to 1e-05) — 层归一化的 epsilon 值。 (可选, 默认为 1e-05)
  • is_training (bool, optional, defaults to False) — 是否在训练或推理模式下运行。 (可选, 默认为 False)
  • use_auxiliary_loss (bool, optional, defaults to True) — 是否使用来自 transformer 解码器的中间预测来计算损失。 (可选, 默认为 True)
  • output_auxiliary_logits (bool, optional, defaults to True) — 是否返回来自 transformer 解码器的中间预测。 (可选, 默认为 True)
  • strides (list, optional, defaults to [4, 8, 16, 32]) — 包含编码器中特征图步幅的列表。 (可选, 默认为 [4, 8, 16, 32])
  • task_seq_len (int, optional, defaults to 77) — 用于标记文本列表输入的序列长度。 (可选, 默认为 77)
  • text_encoder_width (int, optional, defaults to 256) — 文本编码器的隐藏层大小。 (可选, 默认为 256)
  • text_encoder_context_length (int, optional, defaults to 77) — 文本编码器的输入序列长度。
  • text_encoder_num_layers (int, optional, defaults to 6) — 文本编码器中 Transformer 的层数。
  • text_encoder_vocab_size (int, optional, defaults to 49408) — 分词器的词汇表大小。
  • text_encoder_proj_layers (int, optional, defaults to 2) — 用于投影文本查询的 MLP 中的层数。
  • text_encoder_n_ctx (int, optional, defaults to 16) — 可学习的文本上下文查询的数量。
  • conv_dim (int, optional, defaults to 256) — 从主干网络映射输出的特征图维度。
  • mask_dim (int, optional, defaults to 256) — 像素解码器中特征图的维度。
  • hidden_dim (int, optional, defaults to 256) — Transformer 解码器中隐藏状态的维度。
  • encoder_feedforward_dim (int, optional, defaults to 1024) — 像素解码器中 FFN 层的维度。
  • norm (str, optional, defaults to "GN") — 归一化类型。
  • encoder_layers (int, optional, defaults to 6) — 像素解码器中的层数。
  • decoder_layers (int, optional, defaults to 10) — Transformer 解码器中的层数。
  • use_task_norm (bool, optional, defaults to True) — 是否对任务 token 进行归一化。
  • num_attention_heads (int, optional, defaults to 8) — 像素和 Transformer 解码器中 Transformer 层的注意力头数。
  • dropout (float, optional, defaults to 0.1) — 像素和 Transformer 解码器的 dropout 概率。
  • dim_feedforward (int, optional, defaults to 2048) — Transformer 解码器中 FFN 层的维度。
  • pre_norm (bool, optional, defaults to False) — 是否在 Transformer 解码器中的注意力层之前对隐藏状态进行归一化。
  • enforce_input_proj (bool, optional, defaults to False) — 是否在 Transformer 解码器中投影隐藏状态。
  • query_dec_layers (int, optional, defaults to 2) — 查询 Transformer 中的层数。
  • common_stride (int, optional, defaults to 4) — 像素解码器中特征的通用步幅。

这是用于存储 OneFormerModel 配置的配置类。 它用于根据指定的参数实例化 OneFormer 模型,定义模型架构。 使用默认值实例化配置将产生与在 ADE20k-150 上训练的 OneFormer shi-labs/oneformer_ade20k_swin_tiny 架构类似的配置。

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

示例

>>> from transformers import OneFormerConfig, OneFormerModel

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

OneFormerImageProcessor

class transformers.OneFormerImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: float = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float]] = None image_std: typing.Union[float, typing.List[float]] = None ignore_index: typing.Optional[int] = None do_reduce_labels: bool = False repo_path: typing.Optional[str] = 'shi-labs/oneformer_demo' class_info_file: str = None num_text: typing.Optional[int] = None num_labels: typing.Optional[int] = None **kwargs )

参数

  • do_resize (bool, optional, defaults to True) — 是否将输入调整到特定 size 大小。
  • size (int, optional, defaults to 800) — 将输入调整为给定大小。 仅当 do_resize 设置为 True 时才有效。 如果 size 是类似 (width, height) 的序列,则输出大小将与此匹配。 如果 size 是一个整数,则图像的较小边缘将与此数字匹配。 即,如果 height > width,则图像将被重新缩放到 (size * height / width, size)
  • resample (int, optional, defaults to Resampling.BILINEAR) — 可选的重采样过滤器。 可以是 PIL.Image.Resampling.NEARESTPIL.Image.Resampling.BOXPIL.Image.Resampling.BILINEARPIL.Image.Resampling.HAMMINGPIL.Image.Resampling.BICUBICPIL.Image.Resampling.LANCZOS 之一。 仅当 do_resize 设置为 True 时才有效。
  • do_rescale (bool, optional, defaults to True) — 是否将输入重新缩放到特定 scale 比例。
  • rescale_factor (float, optional, defaults to 1/ 255) — 按给定因子重新缩放输入。 仅当 do_rescale 设置为 True 时才有效。
  • do_normalize (bool, 可选, 默认为 True) — 是否使用均值和标准差对输入进行归一化。
  • image_mean (int, 可选, 默认为 [0.485, 0.456, 0.406]) — 用于归一化图像的每个通道的均值序列。默认为 ImageNet 均值。
  • image_std (int, 可选, 默认为 [0.229, 0.224, 0.225]) — 用于归一化图像的每个通道的标准差序列。默认为 ImageNet 标准差。
  • ignore_index (int, 可选) — 分割图中背景像素的标签。如果提供,分割图中标记为 0(背景)的像素将被替换为 ignore_index
  • do_reduce_labels (bool, 可选, 默认为 False) — 是否将分割图的所有标签值减 1。通常用于数据集,其中 0 用于背景,而背景本身不包含在数据集的所有类别中(例如 ADE20k)。背景标签将被 ignore_index 替换。
  • repo_path (str, 可选, 默认为 "shi-labs/oneformer_demo") — 包含数据集类别信息的 JSON 文件的 Hub 仓库路径或本地目录。如果未设置,将在当前工作目录中查找 class_info_file
  • class_info_file (str, 可选) — 包含数据集类别信息的 JSON 文件。有关示例,请参阅 shi-labs/oneformer_demo/cityscapes_panoptic.json
  • num_text (int, 可选) — 文本输入列表中的文本条目数。
  • num_labels (int, 可选) — 分割图中的标签数量。

构建 OneFormer 图像处理器。图像处理器可用于准备图像、任务输入以及模型的可选文本输入和目标。

此图像处理器继承自 BaseImageProcessor,其中包含大多数主要方法。用户应参考此超类以获取有关这些方法的更多信息。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] task_inputs: typing.Optional[typing.List[str]] = None segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None instance_id_to_semantic_id: typing.Optional[typing.Dict[int, int]] = None do_resize: typing.Optional[bool] = None size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None ignore_index: typing.Optional[int] = None do_reduce_labels: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

encode_inputs

< >

( pixel_values_list: typing.List[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]] task_inputs: typing.List[str] segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] = None instance_id_to_semantic_id: typing.Union[typing.List[typing.Dict[int, int]], typing.Dict[int, int], NoneType] = None ignore_index: typing.Optional[int] = None do_reduce_labels: bool = False return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None ) BatchFeature

参数

  • pixel_values_list (List[ImageInput]) — 要填充的图像(像素值)列表。每个图像应为形状为 (channels, height, width) 的张量。
  • task_inputs (List[str]) — 任务值列表。
  • segmentation_maps (ImageInput, 可选) — 相应的语义分割图,带有像素级注释。

    (bool, 可选, 默认为 True): 是否将图像填充到批次中最大的图像,并创建像素掩码。

    如果保留为默认值,将返回像素掩码,其中:

    • 对于真实像素(即未掩码),值为 1,
    • 对于填充像素(即已掩码),值为 0。
  • instance_id_to_semantic_id (List[Dict[int, int]]Dict[int, int], 可选) — 对象实例 ID 和类别 ID 之间的映射。如果传递,segmentation_maps 将被视为实例分割图,其中每个像素代表一个实例 ID。可以提供单个字典(包含全局/数据集级别的映射)或字典列表(每个图像一个),以分别映射每个图像中的实例 ID。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是 NumPy 数组。如果设置为 'pt',则返回 PyTorch torch.Tensor 对象。
  • input_data_format (strChannelDimension, 可选) — 输入图像的通道维度格式。如果未提供,将从输入图像中推断。

Returns

BatchFeature

一个 BatchFeature,包含以下字段

  • pixel_values — 要馈送到模型的像素值。
  • pixel_mask — 要馈送到模型的像素掩码(当 =Truepixel_maskself.model_input_names 中时)。
  • mask_labels — 可选的形状为 (labels, height, width) 的掩码标签列表,用于馈送到模型(当提供 annotations 时)。
  • class_labels — 可选的形状为 (labels) 的类别标签列表,用于馈送到模型(当提供 annotations 时)。它们标识 mask_labels 的标签,例如 mask_labels[i][j] 的标签,如果 class_labels[i][j]
  • text_inputs — 可选的文本字符串条目列表,用于馈送到模型(当提供 annotations 时)。它们标识图像中存在的二元掩码。

将图像填充到批次中最大的图像,并创建相应的 pixel_mask

OneFormer 使用掩码分类范例处理语义分割,因此输入分割图将转换为二元掩码列表及其各自的标签。让我们看一个例子,假设 segmentation_maps = [[2,6,7,9]],输出将包含 mask_labels = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]](四个二元掩码)和 class_labels = [2,6,7,9],每个掩码的标签。

post_process_semantic_segmentation

< >

( outputs target_sizes: typing.Optional[typing.List[typing.Tuple[int, int]]] = None ) List[torch.Tensor]

参数

  • outputs (MaskFormerForInstanceSegmentation) — 模型的原始输出。
  • target_sizes (List[Tuple[int, int]], 可选) — 长度为 (batch_size) 的列表,其中每个列表项 (Tuple[int, int]]) 对应于每个预测请求的最终大小(高度,宽度)。如果留空,则不会调整预测大小。

Returns

List[torch.Tensor]

长度为 batch_size 的列表,其中每个项目是形状为 (height, width) 的语义分割图,对应于 target_sizes 条目(如果指定了 target_sizes)。每个 torch.Tensor 的每个条目对应于一个语义类别 ID。

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

post_process_instance_segmentation

< >

( outputs task_type: str = 'instance' is_demo: bool = True threshold: float = 0.5 mask_threshold: float = 0.5 overlap_mask_area_threshold: float = 0.8 target_sizes: typing.Optional[typing.List[typing.Tuple[int, int]]] = None return_coco_annotation: typing.Optional[bool] = False ) List[Dict]

参数

  • outputs (OneFormerForUniversalSegmentationOutput) — 来自 OneFormerForUniversalSegmentationOutput 的输出。
  • task_type (str, 可选, 默认为 “instance”) — 后处理取决于任务令牌输入。如果 task_type 为 “panoptic”,我们需要忽略 stuff 预测。
  • is_demo (bool, 可选), 默认为 True) — 模型是否处于演示模式。如果为 true,则使用阈值来预测最终掩码。
  • threshold (float, 可选, 默认为 0.5) — 保留预测实例掩码的概率分数阈值。
  • mask_threshold (float, 可选, 默认为 0.5) — 将预测掩码转换为二值时使用的阈值。
  • overlap_mask_area_threshold (float, 可选, 默认为 0.8) — 重叠掩码区域阈值,用于合并或丢弃每个二值实例掩码内的小的断开连接的部分。
  • target_sizes (List[Tuple], 可选) — 长度为 (batch_size) 的列表,其中每个列表项 (Tuple[int, int]]) 对应于批次中每个预测的请求最终大小(高度,宽度)。如果保留为 None,则不会调整预测大小。
  • return_coco_annotation (bool, 可选), 默认为 False) — 是否以 COCO 格式返回预测。

Returns

List[Dict]

字典列表,每张图像一个字典,每个字典包含两个键

  • segmentation — 形状为 (height, width) 的张量,其中每个像素代表一个 segment_id,如果在 threshold 之上未找到掩码,则设置为 None。如果指定了 target_sizes,则分割将被调整为相应的 target_sizes 条目。
  • segments_info — 一个字典,其中包含每个分割的附加信息。
    • id — 表示 segment_id 的整数。
    • label_id — 表示与 segment_id 对应的标签/语义类别 ID 的整数。
    • was_fused — 布尔值,如果 label_idlabel_ids_to_fuse 中则为 True,否则为 False。同一类别/标签的多个实例被融合并分配了单个 segment_id
    • score — 具有 segment_id 的分割的预测分数。

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

post_process_panoptic_segmentation

< >

( outputs threshold: float = 0.5 mask_threshold: float = 0.5 overlap_mask_area_threshold: float = 0.8 label_ids_to_fuse: typing.Optional[typing.Set[int]] = None target_sizes: typing.Optional[typing.List[typing.Tuple[int, int]]] = 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,则不会调整预测大小。

Returns

List[Dict]

字典列表,每张图像一个字典,每个字典包含两个键

  • segmentation — 形状为 (height, width) 的张量,其中每个像素代表一个 segment_id,如果在 threshold 之上未找到掩码,则设置为 None。如果指定了 target_sizes,则分割将被调整为相应的 target_sizes 条目。
  • segments_info — 一个字典,其中包含每个分割的附加信息。
    • id — 表示 segment_id 的整数。
    • label_id — 表示与 segment_id 对应的标签/语义类别 ID 的整数。
    • was_fused — 布尔值,如果 label_idlabel_ids_to_fuse 中则为 True,否则为 False。同一类别/标签的多个实例被融合并分配了单个 segment_id
    • score — 具有 segment_id 的分割的预测分数。

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

OneFormerProcessor

class transformers.OneFormerProcessor

< >

( image_processor = None tokenizer = None max_seq_length: int = 77 task_seq_length: int = 77 **kwargs )

参数

  • image_processor (OneFormerImageProcessor) — 图像处理器是必需的输入。
  • tokenizer ([CLIPTokenizer, CLIPTokenizerFast]) — 分词器是必需的输入。
  • max_seq_len (int, 可选, 默认为 77) — 输入文本列表的序列长度。
  • task_seq_len (int, 可选, 默认为 77) — 输入任务令牌的序列长度。

构建一个 OneFormer 处理器,它将 OneFormerImageProcessorCLIPTokenizer/CLIPTokenizerFast 包装到单个处理器中,该处理器继承了图像处理器和分词器的功能。

encode_inputs

< >

( images = None task_inputs = None segmentation_maps = None **kwargs )

此方法将其所有参数转发到 OneFormerImageProcessor.encode_inputs(),然后对 task_inputs 进行分词。有关更多信息,请参阅此方法的文档字符串。

post_process_instance_segmentation

< >

( *args **kwargs )

此方法将其所有参数转发到 OneFormerImageProcessor.post_process_instance_segmentation()。有关更多信息,请参阅此方法的文档字符串。

post_process_panoptic_segmentation

< >

( *args **kwargs )

此方法将其所有参数转发到 OneFormerImageProcessor.post_process_panoptic_segmentation()。有关更多信息,请参阅此方法的文档字符串。

post_process_semantic_segmentation

< >

( *args **kwargs )

此方法将其所有参数转发到 OneFormerImageProcessor.post_process_semantic_segmentation()。 请参阅此方法的文档字符串以获取更多信息。

OneFormerModel

class transformers.OneFormerModel

< >

( config: OneFormerConfig )

参数

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

裸机 OneFormer 模型输出原始隐藏状态,顶部没有任何特定的头部。 此模型是 PyTorch nn.Module 子类。 将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: Tensor task_inputs: Tensor text_inputs: typing.Optional[torch.Tensor] = None pixel_mask: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。 像素值可以使用 OneFormerProcessor 获得。 有关详细信息,请参阅 OneFormerProcessor.__call__()
  • task_inputs (torch.FloatTensor,形状为 (batch_size, sequence_length)) — 任务输入。 任务输入可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 OneFormerProcessor.__call__()
  • pixel_mask (torch.LongTensor,形状为 (batch_size, height, width)可选) — 用于避免对填充像素值执行注意力的掩码。 在 [0, 1] 中选择的掩码值:

    • 1 代表真实像素(即未被掩码),
    • 0 代表填充像素(即被掩码)。

    什么是注意力掩码?

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

Returns

transformers.models.oneformer.modeling_oneformer.OneFormerModelOutputtuple(torch.FloatTensor)

一个 transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),其中包含各种元素,具体取决于配置 (OneFormerConfig) 和输入。

  • encoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, num_channels, height, width)torch.FloatTensor 元组(每个嵌入输出一个 + 每个阶段输出一个)。 编码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, num_channels, height, width)torch.FloatTensor 元组(每个嵌入输出一个 + 每个阶段输出一个)。 像素解码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元组(每个嵌入输出一个 + 每个阶段输出一个)。 transformer 解码器在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_object_queries (torch.FloatTensor,形状为 (batch_size, num_queries, hidden_dim)) 来自 transformer 解码器最后一层的输出对象查询。
  • transformer_decoder_contrastive_queries (torch.FloatTensor,形状为 (batch_size, num_queries, hidden_dim)) 来自 transformer 解码器的对比查询。
  • transformer_decoder_mask_predictions (torch.FloatTensor,形状为 (batch_size, num_queries, height, width)) 来自 transformer 解码器最后一层的掩码预测。
  • transformer_decoder_class_predictions (torch.FloatTensor,形状为 (batch_size, num_queries, num_classes+1)) — 来自 transformer 解码器最后一层的类别预测。
  • transformer_decoder_auxiliary_predictions (str, torch.FloatTensor 字典元组,可选) — 来自 transformer 解码器每一层的类别和掩码预测的元组。
  • text_queries (torch.FloatTensor可选,形状为 (batch_size, num_queries, hidden_dim)) 从输入文本列表派生的文本查询,用于计算训练期间的对比损失。
  • task_token (torch.FloatTensor,形状为 (batch_size, hidden_dim)) 用于调节查询的 1D 任务令牌。
  • attentions (tuple(tuple(torch.FloatTensor))可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)tuple(torch.FloatTensor) 元组(每层一个)。 来自 transformer 解码器的自注意力和交叉注意力权重。

OneFormerModelOutput

OneFormerModel forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应在此之后调用 Module 实例,而不是调用此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例

>>> import torch
>>> from PIL import Image
>>> import requests
>>> from transformers import OneFormerProcessor, OneFormerModel

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

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

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

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

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

OneFormerForUniversalSegmentation

class transformers.OneFormerForUniversalSegmentation

< >

( config: OneFormerConfig )

参数

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

用于实例、语义和全景图像分割的 OneFormer 模型。 此模型是 PyTorch nn.Module 子类。 将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: Tensor task_inputs: Tensor text_inputs: typing.Optional[torch.Tensor] = None mask_labels: typing.Optional[typing.List[torch.Tensor]] = None class_labels: typing.Optional[typing.List[torch.Tensor]] = None pixel_mask: typing.Optional[torch.Tensor] = None output_auxiliary_logits: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。 像素值可以使用 OneFormerProcessor 获得。 有关详细信息,请参阅 OneFormerProcessor.__call__()
  • task_inputs (torch.FloatTensor,形状为 (batch_size, sequence_length)) — 任务输入。 任务输入可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 OneFormerProcessor.__call__()
  • pixel_mask (torch.LongTensor,形状为 (batch_size, height, width)可选) — 用于避免对填充像素值执行注意力的掩码。 在 [0, 1] 中选择的掩码值:

    • 1 代表真实像素(即未被掩码),
    • 0 代表填充像素(即被掩码)。

    什么是注意力掩码?

  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的 hidden_states
  • output_attentions (bool可选) — 是否返回 Detr 解码器注意力层的注意力张量。
  • return_dict (bool, 可选) — 是否返回一个 ~OneFormerModelOutput 而不是一个普通元组。
  • text_inputs (List[torch.Tensor], 可选) — 形状为 (num_queries, sequence_length) 的张量,将被馈送到模型
  • mask_labels (List[torch.Tensor], 可选) — 形状为 (num_labels, height, width) 的掩码标签列表,将被馈送到模型
  • class_labels (List[torch.LongTensor], 可选) — 目标类别标签列表,形状为 (num_labels, height, width),将被馈送到模型。 它们标识 mask_labels 的标签,例如,如果 class_labels[i][j],则为 mask_labels[i][j] 的标签。

Returns

transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput or tuple(torch.FloatTensor)

一个 transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput 或一个 torch.FloatTensor 的元组 (如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (OneFormerConfig) 和输入。

  • loss (torch.Tensor, 可选) — 计算出的损失,当存在标签时返回。
  • class_queries_logits (torch.FloatTensor) — 形状为 (batch_size, num_queries, num_labels + 1) 的张量,表示每个查询的提议类别。 请注意,需要 + 1 是因为我们加入了空类别。
  • masks_queries_logits (torch.FloatTensor) — 形状为 (batch_size, num_queries, height, width) 的张量,表示每个查询的提议掩码。
  • auxiliary_predictions (Dict[str, torch.FloatTensor] 列表, 可选) — 来自 transformer 解码器每一层的类别和掩码预测列表。
  • encoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, num_channels, height, width)torch.FloatTensor 元组(每个嵌入输出一个 + 每个阶段输出一个)。 编码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, num_channels, height, width)torch.FloatTensor 元组(每个嵌入输出一个 + 每个阶段输出一个)。 像素解码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元组(每个嵌入输出一个 + 每个阶段输出一个)。 transformer 解码器在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_object_queries (torch.FloatTensor,形状为 (batch_size, num_queries, hidden_dim)) 来自 transformer 解码器最后一层的输出对象查询。
  • transformer_decoder_contrastive_queries (torch.FloatTensor,形状为 (batch_size, num_queries, hidden_dim)) 来自 transformer 解码器的对比查询。
  • transformer_decoder_mask_predictions (torch.FloatTensor,形状为 (batch_size, num_queries, height, width)) 来自 transformer 解码器最后一层的掩码预测。
  • transformer_decoder_class_predictions (torch.FloatTensor,形状为 (batch_size, num_queries, num_classes+1)) — 来自 transformer 解码器最后一层的类别预测。
  • transformer_decoder_auxiliary_predictions (Dict[str, torch.FloatTensor] 列表, 可选) — 来自 transformer 解码器每一层的类别和掩码预测列表。
  • text_queries (torch.FloatTensor可选,形状为 (batch_size, num_queries, hidden_dim)) 从输入文本列表派生的文本查询,用于计算训练期间的对比损失。
  • task_token (torch.FloatTensor,形状为 (batch_size, hidden_dim)) 用于调节查询的 1D 任务令牌。
  • attentions (tuple(tuple(torch.FloatTensor))可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)tuple(torch.FloatTensor) 元组(每层一个)。 来自 transformer 解码器的自注意力和交叉注意力权重。

OneFormerUniversalSegmentationOutput

OneFormerForUniversalSegmentation 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应在此之后调用 Module 实例,而不是调用此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例

通用分割示例

>>> from transformers import OneFormerProcessor, OneFormerForUniversalSegmentation
>>> from PIL import Image
>>> import requests
>>> import torch

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

>>> url = (
...     "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
... )
>>> image = Image.open(requests.get(url, stream=True).raw)

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

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

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

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

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

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

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

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

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