Transformers documentation

SegGPT

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2023-04-06 在 HF papers 上发布,并于 2024-02-26 贡献至 Hugging Face Transformers。

SegGPT

概述

SegGPT 模型由 Xinlong Wang、Xiaosong Zhang、Yue Cao、Wen Wang、Chunhua Shen 和 Tiejun Huang 在 SegGPT: Segmenting Everything In Context 中提出。SegGPT 采用仅解码器(decoder-only)的 Transformer,在给定输入图像、提示图像及其对应的提示掩码时,能够生成分割掩码。该模型在 COCO-20 上取得了 56.1 mIoU,在 FSS-1000 上取得了 85.6 mIoU 的卓越单样本(one-shot)结果。

该论文的摘要如下:

我们提出了 SegGPT,一个用于在上下文中分割一切事物的通用模型。我们将各种分割任务统一到一个通用的上下文学习框架中,通过将不同种类的分割数据转换为相同格式的图像来适应它们。SegGPT 的训练被表述为一个上下文着色问题,其中每个数据样本都使用随机的颜色映射。其目标是根据上下文完成多样化的任务,而不是依赖特定的颜色。训练完成后,SegGPT 可以通过上下文推理在图像或视频中执行任意分割任务,例如物体实例、stuff、部件、轮廓和文本。我们在广泛的任务上评估了 SegGPT,包括少样本语义分割、视频目标分割、语义分割和全景分割。我们的结果表明,SegGPT 在分割域内和域外

提示:

  • 可以使用 SegGptImageProcessor 为模型准备图像输入、提示词和掩码。
  • 可以使用分割图或 RGB 图像作为提示掩码。如果使用后者,请确保在 preprocess 方法中设置 do_convert_rgb=False。
  • 在使用 SegGptImageProcessor 进行预处理和后处理时,强烈建议在传入 segmentation_maps(不考虑背景)时同时传入 num_labels。
  • 使用 SegGptForImageSegmentation 进行推理时,如果 batch_size 大于 1,您可以在 forward 方法中传入 feature_ensemble=True,以在图像之间使用特征集成。

以下是如何使用该模型进行单样本语义分割:

import torch
from datasets import load_dataset

from transformers import SegGptForImageSegmentation, SegGptImageProcessor


checkpoint = "BAAI/seggpt-vit-large"
image_processor = SegGptImageProcessor.from_pretrained(checkpoint)
model = SegGptForImageSegmentation.from_pretrained(checkpoint, device_map="auto")

dataset_id = "EduardoPacheco/FoodSeg103"
ds = load_dataset(dataset_id, split="train")
# Number of labels in FoodSeg103 (not including background)
num_labels = 103

image_input = ds[4]["image"]
ground_truth = ds[4]["label"]
image_prompt = ds[29]["image"]
mask_prompt = ds[29]["label"]

inputs = image_processor(
    images=image_input,
    prompt_images=image_prompt,
    segmentation_maps=mask_prompt,
    num_labels=num_labels,
    return_tensors="pt"
)

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

target_sizes = [image_input.size[::-1]]
mask = image_processor.post_process_semantic_segmentation(outputs, target_sizes, num_labels=num_labels)[0]

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

SegGptConfig

class transformers.SegGptConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 1024num_hidden_layers: int = 24num_attention_heads: int = 16hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06image_size: int | list[int] | tuple[int, ...] = (896, 448)patch_size: int | list[int] | tuple[int, int] = 16num_channels: int = 3qkv_bias: bool = Truemlp_dim: int | None = Nonedrop_path_rate: float | int = 0.1pretrain_image_size: int | list[int] | tuple[int, int] = 224decoder_hidden_size: int = 64use_relative_position_embeddings: bool = Truemerge_index: int = 2intermediate_hidden_state_indices: list[int] | tuple[int, ...] = (5, 11, 17, 23)beta: float = 0.01 )

