Transformers 文档

SegGPT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

SegGPT

PyTorch

概览

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
  • 强烈建议在使用 segmentation_maps (不考虑背景)时,在预处理和后处理中使用 SegGptImageProcessor 时,为您的用例传递 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

class 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`, *可选的*, 默认为 1024) — 编码器层和池化器层的维度。
  • **num_hidden_layers** (`int`, *可选的*, 默认为 24) — Transformer 编码器中隐藏层的数量。
  • **num_attention_heads** (`int`, *可选的*, 默认为 16) — Transformer 编码器中每个注意力层的注意力头数。
  • **hidden_act** (`str` 或 `function`, *可选的*, 默认为 `"gelu"`) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持 `"gelu"`, `"relu"`, `"selu"` 和 `"gelu_new"`。
  • **hidden_dropout_prob** (`float`, *可选的*, 默认为 0.0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • **initializer_range** (`float`, *可选的*, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • **layer_norm_eps** (`float`, *可选的*, 默认为 1e-06) — 层归一化层使用的 epsilon 值。
  • **image_size** (`List[int]`, *可选的*, 默认为 `[896, 448]`) — 每张图片的大小(分辨率)。
  • **patch_size** (`int`, *可选的*, 默认为 16) — 每个 patch 的大小(分辨率)。
  • **num_channels** (`int`, *可选的*, 默认为 3) — 输入通道数。
  • **qkv_bias** (`bool`, *可选的*, 默认为 `True`) — 是否向 queries、keys 和 values 添加偏置。
  • mlp_dim (int, 可选) — Transformer 编码器中 MLP 层的维度。如果未设置,则默认为 hidden_size * 4。
  • drop_path_rate (float, 可选, 默认为 0.1) — dropout 层的 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 模型,定义模型架构。使用默认值实例化配置将生成与 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

< >

( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = <Resampling.BICUBIC: 3> 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) — 是否将 prompt mask 转换为 RGB 格式。可以被 preprocess 方法中的 do_convert_rgb 参数覆盖。

构建 SegGpt 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None prompt_images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None prompt_masks: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['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] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )

参数

  • images (ImageInput) — 要 _preprocess 的图像。 期望是像素值范围为 0 到 255 的单张或批量图像。 如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • prompt_images (ImageInput) — 要 _preprocess 的 prompt 图像。 期望是像素值范围为 0 到 255 的单张或批量图像。 如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • prompt_masks (ImageInput) — 来自 prompt 图像的 Prompt mask,用于指定预处理输出中的 prompt_masks 值。 可以是分割图(无通道)或 RGB 图像格式。 如果是 RGB 图像格式,则应将 do_convert_rgb 设置为 False。 如果是分割图格式,建议使用指定 num_labelsnum_labels 来构建调色板,以将 prompt mask 从单通道映射到 3 通道 RGB。 如果未指定 num_labels,则 prompt mask 将在通道维度上复制。
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], 可选, 默认为 self.size) — 字典格式为 {"height": h, "width": w},指定调整大小后输出图像的大小。
  • resample (PILImageResampling 滤波器, 可选, 默认为 self.resample) — PILImageResampling 滤波器,用于在调整图像大小时使用,例如 PILImageResampling.BICUBIC。 仅在 do_resize 设置为 True 时生效。 不适用于 prompt mask,因为它使用最近邻方法调整大小。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,则通过此缩放因子来缩放图像。
  • do_normalize (bool, 可选, 默认为 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, 可选): 分割任务中的类别数量(不包括背景)。如果指定,将构建一个调色板,假设 class_idx 0 是背景,以将提示掩码从没有通道的纯分割图映射到 3 通道 RGB。如果不指定此项,则如果提示掩码已经是 RGB 格式(如果 do_convert_rgb 为 false),则会按原样传递,否则将在通道维度上复制。
  • return_tensors (strTensorType, 可选) — 要返回的张量类型。可以是以下之一:
    • Unset: 返回 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)。
    • Unset: 使用输入图像的通道维度格式。
  • 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 ) semantic_segmentation

参数

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

返回值

semantic_segmentation

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

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

SegGptModel

class transformers.SegGptModel

< >

( config: SegGptConfig )

参数

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

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

forward

< >

( 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 (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 像素值。像素值可以使用 AutoImageProcessor 获取。 有关详细信息,请参阅 SegGptImageProcessor.call()
  • prompt_pixel_values (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 提示像素值。提示像素值可以使用 AutoImageProcessor 获取。 有关详细信息,请参阅 SegGptImageProcessor.call()
  • prompt_masks (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 提示掩码。提示掩码可以使用 AutoImageProcessor 获取。 有关详细信息,请参阅 SegGptImageProcessor.call()
  • bool_masked_pos (形状为 (batch_size, num_patches)torch.BoolTensor, 可选) — 布尔掩码位置。指示哪些 patch 被掩码 (1),哪些没有 (0)。
  • feature_ensemble (bool, 可选) — 布尔值,指示是否使用特征集成。如果为 True,则当我们至少有两个提示时,模型将使用特征集成。如果为 False,则模型将不使用特征集成。当对输入图像进行少样本推理时(即同一图像有多个提示),应考虑此参数。
  • embedding_type (str, optional) — 嵌入类型。指示 prompt 是语义嵌入还是实例嵌入。可以是 instance 或 semantic。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。 详见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 详见返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 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.SegGptEncoderOutputtorch.FloatTensor 的元组(如果传递了 return_dict=False 或者当 config.return_dict=False 时),包含各种元素,具体取决于配置 (SegGptConfig) 和输入。

  • last_hidden_state (torch.FloatTensor of shape (batch_size, patch_height, patch_width, hidden_size)) — 模型最后一层的输出处的隐藏状态序列。
  • hidden_states (Tuple[torch.FloatTensor], optional, 当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(embeddings 的输出一个,每层的输出一个),形状为 (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__ 特殊方法。

虽然 forward 传递的配方需要在该函数中定义,但应该调用 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

class transformers.SegGptForImageSegmentation

< >

( config: SegGptConfig )

参数

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

带有用于单次图像分割的解码器的 SegGpt 模型。 此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解所有与常规用法和行为相关的事项。

forward

< >

( 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)) — Prompt 像素值。 Prompt 像素值可以使用 AutoImageProcessor 获得。 参见 SegGptImageProcessor.call() 了解详情。
  • prompt_masks (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — Prompt 掩码。 Prompt 掩码可以使用 AutoImageProcessor 获得。 参见 SegGptImageProcessor.call() 了解详情。
  • bool_masked_pos (torch.BoolTensor of shape (batch_size, num_patches), optional) — 布尔掩码位置。 指示哪些 patch 被掩码 (1) 以及哪些没有 (0)。
  • feature_ensemble (bool, optional) — 布尔值,指示是否使用特征集成。 如果为 True,则当至少有两个 prompt 时,模型将使用特征集成。 如果为 False,则模型将不使用特征集成。 当对输入图像进行少样本推理时,即同一图像有多个 prompt 时,应考虑此参数。
  • embedding_type (str, optional) — 嵌入类型。指示 prompt 是语义嵌入还是实例嵌入。可以是 instance 或 semantic。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。 详见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 详见返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 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.SegGptImageSegmentationOutputtorch.FloatTensor 的元组(如果传递了 return_dict=False 或者当 config.return_dict=False 时),包含各种元素,具体取决于配置 (SegGptConfig) 和输入。

  • loss (torch.FloatTensor, optional, 当提供 labels 时返回) — 损失值。
  • pred_masks (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 预测的掩码。
  • hidden_states (Tuple[torch.FloatTensor], optional, 当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(embeddings 的输出一个,每层的输出一个),形状为 (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)

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

虽然 forward 传递的配方需要在该函数中定义,但应该调用 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]
< > 在 GitHub 上更新