Transformers documentation

SAM

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

and get access to the augmented documentation experience

to get started

このモデルは2023年4月5日にHF papersで公開され、2023年4月19日にHugging Face Transformersに貢献されました。

SAM

概要

SAM (Segment Anything Model) は、Alexander Kirillov、Eric Mintun、Nikhila Ravi、Hanzi Mao、Chloe Rolland、Laura Gustafson、Tete Xiao、Spencer Whitehead、Alex Berg、Wan-Yen Lo、Piotr Dollar、Ross Girshick によって Segment Anything で提案されました。

モデルは、入力画像が与えられた場合、対象となる任意のオブジェクトのセグメンテーションマスクを予測するために使用できます。

example image

論文の抄録は以下の通りです。

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

ヒント:

  • モデルは、与えられた画像において対象オブジェクトが存在するかどうかを示すバイナリマスクを予測します。
  • 入力として2Dの点と/または入力バウンディングボックスが提供される場合、モデルははるかに優れた結果を予測します
  • 同じ画像に対して複数のポイントをプロンプトとして指定し、単一のマスクを予測できます。
  • モデルのファインチューニングは現在サポートされていません
  • 論文によると、テキスト入力もサポートされるべきです。しかし、執筆時点では、公式リポジトリによるとサポートされていないようです。

このモデルは、ybelkada と ArthurZ によって提供されました。 元のコードはこちらで確認できます。

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

import requests
import torch
from PIL import Image

from transformers import SamModel, SamProcessor


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

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

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

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

プロセッサでは、入力画像と並行して独自のマスクも処理し、モデルに渡すことができます。

import requests
import torch
from PIL import Image

from transformers import SamModel, SamProcessor


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

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

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

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

リソース

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

SlimSAM

SAMの剪定版であるSlimSAMは、Zigeng Chen らによって0.1% Data Makes Segment Anything Slimで提案されました。SlimSAMは、SAMモデルのサイズを大幅に削減しながら、同じ性能を維持します。

hubでチェックポイントを見つけることができ、SAMのドロップイン代替として使用できます。

Grounded SAM

Grounding DINOとSAMを組み合わせることで、Grounded SAM: Assembling Open-World Models for Diverse Visual Tasksで紹介されているテキストベースのマスク生成を行うことができます。詳細については、このデモノートブック🌍を参照してください。

drawing Grounded SAM overview. Taken from the original repository.

SamConfig

class transformers.SamConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprompt_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonemask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinitializer_range: float = 0.02tie_word_embeddings: bool = True )

パラメータ

  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig]、任意) — ビジョンバックボーンの config オブジェクトまたは辞書です。
  • prompt_encoder_config (Union[dict, SamPromptEncoderConfig], 省略可) — SamPromptEncoderConfigを初期化するために使用される設定オプションの辞書。
  • mask_decoder_config (Union[dict, SamMaskDecoderConfig], 省略可) — SamMaskDecoderConfigを初期化するために使用される設定オプションの辞書です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
  • tie_word_embeddings (bool、任意、デフォルトは True) — モデルの tied_weights_keys マッピングに従って重み埋め込みを共有するかどうかを指定します。

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

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

例:

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

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

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

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

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

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

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

SamVisionConfig

class transformers.SamVisionConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 768output_channels: int = 256num_hidden_layers: int = 12num_attention_heads: int = 12num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 1024patch_size: int | list[int] | tuple[int, int] = 16hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06attention_dropout: float | int = 0.0initializer_range: float = 1e-10qkv_bias: bool = Truemlp_ratio: float = 4.0use_abs_pos: bool = Trueuse_rel_pos: bool = Truewindow_size: int = 14global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)num_pos_feats: int = 128mlp_dim: int | None = None )