参数

  • hidden_size (int,可选,默认为 1024) — 隐藏表示的维度。
  • num_hidden_layers (int,可选,默认为 24) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • hidden_dropout_prob (Union[float, int],可选,默认为 0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float,可选,默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • image_size (Union[int, list[int], tuple[int, ...]],可选,默认为 (896, 448)) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • mlp_dim (int, 可选) — Transformer 编码器中 MLP 层的维度。如果未设置,默认值为 hidden_size * 4。
  • drop_path_rate (Union[float, int],可选,默认为 0.1) — 用于 patch 融合的 drop path 比率。
  • pretrain_image_size (int,可选,默认为 224) — 绝对位置嵌入的预训练尺寸。
  • decoder_hidden_size (int,可选,默认为 64) — 隐藏表示的维度。
  • use_relative_position_embeddings (bool,可选,默认为 True) — 是否在注意力层中使用相对位置嵌入。
  • merge_index (int,可选,默认为 2) — 用于合并嵌入的编码器层索引。
  • intermediate_hidden_state_indices (list[int],可选,默认为 [5, 11, 17, 23]) — 作为解码器特征存储的编码器层索引。
  • beta (float,可选,默认值为 0.01) — SegGptLoss(smooth-l1 损失)的正则化系数。

这是用于存储 SegGptModel 配置的类。它根据指定的参数实例化 Seggpt 模型,并定义模型架构。使用默认值实例化配置将生成与 BAAI/seggpt-vit-large 类似的配置。

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

示例:

>>> from transformers import SegGptConfig, SegGptModel

>>> # Initializing a SegGPT seggpt-vit-large style configuration
>>> configuration = SegGptConfig()

>>> # Initializing a model (with random weights) from the seggpt-vit-large style configuration
>>> model = SegGptModel(configuration)

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

SegGptImageProcessor

class transformers.SegGptImageProcessor

< >

( **kwargs: *<class 'transformers.models.seggpt.image_processing_seggpt.SegGptImageProcessorKwargs'> )

参数

  • 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,默认为 {'height' -- 448, 'width': 448}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 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,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • num_labels (int, kwargs, optional) — 分割任务中的类别数量(不包括背景)。如果指定了该参数,将构建一个调色板,假设 class_idx 0 为背景,用于将提示掩码从普通的分割图映射为 3 通道 RGB 图像。如果不指定该参数,当 do_convert_rgb 为 True 时,提示掩码将在通道维度上进行复制。

构建一个 SegGptImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Noneprompt_images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Noneprompt_masks: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.seggpt.image_processing_seggpt.SegGptImageProcessorKwargs'> ) → ~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。
  • prompt_images (ImageInput,可选) — 用于预处理的提示图像。期望输入单张或一批图像,其像素值范围为 0 到 255。
  • prompt_masks (ImageInput, 可选) — 要预处理的提示掩码。可以是分割图(无通道)或 RGB 图像的格式。 如果为 RGB 图像格式,应将 do_convert_rgb 设置为 False。如果为 分割图格式,建议指定 num_labels 以构建调色板,将提示掩码 从单通道映射为 3 通道 RGB。如果未指定 num_labels,则提示掩码将 在通道维度上复制。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • num_labels (int, kwargs, optional) — 分割任务中的类别数量(不包括背景)。如果指定了该参数,将构建一个调色板,假设 class_idx 0 为背景,用于将提示掩码从普通的分割图映射为 3 通道 RGB 图像。如果不指定该参数,当 do_convert_rgb 为 True 时,提示掩码将在通道维度上进行复制。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

post_process_semantic_segmentation

< >

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

参数

  • outputs (SegGptImageSegmentationOutput) — 模型的原始输出。
  • target_sizes (list[tuple[int, int]], 可选) — 长度为 batch_size 的列表,其中每个元素对应每个预测所需的最终尺寸 (height, width)。如果设置为 None,则不会调整预测结果的尺寸。
  • num_labels (int, 可选) — 分割任务中的类别数量(不包括背景)。如果指定,将构建一个调色板,用于将预测掩码从 RGB 值映射回类别索引。该值应与预处理期间使用的值一致。
  • return_segmentation_scores (bool,可选,默认为 False) — 是否随分割图一起返回分割分数。当 True 时,返回列表中的每个元素都是一个 SemanticSegmentationPostProcessorOutput,包含字段 segmentation(类别 ID,形状为 (height, width))和 segmentation_scores(形状为 (num_labels+1, height, width),表示到每个调色板颜色的负平方 L2 距离;如果未提供 num_labels,则为 None)。

返回值

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_labels+1, height, width))。在这两种情况下,(height, width) 对应于目标尺寸(如果指定了 target_sizes)。

将 SegGptImageSegmentationOutput 的输出转换为分割图。仅支持 PyTorch。

SegGptImageProcessorPil

class transformers.SegGptImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.seggpt.image_processing_pil_seggpt.SegGptImageProcessorKwargs'> )

参数

  • 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,默认为 {'height' -- 448, 'width': 448}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 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,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • num_labels (int, kwargs, optional) — 分割任务中的类别数量(不包括背景)。如果指定了该参数,将构建一个调色板,假设 class_idx 0 为背景,用于将提示掩码从普通的分割图映射为 3 通道 RGB 图像。如果不指定该参数,当 do_convert_rgb 为 True 时,提示掩码将在通道维度上进行复制。

