Transformers 文档

SAM

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2023 年 4 月 5 日在 HF 论文中发布,并于 2023 年 4 月 19 日贡献给 Hugging Face Transformers。

SAM

概述

SAM(Segment Anything Model)由 Alexander Kirillov、Eric Mintun、Nikhila Ravi、Hanzi Mao、Chloe Rolland、Laura Gustafson、Tete Xiao、Spencer Whitehead、Alex Berg、Wan-Yen Lo、Piotr Dollar、Ross Girshick 在 Segment Anything 一文中提出。

该模型可用于根据输入图像预测任何感兴趣对象的分割掩码。

example image

论文摘要如下:

我们介绍了 Segment Anything (SA) 项目:一个用于图像分割的新任务、模型和数据集。通过在数据收集循环中使用我们的高效模型,我们构建了迄今为止最大的分割数据集,包含 1100 万张获得许可且保护隐私的图像上的超过 10 亿个掩码。该模型经过设计和训练,具有可提示性,因此可以零样本迁移到新的图像分布和任务。我们在众多任务上评估了其能力,发现其零样本表现令人印象深刻——通常可与之前的全监督结果竞争,甚至优于它们。我们正在 https://segment-anything.com 发布 Segment Anything Model (SAM) 和相应的 10 亿掩码及 1100 万张图像数据集 (SA-1B),以促进计算机视觉基础模型的研究。

技巧

  • 该模型预测二进制掩码,用于说明在给定图像的情况下是否存在感兴趣的对象。
  • 如果提供输入 2D 点和/或输入边界框,模型将预测出更好的结果。
  • 您可以为同一图像提示多个点,并预测单个掩码。
  • 暂不支持对模型进行微调。
  • 根据论文,文本输入也应受到支持。然而,在撰写本文时,根据官方存储库,这似乎尚不支持。

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

以下是关于如何根据图像和 2D 点运行掩码生成的示例。

import requests
import torch
from PIL import Image

from transformers import SamModel, SamProcessor


model = SamModel.from_pretrained("facebook/sam-vit-huge", device_map="auto")
processor = SamProcessor.from_pretrained("facebook/sam-vit-huge")

img_url = "https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png"
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
input_points = [[[450, 600]]]  # 2D location of a window in the image

inputs = processor(raw_image, input_points=input_points, return_tensors="pt").to(model.device)
with torch.no_grad():
    outputs = model(**inputs)

masks = processor.image_processor.post_process_masks(
    outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu()
)
scores = outputs.iou_scores

您还可以在处理器中处理您自己的掩码以及输入图像,以便将其传递给模型。

import requests
import torch
from PIL import Image

from transformers import SamModel, SamProcessor


model = SamModel.from_pretrained("facebook/sam-vit-huge", device_map="auto")
processor = SamProcessor.from_pretrained("facebook/sam-vit-huge")

img_url = "https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png"
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
mask_url = "https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png"
segmentation_map = Image.open(requests.get(mask_url, stream=True).raw).convert("1")
input_points = [[[450, 600]]]  # 2D location of a window in the image

inputs = processor(raw_image, input_points=input_points, segmentation_maps=segmentation_map, return_tensors="pt").to(model.device)
with torch.no_grad():
    outputs = model(**inputs)

masks = processor.image_processor.post_process_masks(
    outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu()
)
scores = outputs.iou_scores

资源

以下是一份官方 Hugging Face 和社区(以 🌎 标示)资源列表,旨在帮助您开始使用 SAM。

SlimSAM

SlimSAM 是 SAM 的剪枝版本,由 Zigeng Chen 等人在 0.1% Data Makes Segment Anything Slim 中提出。SlimSAM 在保持相同性能的同时,显著减小了 SAM 模型的大小。

检查点可在 hub 上找到,它们可以用作 SAM 的直接替代品。

Grounded SAM

