Transformers 文档

SegGPT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

此模型于 2023 年 4 月 6 日发布在 HF 论文中,并于 2024 年 2 月 26 日贡献给 Hugging Face Transformers。

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 的显著少样本(one-shot)成果。

论文摘要如下:

我们提出了 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 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 = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None hidden_size: int = 1024 num_hidden_layers: int = 24 num_attention_heads: int = 16 hidden_act: str = 'gelu' hidden_dropout_prob: float | int = 0.0 initializer_range: float = 0.02 layer_norm_eps: float = 1e-06 image_size: int | list[int] | tuple[int, ...] = (896, 448) patch_size: int | list[int] | tuple[int, int] = 16 num_channels: int = 3 qkv_bias: bool = True mlp_dim: int | None = None drop_path_rate: float | int = 0.1 pretrain_image_size: int | list[int] | tuple[int, int] = 224 decoder_hidden_size: int = 64 use_relative_position_embeddings: bool = True merge_index: int = 2 intermediate_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) — 嵌入、编码器和池化层中所有全连接层的丢弃概率。
  • initializer_range (float, 可选, 默认值为 0.02) — 用于初始化所有权重矩阵的截断正态分布初始化器的标准差。
  • 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) — 是否为查询(queries)、键(keys)和值(values)添加偏差。
  • mlp_dim (int, 可选) — Transformer 编码器中 MLP 层的维度。如果未设置,则默认为 hidden_size * 4。
  • drop_path_rate (Union[float, int], 可选, 默认值为 0.1) — 用于块融合(patch fusion)的 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: typing_extensions.Unpack[transformers.models.seggpt.image_processing_seggpt.SegGptImageProcessorKwargs] )

参数

  • num_labels (int, kwargs, 可选) — 分割任务中的类别数量(不含背景)。如果指定了该参数,将假设 class_idx 0 为背景并构建调色板,将提示掩码从普通分割图映射为 3 通道的 RGB 图像。若不指定此参数,当 do_convert_rgbTrue 时,提示掩码将沿通道维度进行复制。
  • **kwargs (ImagesKwargs, 可选) — 附加的图像预处理选项。模型特定的 kwargs 列在上面;请参阅 TypedDict 类以获取支持参数的完整列表。