构建一个 SegGptImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Noneprompt_images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Noneprompt_masks: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.seggpt.image_processing_pil_seggpt.SegGptImageProcessorKwargs'> ) → ~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。
  • prompt_images (ImageInput,可选) — 用于预处理的提示图像。期望输入单张或一批图像,其像素值范围为 0 到 255。
  • prompt_masks (ImageInput, 可选) — 要预处理的提示掩码。可以是分割图(无通道)或 RGB 图像的格式。 如果为 RGB 图像格式,应将 do_convert_rgb 设置为 False。如果为 分割图格式,建议指定 num_labels 以构建调色板,将提示掩码 从单通道映射为 3 通道 RGB。如果未指定 num_labels,则提示掩码将 在通道维度上复制。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • num_labels (int, kwargs, optional) — 分割任务中的类别数量(不包括背景)。如果指定了该参数,将构建一个调色板,假设 class_idx 0 为背景,用于将提示掩码从普通的分割图映射为 3 通道 RGB 图像。如果不指定该参数,当 do_convert_rgb 为 True 时,提示掩码将在通道维度上进行复制。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

post_process_semantic_segmentation

< >

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

参数

  • outputs (SegGptImageSegmentationOutput) — 模型的原始输出。
  • target_sizes (list[tuple[int, int]], 可选) — 长度为 batch_size 的列表,其中每个元素对应每个预测所需的最终尺寸 (height, width)。如果设置为 None,则不会调整预测结果的尺寸。
  • num_labels (int, 可选) — 分割任务中的类别数量(不包括背景)。如果指定,将构建一个调色板,用于将预测掩码从 RGB 值映射回类别索引。该值应与预处理期间使用的值一致。
  • return_segmentation_scores (bool,可选,默认为 False) — 是否随分割图一起返回分割分数。当 True 时,返回列表中的每个元素都是一个 SemanticSegmentationPostProcessorOutput,包含字段 segmentation(类别 ID,形状为 (height, width))和 segmentation_scores(形状为 (num_labels+1, height, width),表示到每个调色板颜色的负平方 L2 距离;如果未提供 num_labels,则为 None)。

返回值

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_labels+1, height, width))。在这两种情况下,(height, width) 对应于目标尺寸(如果指定了 target_sizes)。

将 SegGptImageSegmentationOutput 的输出转换为分割图。仅支持 PyTorch。

SegGptModel

class transformers.SegGptModel

< >

( config: SegGptConfig )

参数

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

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

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

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

forward

< >

