> For the complete documentation index, see [llms.txt](https://boinc-ai.gitbook.io/transformers/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://boinc-ai.gitbook.io/transformers/api/models/multimodal-models/segment-anything.md).

# Segment Anything

## SAM

### Overview

SAM (Segment Anything Model) was proposed in [Segment Anything](https://arxiv.org/pdf/2304.02643v1.pdf) by 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.

The model can be used to predict segmentation masks of any object of interest given an input image.

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

The abstract from the paper is the following:

*We introduce the Segment Anything (SA) project: a new task, model, and dataset for image segmentation. Using our efficient model in a data collection loop, we built the largest segmentation dataset to date (by far), with over 1 billion masks on 11M licensed and privacy respecting images. The model is designed and trained to be promptable, so it can transfer zero-shot to new image distributions and tasks. We evaluate its capabilities on numerous tasks and find that its zero-shot performance is impressive — often competitive with or even superior to prior fully supervised results. We are releasing the Segment Anything Model (SAM) and corresponding dataset (SA-1B) of 1B masks and 11M images at* [*https://segment-anything.com*](https://segment-anything.com/) *to foster research into foundation models for computer vision.*

Tips:

* The model predicts binary masks that states the presence or not of the object of interest given an image.
* The model predicts much better results if input 2D points and/or input bounding boxes are provided
* You can prompt multiple points for the same image, and predict a single mask.
* Fine-tuning the model is not supported yet
* According to the paper, textual input should be also supported. However, at this time of writing this seems to be not supported according to [the official repository](https://github.com/facebookresearch/segment-anything/issues/4#issuecomment-1497626844).

This model was contributed by [ybelkada](https://huggingface.co/ybelkada) and [ArthurZ](https://huggingface.co/ArthurZ). The original code can be found [here](https://github.com/facebookresearch/segment-anything).

Below is an example on how to run mask generation given an image and a 2D point:

Copied

```
import torch
from PIL import Image
import requests
from transformers import SamModel, SamProcessor

device = "cuda" if torch.cuda.is_available() else "cpu"
model = SamModel.from_pretrained("facebook/sam-vit-huge").to(device)
processor = SamProcessor.from_pretrained("facebook/sam-vit-huge")

img_url = "https://boincai.com/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(device)
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
```

Resources:

* [Demo notebook](https://github.com/huggingface/notebooks/blob/main/examples/segment_anything.ipynb) for using the model.
* [Demo notebook](https://github.com/huggingface/notebooks/blob/main/examples/automatic_mask_generation.ipynb) for using the automatic mask generation pipeline.
* [Demo notebook](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/SAM/Run_inference_with_MedSAM_using_HuggingFace_Transformers.ipynb) for inference with MedSAM, a fine-tuned version of SAM on the medical domain.
* [Demo notebook](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/SAM/Fine_tune_SAM_\(segment_anything\)_on_a_custom_dataset.ipynb) for fine-tuning the model on custom data.

### SamConfig

#### class transformers.SamConfig

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/configuration_sam.py#L237)

( vision\_config = Noneprompt\_encoder\_config = Nonemask\_decoder\_config = Noneinitializer\_range = 0.02\*\*kwargs )

Parameters

* **vision\_config** (Union\[`dict`, `SamVisionConfig`], *optional*) — Dictionary of configuration options used to initialize [SamVisionConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamVisionConfig).
* **prompt\_encoder\_config** (Union\[`dict`, `SamPromptEncoderConfig`], *optional*) — Dictionary of configuration options used to initialize [SamPromptEncoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamPromptEncoderConfig).
* **mask\_decoder\_config** (Union\[`dict`, `SamMaskDecoderConfig`], *optional*) — Dictionary of configuration options used to initialize [SamMaskDecoderConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamMaskDecoderConfig).
* **kwargs** (*optional*) — Dictionary of keyword arguments.

[SamConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamConfig) is the configuration class to store the configuration of a [SamModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamModel). It is used to instantiate a SAM model according to the specified arguments, defining the vision model, prompt-encoder model and mask decoder configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the SAM-ViT-H [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.

Configuration objects inherit from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

Example:

Copied

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

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/configuration_sam.py#L139)

( hidden\_size = 768output\_channels = 256num\_hidden\_layers = 12num\_attention\_heads = 12num\_channels = 3image\_size = 1024patch\_size = 16hidden\_act = 'gelu'layer\_norm\_eps = 1e-06attention\_dropout = 0.0initializer\_range = 1e-10qkv\_bias = Truemlp\_ratio = 4.0use\_abs\_pos = Trueuse\_rel\_pos = Truewindow\_size = 14global\_attn\_indexes = \[2, 5, 8, 11]num\_pos\_feats = 128mlp\_dim = None\*\*kwargs )

Parameters

* **hidden\_size** (`int`, *optional*, defaults to 768) — Dimensionality of the encoder layers and the pooler layer.
* **output\_channels** (`int`, *optional*, defaults to 256) — Dimensionality of the output channels in the Patch Encoder.
* **num\_hidden\_layers** (`int`, *optional*, defaults to 12) — Number of hidden layers in the Transformer encoder.
* **num\_attention\_heads** (`int`, *optional*, defaults to 12) — Number of attention heads for each attention layer in the Transformer encoder.
* **num\_channels** (`int`, *optional*, defaults to 3) — Number of channels in the input image.
* **image\_size** (`int`, *optional*, defaults to 1024) — Expected resolution. Target size of the resized input image.
* **patch\_size** (`int`, *optional*, defaults to 16) — Size of the patches to be extracted from the input image.
* **hidden\_act** (`str`, *optional*, defaults to `"gelu"`) — The non-linear activation function (function or string)
* **layer\_norm\_eps** (`float`, *optional*, defaults to 1e-6) — The epsilon used by the layer normalization layers.
* **attention\_dropout** (`float`, *optional*, defaults to 0.0) — The dropout ratio for the attention probabilities.
* **initializer\_range** (`float`, *optional*, defaults to 1e-10) — The standard deviation of the truncated\_normal\_initializer for initializing all weight matrices.
* **qkv\_bias** (`bool`, *optional*, defaults to `True`) — Whether to add a bias to query, key, value projections.
* **mlp\_ratio** (`float`, *optional*, defaults to 4.0) — Ratio of mlp hidden dim to embedding dim.
* **use\_abs\_pos** (`bool`, *optional*, defaults to True) — Whether to use absolute position embedding.
* **use\_rel\_pos** (`bool`, *optional*, defaults to True) — Whether to use relative position embedding.
* **window\_size** (`int`, *optional*, defaults to 14) — Window size for relative position.
* **global\_attn\_indexes** (`List[int]`, *optional*, defaults to `[2, 5, 8, 11]`) — The indexes of the global attention layers.
* **num\_pos\_feats** (`int`, *optional*, defaults to 128) — The dimensionality of the position embedding.
* **mlp\_dim** (`int`, *optional*, defaults to None) — The dimensionality of the MLP layer in the Transformer encoder. If `None`, defaults to `mlp_ratio * hidden_size`.

This is the configuration class to store the configuration of a `SamVisionModel`. It is used to instantiate a SAM vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration defaults will yield a similar configuration to that of the SAM ViT-h [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.

Configuration objects inherit from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

### SamMaskDecoderConfig

#### class transformers.SamMaskDecoderConfig

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/configuration_sam.py#L78)

( hidden\_size = 256hidden\_act = 'relu'mlp\_dim = 2048num\_hidden\_layers = 2num\_attention\_heads = 8attention\_downsample\_rate = 2num\_multimask\_outputs = 3iou\_head\_depth = 3iou\_head\_hidden\_dim = 256layer\_norm\_eps = 1e-06\*\*kwargs )

Parameters

* **hidden\_size** (`int`, *optional*, defaults to 256) — Dimensionality of the hidden states.
* **hidden\_act** (`str`, *optional*, defaults to `"relu"`) — The non-linear activation function used inside the `SamMaskDecoder` module.
* **mlp\_dim** (`int`, *optional*, defaults to 2048) — Dimensionality of the “intermediate” (i.e., feed-forward) layer in the Transformer encoder.
* **num\_hidden\_layers** (`int`, *optional*, defaults to 2) — Number of hidden layers in the Transformer encoder.
* **num\_attention\_heads** (`int`, *optional*, defaults to 8) — Number of attention heads for each attention layer in the Transformer encoder.
* **attention\_downsample\_rate** (`int`, *optional*, defaults to 2) — The downsampling rate of the attention layer.
* **num\_multimask\_outputs** (`int`, *optional*, defaults to 3) — The number of outputs from the `SamMaskDecoder` module. In the Segment Anything paper, this is set to 3.
* **iou\_head\_depth** (`int`, *optional*, defaults to 3) — The number of layers in the IoU head module.
* **iou\_head\_hidden\_dim** (`int`, *optional*, defaults to 256) — The dimensionality of the hidden states in the IoU head module.
* **layer\_norm\_eps** (`float`, *optional*, defaults to 1e-6) — The epsilon used by the layer normalization layers.

This is the configuration class to store the configuration of a `SamMaskDecoder`. It is used to instantiate a SAM mask decoder to the specified arguments, defining the model architecture. Instantiating a configuration defaults will yield a similar configuration to that of the SAM-vit-h [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.

Configuration objects inherit from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

### SamPromptEncoderConfig

#### class transformers.SamPromptEncoderConfig

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/configuration_sam.py#L31)

( hidden\_size = 256image\_size = 1024patch\_size = 16mask\_input\_channels = 16num\_point\_embeddings = 4hidden\_act = 'gelu'layer\_norm\_eps = 1e-06\*\*kwargs )

Parameters

* **hidden\_size** (`int`, *optional*, defaults to 256) — Dimensionality of the hidden states.
* **image\_size** (`int`, *optional*, defaults to 1024) — The expected output resolution of the image.
* **patch\_size** (`int`, *optional*, defaults to 16) — The size (resolution) of each patch.
* **mask\_input\_channels** (`int`, *optional*, defaults to 16) — The number of channels to be fed to the `MaskDecoder` module.
* **num\_point\_embeddings** (`int`, *optional*, defaults to 4) — The number of point embeddings to be used.
* **hidden\_act** (`str`, *optional*, defaults to `"gelu"`) — The non-linear activation function in the encoder and pooler.

This is the configuration class to store the configuration of a `SamPromptEncoder`. The `SamPromptEncoder` module is used to encode the input 2D points and bounding boxes. Instantiating a configuration defaults will yield a similar configuration to that of the SAM-vit-h [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.

Configuration objects inherit from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the documentation from [PretrainedConfig](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/configuration#transformers.PretrainedConfig) for more information.

### SamProcessor

#### class transformers.SamProcessor

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/processing_sam.py#L35)

( image\_processor )

Parameters

* **image\_processor** (`SamImageProcessor`) — An instance of [SamImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamImageProcessor). The image processor is a required input.

Constructs a SAM processor which wraps a SAM image processor and an 2D points & Bounding boxes processor into a single processor.

[SamProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamProcessor) offers all the functionalities of [SamImageProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamImageProcessor). See the docstring of [**call**()](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/deit#transformers.DeiTFeatureExtractor.__call__) for more information.

### SamImageProcessor

#### class transformers.SamImageProcessor

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/image_processing_sam.py#L64)

( do\_resize: bool = Truesize: typing.Dict\[str, int] = Noneresample: Resampling = \<Resampling.BILINEAR: 2>do\_rescale: bool = Truerescale\_factor: typing.Union\[int, float] = 0.00392156862745098do\_normalize: bool = Trueimage\_mean: typing.Union\[float, typing.List\[float], NoneType] = Noneimage\_std: typing.Union\[float, typing.List\[float], NoneType] = Nonedo\_pad: bool = Truepad\_size: int = Nonedo\_convert\_rgb: bool = True\*\*kwargs )

Parameters

* **do\_resize** (`bool`, *optional*, defaults to `True`) — Whether to resize the image’s (height, width) dimensions to the specified `size`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
* **size** (`dict`, *optional*, defaults to `{"longest_edge" -- 1024}`): Size of the output image after resizing. Resizes the longest edge of the image to match `size["longest_edge"]` while maintaining the aspect ratio. Can be overridden by the `size` parameter in the `preprocess` method.
* **resample** (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`) — Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the `preprocess` method.
* **do\_rescale** (`bool`, *optional*, defaults to `True`) — Wwhether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale` parameter in the `preprocess` method.
* **rescale\_factor** (`int` or `float`, *optional*, defaults to `1/255`) — Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be overridden by the `rescale_factor` parameter in the `preprocess` method.
* **do\_normalize** (`bool`, *optional*, defaults to `True`) — Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess` method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
* **image\_mean** (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`) — Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be overridden by the `image_mean` parameter in the `preprocess` method.
* **image\_std** (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`) — Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method. Can be overridden by the `image_std` parameter in the `preprocess` method.
* **do\_pad** (`bool`, *optional*, defaults to `True`) — Whether to pad the image to the specified `pad_size`. Can be overridden by the `do_pad` parameter in the `preprocess` method.
* **pad\_size** (`dict`, *optional*, defaults to `{"height" -- 1024, "width": 1024}`): Size of the output image after padding. Can be overridden by the `pad_size` parameter in the `preprocess` method.
* **do\_convert\_rgb** (`bool`, *optional*, defaults to `True`) — Whether to convert the image to RGB.

Constructs a SAM image processor.

**filter\_masks**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/image_processing_sam.py#L631)

( masksiou\_scoresoriginal\_sizecropped\_box\_imagepred\_iou\_thresh = 0.88stability\_score\_thresh = 0.95mask\_threshold = 0stability\_score\_offset = 1return\_tensors = 'pt' )

Parameters

* **masks** (`Union[torch.Tensor, tf.Tensor]`) — Input masks.
* **iou\_scores** (`Union[torch.Tensor, tf.Tensor]`) — List of IoU scores.
* **original\_size** (`Tuple[int,int]`) — Size of the orginal image.
* **cropped\_box\_image** (`np.array`) — The cropped image.
* **pred\_iou\_thresh** (`float`, *optional*, defaults to 0.88) — The threshold for the iou scores.
* **stability\_score\_thresh** (`float`, *optional*, defaults to 0.95) — The threshold for the stability score.
* **mask\_threshold** (`float`, *optional*, defaults to 0) — The threshold for the predicted masks.
* **stability\_score\_offset** (`float`, *optional*, defaults to 1) — The offset for the stability score used in the `_compute_stability_score` method.
* **return\_tensors** (`str`, *optional*, defaults to `pt`) — If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.

Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to bounding boxes and pad the predicted masks if necessary.

**generate\_crop\_boxes**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/image_processing_sam.py#L566)

( imagetarget\_sizecrop\_n\_layers: int = 0overlap\_ratio: float = 0.3413333333333333points\_per\_crop: typing.Optional\[int] = 32crop\_n\_points\_downscale\_factor: typing.Optional\[typing.List\[int]] = 1device: typing.Optional\[ForwardRef('torch.device')] = Noneinput\_data\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension, NoneType] = Nonereturn\_tensors: str = 'pt' )

Parameters

* **image** (`np.array`) — Input original image
* **target\_size** (`int`) — Target size of the resized image
* **crop\_n\_layers** (`int`, *optional*, defaults to 0) — If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2\*\*i\_layer number of image crops.
* **overlap\_ratio** (`float`, *optional*, defaults to 512/1500) — Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap.
* **points\_per\_crop** (`int`, *optional*, defaults to 32) — Number of points to sample from each crop.
* **crop\_n\_points\_downscale\_factor** (`List[int]`, *optional*, defaults to 1) — The number of points-per-side sampled in layer n is scaled down by crop\_n\_points\_downscale\_factor\*\*n.
* **device** (`torch.device`, *optional*, defaults to None) — Device to use for the computation. If None, cpu will be used.
* **input\_data\_format** (`str` or `ChannelDimension`, *optional*) — The channel dimension format of the input image. If not provided, it will be inferred.
* **return\_tensors** (`str`, *optional*, defaults to `pt`) — If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.

Generates a list of crop boxes of different sizes. Each layer has (2**i)**&#x32; boxes for the ith layer.

**pad\_image**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/image_processing_sam.py#L142)

( image: ndarraypad\_size: typing.Dict\[str, int]data\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension, NoneType] = Noneinput\_data\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension, NoneType] = None\*\*kwargs )

Parameters

* **image** (`np.ndarray`) — Image to pad.
* **pad\_size** (`Dict[str, int]`) — Size of the output image after padding.
* **data\_format** (`str` or `ChannelDimension`, *optional*) — The data format of the image. Can be either “channels\_first” or “channels\_last”. If `None`, the `data_format` of the `image` will be used.
* **input\_data\_format** (`str` or `ChannelDimension`, *optional*) — The channel dimension format of the input image. If not provided, it will be inferred.

Pad an image to `(pad_size["height"], pad_size["width"])` with zeros to the right and bottom.

**post\_process\_for\_mask\_generation**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/image_processing_sam.py#L543)

( all\_masksall\_scoresall\_boxescrops\_nms\_threshreturn\_tensors = 'pt' )

Parameters

* **all\_masks** (`Union[List[torch.Tensor], List[tf.Tensor]]`) — List of all predicted segmentation masks
* **all\_scores** (`Union[List[torch.Tensor], List[tf.Tensor]]`) — List of all predicted iou scores
* **all\_boxes** (`Union[List[torch.Tensor], List[tf.Tensor]]`) — List of all bounding boxes of the predicted masks
* **crops\_nms\_thresh** (`float`) — Threshold for NMS (Non Maximum Suppression) algorithm.
* **return\_tensors** (`str`, *optional*, defaults to `pt`) — If `pt`, returns `torch.Tensor`. If `tf`, returns `tf.Tensor`.

Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.

**post\_process\_masks**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/image_processing_sam.py#L399)

( masksoriginal\_sizesreshaped\_input\_sizesmask\_threshold = 0.0binarize = Truepad\_size = Nonereturn\_tensors = 'pt' ) → (`Union[torch.Tensor, tf.Tensor]`)

Parameters

* **masks** (`Union[List[torch.Tensor], List[np.ndarray], List[tf.Tensor]]`) — Batched masks from the mask\_decoder in (batch\_size, num\_channels, height, width) format.
* **original\_sizes** (`Union[torch.Tensor, tf.Tensor, List[Tuple[int,int]]]`) — The original sizes of each image before it was resized to the model’s expected input shape, in (height, width) format.
* **reshaped\_input\_sizes** (`Union[torch.Tensor, tf.Tensor, List[Tuple[int,int]]]`) — The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
* **mask\_threshold** (`float`, *optional*, defaults to 0.0) — The threshold to use for binarizing the masks.
* **binarize** (`bool`, *optional*, defaults to `True`) — Whether to binarize the masks.
* **pad\_size** (`int`, *optional*, defaults to `self.pad_size`) — The target size the images were padded to before being passed to the model. If None, the target size is assumed to be the processor’s `pad_size`.
* **return\_tensors** (`str`, *optional*, defaults to `"pt"`) — If `"pt"`, return PyTorch tensors. If `"tf"`, return TensorFlow tensors.

Returns

(`Union[torch.Tensor, tf.Tensor]`)

Batched masks in batch\_size, num\_channels, height, width) format, where (height, width) is given by original\_size.

Remove padding and upscale masks to the original image size.

**preprocess**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/image_processing_sam.py#L239)

( images: typing.Union\[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List\[ForwardRef('PIL.Image.Image')], typing.List\[numpy.ndarray], typing.List\[ForwardRef('torch.Tensor')]]do\_resize: typing.Optional\[bool] = Nonesize: typing.Union\[typing.Dict\[str, int], NoneType] = Noneresample: typing.Optional\[ForwardRef('PILImageResampling')] = Nonedo\_rescale: typing.Optional\[bool] = Nonerescale\_factor: typing.Union\[int, float, NoneType] = Nonedo\_normalize: typing.Optional\[bool] = Noneimage\_mean: typing.Union\[float, typing.List\[float], NoneType] = Noneimage\_std: typing.Union\[float, typing.List\[float], NoneType] = Nonedo\_pad: typing.Optional\[bool] = Nonepad\_size: typing.Union\[typing.Dict\[str, int], NoneType] = Nonedo\_convert\_rgb: bool = Nonereturn\_tensors: typing.Union\[str, transformers.utils.generic.TensorType, NoneType] = Nonedata\_format: ChannelDimension = \<ChannelDimension.FIRST: 'channels\_first'>input\_data\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension, NoneType] = None\*\*kwargs )

Parameters

* **images** (`ImageInput`) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
* **do\_resize** (`bool`, *optional*, defaults to `self.do_resize`) — Whether to resize the image.
* **size** (`Dict[str, int]`, *optional*, defaults to `self.size`) — Controls the size of the image after `resize`. The longest edge of the image is resized to `size["longest_edge"]` whilst preserving the aspect ratio.
* **resample** (`PILImageResampling`, *optional*, defaults to `self.resample`) — `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
* **do\_rescale** (`bool`, *optional*, defaults to `self.do_rescale`) — Whether to rescale the image pixel values by rescaling factor.
* **rescale\_factor** (`int` or `float`, *optional*, defaults to `self.rescale_factor`) — Rescale factor to apply to the image pixel values.
* **do\_normalize** (`bool`, *optional*, defaults to `self.do_normalize`) — Whether to normalize the image.
* **image\_mean** (`float` or `List[float]`, *optional*, defaults to `self.image_mean`) — Image mean to normalize the image by if `do_normalize` is set to `True`.
* **image\_std** (`float` or `List[float]`, *optional*, defaults to `self.image_std`) — Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
* **do\_pad** (`bool`, *optional*, defaults to `self.do_pad`) — Whether to pad the image.
* **pad\_size** (`Dict[str, int]`, *optional*, defaults to `self.pad_size`) — Controls the size of the padding applied to the image. The image is padded to `pad_size["height"]` and `pad_size["width"]` if `do_pad` is set to `True`.
* **do\_convert\_rgb** (`bool`, *optional*, defaults to `self.do_convert_rgb`) — Whether to convert the image to RGB.
* **return\_tensors** (`str` or `TensorType`, *optional*) — The type of tensors to return. Can be one of:
  * Unset: Return a list of `np.ndarray`.
  * `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  * `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  * `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  * `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
* **data\_format** (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`) — The channel dimension format for the output image. Can be one of:
  * `"channels_first"` or `ChannelDimension.FIRST`: image in (num\_channels, height, width) format.
  * `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num\_channels) format.
  * Unset: Use the channel dimension format of the input image.
* **input\_data\_format** (`ChannelDimension` or `str`, *optional*) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:
  * `"channels_first"` or `ChannelDimension.FIRST`: image in (num\_channels, height, width) format.
  * `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num\_channels) format.
  * `"none"` or `ChannelDimension.NONE`: image in (height, width) format.

Preprocess an image or batch of images.

**resize**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/image_processing_sam.py#L190)

( image: ndarraysize: typing.Dict\[str, int]resample: Resampling = \<Resampling.BICUBIC: 3>data\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension, NoneType] = Noneinput\_data\_format: typing.Union\[str, transformers.image\_utils.ChannelDimension, NoneType] = None\*\*kwargs ) → `np.ndarray`

Parameters

* **image** (`np.ndarray`) — Image to resize.
* **size** (`Dict[str, int]`) — Dictionary in the format `{"longest_edge": int}` specifying the size of the output image. The longest edge of the image will be resized to the specified size, while the other edge will be resized to maintain the aspect ratio. resample — `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
* **data\_format** (`ChannelDimension` or `str`, *optional*) — The channel dimension format for the output image. If unset, the channel dimension format of the input image is used. Can be one of:
  * `"channels_first"` or `ChannelDimension.FIRST`: image in (num\_channels, height, width) format.
  * `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num\_channels) format.
* **input\_data\_format** (`ChannelDimension` or `str`, *optional*) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:
  * `"channels_first"` or `ChannelDimension.FIRST`: image in (num\_channels, height, width) format.
  * `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num\_channels) format.

Returns

`np.ndarray`

The resized image.

Resize an image to `(size["height"], size["width"])`.

### SamModel

#### class transformers.SamModel

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/modeling_sam.py#L1192)

( config )

Parameters

* **config** ([SamConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

Segment Anything Model (SAM) for generating segmentation masks, given an input image and optional 2D location and bounding boxes. This model inherits from [PreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

**forward**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/modeling_sam.py#L1285)

( pixel\_values: typing.Optional\[torch.FloatTensor] = Noneinput\_points: typing.Optional\[torch.FloatTensor] = Noneinput\_labels: typing.Optional\[torch.LongTensor] = Noneinput\_boxes: typing.Optional\[torch.FloatTensor] = Noneinput\_masks: typing.Optional\[torch.LongTensor] = Noneimage\_embeddings: typing.Optional\[torch.FloatTensor] = Nonemultimask\_output: bool = Trueattention\_similarity: typing.Optional\[torch.FloatTensor] = Nonetarget\_embedding: typing.Optional\[torch.FloatTensor] = Noneoutput\_attentions: typing.Optional\[bool] = Noneoutput\_hidden\_states: typing.Optional\[bool] = Nonereturn\_dict: typing.Optional\[bool] = None\*\*kwargs )

Parameters

* **pixel\_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) — Pixel values. Pixel values can be obtained using [SamProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamProcessor). See `SamProcessor.__call__()` for details.
* **input\_points** (`torch.FloatTensor` of shape `(batch_size, num_points, 2)`) — Input 2D spatial points, this is used by the prompt encoder to encode the prompt. Generally yields to much better results. The points can be obtained by passing a list of list of list to the processor that will create corresponding `torch` tensors of dimension 4. The first dimension is the image batch size, the second dimension is the point batch size (i.e. how many segmentation masks do we want the model to predict per input point), the third dimension is the number of points per segmentation mask (it is possible to pass multiple points for a single mask), and the last dimension is the x (vertical) and y (horizontal) coordinates of the point. If a different number of points is passed either for each image, or for each mask, the processor will create “PAD” points that will correspond to the (0, 0) coordinate, and the computation of the embedding will be skipped for these points using the labels.
* **input\_labels** (`torch.LongTensor` of shape `(batch_size, point_batch_size, num_points)`) — Input labels for the points, this is used by the prompt encoder to encode the prompt. According to the official implementation, there are 3 types of labels

  * `1`: the point is a point that contains the object of interest
  * `0`: the point is a point that does not contain the object of interest
  * `-1`: the point corresponds to the background

  We added the label:

  * `-10`: the point is a padding point, thus should be ignored by the prompt encoder

  The padding labels should be automatically done by the processor.
* **input\_boxes** (`torch.FloatTensor` of shape `(batch_size, num_boxes, 4)`) — Input boxes for the points, this is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks. The boxes can be obtained by passing a list of list of list to the processor, that will generate a `torch` tensor, with each dimension corresponding respectively to the image batch size, the number of boxes per image and the coordinates of the top left and botton right point of the box. In the order (`x1`, `y1`, `x2`, `y2`):
  * `x1`: the x coordinate of the top left point of the input box
  * `y1`: the y coordinate of the top left point of the input box
  * `x2`: the x coordinate of the bottom right point of the input box
  * `y2`: the y coordinate of the bottom right point of the input box
* **input\_masks** (`torch.FloatTensor` of shape `(batch_size, image_size, image_size)`) — SAM model also accepts segmentation masks as input. The mask will be embedded by the prompt encoder to generate a corresponding embedding, that will be fed later on to the mask decoder. These masks needs to be manually fed by the user, and they need to be of shape (`batch_size`, `image_size`, `image_size`).
* **image\_embeddings** (`torch.FloatTensor` of shape `(batch_size, output_channels, window_size, window_size)`) — Image embeddings, this is used by the mask decder to generate masks and iou scores. For more memory efficient computation, users can first retrieve the image embeddings using the `get_image_embeddings` method, and then feed them to the `forward` method instead of feeding the `pixel_values`.
* **multimask\_output** (`bool`, *optional*) — In the original implementation and paper, the model always outputs 3 masks per image (or per point / per bounding box if relevant). However, it is possible to just output a single mask, that corresponds to the “best” mask, by specifying `multimask_output=False`.
* **attention\_similarity** (`torch.FloatTensor`, *optional*) — Attention similarity tensor, to be provided to the mask decoder for target-guided attention in case the model is used for personalization as introduced in [PerSAM](https://arxiv.org/abs/2305.03048).
* **target\_embedding** (`torch.FloatTensor`, *optional*) — Embedding of the target concept, to be provided to the mask decoder for target-semantic prompting in case the model is used for personalization as introduced in [PerSAM](https://arxiv.org/abs/2305.03048).
* **output\_attentions** (`bool`, *optional*) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
* **output\_hidden\_states** (`bool`, *optional*) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.
* **return\_dict** (`bool`, *optional*) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.

  Example —

The [SamModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamModel) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

### TFSamModel

#### class transformers.TFSamModel

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/modeling_tf_sam.py#L1237)

( \*args\*\*kwargs )

Parameters

* **config** ([SamConfig](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.TFPreTrainedModel.from_pretrained) method to load the model weights.

Segment Anything Model (SAM) for generating segmentation masks, given an input image and optional 2D location and bounding boxes. This model inherits from [TFPreTrainedModel](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/model#transformers.TFPreTrainedModel). Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a TensorFlow [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it as a regular TensorFlow Model and refer to the TensorFlow documentation for all matter related to general usage and behavior.

**call**

[\<source>](https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/sam/modeling_tf_sam.py#L1327)

( pixel\_values: TFModelInputType | None = Noneinput\_points: tf.Tensor | None = Noneinput\_labels: tf.Tensor | None = Noneinput\_boxes: tf.Tensor | None = Noneinput\_masks: tf.Tensor | None = Noneimage\_embeddings: tf.Tensor | None = Nonemultimask\_output: bool = Trueoutput\_attentions: bool | None = Noneoutput\_hidden\_states: bool | None = Nonereturn\_dict: bool | None = Nonetraining: bool = False\*\*kwargs )

Parameters

* **pixel\_values** (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`) — Pixel values. Pixel values can be obtained using [SamProcessor](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.SamProcessor). See `SamProcessor.__call__()` for details.
* **input\_points** (`tf.Tensor` of shape `(batch_size, num_points, 2)`) — Input 2D spatial points, this is used by the prompt encoder to encode the prompt. Generally yields to much better results. The points can be obtained by passing a list of list of list to the processor that will create corresponding `tf` tensors of dimension 4. The first dimension is the image batch size, the second dimension is the point batch size (i.e. how many segmentation masks do we want the model to predict per input point), the third dimension is the number of points per segmentation mask (it is possible to pass multiple points for a single mask), and the last dimension is the x (vertical) and y (horizontal) coordinates of the point. If a different number of points is passed either for each image, or for each mask, the processor will create “PAD” points that will correspond to the (0, 0) coordinate, and the computation of the embedding will be skipped for these points using the labels.
* **input\_labels** (`tf.Tensor` of shape `(batch_size, point_batch_size, num_points)`) — Input labels for the points, this is used by the prompt encoder to encode the prompt. According to the official implementation, there are 3 types of labels

  * `1`: the point is a point that contains the object of interest
  * `0`: the point is a point that does not contain the object of interest
  * `-1`: the point corresponds to the background

  We added the label:

  * `-10`: the point is a padding point, thus should be ignored by the prompt encoder

  The padding labels should be automatically done by the processor.
* **input\_boxes** (`tf.Tensor` of shape `(batch_size, num_boxes, 4)`) — Input boxes for the points, this is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks. The boxes can be obtained by passing a list of list of list to the processor, that will generate a `tf` tensor, with each dimension corresponding respectively to the image batch size, the number of boxes per image and the coordinates of the top left and botton right point of the box. In the order (`x1`, `y1`, `x2`, `y2`):
  * `x1`: the x coordinate of the top left point of the input box
  * `y1`: the y coordinate of the top left point of the input box
  * `x2`: the x coordinate of the bottom right point of the input box
  * `y2`: the y coordinate of the bottom right point of the input box
* **input\_masks** (`tf.Tensor` of shape `(batch_size, image_size, image_size)`) — SAM model also accepts segmentation masks as input. The mask will be embedded by the prompt encoder to generate a corresponding embedding, that will be fed later on to the mask decoder. These masks needs to be manually fed by the user, and they need to be of shape (`batch_size`, `image_size`, `image_size`).
* **image\_embeddings** (`tf.Tensor` of shape `(batch_size, output_channels, window_size, window_size)`) — Image embeddings, this is used by the mask decder to generate masks and iou scores. For more memory efficient computation, users can first retrieve the image embeddings using the `get_image_embeddings` method, and then feed them to the `call` method instead of feeding the `pixel_values`.
* **multimask\_output** (`bool`, *optional*) — In the original implementation and paper, the model always outputs 3 masks per image (or per point / per bounding box if relevant). However, it is possible to just output a single mask, that corresponds to the “best” mask, by specifying `multimask_output=False`.
* **output\_attentions** (`bool`, *optional*) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
* **output\_hidden\_states** (`bool`, *optional*) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.
* **return\_dict** (`bool`, *optional*) — Whether or not to return a [ModelOutput](https://huggingface.co/docs/transformers/v4.34.1/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.

The [TFSamModel](https://huggingface.co/docs/transformers/v4.34.1/en/model_doc/sam#transformers.TFSamModel) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
