Transformers documentation

SAM-HQ

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

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

SAM-HQ

概述

SAM-HQ(高质量 Segment Anything 模型)由 Lei Ke、Mingqiao Ye、Martin Danelljan、Yifan Liu、Yu-Wing Tai、Chi-Keung Tang 和 Fisher Yu 在 Segment Anything in High Quality 中提出。

该模型是对原始 SAM 模型的增强,在保持 SAM 原有的可提示设计、高效性和零样本泛化能力的同时,能够生成质量显著更高的分割掩码。

example image

SAM-HQ 在原始 SAM 模型的基础上引入了多项关键改进:

  1. 高质量输出标记:注入到 SAM 的掩码解码器中,用于实现更高质量的掩码预测的可学习标记
  2. 全局-局部特征融合:结合模型不同阶段的特征,以改善掩码细节
  3. 训练数据:使用精心筛选的 44K 高质量掩码数据集,而非 SA-1B
  4. 效率:仅增加 0.5% 的额外参数,同时显著提升掩码质量
  5. 零样本能力:在保持 SAM 强大零样本性能的同时,提升了准确性

该论文的摘要如下:

近期的 Segment Anything Model (SAM) 在分割模型的规模化方面实现了重大突破,赋予了模型强大的零样本能力和灵活的提示机制。尽管 SAM 使用了 11 亿个掩码进行训练,但其掩码预测质量在许多情况下仍显不足,尤其是在处理具有复杂结构的物体时。我们提出了 HQ-SAM,在保持 SAM 原有的可提示设计、高效性和零样本泛化能力的前提下,使其具备精确分割任意物体的能力。我们的精心设计复用并保留了 SAM 的预训练模型权重,同时仅引入极少量的额外参数和计算开销。我们设计了一个可学习的高质量输出 Token,将其注入 SAM 的掩码解码器中,用于预测高质量掩码。我们并非仅将其应用于掩码解码器特征,而是先将其与早期和最终的 ViT 特征进行融合,以改善掩码细节。为了训练我们引入的可学习参数,我们从多个来源构建了一个包含 44K 个细粒度掩码的数据集。HQ-SAM 仅在该 44k 掩码数据集上进行训练,在 8 块 GPU 上仅需 4 小时即可完成。

提示:

  • SAM-HQ 生成的掩码质量高于原始 SAM 模型,尤其适用于具有复杂结构和精细细节的物体
  • 该模型预测的二值掩码具有更精确的边界,并且能更好地处理细结构
  • 与 SAM 类似,该模型在使用 2D 点输入和/或边界框输入时表现更佳
  • 您可以为同一图像提示多个点,并预测出单个高质量掩码
  • 该模型保留了 SAM 的零样本泛化能力
  • 与 SAM 相比,SAM-HQ 仅增加了约 0.5% 的额外参数
  • 目前尚不支持微调模型

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

以下示例展示了如何根据图像和 2D 点运行掩码生成:

import requests
import torch
from PIL import Image

from transformers import SamHQModel, SamHQProcessor


model = SamHQModel.from_pretrained("syscv-community/sam-hq-vit-base", device_map="auto")
processor = SamHQProcessor.from_pretrained("syscv-community/sam-hq-vit-base")

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 SamHQModel, SamHQProcessor


model = SamHQModel.from_pretrained("syscv-community/sam-hq-vit-base", device_map="auto")
processor = SamHQProcessor.from_pretrained("syscv-community/sam-hq-vit-base")

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-HQ:

SamHQConfig

class transformers.SamHQConfig

< >

( 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 = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprompt_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonemask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinitializer_range: float = 0.02tie_word_embeddings: bool = True )

参数

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

这是用于存储 SamHQModel 配置的类。它根据指定的参数实例化 Sam Hq 模型,并定义模型架构。使用默认值实例化配置将生成与 syscv-community/sam-hq-vit-base 类似的配置。

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

SamHQVisionConfig

class transformers.SamHQVisionConfig

< >

( 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 = 768output_channels: int = 256num_hidden_layers: int = 12num_attention_heads: int = 12num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 1024patch_size: int | list[int] | tuple[int, int] = 16hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06attention_dropout: float | int = 0.0initializer_range: float = 1e-10qkv_bias: bool = Truemlp_ratio: float = 4.0use_abs_pos: bool = Trueuse_rel_pos: bool = Truewindow_size: int = 14global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)num_pos_feats: int = 128mlp_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],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 1e-10) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • mlp_ratio (float,可选,默认为 4.0) — MLP 隐藏层维度与嵌入维度的比值。
  • use_abs_pos (bool,可选,默认为 True) — 是否使用绝对位置嵌入。
  • use_rel_pos (bool,可选,默认为 True) — 是否使用相对位置嵌入。
  • window_size (int,可选,默认为 14) — 相对位置的窗口大小。
  • global_attn_indexes (list[int],可选,默认为 [2, 5, 8, 11]) — 全局注意力层的索引。
  • num_pos_feats (int,可选,默认为 128) — 位置嵌入的维度。
  • mlp_dim (int, 可选) — Transformer 编码器中 MLP 层的维度。如果为 None,则默认为 mlp_ratio * hidden_size。

