# 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) プロジェクトをご紹介します。これは、画像セグメンテーションのための新しいタスク、モデル、およびデータセットです。効率的なモデルをデータ収集ループに組み込むことで、1100万枚のライセンス済みかつプライバシーに配慮した画像に対して10億を超えるマスクを含む、これまでで最大規模（圧倒的に）のセグメンテーションデータセットを構築しました。このモデルはプロンプト可能になるよう設計・訓練されており、新しい画像分布やタスクにゼロショットで転移できます。多数のタスクでその能力を評価したところ、ゼロショット性能は非常に高く、従来の完全教師ありの結果と競合するだけでなく、それを超える場合もあることがわかりました。コンピュータビジョンのファウンデーションモデルに関する研究を促進するため、Segment Anything Model (SAM) と、10億のマスクと1100万枚の画像からなる対応するデータセット (SA-1B) を [https://segment-anything.com](https://segment-anything.com) で公開しています。*

ヒント:

- モデルは、与えられた画像において対象オブジェクトが存在するかどうかを示すバイナリマスクを予測します。
- 入力として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)で確認できます。

画像と2次元の点を与えてマスクを生成する方法の例を以下に示します。

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

## リソース

SAMの入門を支援するための、Hugging Face公式およびコミュニティ（🌎で示す）のリソースのリストです。

- モデルを使用するための[デモノートブック](https://github.com/huggingface/notebooks/blob/main/examples/segment_anything.ipynb)。
- 自動マスク生成パイプラインを使用するための[デモノートブック](https://github.com/huggingface/notebooks/blob/main/examples/automatic_mask_generation.ipynb)。
- 医療分野にファインチューニングされたSAMであるMedSAMによる推論用の[Demo notebook](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/SAM/Run_inference_with_MedSAM_using_HuggingFace_Transformers.ipynb)。🌎
- [デモノートブック](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/SAM/Fine_tune_SAM_(segment_anything)_on_a_custom_dataset.ipynb)：カスタムデータでのモデルのファインチューニング。🌎

## SlimSAM

SAMの剪定版であるSlimSAMは、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/v5.24.1/src/transformers/models/sam/configuration_sam.py#L146)

**パラメータ:**

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *任意*) : ビジョンバックボーンの config オブジェクトまたは辞書。

prompt_encoder_config (Union[`dict`, `SamPromptEncoderConfig`], *optional*) : [SamPromptEncoderConfig](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamPromptEncoderConfig)を初期化するために使用される設定オプションの辞書。

mask_decoder_config (Union[`dict`, `SamMaskDecoderConfig`], *optional*) : [SamMaskDecoderConfig](/docs/transformers/v5.24.1/ja/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/v5.24.1/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/v5.24.1/ja/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/v5.24.1/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`) : 各パッチのサイズ（解像度）。

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

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`, *optional*, デフォルトは 14) : 相対位置のウィンドウサイズ。

global_attn_indexes (`list[int]`、*任意*、デフォルトは`[2, 5, 8, 11]`) : グローバルアテンションレイヤーのインデックスです。

num_pos_feats (`int`、*optional*、デフォルトは 128) : 位置埋め込みの次元数。

mlp_dim (`int`, *optional*) : TransformerエンコーダーのMLP層の次元数。`None`の場合、デフォルトは`mlp_ratio * hidden_size`です。

これはSamModelの設定を保存するための設定クラスです。指定された引数に従ってSamモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) と同様の設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/v5.24.1/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/v5.24.1/ja/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/v5.24.1/src/transformers/models/sam/configuration_sam.py#L50)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`256`) : 隠れ表現の次元数。