正如 Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks 所介绍的那样,可以将 Grounding DINO 与 SAM 结合用于基于文本的掩码生成。详情请参阅此 演示笔记本 🌍。

drawing Grounded SAM 概述。摘自原始存储库

SamConfig

class transformers.SamConfig

< >

( 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 vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None prompt_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None mask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None initializer_range: float = 0.02 tie_word_embeddings: bool = True )

参数

  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig], 可选) — 视觉主干网络的配置对象或字典。
  • prompt_encoder_config (Union[dict, SamPromptEncoderConfig], 可选) — 用于初始化 SamPromptEncoderConfig 的配置选项字典。
  • mask_decoder_config (Union[dict, SamMaskDecoderConfig], 可选) — 用于初始化 SamMaskDecoderConfig 的配置选项字典。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • tie_word_embeddings (bool, 可选, 默认为 True) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 SamModel 配置的配置类。它用于根据指定的参数实例化 Sam 模型,定义模型架构。使用默认值实例化配置将产生与 facebook/sam-vit-huge 相似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。阅读 PreTrainedConfig 的文档以获取更多信息。

示例

>>> from transformers import (
...     SamVisionConfig,
...     SamPromptEncoderConfig,
...     SamMaskDecoderConfig,
...     SamModel,
... )

>>> # Initializing a SamConfig with `"facebook/sam-vit-huge"` style configuration
>>> configuration = SamConfig()

>>> # Initializing a SamModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
>>> model = SamModel(configuration)

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

>>> # We can also initialize a SamConfig from a SamVisionConfig, SamPromptEncoderConfig, and SamMaskDecoderConfig

>>> # Initializing SAM vision, SAM Q-Former and language model configurations
>>> vision_config = SamVisionConfig()
>>> prompt_encoder_config = SamPromptEncoderConfig()
>>> mask_decoder_config = SamMaskDecoderConfig()

>>> config = SamConfig(vision_config, prompt_encoder_config, mask_decoder_config)

SamVisionConfig

class transformers.SamVisionConfig

< >

( 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 = 768 output_channels: int = 256 num_hidden_layers: int = 12 num_attention_heads: int = 12 num_channels: int = 3 image_size: int | list[int] | tuple[int, int] = 1024 patch_size: int | list[int] | tuple[int, int] = 16 hidden_act: str = 'gelu' layer_norm_eps: float = 1e-06 attention_dropout: float | int = 0.0 initializer_range: float = 1e-10 qkv_bias: bool = True mlp_ratio: float = 4.0 use_abs_pos: bool = True use_rel_pos: bool = True window_size: int = 14 global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11) num_pos_feats: int = 128 mlp_dim: int | None = None )

参数

  • hidden_size (int, 可选, 默认为 768) — 隐藏表示的维度。
  • output_channels (int, 可选, 默认为 256) — Patch Encoder 中输出通道的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int, 可选, 默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • image_size (Union[int, list[int], tuple[int, int]], 可选, 默认为 1024) — 每个图像的大小(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]], 可选, 默认为 16) — 每个补丁(patch)的大小(分辨率)。
  • hidden_act (str, 可选, 默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu", "relu", "silu" 等。
  • layer_norm_eps (float, 可选, 默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int], optional, defaults to 0.0) — 注意力概率的丢弃率(dropout ratio)。
  • initializer_range (float, optional, defaults to 1e-10) — 用于初始化所有权重矩阵的截断正态分布初始化器(truncated_normal_initializer)的标准差。
  • qkv_bias (bool, optional, defaults to True) — 是否为查询(queries)、键(keys)和值(values)添加偏置(bias)。
  • mlp_ratio (float, optional, defaults to 4.0) — MLP 隐藏维度与嵌入维度的比例。
  • use_abs_pos (bool, optional, defaults to True) — 是否使用绝对位置嵌入。
  • use_rel_pos (bool, optional, defaults to True) — 是否使用相对位置嵌入。
  • window_size (int, optional, defaults to 14) — 相对位置的窗口大小。
  • global_attn_indexes (list[int], optional, defaults to [2, 5, 8, 11]) — 全局注意力层的索引。
  • num_pos_feats (int, optional, defaults to 128) — 位置嵌入的维度。
  • mlp_dim (int, optional) — Transformer 编码器中 MLP 层的维度。如果为 None,则默认为 mlp_ratio * hidden_size