这是用于存储 SamHQModel 配置的类。它根据指定的参数实例化 Sam Hq 模型,并定义模型架构。使用默认值实例化配置将生成与 syscv-community/sam-hq-vit-base 类似的配置。

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

示例:

>>> from transformers import (
...     SamHQVisionConfig,
...     SamHQVisionModel,
... )

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

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

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

SamHQMaskDecoderConfig

class transformers.SamHQMaskDecoderConfig

< >

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

参数

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

这是用于存储 SamHQModel 配置的类。它根据指定的参数实例化 Sam Hq 模型,并定义模型架构。使用默认值实例化配置将生成与 syscv-community/sam-hq-vit-base 类似的配置。

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

SamHQPromptEncoderConfig

class transformers.SamHQPromptEncoderConfig

< >

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

参数

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

这是用于存储 SamHQModel 配置的类。它根据指定的参数实例化 Sam Hq 模型,并定义模型架构。使用默认值实例化配置将生成与 syscv-community/sam-hq-vit-base 类似的配置。

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

SamHQProcessor

class transformers.SamHQProcessor

< >

( image_processor )

参数

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

构建一个 SamHQProcessor,它将图像处理器封装为单一处理器。

SamHQProcessor 提供了 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**kwargs: *<class 'transformers.models.sam_hq.processing_sam_hq.SamHQProcessorKwargs'> ) → ~feature_extraction_utils.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, kwargs, 可选) — 与输入图像一起处理的真实分割图。这些分割图用于训练或评估,并会被调整大小和归一化,以匹配处理后的图像尺寸。
  • input_points (NestedList, kwargs, 可选) — 用于基于提示的分割的输入点。应为一个嵌套列表,结构为 [image_level, object_level, point_level, [x, y]],其中每个点以原始图像空间中的 [x, y] 坐标表示。 在传递给模型之前,这些点会被归一化到目标图像尺寸。
  • input_labels (NestedList, kwargs, 可选) — 输入点的标签,指示每个点是前景(1)还是背景(0)。 应为具有 [image_level, object_level, point_level] 结构的嵌套列表。必须与 input_points 具有相同的结构(不包括坐标维度)。
  • input_boxes (NestedList, kwargs, 可选) — 用于基于提示的分割的边界框。应为具有结构 [image_level, box_level, [x1, y1, x2, y2]] 的嵌套列表,其中每个框以原始图像空间中的 [x1, y1, x2, y2] 坐标指定。在传递给模型之前,边界框会归一化到目标图像大小。
  • point_pad_value (int, kwargs, 可选, 默认为 None) — 在对不同长度的序列进行批处理时,用于填充输入点的值。该值用于标记填充位置,并在坐标归一化过程中保留,以区分真实点和填充。如果 None,则使用处理器配置中的默认填充值。
  • mask_size (dict[str, *kwargs*, int], 可选) — 一个字典,用于指定目标掩码大小,键为 "height" 和 "width"。它决定了模型生成的输出分割掩码的分辨率。
  • mask_pad_size (dict[str, *kwargs*, int], 可选) — 一个字典,用于指定掩码的填充大小,键为 "height" 和 "width"。当对大小不同的掩码进行批处理时,使用此参数以确保维度一致。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

返回值

