Transformers documentation
OneFormer
该模型于 2022-11-10 在 HF papers 上发布,并于 2023-01-19 贡献至 Hugging Face Transformers。
OneFormer
概述
OneFormer 模型由 Jitesh Jain、Jiachen Li、MangTik Chiu、Ali Hassani、Nikita Orlov 和 Humphrey Shi 在 OneFormer: One Transformer to Rule Universal Image Segmentation 中提出。OneFormer 是一个通用图像分割框架,可以在单个全景数据集上进行训练,以执行语义分割、实例分割和全景分割任务。OneFormer 使用任务 token 来使模型适应当前关注的任务,从而使架构在训练时具有任务引导性,在推理时具有任务动态性。
该论文的摘要如下:
通用图像分割并非一个新概念。过去几十年中,统一图像分割的尝试包括场景解析、全景分割,以及更近期的新型全景分割架构。然而,这些全景分割架构并未真正实现图像分割的统一,因为它们需要针对语义分割、实例分割或全景分割分别进行训练,才能达到最佳性能。理想情况下,一个真正通用的框架应只需训练一次,即可在所有三种图像分割任务上取得 SOTA 性能。为此,我们提出了 OneFormer,一个通过多任务“一次训练”设计来统一分割的通用图像分割框架。首先,我们提出了一种任务条件联合训练策略,使得在单一的多任务训练过程中,能够基于每个领域(语义分割、实例分割和全景分割)的真值进行训练。其次,我们引入了任务 token,使模型能够根据当前任务进行条件化,从而使模型具备任务动态性,以支持多任务训练和推理。第三,我们提出在训练过程中使用查询-文本对比损失,以建立更好的任务间和类别间区分度。值得注意的是,尽管 Mask2Former 针对三个任务分别进行了训练,且使用了三倍的资源,但我们的单一 OneFormer 模型在 ADE20k、CityScapes 和 COCO 上的所有三种分割任务上均优于专门的 Mask2Former 模型。使用新的 ConvNeXt 和 DiNAT 骨干网络后,我们观察到性能进一步提升。我们认为 OneFormer 是使图像分割更加通用和易于获取的重要一步。
下图展示了 OneFormer 的架构。摘自原始论文。
该模型由 Jitesh Jain 贡献。原始代码可在 此处 找到。
使用技巧
- OneFormer 在推理时需要两个输入:image 和 task token。
- 在训练过程中,OneFormer 仅使用全景分割标注。
- 如果要在跨多个节点的分布式环境中训练模型,则应更新
modeling_oneformer.py中OneFormerLoss类内部的get_num_masks函数。在多节点训练时,该值应设置为所有节点上目标掩码数量的平均值,具体可参见原始实现中的此处。 - 可以使用 OneFormerProcessor 为模型准备输入图像和任务输入,以及可选的模型目标。OneFormerProcessor 将 OneFormerImageProcessor 和 CLIPTokenizer 封装为单一实例,以同时完成图像准备和任务输入编码。
- 要获取最终的分割结果,根据任务的不同,你可以调用
post_process_semantic_segmentation()或 post_process_instance_segmentation() 或 post_process_panoptic_segmentation()。这三种任务都可以使用 OneFormerForUniversalSegmentation 的输出来解决,全景分割接受一个可选的label_ids_to_fuse参数,用于将目标对象(例如天空)的实例融合在一起。
资源
以下是来自 Hugging Face 官方和社区(以 🌎 标识)的资源列表,可帮助您快速上手 OneFormer。
- 有关在自定义数据上进行推理 + 微调的演示笔记本可在此处找到。
如果您有兴趣提交资源以收录在此处,请随时发起 Pull Request,我们将对其进行审核。 该资源最好能展示一些新内容,而不是重复已有的资源。
OneFormer 特定输出
class transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput
< source >( encoder_hidden_states: tuple[torch.FloatTensor] | None = Nonepixel_decoder_hidden_states: tuple[torch.FloatTensor] | None = Nonetransformer_decoder_hidden_states: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_object_queries: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_contrastive_queries: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_mask_predictions: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_class_predictions: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_auxiliary_predictions: tuple[dict[str, torch.FloatTensor]] | None = Nonetext_queries: typing.Optional[torch.FloatTensor] = Nonetask_token: typing.Optional[torch.FloatTensor] = Noneattentions: tuple[torch.FloatTensor] | None = None )
参数
- encoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) —torch.FloatTensor的元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, num_channels, height, width)。编码器模型在每个阶段输出处的隐藏状态(也称为特征图)。 - pixel_decoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) —torch.FloatTensor的元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出处的隐藏状态(也称为特征图)。 - transformer_decoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.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 decoder 的对比查询。 - 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 (
Tupleof Dict ofstr, torch.FloatTensor, 可选) — Transformer 解码器每一层的类别和掩码预测组成的元组。 - text_queries (
torch.FloatTensor,形状为(batch_size, num_queries, hidden_dim)的 可选 参数) — 从输入文本列表派生的文本查询,用于在训练期间计算对比损失。 - task_token(形状为
(batch_size, hidden_dim)的torch.FloatTensor)— 用于条件化查询的一维任务标记。 - attentions (
tuple(tuple(torch.FloatTensor)),可选,在传入output_attentions=True或config.output_attentions=True时返回) —tuple(torch.FloatTensor)的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。来自 Transformer 解码器的自注意力(Self Attention)和交叉注意力(Cross Attention)权重。
OneFormerModel 的输出类。该类返回计算 logits 所需的所有隐藏状态。
class transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput
< source >( loss: typing.Optional[torch.FloatTensor] = Noneclass_queries_logits: typing.Optional[torch.FloatTensor] = Nonemasks_queries_logits: typing.Optional[torch.FloatTensor] = Noneauxiliary_predictions: list = Noneencoder_hidden_states: tuple[torch.FloatTensor] | None = Nonepixel_decoder_hidden_states: list[torch.FloatTensor] | None = Nonetransformer_decoder_hidden_states: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_object_queries: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_contrastive_queries: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_mask_predictions: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_class_predictions: typing.Optional[torch.FloatTensor] = Nonetransformer_decoder_auxiliary_predictions: list[dict[str, torch.FloatTensor]] | None = Nonetext_queries: typing.Optional[torch.FloatTensor] = Nonetask_token: typing.Optional[torch.FloatTensor] = Noneattentions: tuple[tuple[torch.FloatTensor]] | None = 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 (
Listof Dict ofstr, torch.FloatTensor,可选) — Transformer 解码器每一层的类别和掩码预测列表。 - encoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) —torch.FloatTensor的元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, num_channels, height, width)。编码器模型在每个阶段输出处的隐藏状态(也称为特征图)。 - pixel_decoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) —torch.FloatTensor的元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出处的隐藏状态(也称为特征图)。 - transformer_decoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.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 decoder 的对比查询。 - 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 (
Listof Dict ofstr, torch.FloatTensor, 可选) — Transformer 解码器每一层的类别和掩码预测列表。 - text_queries (
torch.FloatTensor,形状为(batch_size, num_queries, hidden_dim)的 可选 参数) — 从输入文本列表派生的文本查询,用于在训练期间计算对比损失。 - task_token(形状为
(batch_size, hidden_dim)的torch.FloatTensor)— 用于条件化查询的一维任务标记。 - attentions (
tuple(tuple(torch.FloatTensor)),可选,在传入output_attentions=True或config.output_attentions=True时返回) —tuple(torch.FloatTensor)的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。来自 Transformer 解码器的自注意力(Self Attention)和交叉注意力(Cross Attention)权重。
OneFormerForUniversalSegmentationOutput 的输出类。
该输出可以直接传递给 post_process_semantic_segmentation() 或 post_process_instance_segmentation() 或 post_process_panoptic_segmentation(),具体取决于任务。有关用法的详细信息,请参阅 [`~OneFormerImageProcessor]。
OneFormerConfig
class transformers.OneFormerConfig
< 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 = Noneignore_value: int = 255num_queries: int = 150no_object_weight: float = 0.1class_weight: float = 2.0mask_weight: float = 5.0dice_weight: float = 5.0contrastive_weight: float = 0.5contrastive_temperature: float = 0.07train_num_points: int = 12544oversample_ratio: float = 3.0importance_sample_ratio: float = 0.75init_std: float = 0.02init_xavier_std: float = 1.0layer_norm_eps: float = 1e-05is_training: bool = Falseuse_auxiliary_loss: bool = Trueoutput_auxiliary_logits: bool = Truestrides: list[int] | tuple[int, ...] = (4, 8, 16, 32)task_seq_len: int = 77text_encoder_width: int = 256text_encoder_context_length: int = 77text_encoder_num_layers: int = 6text_encoder_vocab_size: int = 49408text_encoder_proj_layers: int = 2text_encoder_n_ctx: int = 16conv_dim: int = 256mask_dim: int = 256hidden_dim: int = 256encoder_feedforward_dim: int = 1024norm: str = 'GN'encoder_layers: int = 6decoder_layers: int = 10use_task_norm: bool = Truenum_attention_heads: int = 8dropout: float | int = 0.1dim_feedforward: int = 2048pre_norm: bool = Falseenforce_input_proj: bool = Falsequery_dec_layers: int = 2common_stride: int = 4 )
参数
- backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。 - ignore_value (
int,可选,默认为 255) — 在计算损失时,GT 标签中需要忽略的值。 - num_queries (
int,可选,默认为 150) — 对象查询的数量。 - no_object_weight (
float, 可选,默认为0.1) — 目标检测损失中无目标类别的相对分类权重。 - class_weight (
float,可选,默认为2.0) — 匈牙利匹配代价中分类错误的相对权重。 - mask_weight (
float,可选,默认为5.0) — 全景分割损失中焦点损失的相对权重。 - dice_weight (
float,可选,默认为5.0) — 全景分割损失中 dice 损失的相对权重。 - contrastive_weight (
float,可选,默认为 0.5) — 对比损失的权重。 - contrastive_temperature (
float,可选,默认值为 0.07) — 用于缩放对比 logits 的初始值。 - train_num_points (
int,可选,默认为 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 初始化的缩放因子。 - layer_norm_eps (
float,可选,默认为1e-05) — 层归一化层所使用的 epsilon 值。 - is_training (
bool,可选,默认为False) — 是否以训练模式或推理模式运行。 - use_auxiliary_loss (
bool,可选,默认为True) — 是否使用 transformer decoder 的中间预测值来计算损失。 - output_auxiliary_logits (
bool,可选,默认为True) — 是否返回 transformer decoder 的中间预测结果。 - strides(
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) — 文本编码器中 Transformer 的层数。 - text_encoder_vocab_size (
int,可选,默认值为 49408) — 分词器的词汇表大小。 - text_encoder_proj_layers (
int,可选,默认为 2) — 用于投影文本查询的 MLP 层数。 - text_encoder_n_ctx(
int,可选,默认值为 16)— 可学习的文本上下文查询数量。 - conv_dim (
int,可选,默认为 256) — 用于将主干网络输出映射到特征图的维度。 - mask_dim (
int,可选,默认为 256) — 像素解码器中特征图的维度。 - hidden_dim (
int,可选,默认为 256) — Transformer 解码器中隐藏状态的维度。 - encoder_feedforward_dim (
int, 可选,默认为 1024) — 像素解码器中 FFN 层的维度。 - norm (
str,可选,默认为"GN") — 归一化类型。 - encoder_layers (
int,可选,默认为6) — Transformer 编码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - decoder_layers (
int,可选,默认为10) — Transformer 解码器中的隐藏层数。如果未设置,将使用与num_layers相同的值。 - use_task_norm (
bool,可选,默认为True) — 是否对任务标记进行归一化。 - num_attention_heads (
int,可选,默认为8) — Transformer 解码器中每个注意力层的注意力头数量。 - dropout (
Union[float, int],可选,默认为0.1) — 所有 dropout 层的比率。 - dim_feedforward (
int,可选,默认为 2048) — Transformer 解码器中 FFN 层的维度。 - pre_norm (
bool,可选,默认为False) — 是否在 transformer 解码器的注意力层之前对隐藏状态进行归一化。 - enforce_input_proj (
bool,可选,默认为False) — 是否在 transformer 解码器中对隐藏状态进行投影。 - query_dec_layers (
int,可选,默认为 2) — 查询 Transformer 的层数。 - common_stride (
int,可选,默认为 4) — 像素解码器中特征使用的公共步长。
这是用于存储 OneFormerModel 配置的类。它根据指定的参数实例化 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.configOneFormerImageProcessor
class transformers.OneFormerImageProcessor
< source >( **kwargs: *<class 'transformers.models.oneformer.image_processing_oneformer.OneFormerImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为True) — 是否将图像转换为 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 (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - repo_path (
str, kwargs, optional, 默认为shi-labs/oneformer_demo) — 指向包含模型元数据的本地目录或 HuggingFace Hub 仓库的路径。 - class_info_file (
str, kwargs, 可选) — 仓库中包含类元数据的 JSON 文件的路径。 - num_text (
int,kwargs,可选) — 文本编码器使用的文本查询数量,用作任务引导提示。 - num_labels (
int, kwargs, 可选) — 用于分割的语义类别数量,决定输出层的大小。 - ignore_index (
int,kwargs,可选) — 在分割掩码中需要忽略的标签,通常用于填充。 - do_reduce_labels (
bool,kwargs,可选,默认为False) — 是否将所有标签值减 1,将背景类映射到ignore_index。
构建一个 OneFormerImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]task_inputs: list[str] | None = Nonesegmentation_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.oneformer.image_processing_oneformer.OneFormerImageProcessorKwargs'> ) → ~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。 - task_inputs (
list[str], 可选) — 批次中每张图片对应的任务列表("panoptic"、"instance"、"semantic")。 - 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 (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - repo_path (
str, kwargs, optional, 默认为shi-labs/oneformer_demo) — 指向包含模型元数据的本地目录或 HuggingFace Hub 仓库的路径。 - class_info_file (
str, kwargs, 可选) — 仓库中包含类元数据的 JSON 文件的路径。 - num_text (
int,kwargs,可选) — 文本编码器使用的文本查询数量,用作任务引导提示。 - num_labels (
int, kwargs, 可选) — 用于分割的语义类别数量,决定输出层的大小。 - ignore_index (
int,kwargs,可选) — 在分割掩码中需要忽略的标签,通常用于填充。 - do_reduce_labels (
bool,kwargs,可选,默认为False) — 是否将所有标签值减 1,将背景类映射到ignore_index。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_semantic_segmentation
< source >( outputstarget_sizes: list[tuple[int, int]] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]
参数
- outputs (OneFormerForUniversalSegmentation) — 模型的原始输出。
- 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)。
将 OneFormerForUniversalSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
post_process_instance_segmentation
< source >( outputstask_type: str = 'instance'is_demo: bool = Truethreshold: float = 0.5mask_threshold: float = 0.5overlap_mask_area_threshold: float = 0.8target_sizes: list[tuple[int, int]] | None = Nonereturn_coco_annotation: bool | None = False ) → List[Dict]
参数
- outputs (
OneFormerForUniversalSegmentationOutput) —OneFormerForUniversalSegmentationOutput的输出。 - task_type (
str,可选,默认为 “instance”) — 后处理取决于任务标记输入。如果task_type为 “panoptic”,则需要忽略 stuff 预测。 - is_demo (
bool,可选,默认为True) — 模型是否处于演示模式。如果为 true,则使用 threshold 来预测最终掩码。 - 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 格式返回预测结果。
返回值
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 — 一个表示
将 OneFormerForUniversalSegmentationOutput 的输出转换为图像实例分割预测结果。仅支持 PyTorch。
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 (
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的片段的预测分数。
- id — 一个表示
将 MaskFormerForInstanceSegmentationOutput 的输出转换为图像全景分割预测。仅支持 PyTorch。
OneFormerImageProcessorPil
class transformers.OneFormerImageProcessorPil
< source >( **kwargs: *<class 'transformers.models.oneformer.image_processing_pil_oneformer.OneFormerImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为True) — 是否将图像转换为 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 (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - repo_path (
str, kwargs, optional, 默认为shi-labs/oneformer_demo) — 指向包含模型元数据的本地目录或 HuggingFace Hub 仓库的路径。 - class_info_file (
str, kwargs, 可选) — 仓库中包含类元数据的 JSON 文件的路径。 - num_text (
int,kwargs,可选) — 文本编码器使用的文本查询数量,用作任务引导提示。 - num_labels (
int, kwargs, 可选) — 用于分割的语义类别数量,决定输出层的大小。 - ignore_index (
int,kwargs,可选) — 在分割掩码中需要忽略的标签,通常用于填充。 - do_reduce_labels (
bool,kwargs,可选,默认为False) — 是否将所有标签值减 1,将背景类映射到ignore_index。
构建一个 OneFormerImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]task_inputs: list[str] | None = Nonesegmentation_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.oneformer.image_processing_pil_oneformer.OneFormerImageProcessorKwargs'> ) → ~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。 - task_inputs (
list[str], 可选) — 批次中每张图片对应的任务列表("panoptic"、"instance"、"semantic")。 - 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 (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - repo_path (
str, kwargs, optional, 默认为shi-labs/oneformer_demo) — 指向包含模型元数据的本地目录或 HuggingFace Hub 仓库的路径。 - class_info_file (
str, kwargs, 可选) — 仓库中包含类元数据的 JSON 文件的路径。 - num_text (
int,kwargs,可选) — 文本编码器使用的文本查询数量,用作任务引导提示。 - num_labels (
int, kwargs, 可选) — 用于分割的语义类别数量,决定输出层的大小。 - ignore_index (
int,kwargs,可选) — 在分割掩码中需要忽略的标签,通常用于填充。 - do_reduce_labels (
bool,kwargs,可选,默认为False) — 是否将所有标签值减 1,将背景类映射到ignore_index。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_semantic_segmentation
< source >( outputstarget_sizes: list[tuple[int, int]] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]
参数
- outputs (OneFormerForUniversalSegmentation) — 模型的原始输出。
- 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)。
将 OneFormerForUniversalSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
post_process_instance_segmentation
< source >( outputstask_type: str = 'instance'is_demo: bool = Truethreshold: float = 0.5mask_threshold: float = 0.5overlap_mask_area_threshold: float = 0.8target_sizes: list[tuple[int, int]] | None = Nonereturn_coco_annotation: bool | None = False ) → List[Dict]
参数
- outputs (
OneFormerForUniversalSegmentationOutput) —OneFormerForUniversalSegmentationOutput的输出。 - task_type (
str,可选,默认为 “instance”) — 后处理取决于任务标记输入。如果task_type为 “panoptic”,则需要忽略 stuff 预测。 - is_demo (
bool,可选,默认为True) — 模型是否处于演示模式。如果为 true,则使用 threshold 来预测最终掩码。 - 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 格式返回预测结果。
返回值
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 — 一个表示
将 OneFormerForUniversalSegmentationOutput 的输出转换为图像实例分割预测结果。仅支持 PyTorch。
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 (
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的片段的预测分数。
- id — 一个表示
将 MaskFormerForInstanceSegmentationOutput 的输出转换为图像全景分割预测。仅支持 PyTorch。
OneFormerProcessor
class transformers.OneFormerProcessor
< source >( image_processor = Nonetokenizer = Nonemax_seq_length: int = 77task_seq_length: int = 77**kwargs )
构建一个 OneFormerProcessor,它将图像处理器和分词器封装为单个处理器。
OneFormerProcessor 提供了 OneFormerImageProcessor 和 CLIPTokenizer 的所有功能。有关更多信息,请参阅 ~OneFormerImageProcessor 和 ~CLIPTokenizer。
__call__
< source >( images = Nonetask_inputs = Nonesegmentation_maps = None**kwargs ) → BatchFeature
参数
- images (`
) -- Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, setdo_rescale=False`. - task_inputs (
str或list[str],必填) — 分割的任务类型。必须是"semantic"、"instance"或"panoptic"中的一个或多个。 对于单张图像,可以是单个字符串;对于批量处理,可以是字符串列表(每张图像对应一个)。 任务类型决定了模型将在输入图像上执行哪种类型的分割。 - segmentation_maps (
ImageInput, 可选) — 对应的语义分割图,包含逐像素的标注。(
bool,可选,默认为True): 是否将图像填充至批次中最大图像的尺寸,并创建像素掩码。如果保持默认设置,将返回一个像素掩码,其内容为:
- 对于真实的像素(即未被掩码的像素),值为 1,
- 对于填充像素(即 被屏蔽 的像素),值为 0。
- return_tensors (
str或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
返回值
一个包含以下字段的 BatchFeature:
- task_inputs — 要输入模型的 token id 列表。当
text不为None时返回。 - pixel_values — 输入模型的像素值。当
images不为None时返回。
OneFormerModel
class transformers.OneFormerModel
< source >( config: OneFormerConfig )
参数
- config (OneFormerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Oneformer 模型,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensortask_inputs: Tensortext_inputs: typing.Optional[torch.Tensor] = Nonepixel_mask: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Noneoutput_attentions: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → OneFormerModelOutput or tuple(torch.FloatTensor)
参数
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor)— 与输入图像对应的张量。可以使用 OneFormerImageProcessor 获取像素值。有关详细信息,请参阅 OneFormerImageProcessor.call()(OneFormerProcessor 使用 OneFormerImageProcessor 来处理图像)。 - task_inputs(形状为
(batch_size, sequence_length)的torch.FloatTensor)— 任务输入。可以使用 AutoImageProcessor 获取任务输入。有关详细信息,请参阅 OneFormerProcessor.call()。 - text_inputs (
list[torch.Tensor],可选) — 形状为(num_queries, sequence_length)的张量,用于输入模型 - 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 而不是普通元组。
返回值
OneFormerModelOutput 或 tuple(torch.FloatTensor)
一个 OneFormerModelOutput 或 torch.FloatTensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(OneFormerConfig)和输入。
OneFormerModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- encoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, num_channels, height, width)。编码器模型在每个阶段输出处的隐藏状态(也称为特征图)。 - pixel_decoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出处的隐藏状态(也称为特征图)。 - transformer_decoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, sequence_length, hidden_size)。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 decoder 的对比查询。 - transformer_decoder_mask_predictions(形状为
(batch_size, num_queries, height, width)的torch.FloatTensor)— 来自 Transformer 解码器最后一层的掩码预测。 - transformer_decoder_class_predictions(形状为
(batch_size, num_queries, num_classes+1)的torch.FloatTensor)— 来自 transformer 解码器最后一层的类别预测。 - transformer_decoder_auxiliary_predictions (
Tupleof Dict ofstr, torch.FloatTensor, optional) — Tuple of class and mask predictions from each layer of the transformer decoder. - text_queries(
torch.FloatTensor,可选,形状为(batch_size, num_queries, hidden_dim))— 从输入文本列表派生的文本查询,用于在训练期间计算对比损失。 - task_token(形状为
(batch_size, hidden_dim)的torch.FloatTensor)— 用于条件化查询的一维任务 token。 - attentions(
tuple(tuple(torch.FloatTensor)),可选,在传入output_attentions=True或config.output_attentions=True时返回)—— 一个tuple(torch.FloatTensor)元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力(Self Attention)和交叉注意力(Cross Attention)权重。
示例:
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import OneFormerProcessor, OneFormerModel
>>> # download test image
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> # 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
< source >( config: OneFormerConfig )
参数
- config (OneFormerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
OneFormer 模型,用于实例分割、语义分割和全景分割。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensortask_inputs: Tensortext_inputs: typing.Optional[torch.Tensor] = Nonemask_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 ) → OneFormerForUniversalSegmentationOutput or tuple(torch.FloatTensor)
参数
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor)— 与输入图像对应的张量。可以使用 OneFormerImageProcessor 获取像素值。有关详细信息,请参阅 OneFormerImageProcessor.call()(OneFormerProcessor 使用 OneFormerImageProcessor 来处理图像)。 - task_inputs(形状为
(batch_size, sequence_length)的torch.FloatTensor)— 任务输入。可以使用 AutoImageProcessor 获取任务输入。有关详细信息,请参阅 OneFormerProcessor.call()。 - 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]的标签。 - 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 而不是普通元组。
返回值
OneFormerForUniversalSegmentationOutput 或 tuple(torch.FloatTensor)
一个 OneFormerForUniversalSegmentationOutput,或一个由 torch.FloatTensor 组成的元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(OneFormerConfig)和输入。
OneFormerForUniversalSegmentation 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- 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 (
Listof Dict ofstr, torch.FloatTensor, optional) — List of class and mask predictions from each layer of the transformer decoder. - encoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, num_channels, height, width)。编码器模型在每个阶段输出处的隐藏状态(也称为特征图)。 - pixel_decoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出处的隐藏状态(也称为特征图)。 - transformer_decoder_hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(包含一个嵌入层输出以及每个阶段的输出),形状为(batch_size, sequence_length, hidden_size)。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 decoder 的对比查询。 - transformer_decoder_mask_predictions(形状为
(batch_size, num_queries, height, width)的torch.FloatTensor)— 来自 Transformer 解码器最后一层的掩码预测。 - transformer_decoder_class_predictions(形状为
(batch_size, num_queries, num_classes+1)的torch.FloatTensor)— 来自 transformer 解码器最后一层的类别预测。 - transformer_decoder_auxiliary_predictions (
Listof Dict ofstr, torch.FloatTensor, optional) — List of class and mask predictions from each layer of the transformer decoder. - text_queries(
torch.FloatTensor,可选,形状为(batch_size, num_queries, hidden_dim))— 从输入文本列表派生的文本查询,用于在训练期间计算对比损失。 - task_token(形状为
(batch_size, hidden_dim)的torch.FloatTensor)— 用于条件化查询的一维任务 token。 - attentions(
tuple(tuple(torch.FloatTensor)),可选,在传入output_attentions=True或config.output_attentions=True时返回)—— 一个tuple(torch.FloatTensor)元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力(Self Attention)和交叉注意力(Cross Attention)权重。
示例:
通用分割示例:
>>> from transformers import OneFormerProcessor, OneFormerForUniversalSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> 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"
... )
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> # 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]'