这是用于存储 SamModel 配置的配置类。它用于根据指定的参数实例化 Sam 模型,定义模型架构。使用默认值实例化配置将产生与 facebook/sam-vit-huge 相似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。阅读 PreTrainedConfig 的文档以获取更多信息。

示例

>>> from transformers import (
...     SamVisionConfig,
...     SamVisionModel,
... )

>>> # Initializing a SamVisionConfig with `"facebook/sam-vit-huge"` style configuration
>>> configuration = SamVisionConfig()

>>> # Initializing a SamVisionModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
>>> model = SamVisionModel(configuration)

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

SamMaskDecoderConfig

class transformers.SamMaskDecoderConfig

< >

( 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 = 256 hidden_act: str = 'relu' mlp_dim: int = 2048 num_hidden_layers: int = 2 num_attention_heads: int = 8 attention_downsample_rate: int = 2 num_multimask_outputs: int = 3 iou_head_depth: int = 3 iou_head_hidden_dim: int = 256 layer_norm_eps: float = 1e-06 )

参数

  • hidden_size (int, optional, defaults to 256) — 隐藏表示的维度。
  • hidden_act (str, optional, defaults to relu) — 解码器中的非线性激活函数(函数或字符串)。例如:"gelu""relu""silu" 等。
  • mlp_dim (int, optional, defaults to 2048) — Transformer 编码器中“中间”(即前馈)层的维度。
  • num_hidden_layers (int, optional, defaults to 2) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int, optional, defaults to 8) — Transformer 解码器中每个注意力层的注意力头数。
  • attention_downsample_rate (int, optional, defaults to 2) — 注意力层的下采样率。
  • num_multimask_outputs (int, optional, defaults to 3) — SamMaskDecoder 模块的输出数量。在 Segment Anything 论文中,此值设为 3。
  • iou_head_depth (int, optional, defaults to 3) — IoU 头模块中的层数。
  • iou_head_hidden_dim (int, optional, defaults to 256) — IoU 头模块中隐藏状态的维度。
  • layer_norm_eps (float, optional, defaults to 1e-06) — 层归一化层所使用的 epsilon 值。

这是用于存储 SamModel 配置的配置类。它用于根据指定的参数实例化 Sam 模型,定义模型架构。使用默认值实例化配置将产生与 facebook/sam-vit-huge 相似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。阅读 PreTrainedConfig 的文档以获取更多信息。

SamPromptEncoderConfig

class transformers.SamPromptEncoderConfig

< >

( 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 = 256 image_size: int | list[int] | tuple[int, int] = 1024 patch_size: int | list[int] | tuple[int, int] = 16 mask_input_channels: int = 16 num_point_embeddings: int = 4 hidden_act: str = 'gelu' layer_norm_eps: float = 1e-06 )

