# 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](https://huggingface.co/papers/2304.02643) 中提出。

给定一张输入图像，该模型可用于预测任意感兴趣对象的分割掩码。

![example image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-output.png)

该论文的摘要如下：

*我们推出了 Segment Anything（SA）项目：一个用于图像分割的新任务、新模型和新数据集。利用我们的高效模型进行数据收集循环，我们构建了迄今为止规模最大的分割数据集（远超以往），包含超过 10 亿个掩码，覆盖 1100 万张具有授权且尊重隐私的图像。该模型经过专门设计和训练，支持提示（promptable），因此可以零样本迁移到新的图像分布和任务中。我们在众多任务上评估了其能力，发现其零样本性能令人印象深刻——通常与以往的完全监督结果相当，甚至更优。我们在 [https://segment-anything.com](https://segment-anything.com) 发布了 Segment Anything Model（SAM）以及包含 10 亿个掩码和 1100 万张图像的数据集（SA-1B），以促进计算机视觉基础模型的研究。*

提示：

- 该模型预测二值掩码，用于指示给定图像中目标对象是否存在。
- 如果提供 2D 输入点和/或输入边界框，模型的预测结果会好得多
- 您可以为同一图像提示多个点，并预测单个掩码。
- 目前尚不支持微调模型
- 根据论文，文本输入也应得到支持。然而，截至本文撰写之时，[官方仓库](https://github.com/facebookresearch/segment-anything/issues/4#issuecomment-1497626844)似乎尚未支持该功能。

该模型由 [ybelkada](https://huggingface.co/ybelkada) 和 [ArthurZ](https://huggingface.co/ArthurZ) 贡献。原始代码可在[此处](https://github.com/facebookresearch/segment-anything)找到。

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

```python
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
```

您也可以在处理器中同时处理输入图像和自定义掩码，并将其传递给模型。

```python
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。

- 用于使用该模型的[演示笔记本](https://github.com/huggingface/notebooks/blob/main/examples/segment_anything.ipynb)。
- 用于自动掩码生成流水线的[演示笔记本](https://github.com/huggingface/notebooks/blob/main/examples/automatic_mask_generation.ipynb)。
- 用于 MedSAM 推理的[演示笔记本](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/SAM/Run_inference_with_MedSAM_using_HuggingFace_Transformers.ipynb)，MedSAM 是 SAM 在医疗领域的微调版本。🌎
- 用于在自定义数据上微调模型的[演示笔记本](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/SAM/Fine_tune_SAM_(segment_anything)_on_a_custom_dataset.ipynb)。🌎

## SlimSAM

SlimSAM 是 SAM 的剪枝版本，由 Zigeng Chen 等人在 [0.1% Data Makes Segment Anything Slim](https://huggingface.co/papers/2312.05284) 中提出。SlimSAM 在保持相同性能的同时，大幅减小了 SAM 模型的体积。

可以在 [hub](https://huggingface.co/models?other=slimsam) 上找到检查点，它们可以作为 SAM 的直接替代品使用。

## Grounded SAM

可以将 [Grounding DINO](grounding-dino) 与 SAM 结合，实现基于文本的掩码生成，如 [Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks](https://huggingface.co/papers/2401.14159) 中所述。有关详细信息，请参阅此 [演示笔记本](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Grounding%20DINO/GroundingDINO_with_Segment_Anything.ipynb) 🌍。

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/grounded_sam.png"
alt="drawing" width="900"/>

 Grounded SAM 概览。摘自原始仓库。

## SamConfig[[transformers.SamConfig]]

#### transformers.SamConfig[[transformers.SamConfig]]

```python
transformers.SamConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = 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: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = 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)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/configuration_sam.py#L146)

**参数：**

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：视觉骨干网络的配置对象或字典。

prompt_encoder_config (Union[`dict`, `SamPromptEncoderConfig`], *可选*) : 用于初始化 [SamPromptEncoderConfig](/docs/transformers/main/zh/model_doc/sam#transformers.SamPromptEncoderConfig) 的配置选项字典。

mask_decoder_config (Union[`dict`, `SamMaskDecoderConfig`], *可选*) : 用于初始化 [SamMaskDecoderConfig](/docs/transformers/main/zh/model_doc/sam#transformers.SamMaskDecoderConfig) 的配置选项字典。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

tie_word_embeddings (`bool`，*可选*，默认为 `True`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 SamModel 配置的类。它根据指定的参数实例化 Sam 模型，并定义模型架构。使用默认值实例化配置将生成与 [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> 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[[transformers.SamVisionConfig]]

#### transformers.SamVisionConfig[[transformers.SamVisionConfig]]

```python
transformers.SamVisionConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = 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: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = 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)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/configuration_sam.py#L81)

**参数：**

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`。

这是用于存储 SamModel 配置的类。它根据指定的参数实例化 Sam 模型，并定义模型架构。使用默认值实例化配置将生成与 [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> 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[[transformers.SamMaskDecoderConfig]]

#### transformers.SamMaskDecoderConfig[[transformers.SamMaskDecoderConfig]]

```python
transformers.SamMaskDecoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = 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: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = 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)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/configuration_sam.py#L50)

**参数：**

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。

这是用于存储 SamModel 配置的类。它根据指定的参数实例化 Sam 模型，并定义模型架构。使用默认值实例化配置将生成与 [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

## SamPromptEncoderConfig[[transformers.SamPromptEncoderConfig]]

#### transformers.SamPromptEncoderConfig[[transformers.SamPromptEncoderConfig]]

```python
transformers.SamPromptEncoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = 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: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = 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)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/configuration_sam.py#L24)

**参数：**

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。

这是用于存储 SamModel 配置的类。它根据指定的参数实例化 Sam 模型，并定义模型架构。使用默认值实例化配置将生成与 [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

## SamProcessor[[transformers.SamProcessor]]

#### transformers.SamProcessor[[transformers.SamProcessor]]

```python
transformers.SamProcessor(image_processor)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/processing_sam.py#L82)

**参数：**

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

构建一个 SamProcessor，将图像处理器封装为单一处理器。

[SamProcessor](/docs/transformers/main/zh/model_doc/sam#transformers.SamProcessor) 提供了 [SamImageProcessor](/docs/transformers/main/zh/model_doc/sam#transformers.SamImageProcessor) 的所有功能。有关更多信息，请参阅 [~SamImageProcessor](/docs/transformers/main/zh/model_doc/sam#transformers.SamImageProcessor)。

#### __调用__[[transformers.SamProcessor.__call__]]

```python
__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)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/processing_sam.py#L87)

**参数：**

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`。

text (`Union[str, list[str], list[list[str]]]`，*可选*)：要编码的序列或序列批次。每个序列可以是字符串或字符串列表（预分词字符串）。如果传入预分词输入，请设置 `is_split_into_words=True` 以避免与批量输入产生歧义。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

**返回：** `~tokenization_utils_base.BatchEncoding`

- **data** (`dict`，*可选*) -- 由 `__call__`/`encode_plus`/`batch_encode_plus` 方法返回的列表/数组/张量字典（'input_ids'、'attention_mask' 等）。
- **encoding**（`tokenizers.Encoding` 或 `Sequence[tokenizers.Encoding]`，*可选*）-- 如果分词器是快速分词器，并且会输出诸如从词/字符空间到 token 空间的映射等附加信息，则 `tokenizers.Encoding` 实例或实例列表（用于批次）将保存这些信息。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
- **prepend_batch_axis** (`bool`，*可选*，默认为 `False`) -- 在转换为张量时是否添加批次轴（参见上文中的 `tensor_type`）。请注意，仅当参数 `tensor_type` 被设置时，此参数才会生效，*否则无效*。
- **n_sequences** (`int`, *可选*) -- 每个编码所表示的输入序列数量（`None` 表示未知，`1` 表示单个序列，`2` 表示一对序列）。

## SamImageProcessor[[transformers.SamImageProcessor]]

#### transformers.SamImageProcessor[[transformers.SamImageProcessor]]

```python
transformers.SamImageProcessor(**kwargs: *<class 'transformers.models.sam.image_processing_sam.SamImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/image_processing_sam.py#L61)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `True`)：是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'longest_edge' : 1024}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认为 `2`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.485, 0.456, 0.406]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.229, 0.224, 0.225]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*，默认为 `True`) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 1024, 'width': 1024}`)：用于填充图像的 `{"height": int, "width" int}` 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

mask_size (`dict[str, *kwargs*, int]`, *可选*) : 用于将分割图调整大小的尺寸 `{"longest_edge": int}`。

mask_pad_size (`dict[str, *kwargs*, int]`, *可选*) : 用于填充分割图的尺寸 `{"height": int, "width": int}`。必须大于为预处理提供的任何分割图尺寸。

构建一个 SamImageProcessor 图像处理器。

#### preprocess[[transformers.SamImageProcessor.preprocess]]

```python
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: *<class 'transformers.models.sam.image_processing_sam.SamImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/image_processing_sam.py#L79)

**参数：**

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`，*可选*)：要预处理的分割图。

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*)：描述模型的最大输入维度。

default_to_square (`bool`, *kwargs*, *可选*) : 当 size 为 int 时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*) : 是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *kwargs*, *可选*) : 是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

mask_size (`dict[str, *kwargs*, int]`, *可选*) : 用于将分割图调整大小的尺寸 `{"longest_edge": int}`。

mask_pad_size (`dict[str, *kwargs*, int]`, *可选*) : 用于填充分割图的尺寸 `{"height": int, "width": int}`。必须大于为预处理提供的任何分割图尺寸。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

## SamImageProcessorPil[[transformers.SamImageProcessorPil]]

#### transformers.SamImageProcessorPil[[transformers.SamImageProcessorPil]]

```python
transformers.SamImageProcessorPil(**kwargs: *<class 'transformers.models.sam.image_processing_pil_sam.SamImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/image_processing_pil_sam.py#L82)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `True`)：是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'longest_edge' : 1024}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认为 `2`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.485, 0.456, 0.406]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.229, 0.224, 0.225]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*，默认为 `True`) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 1024, 'width': 1024}`)：用于填充图像的 `{"height": int, "width" int}` 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

mask_size (`dict[str, *kwargs*, int]`, *可选*) : 用于将分割图调整大小的尺寸 `{"longest_edge": int}`。

mask_pad_size (`dict[str, *kwargs*, int]`, *可选*) : 用于填充分割图的尺寸 `{"height": int, "width": int}`。必须大于为预处理提供的任何分割图尺寸。

构建一个 SamImageProcessor 图像处理器。

#### preprocess[[transformers.SamImageProcessorPil.preprocess]]

```python
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: *<class 'transformers.models.sam.image_processing_pil_sam.SamImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/image_processing_pil_sam.py#L100)

**参数：**

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`，*可选*)：要预处理的分割图。

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*)：描述模型的最大输入维度。