パラメータ

  • hidden_size (int、任意、デフォルトは 768) — 隠れ表現の次元数。
  • output_channels (int、任意、デフォルトは 256) — Patch Encoder の出力チャネルの次元数。
  • num_hidden_layers (int、任意、デフォルトは 12) — Transformer デコーダーの隠れ層の数。
  • num_attention_heads (int、任意、デフォルトは12) — Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。
  • num_channels (int、任意、デフォルトは3) — 入力チャネル数。
  • image_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは 1024) — 各画像のサイズ(解像度)です。
  • patch_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは16) — 各パッチのサイズ(解像度)です。
  • hidden_act (str、任意、デフォルトは gelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する 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, 任意、デフォルト値は 14)— 相対位置のウィンドウサイズです。
  • global_attn_indexes (list[int]、任意、デフォルトは [2, 5, 8, 11]) — グローバルアテンションレイヤーのインデックスです。
  • num_pos_feats (int、任意、デフォルトは 128) — 位置埋め込みの次元数です。
  • mlp_dim (int, 任意) — Transformer エンコーダーにおける MLP レイヤーの次元数です。None の場合、デフォルトで mlp_ratio * hidden_size になります。

This is the configuration class to store the configuration of a SamModel. It is used to instantiate a Sam model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the facebook/sam-vit-huge

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

例:

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

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

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

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

SamMaskDecoderConfig

class transformers.SamMaskDecoderConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 256hidden_act: str = 'relu'mlp_dim: int = 2048num_hidden_layers: int = 2num_attention_heads: int = 8attention_downsample_rate: int = 2num_multimask_outputs: int = 3iou_head_depth: int = 3iou_head_hidden_dim: int = 256layer_norm_eps: float = 1e-06 )

パラメータ

  • hidden_size (int、任意、デフォルトは 256) — 隠れ表現の次元数。
  • hidden_act (str、任意、デフォルトは relu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • mlp_dim (int、任意、デフォルト値は 2048) — Transformer エンコーダーにおける「中間」(すなわちフィードフォワード) 層の次元数。
  • num_hidden_layers (int、任意、デフォルトは2) — Transformerデコーダーの隠れ層の数。
  • num_attention_heads (int、任意、デフォルトは 8) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • attention_downsample_rate (int、任意、デフォルトは 2) — アテンション層のダウンサンプリング率です。
  • num_multimask_outputs (int、任意、デフォルトは 3) — SamMaskDecoder モジュールからの出力数です。Segment Anything の論文では、この値は 3 に設定されています。
  • iou_head_depth (int、任意、デフォルトは 3) — IoU ヘッドモジュールの層数です。
  • iou_head_hidden_dim (int, 任意、デフォルトは 256) — IoU head モジュールにおける隠れ状態の次元数です。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する epsilon です。

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

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

SamPromptEncoderConfig

class transformers.SamPromptEncoderConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 256image_size: int | list[int] | tuple[int, int] = 1024patch_size: int | list[int] | tuple[int, int] = 16mask_input_channels: int = 16num_point_embeddings: int = 4hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06 )

パラメータ

  • hidden_size (int、任意、デフォルトは 256) — 隠れ表現の次元数。
  • image_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは 1024) — 各画像のサイズ(解像度)です。
  • patch_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは16) — 各パッチのサイズ(解像度)です。
  • mask_input_channels (int、任意、デフォルトは 16)— MaskDecoder モジュールに渡すチャネル数です。
  • num_point_embeddings (int、任意、デフォルトは 4) — 使用する point embeddings の数です。
  • hidden_act (str、任意、デフォルトは gelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する epsilon です。

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

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

SamProcessor

class transformers.SamProcessor

< >

( image_processor )

パラメータ

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

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

SamProcessor は SamImageProcessor のすべての機能を提供します。詳細については、~SamImageProcessor を参照してください。

__call__

< >

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

パラメータ

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 任意) — 前処理対象の画像です。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチを想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、do_rescale=False を設定してください。
  • text (Union[str, list[str], list[list[str]]]、省略可) — エンコード対象のシーケンスまたはシーケンスのバッチです。各シーケンスは文字列、または文字列のリスト(事前トークン化済み文字列)であることができます。事前トークン化済みの入力を渡す場合は、バッチ入力との曖昧さを避けるために is_split_into_words=True を設定してください。
  • return_tensors (str または TensorType, 省略可) — 設定すると、特定のフレームワークのテンソルを返します。使用可能な値は以下の通りです:
    • 'pt': PyTorchのtorch.Tensorオブジェクトを返します。
    • 'np': NumPyのnp.ndarrayオブジェクトを返します。