( pixel_values: Tensorprompt_pixel_values: Tensorprompt_masks: Tensorbool_masked_pos: typing.Optional[torch.BoolTensor] = Nonefeature_ensemble: bool | None = Noneembedding_type: str | None = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → SegGptEncoderOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。像素值可通过 SegGptImageProcessor 获取。有关详细信息,请参阅 SegGptImageProcessor.call()(processor_class 使用 SegGptImageProcessor 处理图像)。
  • prompt_pixel_values (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 提示像素值。可以使用 AutoImageProcessor 获取提示像素值。有关详细信息,请参阅 SegGptImageProcessor.call()。
  • prompt_masks (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 提示掩码。可以使用 AutoImageProcessor 获取提示掩码。有关详细信息,请参阅 SegGptImageProcessor.call()。
  • bool_masked_pos(形状为 (batch_size, num_patches) 的 torch.BoolTensor,可选)— 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。
  • feature_ensemble (bool, 可选) — 布尔值,指示是否使用特征集成。如果为 True,当存在至少两个提示时,模型将使用特征集成。如果为 False,模型将不使用特征集成。在对输入图像进行少样本推理(即为同一图像提供多个提示)时,应考虑此参数。
  • embedding_type (str, 可选) — 嵌入类型。指示提示是语义嵌入还是实例嵌入。可以是 instance 或 semantic。
  • labels (torch.Tensor of shape (batch_size, num_channels, height, width), optional) — 输入图像的真实掩码。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

SegGptEncoderOutput 或 tuple(torch.Tensor)

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

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

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

  • last_hidden_state(形状为 (batch_size, patch_height, patch_width, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。
  • hidden_states (tuple[torch.Tensor],optional,当 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(包含嵌入层的输出以及每一层的输出),形状为 (batch_size, patch_height, patch_width, hidden_size)。
  • attentions (tuple[torch.Tensor],optional,当 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, seq_len, seq_len)。
  • intermediate_hidden_states (tuple[torch.Tensor],可选,当设置了 config.intermediate_hidden_state_indices 时返回) — 形状为 (batch_size, patch_height, patch_width, hidden_size) 的 torch.Tensor 元组。 元组中的每个元素对应 config.intermediate_hidden_state_indices 中指定层的输出。 此外,每个特征都会经过一个 LayerNorm。

示例:

>>> from transformers import SegGptImageProcessor, SegGptModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
>>> image_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1.jpg"
>>> mask_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1_target.png"

>>> with httpx.stream("GET", image_input_url) as response:
...     image_input = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", image_prompt_url) as response:
...     image_prompt = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", mask_prompt_url) as response:
...     mask_prompt = Image.open(BytesIO(response.read())).convert("L")

>>> checkpoint = "BAAI/seggpt-vit-large"
>>> model = SegGptModel.from_pretrained(checkpoint)
>>> image_processor = SegGptImageProcessor.from_pretrained(checkpoint)

>>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensors="pt")

>>> outputs = model(**inputs)
>>> list(outputs.last_hidden_state.shape)
[1, 56, 28, 1024]

SegGptForImageSegmentation

class transformers.SegGptForImageSegmentation

< >

( config: SegGptConfig )

参数

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

在 SegGpt 模型上方添加解码器,用于单样本图像分割。

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

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

forward

< >

( pixel_values: Tensorprompt_pixel_values: Tensorprompt_masks: Tensorbool_masked_pos: typing.Optional[torch.BoolTensor] = Nonefeature_ensemble: bool | None = Noneembedding_type: str | None = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → SegGptImageSegmentationOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。像素值可通过 SegGptImageProcessor 获取。有关详细信息,请参阅 SegGptImageProcessor.call()(processor_class 使用 SegGptImageProcessor 处理图像)。
  • prompt_pixel_values (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 提示像素值。可以使用 AutoImageProcessor 获取提示像素值。有关详细信息,请参阅 SegGptImageProcessor.call()。
  • prompt_masks (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 提示掩码。可以使用 AutoImageProcessor 获取提示掩码。有关详细信息,请参阅 SegGptImageProcessor.call()。
  • bool_masked_pos(形状为 (batch_size, num_patches) 的 torch.BoolTensor,可选)— 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。
  • feature_ensemble (bool, 可选) — 布尔值,指示是否使用特征集成。如果为 True,当存在至少两个提示时,模型将使用特征集成。如果为 False,模型将不使用特征集成。在对输入图像进行少样本推理(即为同一图像提供多个提示)时,应考虑此参数。
  • embedding_type (str, 可选) — 嵌入类型。指示提示是语义嵌入还是实例嵌入。可以是 instance 或 semantic。
  • labels (torch.Tensor of shape (batch_size, num_channels, height, width), optional) — 输入图像的真实掩码。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

SegGptImageSegmentationOutput 或 tuple(torch.Tensor)

SegGptImageSegmentationOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(SegGptConfig)和输入而定的各种元素。

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

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

  • loss(torch.Tensor,可选,在提供 labels 时返回)— 损失值。
  • pred_masks(形状为 (batch_size, num_channels, height, width) 的 torch.Tensor)— 预测的掩码。
  • hidden_states (tuple[torch.Tensor],optional,当 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(包含嵌入层的输出以及每一层的输出),形状为 (batch_size, patch_height, patch_width, hidden_size)。
  • attentions(tuple[torch.Tensor],optional,当 config.output_attentions=True 时返回)—— 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, seq_len, seq_len)。

示例:

>>> from transformers import SegGptImageProcessor, SegGptForImageSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
>>> image_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1.jpg"
>>> mask_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1_target.png"

>>> with httpx.stream("GET", image_input_url) as response:
...     image_input = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", image_prompt_url) as response:
...     image_prompt = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", mask_prompt_url) as response:
...     mask_prompt = Image.open(BytesIO(response.read())).convert("L")

>>> checkpoint = "BAAI/seggpt-vit-large"
>>> model = SegGptForImageSegmentation.from_pretrained(checkpoint)
>>> image_processor = SegGptImageProcessor.from_pretrained(checkpoint)

>>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensors="pt")
>>> outputs = model(**inputs)
>>> result = image_processor.post_process_semantic_segmentation(outputs, target_sizes=[(image_input.height, image_input.width)])[0]
>>> print(list(result.shape))
[170, 297]
Update on GitHub