参数

  • hidden_size (int, optional, 默认为 256) — 隐藏表示的维度。
  • image_size (Union[int, list[int], tuple[int, int]], optional, 默认为 1024) — 每个图像的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]], optional, 默认为 16) — 每个块(patch)的尺寸(分辨率)。
  • mask_input_channels (int, optional, 默认为 16) — 提供给 MaskDecoder 模块的通道数。
  • num_point_embeddings (int, optional, 默认为 4) — 要使用的点嵌入(point embeddings)数量。
  • hidden_act (str, optional, 默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如:"gelu", "relu", "silu" 等。
  • layer_norm_eps (float, optional, 默认为 1e-06) — 层归一化层使用的 epsilon 值。

这是用于存储 SamModel 配置的配置类。它用于根据指定的参数实例化 Sam 模型,定义模型架构。使用默认值实例化配置将产生与 facebook/sam-vit-huge 相似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。阅读 PreTrainedConfig 的文档以获取更多信息。

SamProcessor

class transformers.SamProcessor

< >

( image_processor )

参数

  • image_processor (SamImageProcessor) — 图像处理器是必需的输入。

构建一个将图像处理器包装成单个处理器的 SamProcessor。

SamProcessor 提供了 SamImageProcessor 的所有功能。有关更多信息,请参阅 ~SamImageProcessor

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None text: str | list[str] | list[list[str]] | None = None **kwargs ) ~tokenization_utils_base.BatchEncoding

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], optional) — 要预处理的图像。期望输入单个图像或一批像素值在 0 到 255 之间的图像。如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • text (Union[str, list[str], list[list[str]]], optional) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词字符串)。如果您传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入混淆。
  • return_tensors (strTensorType, optional) — 如果设置,将返回特定框架的张量。可接受的值为:

    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。

返回

~tokenization_utils_base.BatchEncoding

  • data (dict, optional) — 由 __call__/encode_plus/batch_encode_plus 方法返回的列表/数组/张量字典(‘input_ids’、‘attention_mask’ 等)。
  • encoding (tokenizers.Encoding or Sequence[tokenizers.Encoding], optional) — 如果分词器是一个快速分词器,它会输出额外的映射信息(例如从单词/字符空间到分词空间的映射),则 tokenizers.Encoding 实例或实例列表(用于批处理)将包含此信息。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。
  • prepend_batch_axis (bool, optional, defaults to False) — 转换成张量时是否添加批处理轴(参见上面的 tensor_type)。请注意,此参数仅在设置了参数 tensor_type 时才有效,否则无效
  • n_sequences (int, 可选) — 你可以在此处提供一个 tensor_type,以便在初始化时将整数列表转换为 PyTorch/Numpy 张量。

SamImageProcessor

class transformers.SamImageProcessor

< >

( **kwargs: typing_extensions.Unpack[transformers.models.sam.image_processing_sam.SamImageProcessorKwargs] )

参数

  • mask_size (dict[str, *kwargs*, int], optional) — 用于将分割图调整为的目标尺寸 {"longest_edge": int}
  • mask_pad_size (dict[str, *kwargs*, int], optional) — 用于将分割图填充到的目标尺寸 {"height": int, "width": int}。必须大于为预处理提供的任何分割图尺寸。
  • **kwargs (ImagesKwargs, optional) — 其他图像预处理选项。模型特定的 kwargs 列在上面;请参阅 TypedDict 类以获取支持参数的完整列表。

构建一个 SamImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] segmentation_maps: 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.sam.image_processing_sam.SamImageProcessorKwargs] ) ~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
  • segmentation_maps (ImageInput, optional) — 要预处理的分割图。
  • mask_size (dict[str, *kwargs*, int], 可选) — 用于将分割图调整大小的尺寸 {"longest_edge": int}
  • mask_pad_size (dict[str, *kwargs*, int], 可选) — 用于填充分割图的尺寸 {"height": int, "width": int}。必须大于为预处理提供的任何分割图尺寸。
  • 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 张量。

SamImageProcessorPil

class transformers.SamImageProcessorPil

< >

( **kwargs: typing_extensions.Unpack[transformers.models.sam.image_processing_pil_sam.SamImageProcessorKwargs] )

参数

  • mask_size (dict[str, *kwargs*, int], 可选) — 用于将分割图调整大小的尺寸 {"longest_edge": int}
  • mask_pad_size (dict[str, *kwargs*, int], 可选) — 用于填充分割图的尺寸 {"height": int, "width": int}。必须大于为预处理提供的任何分割图尺寸。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 列在上方;请参阅 TypedDict 类以获取支持参数的完整列表。