戻り値

~tokenization_utils_base.BatchEncoding

  • data (dict、任意) — __call__/encode_plus/batch_encode_plus メソッドによって返される、リスト/配列/テンソルの辞書(‘input_ids’、‘attention_mask’ など)。
  • エンコーディング(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

class transformers.SamImageProcessor

< >

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

パラメータ

  • 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 が 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, デフォルトは 2) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResampling の列挙型のいずれかを使用できます。do_resize が True に設定されている場合のみ、効果が現れます。
  • do_rescale (bool、kwargs、任意、デフォルトはTrue) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意、デフォルト値は 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, defaults to {'height' -- 1024, 'width': 1024}): The size in {"height": int, "width" int} to pad the images to. Must be larger than any image size provided for preprocessing. If pad_size is not provided, images will be padded to the largest height and width in the batch. Applied only when do_pad=True.
  • do_center_crop (bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。
  • data_format (Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのは 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: (高さ, 幅, チャネル数) 形式の画像。
    • "none" または ChannelDimension.NONE: (height, width) 形式の画像。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。
  • image_seq_length (int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。
  • mask_size (dict[str, *kwargs*, int], 任意) — セグメンテーションマップをリサイズするサイズ {"longest_edge": int}。
  • mask_pad_size (dict[str, *kwargs*, int], 省略可) — セグメンテーションマップをパディングするサイズ {"height": int, "width": int}です。前処理用に提供されるセグメンテーションマップのサイズよりも大きい必要があります。

SamImageProcessor画像プロセッサを構築します。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.sam.image_processing_sam.SamImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

パラメータ

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 前処理対象の画像です。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチを想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、do_rescale=False を設定してください。
  • segmentation_maps (ImageInput、任意) — 前処理を行うセグメンテーションマップです。
  • do_convert_rgb (bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。
  • do_resize (bool、kwargs、optional) — 画像をリサイズするかどうか。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — モデルへの最大入力次元を記述します。
  • default_to_square (bool、kwargs、任意) — サイズが整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。
  • 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、optional) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意) — 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, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。
  • 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、任意) — サポートされているのは 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: (高さ, 幅, チャネル数) 形式の画像。
    • "none" または ChannelDimension.NONE: (height, width) 形式の画像。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。
  • image_seq_length (int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。
  • 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

class transformers.SamImageProcessorPil

< >

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

パラメータ

  • 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 が 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, デフォルトは 2) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResampling の列挙型のいずれかを使用できます。do_resize が True に設定されている場合のみ、効果が現れます。
  • do_rescale (bool、kwargs、任意、デフォルトはTrue) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意、デフォルト値は 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, defaults to {'height' -- 1024, 'width': 1024}): The size in {"height": int, "width" int} to pad the images to. Must be larger than any image size provided for preprocessing. If pad_size is not provided, images will be padded to the largest height and width in the batch. Applied only when do_pad=True.
  • do_center_crop (bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。
  • data_format (Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのは 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: (高さ, 幅, チャネル数) 形式の画像。
    • "none" または ChannelDimension.NONE: (height, width) 形式の画像。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。
  • image_seq_length (int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。
  • mask_size (dict[str, *kwargs*, int]、任意) — セグメンテーションマップをリサイズするサイズ {"longest_edge": int}。
  • mask_pad_size (dict[str, *kwargs*, int], 省略可) — セグメンテーションマップをパディングするサイズ {"height": int, "width": int}です。前処理用に提供されるセグメンテーションマップのサイズよりも大きくなければなりません。

SamImageProcessor画像プロセッサを構築します。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.sam.image_processing_pil_sam.SamImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

パラメータ

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 前処理対象の画像です。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチを想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、do_rescale=False を設定してください。
  • segmentation_maps (ImageInput、任意) — 前処理を行うセグメンテーションマップです。
  • do_convert_rgb (bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。
  • do_resize (bool、kwargs、optional) — 画像をリサイズするかどうか。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — モデルへの最大入力次元を記述します。
  • default_to_square (bool、kwargs、任意) — サイズが整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。
  • 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、optional) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意) — 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, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。
  • 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、任意) — サポートされているのは 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: (高さ, 幅, チャネル数) 形式の画像。
    • "none" または ChannelDimension.NONE: (height, width) 形式の画像。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。
  • image_seq_length (int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。
  • 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

class transformers.SamVisionModel

< >

( config: SamVisionConfig )

パラメータ

  • config (SamVisionConfig) — モデルのすべてのパラメータを含むモデル設定クラス。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。

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

このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

forward

< >

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

パラメータ

  • pixel_values (torch.FloatTensor、形状 (batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は SamImageProcessor を使用して取得できます。詳細については SamImageProcessor.call() を参照してください(SamProcessor は画像の処理に SamImageProcessor を使用します)。

戻り値

SamVisionEncoderOutput または tuple(torch.FloatTensor)

SamVisionEncoderOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(SamConfig)と入力に応じて、さまざまな要素で構成されます。

SamVisionModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

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

  • image_embeds (torch.FloatTensor、shape (batch_size, output_dim)、optional、モデルがwith_projection=Trueで初期化された場合に返されます)— pooler_output に投影層を適用して得られる画像埋め込みです。

  • last_hidden_state (torch.FloatTensor、shape (batch_size, sequence_length, hidden_size)、optional) — モデルの最終層の出力における隠れ状態のシーケンス。

  • hidden_states (tuple[torch.FloatTensor, ...]、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返されます) — torch.FloatTensor のタプル(埋め込み層を持つモデルの場合、埋め込みの出力が 1 つ、各層の出力がそれぞれ 1 つずつ)で、形状は (batch_size, sequence_length, hidden_size) です。

    各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。

  • attentions (tuple[torch.FloatTensor, ...]、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます)— torch.FloatTensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length) です。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

SamModel

class transformers.SamModel

< >

( config: SamConfig )

パラメータ

  • config (SamConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。

入力画像と、入力となるポイントとラベル、ボックス、またはマスクを指定してセグメンテーションマスクを生成するためのSegment Anything Model (SAM)。

このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

forward

< >

( pixel_values: 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] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SamImageSegmentationOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.FloatTensor、形状 (batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は SamImageProcessor を使用して取得できます。詳細については SamImageProcessor.call() を参照してください(SamProcessor は画像の処理に SamImageProcessor を使用します)。
  • input_points (torch.FloatTensor、shape (batch_size, num_points, 2)) — 入力となる 2 次元空間上の点です。プロンプトエンコーダがプロンプトをエンコードするために使用されます。一般的に、これによりはるかに良い結果が得られます。点は、リストのリストのリストをプロセッサに渡すことで取得でき、これにより次元 4 の対応する torch テンソルが作成されます。最初の次元は画像のバッチサイズ、2 番目の次元は点のバッチサイズ(つまり、入力点ごとにモデルに予測させたいセグメンテーションマスクの数)、3 番目の次元はセグメンテーションマスクごとの点の数(1 つのマスクに対して複数の点を渡すことも可能です)、最後の次元は点の x(縦)および y(横)座標です。画像ごと、またはマスクごとに異なる数の点が渡された場合、プロセッサは (0, 0) 座標に対応する「PAD」点を作成し、これらの点についてはラベルを使用して埋め込みの計算をスキップします。
  • input_labels (torch.LongTensor の形状 (batch_size, point_batch_size, num_points)) — ポイントの入力ラベルです。プロンプトエンコーダーによってプロンプトをエンコードするために使用されます。公式実装によると、ラベルには 3 種類あります
    • 1: 対象オブジェクトを含む点
    • 0: 対象オブジェクトを含まない点
    • -1: 背景に対応する点

    ラベルを追加しました:

    • -10: その点はパディングポイントであるため、プロンプトエンコーダーによって無視されるべきです

    パディングラベルは、プロセッサによって自動的に処理されるべきです。

  • input_boxes (torch.FloatTensor の形状 (batch_size, num_boxes, 4)) — ポイント用の入力ボックスです。プロンプトエンコーダーによってプロンプトをエンコードするために使用されます。一般的に、より優れた生成マスクが得られます。ボックスは、リストのリストのリストをプロセッサーに渡すことで取得でき、 torch テンソルが生成されます。各次元は、それぞれ画像のバッチサイズ、画像ごとのボックス数、およびボックスの左上と右下の点の座標に対応します。順序は (x1, y1, x2, y2):
    • x1: 入力ボックスの左上の点のx座標
    • y1: 入力ボックスの左上の点のy座標
    • x2: 入力ボックスの右下の点のx座標
    • y2: 入力ボックスの右下隅の y 座標
  • input_masks (torch.FloatTensor、shape (batch_size, image_size, image_size)) — SAM モデルは、セグメンテーションマスクも入力として受け入れます。マスクはプロンプトエンコーダーによって埋め込まれ、対応する埋め込みが生成されます。この埋め込みは、後でマスクデコーダーに渡されます。これらのマスクはユーザーが手動で渡す必要があり、shape は (batch_size, image_size, image_size) である必要があります。
  • image_embeddings (torch.FloatTensor、shape (batch_size, output_channels, window_size, window_size)) — 画像埋め込みです。マスクデコーダーがマスクと IoU スコアを生成するために使用されます。メモリ効率の高い計算を行うには、まず get_image_embeddings メソッドで画像埋め込みを取得し、pixel_values を渡す代わりに、それを forward メソッドに渡すことができます。
  • multimask_output (bool, 任意) — 元の実装および論文では、モデルは常に1枚の画像ごとに3つのマスクを出力します(関連する場合は、ポイントごとまたはバウンディングボックスごと)。ただし、multimask_output=Falseを指定することで、「最良」のマスクに相当する単一のマスクのみを出力することも可能です。
  • attention_similarity (torch.FloatTensor, 任意) — ターゲットガイドドアテンションのためにマスクデコーダーに渡すアテンション類似度テンソル。モデルがPerSAMで導入されたパーソナライゼーションに使用される場合に指定します。
  • target_embedding (torch.FloatTensor, 任意) — ターゲット概念の埋め込み。モデルがPerSAMで導入されたパーソナライゼーションに使用される場合、ターゲット意味プロンプティングのためにマスクデコーダーに提供されます。

戻り値

SamImageSegmentationOutput または tuple(torch.FloatTensor)

SamImageSegmentationOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(SamConfig)と入力に応じて、さまざまな要素で構成されます。

SamModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

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

  • iou_scores (torch.FloatTensor、shape (batch_size, num_masks)) — 予測されたマスクの IoU スコア。

  • pred_masks (torch.FloatTensor、shape (batch_size, num_masks, height, width)) — 予測された低解像度のマスクです。プロセッサによる後処理が必要です。

  • vision_hidden_states (tuple(torch.FloatTensor)、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返される)— torch.FloatTensor のタプル(埋め込み層を持つモデルの場合、埋め込みの出力が 1 つ、各層の出力がそれぞれ 1 つずつ)で、形状は (batch_size, sequence_length, hidden_size) です。

    ビジョンモデルの各層の出力における隠れ状態、および任意の初期埋め込み出力。

  • vision_attentions (tuple(torch.FloatTensor)、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます) — torch.FloatTensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length)。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

  • mask_decoder_attentions (tuple(torch.FloatTensor)、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます) — torch.FloatTensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length)。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

>>> 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"]
... )
Update on GitHub