hidden_act (`str`、*任意*、デフォルトは `relu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"` など。

mlp_dim (`int`、*optional*、デフォルトは 2048) : Transformer エンコーダーにおける「intermediate」（すなわち、feed-forward）層の次元数。

num_hidden_layers (`int`、*任意*、デフォルトは `2`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `8`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

attention_downsample_rate (`int`、*任意*、デフォルトは 2) : アテンション層のダウンサンプリング率です。

num_multimask_outputs (`int`、*optional*、デフォルトは 3) : `SamMaskDecoder` モジュールからの出力数です。Segment Anything の論文では、この値は 3 に設定されています。

iou_head_depth (`int`, *任意*, デフォルトは 3) : IoU ヘッドモジュールの層数。

iou_head_hidden_dim (`int`、*optional*、デフォルトは 256) : IoU ヘッドモジュールにおける隠れ状態の次元数。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

これはSamModelの設定を保存するための設定クラスです。指定された引数に従ってSamモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) と同様の設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/v5.24.1/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/v5.24.1/ja/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/v5.24.1/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`) : 各パッチのサイズ（解像度）。

mask_input_channels (`int`、*任意*、デフォルトは 16) : `MaskDecoder` モジュールに渡すチャネル数です。

num_point_embeddings (`int`、*任意*、デフォルトは 4) : 使用するポイント埋め込みの数。

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

これはSamModelの設定を保存するための設定クラスです。指定された引数に従ってSamモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) と同様の設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/v5.24.1/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/v5.24.1/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

## SamProcessor[[transformers.SamProcessor]]

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

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

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/sam/processing_sam.py#L93)

**パラメータ:**

image_processor (`SamImageProcessor`) : 画像プロセッサは必須の入力です。

画像プロセッサーを単一のプロセッサーにラップするSamProcessorを構築します。

[SamProcessor](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamProcessor) は [SamImageProcessor](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamImageProcessor) のすべての機能を提供します。詳細については、[~SamImageProcessor](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamImageProcessor) を参照してください。

#### __call__[[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, 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, input_points: NestedList | torch.Tensor | None = None, input_labels: NestedList | int | torch.Tensor | None = None, input_boxes: NestedList | torch.Tensor | None = None, **kwargs: *<class 'transformers.models.sam.processing_sam.SamProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/sam/processing_sam.py#L102)

**パラメータ:**

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` を設定してください。

segmentation_maps (`ImageInput`, *任意*) : 入力画像と並行して処理する正解セグメンテーションマップです。これらのマップは学習または評価のために使用され、処理された画像の寸法に合わせてリサイズおよび正規化されます。

input_points (`NestedList`, *任意*) : プロンプトベースのセグメンテーション用の入力ポイント。各ポイントが元の画像空間における `[x, y]` 座標で指定される、構造が `[image_level, object_level, point_level, [x, y]]` のネストされたリストである必要があります。ポイントはモデルに渡される前に、ターゲットの画像サイズに正規化されます。

input_labels (`NestedList`, *任意*) : 入力ポイントのラベル。各ポイントが前景 (1) であるか背景 (0) であるかを示します。`[image_level, object_level, point_level]` という構造を持つネストされたリストである必要があります。`input_points` と同じ構造 (座標次元を除く) である必要があります。

input_boxes (`NestedList`, *任意*) : プロンプトベースのセグメンテーション用のバウンディングボックス。構造が`[image_level, box_level, [x1, y1, x2, y2]]`のネストされたリストである必要があります。各ボックスは、元の画像空間における`[x1, y1, x2, y2]`座標で指定されます。ボックスは、モデルに渡される前にターゲット画像サイズに正規化されます。

segmentation_maps (`ImageInput`, *kwargs*, *optional*) : 非推奨です。代わりに、[SamProcessor.__call__()](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamProcessor.__call__) に `segmentation_maps` として直接渡してください。入力画像と並行して処理する正解セグメンテーションマップです。これらのマップは、学習や評価のために使用され、処理された画像の寸法に合わせてリサイズおよび正規化されます。

input_points (`NestedList`, *kwargs*, *optional*) : 非推奨です。代わりに、[SamProcessor.__call__()](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamProcessor.__call__) に `input_points` として直接渡してください。プロンプトベースのセグメンテーション用の入力ポイントです。構造が `[image_level, object_level, point_level, [x, y]]` のネストされたリストである必要があります。各ポイントは、元の画像空間における `[x, y]` 座標で指定されます。ポイントは、モデルに渡される前に、ターゲットの画像サイズに正規化されます。

input_labels (`NestedList`, *kwargs*, *optional*) : 非推奨です。代わりに、[SamProcessor.__call__()](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamProcessor.__call__) に `input_labels` として直接渡してください。入力ポイントのラベルで、各ポイントが前景 (1) であるか背景 (0) であるかを示します。`[image_level, object_level, point_level]` という構造のネストされたリストである必要があります。`input_points` と同じ構造 (座標次元を除く) である必要があります。

input_boxes (`NestedList`, *kwargs*, *optional*) : 非推奨です。代わりに、[SamProcessor.__call__()](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamProcessor.__call__) に `input_boxes` として直接渡してください。プロンプトベースのセグメンテーション用のバウンディングボックスです。構造が `[image_level, box_level, [x1, y1, x2, y2]]` のネストされたリストである必要があります。ここで、各ボックスは元の画像空間における `[x1, y1, x2, y2]` 座標で指定されます。ボックスは、モデルに渡される前に、ターゲットの画像サイズに正規化されます。

point_pad_value (`int`, *kwargs*, *optional*) : 非推奨です。`SamProcessorKwargs.point_pad_value` を使用してください。異なる長さのシーケンスをバッチ処理する際に、入力ポイントのパディングに使用される値です。この値はパディングされた位置を示し、座標正規化の間も保持されることで、実際のポイントとパディングを区別します。

mask_size (`dict[str, *kwargs*, int]`, *任意*) : キー `"height"` と `"width"` を持つ辞書で、ターゲットマスクのサイズを指定します。これにより、モデルが生成する出力セグメンテーションマスクの解像度が決定されます。

mask_pad_size (`dict[str, *kwargs*, int]`, *任意*) : キーに`"height"`と`"width"`を持つ、マスクのパディングサイズを指定する辞書です。これは、異なるサイズのマスクをバッチ処理する際に、次元の一貫性を確保するために使用されます。

return_mm_token_type_ids (`bool`, *kwargs*) : マルチモーダルプレースホルダトークンの位置を示すマルチモーダルトークンタイプIDを返すかどうか。

return_text_replacement_offsets (`bool`, *kwargs*) : 各マルチモーダルプレースホルダーとその置換文字列の文字オフセットを返すかどうか。

point_pad_value (`int`, *kwargs*, *optional*, デフォルトは`-10`) : 長さの異なるシーケンスをバッチ処理する際に、入力ポイントのパディングに使用される値。この値はパディングされた位置を示し、座標正規化の間も保持されることで、実際のポイントとパディングを区別するために使用されます。

return_tensors (`str` または [TensorType](/docs/transformers/v5.24.1/ja/internal/file_utils#transformers.TensorType)、*optional*) : 設定されている場合、特定のフレームワークのテンソルを返します。受け入れ可能な値は以下の通りです:  - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.24.1/ja/main_classes/processors#transformers.ProcessingKwargs), *optional*) : 各モダリティ（テキスト、画像、動画、音声）の追加処理オプション。モデル固有のパラメータは上記にリストされています。サポートされている引数の完全なリストについては、TypedDict クラスを参照してください。

**戻り値:** `~tokenization_utils_base.BatchEncoding`

- **data** (`dict`, *optional*) -- `__call__`/`encode_plus`/`batch_encode_plus` メソッドによって返される、リスト/配列/テンソルの辞書（'input_ids'、'attention_mask' など）。
- **encoding**（`tokenizers.Encoding` または `Sequence[tokenizers.Encoding]`、*任意*）-- トークナイザーが、単語/文字空間からトークン空間へのマッピングなどの追加情報を出力する fast tokenizer の場合、`tokenizers.Encoding` のインスタンス、またはそのリスト（バッチの場合）にこの情報が保持されます。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。
- **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/v5.24.1/src/transformers/models/sam/image_processing_sam.py#L61)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `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*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.485, 0.456, 0.406]`) : 正規化に使用する画像の平均値です。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.229, 0.224, 0.225]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *optional*, デフォルトは `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*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

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*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

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/v5.24.1/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*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : 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*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`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*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

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*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

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]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

## 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/v5.24.1/src/transformers/models/sam/image_processing_pil_sam.py#L82)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `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*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.485, 0.456, 0.406]`) : 正規化に使用する画像の平均値です。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.229, 0.224, 0.225]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *optional*, デフォルトは `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*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

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*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

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/v5.24.1/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*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : 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*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`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*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

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*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

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]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

## SamVisionModel[[transformers.SamVisionModel]]

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

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

[ソース](https://github.com/huggingface/transformers/blob/v5.24.1/src/transformers/models/sam/modeling_sam.py#L1080)

**パラメータ:**

config ([SamVisionConfig](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamVisionConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.24.1/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

ヘッドや投影が上に乗せられていないSamのビジョンモデル。

このモデルは [PreTrainedModel](/docs/transformers/v5.24.1/ja/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/v5.24.1/src/transformers/models/sam/modeling_sam.py#L1092)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [SamImageProcessor](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamImageProcessor) を使用して取得できます。詳細は [SamImageProcessor.__call__()](/docs/transformers/v5.24.1/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（[SamProcessor](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamProcessor) は画像の処理に [SamImageProcessor](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamImageProcessor) を使用します）。

**戻り値:** `SamVisionEncoderOutput` または `tuple(torch.Tensor)`

`SamVisionEncoderOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。構成要素は、設定（[SamConfig](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamConfig)）と入力に応じて異なります。

[SamVisionModel](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamVisionModel)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **image_embeds** (`torch.Tensor`、形状 `(batch_size, output_dim)`、*任意*、モデルが `with_projection=True` で初期化された場合に返されます) -- pooler_output に投影層を適用して得られる画像埋め込みです。
- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, sequence_length, hidden_size)`、*任意*) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **hidden_states** (`tuple[torch.Tensor, ...]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple[torch.Tensor, ...]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(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/v5.24.1/src/transformers/models/sam/modeling_sam.py#L1107)

**パラメータ:**

config ([SamConfig](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.24.1/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

入力画像と、入力となる点とラベル、ボックス、またはマスクが与えられた場合にセグメンテーションマスクを生成するためのSegment Anything Model (SAM)。

このモデルは [PreTrainedModel](/docs/transformers/v5.24.1/ja/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/v5.24.1/src/transformers/models/sam/modeling_sam.py#L1190)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [SamImageProcessor](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamImageProcessor) を使用して取得できます。詳細は [SamImageProcessor.__call__()](/docs/transformers/v5.24.1/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（[SamProcessor](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamProcessor) は画像の処理に [SamImageProcessor](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamImageProcessor) を使用します）。

input_points (`torch.Tensor`、shape は `(batch_size, num_points, 2)`) : 入力となる 2 次元空間上の点です。プロンプトエンコーダーがこの点を使用してプロンプトをエンコードします。一般的に、これによりはるかに良い結果が得られます。点は、リストのリストのリストをプロセッサーに渡すことで取得でき、プロセッサーは次元 4 の対応する `torch` テンソルを作成します。最初の次元は画像のバッチサイズ、2 番目の次元は点のバッチサイズ（つまり、1 つの入力点あたりモデルに何つのセグメンテーションマスクを予測させたいか）、3 番目の次元は 1 つのセグメンテーションマスクあたりの点の数（1 つのマスクに対して複数の点を渡すことも可能です）、最後の次元は点の x（縦）および y（横）座標です。画像ごと、またはマスクごとに異なる数の点が渡された場合、プロセッサーは (0, 0) 座標に対応する「PAD」点を作成し、これらの点についてはラベルを使用して埋め込みの計算をスキップします。

input_labels (`torch.LongTensor`、shape は `(batch_size, point_batch_size, num_points)`) : ポイントの入力ラベルです。プロンプトエンコーダーがプロンプトをエンコードするために使用されます。公式実装によると、ラベルには 3 種類あります - `1`: 対象オブジェクトを含むポイント - `0`: 対象オブジェクトを含まないポイント - `-1`: 背景に対応するポイント 追加したラベル: - `-10`: パディングポイントであり、プロンプトエンコーダーによって無視されるべきです パディングラベルは、プロセッサーによって自動的に設定される必要があります。

input_boxes (`torch.Tensor`、shape `(batch_size, num_boxes, 4)`) : ポイント用の入力ボックスです。プロンプトエンコーダーによってプロンプトをエンコードするために使用されます。一般的に、はるかに優れた生成マスクが得られます。ボックスは、リストのリストのリストをプロセッサーに渡すことで取得でき、`torch`テンソルが生成されます。各次元は、それぞれ画像のバッチサイズ、画像ごとのボックス数、ボックスの左上と右下の点の座標に対応します。順序は (`x1`, `y1`, `x2`, `y2`) です:  - `x1`: 入力ボックスの左上の点のx座標 - `y1`: 入力ボックスの左上の点のy座標 - `x2`: 入力ボックスの右下の点のx座標 - `y2`: 入力ボックスの右下の点のy座標

input_masks (`torch.Tensor`、shape `(batch_size, image_size, image_size)`) : SAM モデルはセグメンテーションマスクも入力として受け付けます。マスクはプロンプトエンコーダーによって埋め込まれ、対応する埋め込みが生成されます。この埋め込みは後でマスクデコーダーに渡されます。これらのマスクはユーザーが手動で渡す必要があり、shape は (`batch_size`, `image_size`, `image_size`) である必要があります。

image_embeddings (`torch.Tensor`、shape は `(batch_size, output_channels, window_size, window_size)`) : 画像埋め込み。マスクデコーダーがマスクと IoU スコアを生成するために使用されます。よりメモリ効率の高い計算を行うには、まず `get_image_embeddings` メソッドで画像埋め込みを取得し、`pixel_values` を渡す代わりに、それを `forward` メソッドに渡すことができます。

multimask_output (`bool`, *任意*) : 元の実装および論文では、モデルは常に1画像につき3つのマスクを出力します（関連する場合は、1ポイントごとまたは1バウンディングボックスごと）。ただし、`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/v5.24.1/ja/model_doc/sam#transformers.SamConfig)）と入力に応じて異なります。

[SamModel](/docs/transformers/v5.24.1/ja/model_doc/sam#transformers.SamModel)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **iou_scores** (`torch.Tensor`、形状 `(batch_size, num_masks)`) -- 予測されたマスクの IoU スコアです。
- **pred_masks** (`torch.Tensor`、形状 `(batch_size, num_masks, height, width)`) -- 予測された低解像度のマスクです。プロセッサによる後処理が必要です。
- **vision_hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用 1 つ + 各層の出力用 1 つ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  ビジョンモデルの各層の出力における隠れ状態、および任意の初期埋め込み出力。
- **vision_attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **mask_decoder_attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(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"]
... )
```