~feature_extraction_utils.BatchFeature

  • data (dict,可选) — 由 call/pad 方法返回的列表/数组/张量字典(例如 ‘input_values’、‘attention_mask’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
  • skip_tensor_conversion(list[str] 或 set[str],可选)——即使指定了 tensor_type,也不应转换为张量的键的列表或集合。

SamHQVisionModel

class transformers.SamHQVisionModel

< >

( config: SamHQVisionConfig )

参数

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

SamHQ 的视觉模型,顶部未添加任何头部或投影层。

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SamHQVisionEncoderOutput or tuple(torch.Tensor)

参数

返回值

SamHQVisionEncoderOutput 或 tuple(torch.Tensor)

SamHQVisionEncoderOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(SamHQConfig)和输入。

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

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

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

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

  • hidden_states (tuple[torch.Tensor, ...],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

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

  • attentions (tuple[torch.Tensor, ...],可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

  • intermediate_embeddings (list(torch.Tensor),可选) — 从模型中特定块(通常是没有窗口注意力的块)收集的中间嵌入列表。列表中的每个元素形状为 (batch_size, sequence_length, hidden_size)。 这是 SAM-HQ 特有的,基础 SAM 中不存在。

SamHQModel

class transformers.SamHQModel

< >

( config: SamHQConfig )

参数

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

Segment Anything Model HQ (SAM-HQ) 用于生成掩码,输入为图像以及可选的 2D 位置和边界框。

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Noneinput_points: typing.Optional[torch.Tensor] = Noneinput_labels: typing.Optional[torch.LongTensor] = Noneinput_boxes: typing.Optional[torch.Tensor] = Noneinput_masks: typing.Optional[torch.LongTensor] = Noneimage_embeddings: typing.Optional[torch.Tensor] = Nonemultimask_output: bool = Truehq_token_only: bool = Falseattention_similarity: typing.Optional[torch.Tensor] = Nonetarget_embedding: typing.Optional[torch.Tensor] = Noneintermediate_embeddings: list[torch.Tensor] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 SamImageProcessor 获取像素值。有关详细信息,请参阅 SamImageProcessor.call()(SamHQProcessor 使用 SamImageProcessor 处理图像)。
  • input_points (torch.Tensor,形状为 (batch_size, num_points, 2)) — 输入的二维空间点,提示编码器使用它来编码提示。通常能带来好得多的结果。可以通过向处理器传入列表的列表的列表来获取这些点,处理器将创建维度为 4 的相应 torch 张量。第一个维度是图像批次大小,第二个维度是点批次大小(即对于每个输入点,我们希望模型预测多少个分割掩码),第三个维度是每个分割掩码对应的点数(可以为单个掩码传入多个点),最后一个维度是点的 x(垂直)和 y(水平)坐标。如果为每张图像或每个掩码传入的点数不同,处理器将创建“PAD”点,这些点对应 (0, 0) 坐标,并且使用标签跳过对这些点的嵌入计算。
  • input_labels (torch.LongTensor 形状为 (batch_size, point_batch_size, num_points)) — 点的输入标签,用于提示编码器对提示进行编码。根据官方实现,共有 3 种标签类型
    • 1:该点是一个包含目标对象的点
    • 0:该点不包含目标对象
    • -1:该点对应背景

    我们添加了标签:

    • -10:该点为填充点,因此应被 prompt encoder 忽略

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

  • input_boxes (torch.Tensor 形状为 (batch_size, num_boxes, 4)) — 用于点的输入框,提示编码器会用它来编码提示。通常能生成质量更好的掩码。可以通过向处理器传入列表的列表来获取这些框,这将生成一个 torch 张量,其各维度分别对应图像批次大小、每张图像的框数以及框的左上角和右下角点的坐标。顺序为 (x1, y1, x2, y2):
    • x1:输入框左上角点的 x 坐标
    • y1:输入框左上角点的 y 坐标
    • x2:输入框右下角点的 x 坐标
    • y2:输入框右下角点的 y 坐标
  • input_masks(形状为 (batch_size, image_size, image_size) 的 torch.Tensor)— SAM_HQ 模型也接受分割掩码作为输入。掩码将由提示编码器嵌入,以生成相应的嵌入,随后输入到掩码解码器中。这些掩码需要由用户手动提供,且其形状必须为 (batch_size, image_size, image_size)。
  • image_embeddings (torch.Tensor,形状为 (batch_size, output_channels, window_size, window_size)) — 图像嵌入,供掩码解码器生成掩码和 IoU 分数。为了进行更节省内存的计算,用户可以首先使用 get_image_embeddings 方法获取图像嵌入,然后将它们输入到 forward 方法中,而不是输入 pixel_values。
  • multimask_output (bool, 可选) — 在原始实现和论文中,模型始终为每张图像输出 3 个掩码(如果相关,则为每个点或每个边界框输出 3 个掩码)。不过,可以通过指定 multimask_output=False 来仅输出单个掩码,该掩码对应于“最佳”掩码。
  • hq_token_only (bool,可选,默认为 False) — 是否仅使用 HQ token 路径来生成掩码。当为 False 时,会同时结合标准路径和 HQ 路径。 此参数专用于 SAM-HQ 的架构。
  • attention_similarity (torch.Tensor, 可选) — 注意力相似度张量,当模型用于如 PerSAM 中所述的个性化时,需将其提供给掩码解码器以实现目标引导的注意力。
  • target_embedding (torch.Tensor, 可选) — 目标概念的嵌入,当模型用于 PerSAM 中介绍的个人化时,需将其提供给掩码解码器以进行目标语义提示。
  • intermediate_embeddings (List[torch.Tensor], 可选) — 来自视觉编码器非窗口化块的中间嵌入,用于 SAM-HQ 以增强掩码质量。 当提供预计算的 image_embeddings 而非 pixel_values 时,此项为必填。

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

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

示例:

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

>>> model = AutoModel.from_pretrained("sushmanth/sam_hq_vit_b")
>>> processor = AutoProcessor.from_pretrained("sushmanth/sam_hq_vit_b")

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

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

>>> # For high-quality mask only
>>> outputs = model(**inputs, hq_token_only=True)

>>> # Postprocess masks
>>> masks = processor.post_process_masks(
...     outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
... )
Update on GitHub