构建一个 SamImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] segmentation_maps: 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.sam.image_processing_pil_sam.SamImageProcessorKwargs] ) ~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
  • segmentation_maps (ImageInput, 可选) — 待预处理的分割图。
  • mask_size (dict[str, *kwargs*, int], 可选) — 用于将分割图调整大小的尺寸 {"longest_edge": int}
  • mask_pad_size (dict[str, *kwargs*, int], 可选) — 用于填充分割图的尺寸 {"height": int, "width": int}。必须大于为预处理提供的任何分割图尺寸。
  • 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 张量。

SamVisionModel

class transformers.SamVisionModel

< >

( config: SamVisionConfig )

参数

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

Sam 的视觉模型,没有任何头部或顶部投影。

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

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

forward

< >

( pixel_values: torch.FloatTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) SamVisionEncoderOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor, 可选) — 对应于输入图像的张量。可以使用 SamImageProcessor 获取像素值。有关详细信息,请参阅 SamImageProcessor.__call__()SamProcessor 使用 SamImageProcessor 来处理图像)。

返回

SamVisionEncoderOutputtuple(torch.FloatTensor)

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

SamVisionModel 前向传递方法,覆盖了 __call__ 特殊方法。

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

  • image_embeds (torch.FloatTensor, shape (batch_size, output_dim), 当模型初始化时 with_projection=True 返回可选) — 通过将投影层应用于 pooler_output 得到的图像嵌入。

  • last_hidden_state (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor, 可选,默认为 None) — 模型最后一层输出的隐藏状态序列。

  • hidden_states (tuple[torch.FloatTensor, ...]可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则第一个为嵌入输出,其余为每一层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple[torch.FloatTensor, ...]可选,当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — torch.FloatTensor 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

SamModel

class transformers.SamModel

< >

( config: SamConfig )

参数

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

Segment Anything Model (SAM),用于在给定输入图像、输入点、标签、框或掩码的情况下生成分割掩码。

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

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

forward

< >

( pixel_values: torch.FloatTensor | None = None input_points: torch.FloatTensor | None = None input_labels: torch.LongTensor | None = None input_boxes: torch.FloatTensor | None = None input_masks: torch.LongTensor | None = None image_embeddings: torch.FloatTensor | None = None multimask_output: bool = True attention_similarity: torch.FloatTensor | None = None target_embedding: torch.FloatTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) SamImageSegmentationOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)可选) — 对应于输入图像的张量。像素值可以使用 SamImageProcessor 获取。详情请参阅 SamImageProcessor.__call__()SamProcessor 使用 SamImageProcessor 处理图像)。
  • input_points (torch.FloatTensor,形状为 (batch_size, num_points, 2)) — 输入的二维空间点,供提示编码器(prompt encoder)对提示进行编码。通常会产生更好的结果。这些点可以通过向处理器传入嵌套列表来获取,处理器将创建相应维度的 torch 张量。第一维是图像批次大小,第二维是点批次大小(即我们希望模型为每个输入点预测多少个分割掩码),第三维是每个分割掩码的点数(可以为单个掩码传入多个点),最后一维是点的 x(垂直)和 y(水平)坐标。如果每张图像或每个掩码传入的点数不同,处理器将创建对应于 (0, 0) 坐标的“填充(PAD)”点,并利用标签跳过这些点的嵌入计算。
  • input_labels (torch.LongTensor,形状为 (batch_size, point_batch_size, num_points)) — 点的输入标签,供提示编码器对提示进行编码。根据官方实现,标签共有 3 种类型:

    • 1:该点包含感兴趣的对象
    • 0:该点不包含感兴趣的对象
    • -1:该点对应背景

    我们添加了以下标签:

    • -10:该点是填充点,因此应被提示编码器忽略

    填充标签应由处理器自动处理。

  • input_boxes (torch.FloatTensor,形状为 (batch_size, num_boxes, 4)) — 框的输入坐标,供提示编码器对提示进行编码。通常能生成质量更好的掩码。这些框可以通过向处理器传入嵌套列表来获取,从而生成 torch 张量,其维度分别对应图像批次大小、每张图像的框数以及框的左上角和右下角坐标。顺序为 (x1, y1, x2, y2):

    • x1:输入框左上角的 x 坐标
    • y1:输入框左上角的 y 坐标
    • x2:输入框右下角的 x 坐标
    • y2:输入框右下角的 y 坐标
  • input_masks (torch.FloatTensor,形状为 (batch_size, image_size, image_size)) — SAM 模型也接受分割掩码作为输入。该掩码将由提示编码器嵌入以生成相应的嵌入,随后馈送给掩码解码器。这些掩码需要由用户手动提供,且形状必须为 (batch_size, image_size, image_size)。
  • image_embeddings (torch.FloatTensor,形状为 (batch_size, output_channels, window_size, window_size)) — 图像嵌入,供掩码解码器生成掩码和 IoU 分数。为了获得更高的计算内存效率,用户可以先通过 get_image_embeddings 方法检索图像嵌入,然后将其馈送给 forward 方法,而不是直接传入 pixel_values
  • multimask_output (bool可选) — 在原始实现和论文中,模型始终为每张图像(或每个点/每个边界框,如果相关)输出 3 个掩码。但是,通过指定 multimask_output=False,可以仅输出对应“最佳”掩码的单个掩码。
  • attention_similarity (torch.FloatTensor可选) — 注意力相似度张量,用于在模型被用于如 PerSAM 中介绍的个性化场景时,提供给掩码解码器进行目标引导的注意力计算。
  • target_embedding (torch.FloatTensor可选) — 目标概念的嵌入,用于在模型被用于如 PerSAM 中介绍的个性化场景时,提供给掩码解码器进行目标语义提示。