default_to_square (`bool`, *kwargs*, *可选*) : 当 size 为 int 时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*) : 是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *kwargs*, *可选*) : 是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

mask_size (`dict[str, *kwargs*, int]`, *可选*) : 用于将分割图调整大小的尺寸 `{"longest_edge": int}`。

mask_pad_size (`dict[str, *kwargs*, int]`, *可选*) : 用于填充分割图的尺寸 `{"height": int, "width": int}`。必须大于为预处理提供的任何分割图尺寸。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

## SamVisionModel[[transformers.SamVisionModel]]

#### transformers.SamVisionModel[[transformers.SamVisionModel]]

```python
transformers.SamVisionModel(config: SamVisionConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/modeling_sam.py#L1081)

**参数：**

config ([SamVisionConfig](/docs/transformers/main/zh/model_doc/sam#transformers.SamVisionConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.SamVisionModel.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/modeling_sam.py#L1093)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [SamImageProcessor](/docs/transformers/main/zh/model_doc/sam#transformers.SamImageProcessor) 获取像素值。有关详细信息，请参阅 [SamImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[SamProcessor](/docs/transformers/main/zh/model_doc/sam#transformers.SamProcessor) 使用 [SamImageProcessor](/docs/transformers/main/zh/model_doc/sam#transformers.SamImageProcessor) 处理图像）。

**返回：** `SamVisionEncoderOutput` 或 `tuple(torch.Tensor)`

`SamVisionEncoderOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[SamConfig](/docs/transformers/main/zh/model_doc/sam#transformers.SamConfig)）和输入。

[SamVisionModel](/docs/transformers/main/zh/model_doc/sam#transformers.SamVisionModel) 的 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 后的注意力权重，用于在自注意力头中计算加权平均值。

## SamModel[[transformers.SamModel]]

#### transformers.SamModel[[transformers.SamModel]]

```python
transformers.SamModel(config: SamConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/modeling_sam.py#L1108)

**参数：**

config ([SamConfig](/docs/transformers/main/zh/model_doc/sam#transformers.SamConfig))：模型配置类，包含模型的所有参数。使用配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

Segment Anything Model (SAM)，用于根据输入图像以及输入的点及标签、边界框或掩码来生成分割掩码。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.SamModel.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, input_points: typing.Optional[torch.Tensor] = None, input_labels: typing.Optional[torch.LongTensor] = None, input_boxes: typing.Optional[torch.Tensor] = None, input_masks: typing.Optional[torch.LongTensor] = None, image_embeddings: typing.Optional[torch.Tensor] = None, multimask_output: bool = True, attention_similarity: typing.Optional[torch.Tensor] = None, target_embedding: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam/modeling_sam.py#L1191)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [SamImageProcessor](/docs/transformers/main/zh/model_doc/sam#transformers.SamImageProcessor) 获取像素值。有关详细信息，请参阅 [SamImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[SamProcessor](/docs/transformers/main/zh/model_doc/sam#transformers.SamProcessor) 使用 [SamImageProcessor](/docs/transformers/main/zh/model_doc/sam#transformers.SamImageProcessor) 处理图像）。

input_points (`torch.Tensor`，形状为 `(batch_size, num_points, 2)`)：输入的二维空间点，供提示编码器（prompt encoder）用于编码提示。通常能带来显著更好的结果。可以通过向处理器传入列表的列表的列表来获取这些点，处理器将创建维度为 4 的相应 `torch` 张量。第一个维度是图像批次大小，第二个维度是点批次大小（即对于每个输入点，我们希望模型预测多少个分割掩码），第三个维度是每个分割掩码对应的点数（可以为单个掩码传入多个点），最后一个维度是点的 x（垂直）和 y（水平）坐标。如果为每张图像或每个掩码传入的点数不同，处理器将创建“PAD”点，这些点对应 (0, 0) 坐标，并且在使用标签时，将跳过对这些点的嵌入计算。

input_labels (`torch.LongTensor`，形状为 `(batch_size, point_batch_size, num_points)`)：点的输入标签，供提示编码器用于编码提示。根据官方实现，共有 3 种标签类型 - `1`：该点包含感兴趣的对象 - `0`：该点不包含感兴趣的对象 - `-1`：该点对应背景 我们添加了标签： - `-10`：该点为填充点，因此应被提示编码器忽略 填充标签应由处理器自动处理。

input_boxes (`torch.Tensor`，形状为 `(batch_size, num_boxes, 4)`)：用于点的输入框，提示编码器使用它来编码提示。通常能生成质量更好的掩码。可以通过向处理器传入列表的列表的列表来获取这些框，这将生成一个 `torch` 张量，其各维度分别对应图像批次大小、每张图像的框数量以及框左上角和右下角点的坐标。顺序为 (`x1`, `y1`, `x2`, `y2`)： - `x1`：输入框左上角点的 x 坐标 - `y1`：输入框左上角点的 y 坐标 - `x2`：输入框右下角点的 x 坐标 - `y2`：输入框右下角点的 y 坐标

input_masks (`torch.Tensor`，形状为 `(batch_size, image_size, image_size)`)：SAM 模型也接受分割掩码作为输入。掩码将由提示编码器嵌入以生成相应的嵌入，随后输入到掩码解码器中。这些掩码需要由用户手动提供，且其形状必须为 (`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` 来仅输出单个掩码，该掩码对应于“最佳”掩码。

attention_similarity (`torch.Tensor`, *可选*) : 注意力相似度张量，当模型用于如 [PerSAM](https://huggingface.co/papers/2305.03048) 中所述的个性化时，需将其提供给掩码解码器以实现目标引导的注意力。

target_embedding (`torch.Tensor`, *可选*) : 目标概念的嵌入，当模型用于个性化（如 [PerSAM](https://huggingface.co/papers/2305.03048) 中所述）时，需将其提供给掩码解码器以进行目标语义提示。

**返回：** `SamImageSegmentationOutput` 或 `tuple(torch.Tensor)`

`SamImageSegmentationOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[SamConfig](/docs/transformers/main/zh/model_doc/sam#transformers.SamConfig)）和输入。

[SamModel](/docs/transformers/main/zh/model_doc/sam#transformers.SamModel) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **iou_scores**（形状为 `(batch_size, num_masks)` 的 `torch.Tensor`）-- 预测掩码的 iou 分数。
- **pred_masks**（形状为 `(batch_size, num_masks, height, width)` 的 `torch.Tensor`）-- 预测的低分辨率掩码。需要由处理器进行后处理
- **vision_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  视觉模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **vision_attentions** (`tuple(torch.Tensor)`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **mask_decoder_attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

示例：

```python
>>> from PIL import Image
>>> from huggingface_hub.utils 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"]
... )
```

