Transformers 文档

SegGPT

SegGPT

概述

SegGPT模型由Xinlong Wang、Xiaosong Zhang、Yue Cao、Wen Wang、Chunhua Shen、Tiejun Huang在SegGPT: Segmenting Everything In Context中提出。SegGPT采用了一个仅解码器的Transformer,可以在给定输入图像、提示图像及其对应的提示掩码的情况下生成分割掩码。该模型在COCO-20上实现了56.1 mIoU的显著一次性结果,在FSS-1000上实现了85.6 mIoU。

论文的摘要如下:

我们介绍了SegGPT,一个用于在上下文中分割一切的通用模型。我们将各种分割任务统一到一个通用的上下文学习框架中,通过将它们转换为相同的图像格式来适应不同类型的分割数据。SegGPT的训练被表述为一个上下文着色问题,每个数据样本都有随机的颜色映射。目标是根据上下文完成各种任务,而不是依赖于特定的颜色。训练后,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 SegGptImageProcessor, SegGptForImageSegmentation

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

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

transformers.SegGptConfig

< >

( hidden_size = 1024 num_hidden_layers = 24 num_attention_heads = 16 hidden_act = 'gelu' hidden_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-06 image_size = [896, 448] patch_size = 16 num_channels = 3 qkv_bias = True mlp_dim = None drop_path_rate = 0.1 pretrain_image_size = 224 decoder_hidden_size = 64 use_relative_position_embeddings = True merge_index = 2 intermediate_hidden_state_indices = [5, 11, 17, 23] beta = 0.01 **kwargs )

参数

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

这是用于存储SegGptModel配置的配置类。它用于根据指定的参数实例化一个SegGPT模型,定义模型架构。使用默认值实例化配置将产生与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

transformers.SegGptImageProcessor

< >

( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: bool = True **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为指定的 (size["height"], size["width"])。可以在 preprocess 方法中通过 do_resize 参数覆盖此设置。
  • size (dict, 可选, 默认为 {"height" -- 448, "width": 448}): 调整大小后输出图像的尺寸。可以在 preprocess 方法中通过 size 参数覆盖此设置。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BICUBIC) — 如果调整图像大小,则使用的重采样过滤器。可以在 preprocess 方法中通过 resample 参数覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的比例 rescale_factor 重新缩放图像。可以在 preprocess 方法中通过 do_rescale 参数覆盖此设置。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可以在 preprocess 方法中通过 rescale_factor 参数覆盖此值。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可以在 preprocess 方法中通过 do_normalize 参数进行覆盖。
  • image_mean (floatList[float], 可选, 默认为 IMAGENET_DEFAULT_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以通过 preprocess 方法中的 image_mean 参数进行覆盖。
  • image_std (floatList[float], 可选, 默认为 IMAGENET_DEFAULT_STD) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以在 preprocess 方法中通过 image_std 参数覆盖此值。
  • do_convert_rgb (bool, 可选, 默认为 True) — 是否将提示掩码转换为RGB格式。可以在preprocess方法中通过do_convert_rgb参数覆盖此设置。

构建一个SegGpt图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')], NoneType] = None prompt_images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')], NoneType] = None prompt_masks: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')], NoneType] = None do_resize: typing.Optional[bool] = None size: 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 do_convert_rgb: typing.Optional[bool] = None num_labels: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )

参数

  • 图像 (ImageInput) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置do_rescale=False.
  • prompt_images (ImageInput) — 提示图像进行预处理。期望输入单个或批量的图像,像素值范围为0到255。如果传入的图像的像素值在0到1之间,请设置do_rescale=False.
  • prompt_masks (ImageInput) — 从提示图像到_preprocess的提示掩码,指定预处理输出中的prompt_masks值。 可以是分割图(无通道)或RGB图像的格式。如果是RGB图像的格式,应将do_convert_rgb设置为False。如果是分割图的格式,建议指定num_labels以构建调色板,将提示掩码从单通道映射到3通道RGB。如果未指定num_labels,提示掩码将在通道维度上复制。
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小.
  • size (Dict[str, int], 可选, 默认为 self.size) — 指定调整大小后输出图像大小的字典,格式为 {"height": h, "width": w}.
  • resample (PILImageResampling filter, 可选, 默认为 self.resample) — PILImageResampling 过滤器用于调整图像大小,例如 PILImageResampling.BICUBIC。仅在 do_resize 设置为 True 时有效。不适用于提示掩码,因为它使用最近邻调整大小。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果do_rescale设置为True,则用于重新缩放图像的重新缩放因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化处理。
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 如果 do_normalize 设置为 True,则使用的图像均值。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 如果 do_normalize 设置为 True,则使用的图像标准差。
  • do_convert_rgb (bool, 可选, 默认为 self.do_convert_rgb) — 是否将提示掩码转换为RGB格式。如果指定了num_labels,将构建一个调色板 将提示掩码从单通道映射到3通道RGB。如果未设置,提示掩码将在通道维度上复制。 如果提示掩码已经是RGB格式,则必须设置为False
  • num_labels — (int, 可选): 分割任务中的类别数量(不包括背景)。如果指定,将构建一个调色板,假设类别索引0为背景,将提示掩码从没有通道的普通分割图映射到3通道RGB。如果不指定此参数,提示掩码将按原样传递(如果do_convert_rgb为false)或在通道维度上复制(如果do_convert_rgb为true)。
  • return_tensors (strTensorType, 可选) — 返回的张量类型。可以是以下之一:
    • 未设置:返回一个 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回一个类型为 tf.Tensor 的批次。
    • TensorType.PYTORCH'pt':返回一个类型为 torch.Tensor 的批次。
    • TensorType.NUMPY'np':返回一个类型为 np.ndarray 的批次。
    • TensorType.JAX'jax':返回一个类型为 jax.numpy.ndarray 的批次。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