返回

SamImageSegmentationOutputtuple(torch.FloatTensor)

一个 SamImageSegmentationOutput 或一个 torch.FloatTensor 元组(如果传入 return_dict=False 或当 config.return_dict=False 时),根据配置(SamConfig)和输入,包含不同的元素。

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

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

  • iou_scores (torch.FloatTensor,形状为 (batch_size, num_masks)) — 预测掩码的 IoU 分数。

  • pred_masks (torch.FloatTensor,形状为 (batch_size, num_masks, height, width)) — 预测的低分辨率掩码。需要由处理器进行后处理。

  • vision_hidden_states (tuple(torch.FloatTensor)可选,当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元组(一个用于嵌入输出(如果有嵌入层),+ 每个层的输出各一个)。

    视觉模型在每一层输出的隐藏状态,加上可选的初始嵌入输出。

  • vision_attentions (tuple(torch.FloatTensor)可选,当传入 output_attentions=Trueconfig.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)torch.FloatTensor 元组(每一层一个)。

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

  • mask_decoder_attentions (tuple(torch.FloatTensor)可选,当传入 output_attentions=Trueconfig.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)torch.FloatTensor 元组(每一层一个)。

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

示例

>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO
>>> from transformers import AutoModel, AutoProcessor

>>> model = AutoModel.from_pretrained("facebook/sam-vit-base")
>>> processor = AutoProcessor.from_pretrained("facebook/sam-vit-base")

>>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png"
>>> with httpx.stream("GET", url) as response:
...     raw_image = Image.open(BytesIO(response.read())).convert("RGB")
>>> input_points = [[[400, 650]]]  # 2D location of a window on the car
>>> inputs = processor(images=raw_image, input_points=input_points, return_tensors="pt")

>>> # Get segmentation mask
>>> outputs = model(**inputs)

>>> # Postprocess masks
>>> masks = processor.post_process_masks(
...     outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
... )
在 GitHub 上更新

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