构建一个 SegGptImageProcessor 图像处理器。

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 **kwargs: typing_extensions.Unpack[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,提示掩码将沿通道维度进行复制。
  • num_labels (int, kwargs, 可选) — 分割任务中的类别数量(不含背景)。如果指定了该参数,将假设 class_idx 0 为背景并构建调色板,将提示掩码从普通分割图映射为 3 通道的 RGB 图像。若不指定此参数,当 do_convert_rgbTrue 时,提示掩码将沿通道维度进行复制。
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt' 则返回堆叠的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 附加的图像预处理选项。模型特定的 kwargs 列在上面;请参阅 TypedDict 类以获取支持参数的完整列表。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

post_process_semantic_segmentation

< >

( outputs target_sizes: list[tuple[int, int]] | None = None num_labels: int | None = None )

参数

  • outputs (SegGptImageSegmentationOutput) — 模型的原始输出。
  • target_sizes (list[tuple[int, int]], 可选) — 长度为 batch_size 的列表,其中每个项目对应每个预测所需的最终尺寸 (高度, 宽度)。如果留为 None,则不会调整预测结果的大小。
  • num_labels (int, 可选) — 分割任务中的类别数量(不含背景)。如果指定了该参数,将构建调色板以将预测掩码从 RGB 值映射回类别索引。应与预处理期间使用的值匹配。

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

SegGptImageProcessorPil

class transformers.SegGptImageProcessorPil

< >

( **kwargs: typing_extensions.Unpack[transformers.models.seggpt.image_processing_pil_seggpt.SegGptImageProcessorKwargs] )

参数

  • num_labels (int, kwargs, 可选) — 分割任务中的类别数量(不含背景)。如果指定了该参数,将假设 class_idx 0 为背景并构建调色板,将提示掩码从普通分割图映射为 3 通道的 RGB 图像。若不指定此参数,当 do_convert_rgbTrue 时,提示掩码将沿通道维度进行复制。
  • **kwargs (ImagesKwargs, 可选) — 附加的图像预处理选项。模型特定的 kwargs 列在上面;请参阅 TypedDict 类以获取支持参数的完整列表。

构建一个 SegGptImageProcessor 图像处理器。

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 **kwargs: typing_extensions.Unpack[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,提示掩码将沿通道维度进行复制。
  • num_labels (int, kwargs, 可选) — 分割任务中的类别数量(不包括背景)。如果指定,将构建一个调色板,假设 class_idx 0 为背景,用于将提示遮罩(prompt mask)从普通分割图映射为 3 通道 RGB 图像。如果不指定,当 do_convert_rgbTrue 时,提示遮罩将在通道维度上进行复制。
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt',则返回堆叠后的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 列在上方;请参阅 TypedDict 类以获取支持参数的完整列表。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

post_process_semantic_segmentation

< >

( outputs target_sizes: list[tuple[int, int]] | None = None num_labels: int | None = None )

参数

  • outputs (SegGptImageSegmentationOutput) — 模型的原始输出。
  • target_sizes (list[tuple[int, int]], 可选) — 长度为 batch_size 的列表,每一项对应每个预测所请求的最终尺寸 (高度, 宽度)。如果保持为 None,预测结果将不会被调整大小。
  • num_labels (int, 可选) — 分割任务中的类别数量(不包括背景)。如果指定,将构建一个调色板,用于将预测遮罩从 RGB 值映射回类别索引。应与预处理期间使用的值匹配。

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

SegGptModel

class transformers.SegGptModel

< >

( config: SegGptConfig )

参数

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

基础 Seggpt 模型,输出原始隐藏状态,顶部没有任何特定的头(head)。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: Tensor prompt_pixel_values: Tensor prompt_masks: Tensor bool_masked_pos: torch.BoolTensor | None = None feature_ensemble: bool | None = None embedding_type: str | None = None labels: torch.FloatTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) SegGptEncoderOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 输入图像对应的张量。像素值可以使用 SegGptImageProcessor 获取。详情请参阅 SegGptImageProcessor.__call__()processor_class 使用 SegGptImageProcessor 来处理图像)。
  • prompt_pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 提示像素值。提示像素值可以使用 AutoImageProcessor 获取。详情请参阅 SegGptImageProcessor.__call__()
  • prompt_masks (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 提示遮罩。提示遮罩可以使用 AutoImageProcessor 获取。详情请参阅 SegGptImageProcessor.__call__()
  • bool_masked_pos (torch.BoolTensor,形状为 (batch_size, num_patches), 可选) — 布尔遮罩位置。指示哪些块(patches)被遮罩(1),哪些没有(0)。
  • feature_ensemble (bool, 可选) — 指示是否使用特征集成(feature ensemble)的布尔值。如果为 True,且我们至少有两个提示时,模型将使用特征集成。如果为 False,模型将不使用特征集成。当对输入图像进行少样本(few-shot)推理时(即对同一图像使用多个提示),应考虑此参数。
  • embedding_type (str, 可选) — 嵌入类型。指示提示是语义嵌入还是实例嵌入。可以是 instance 或 semantic。
  • labels (torch.FloatTensor,形状为 (batch_size, num_channels, height, width), 可选) — 输入图像的真实标签遮罩(ground truth mask)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量中的 hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 对象,而不是普通元组。

返回

SegGptEncoderOutputtuple(torch.FloatTensor)

根据配置(SegGptConfig)和输入,SegGptEncoderOutputtorch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素。

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

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • last_hidden_state (torch.FloatTensor,形状为 (batch_size, patch_height, patch_width, hidden_size)) — 模型最后一层输出的隐藏状态序列。
  • 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)
  • intermediate_hidden_states (tuple[torch.FloatTensor], 可选, 当设置了 config.intermediate_hidden_state_indices 时返回) — torch.FloatTensor 元组,形状为 (batch_size, patch_height, patch_width, hidden_size)。元组中的每个元素对应 config.intermediate_hidden_state_indices 中指定的层的输出。此外,每个特征都经过了 LayerNorm。

示例

>>> from transformers import SegGptImageProcessor, SegGptModel
>>> from PIL import Image
>>> 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 模型,用于单样本(one-shot)图像分割。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: Tensor prompt_pixel_values: Tensor prompt_masks: Tensor bool_masked_pos: torch.BoolTensor | None = None feature_ensemble: bool | None = None embedding_type: str | None = None labels: torch.FloatTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) SegGptImageSegmentationOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.Tensor) — 输入图像对应的张量。像素值可以使用 SegGptImageProcessor 获取。详细信息请参阅 SegGptImageProcessor.__call__()processor_class 使用 SegGptImageProcessor 来处理图像)。
  • 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可选) — 指示是否使用特征集成(feature ensemble)的布尔值。如果为 True,且我们有至少两个提示时,模型将使用特征集成。如果为 False,模型将不使用特征集成。在对输入图像进行 few-shot 推理时(即对同一图像有多个提示),应考虑此参数。
  • embedding_type (str可选) — 嵌入类型。指示提示是语义嵌入还是实例嵌入。可以是 `instance` 或 `semantic`。
  • labels (形状为 (batch_size, num_channels, height, width)torch.FloatTensor可选) — 输入图像的真实掩码(ground truth mask)。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。更多详细信息请参阅返回张量中的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。更多详细信息请参阅返回张量中的 hidden_states
  • return_dict (bool可选) — 是否返回 ModelOutput 而不是普通的元组。

返回

SegGptImageSegmentationOutputtuple(torch.FloatTensor)

一个 SegGptImageSegmentationOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置(SegGptConfig)和输入,包含各种元素。

SegGptForImageSegmentation 的前向传播方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • loss (torch.FloatTensor可选,在提供 labels 时返回) — 损失值。
  • pred_masks (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 预测的掩码。
  • 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 时返回) — 形状为 (batch_size, num_heads, seq_len, seq_len)torch.FloatTensor 元组(每一层一个)。

示例

>>> from transformers import SegGptImageProcessor, SegGptForImageSegmentation
>>> from PIL import Image
>>> 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]
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.