预处理一张图像或一批图像。

post_process_semantic_segmentation

< >

( outputs target_sizes: typing.Optional[typing.List[typing.Tuple[int, int]]] = None num_labels: typing.Optional[int] = None ) 语义分割

参数

  • 输出 (SegGptImageSegmentationOutput) — 模型的原始输出。
  • target_sizes (List[Tuple[int, int]], optional) — 长度为 (batch_size) 的列表,其中每个列表项 (Tuple[int, int]) 对应于每个预测的请求最终大小(高度,宽度)。如果留空为 None,预测将不会调整大小。
  • num_labels (int, 可选) — 分割任务中的类别数量(不包括背景)。如果指定,将构建一个调色板,假设类别索引0是背景,以将预测掩码从RGB值映射到类别索引。此值应与预处理输入时使用的值相同。

返回

语义分割

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

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

SegGptModel

transformers.SegGptModel

< >

( config: SegGptConfig )

参数

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

裸的SegGpt模型转换器输出原始隐藏状态,没有任何特定的头部。 这个模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有事项。

前进

< >

( pixel_values: Tensor prompt_pixel_values: Tensor prompt_masks: Tensor bool_masked_pos: typing.Optional[torch.BoolTensor] = None feature_ensemble: typing.Optional[bool] = None embedding_type: typing.Optional[str] = None labels: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.seggpt.modeling_seggpt.SegGptEncoderOutputtuple(torch.FloatTensor)

参数

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

返回

transformers.models.seggpt.modeling_seggpt.SegGptEncoderOutputtuple(torch.FloatTensor)

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

  • last_hidden_state (torch.FloatTensor 形状为 (batch_size, patch_height, patch_width, hidden_size)) — 模型最后一层输出的隐藏状态序列。
  • hidden_states (Tuple[torch.FloatTensor], optional, 当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出 + 一个用于每一层的输出) 形状为 (batch_size, patch_height, patch_width, hidden_size)
  • attentions (Tuple[torch.FloatTensor], optional, 当 config.output_attentions=True 时返回) — 由 torch.FloatTensor 组成的元组(每一层一个)形状为 (batch_size, num_heads, seq_len, seq_len)
  • intermediate_hidden_states (Tuple[torch.FloatTensor], optional, 当设置了 config.intermediate_hidden_state_indices 时返回) — 由 torch.FloatTensor 组成的元组,形状为 (batch_size, patch_height, patch_width, hidden_size)。 元组中的每个元素对应于 config.intermediate_hidden_state_indices 中指定的层的输出。 此外,每个特征都通过一个 LayerNorm。

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

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

示例:

>>> from transformers import SegGptImageProcessor, SegGptModel
>>> from PIL import Image
>>> import requests

>>> 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"

>>> image_input = Image.open(requests.get(image_input_url, stream=True).raw)
>>> image_prompt = Image.open(requests.get(image_prompt_url, stream=True).raw)
>>> mask_prompt = Image.open(requests.get(mask_prompt_url, stream=True).raw).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

transformers.SegGptForImageSegmentation

< >

( config: SegGptConfig )

参数

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

SegGpt模型,顶部带有解码器,用于一次性图像分割。 该模型是PyTorch torch.nn.Module的子类。将其 作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( pixel_values: Tensor prompt_pixel_values: Tensor prompt_masks: Tensor bool_masked_pos: typing.Optional[torch.BoolTensor] = None feature_ensemble: typing.Optional[bool] = None embedding_type: typing.Optional[str] = None labels: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.seggpt.modeling_seggpt.SegGptImageSegmentationOutputtuple(torch.FloatTensor)

参数

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

返回

transformers.models.seggpt.modeling_seggpt.SegGptImageSegmentationOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor, 可选, 当提供 labels 时返回) — 损失值。
  • pred_masks (torch.FloatTensor 形状为 (batch_size, num_channels, height, width)) — 预测的掩码。
  • hidden_states (Tuple[torch.FloatTensor], 可选, 当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入的输出 + 一个用于每一层的输出) 形状为 (batch_size, patch_height, patch_width, hidden_size)
  • attentions (Tuple[torch.FloatTensor], 可选, 当 config.output_attentions=True 时返回) — 由 torch.FloatTensor 组成的元组(每一层一个)形状为 (batch_size, num_heads, seq_len, seq_len)

SegGptForImageSegmentation 的前向方法,重写了 __call__ 特殊方法。

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

示例:

>>> from transformers import SegGptImageProcessor, SegGptForImageSegmentation
>>> from PIL import Image
>>> import requests

>>> 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"

>>> image_input = Image.open(requests.get(image_input_url, stream=True).raw)
>>> image_prompt = Image.open(requests.get(image_prompt_url, stream=True).raw)
>>> mask_prompt = Image.open(requests.get(mask_prompt_url, stream=True).raw).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