Transformers documentation
SAM2
このモデルは2025年8月14日にHugging Face Transformersに貢献されました。
SAM2
概要
SAM2 (Segment Anything Model 2) は、Nikhila Ravi、Valentin Gabeur、Yuan-Ting Hu、Ronghang Hu、Chaitanya Ryali、Tengyu Ma、Haitham Khedr、Roman Rädle、Chloe Rolland、Laura Gustafson、Eric Mintun、Junting Pan、Kalyan Vasudev Alwala、Nicolas Carion、Chao-Yuan Wu、Ross Girshick、Piotr Dollár、Christoph Feichtenhofer によって、Segment Anything in Images and Videos で提案されました。
モデルは、入力画像または動画、および入力されたポイントまたはバウンディングボックスを指定することで、対象とする任意のオブジェクトのセグメンテーションマスクを予測するために使用できます。

論文の抄録は以下の通りです。
画像および動画におけるプロンプト可能な視覚セグメンテーションの解決に向けた基盤モデルであるSegment Anything Model 2 (SAM 2) を紹介します。ユーザーとのインタラクションを通じてモデルとデータを改善するデータエンジンを構築し、これまでに収集された最大規模の動画セグメンテーションデータセットを収集しました。当社のモデルは、リアルタイムの動画処理に対応するストリーミングメモリを備えたシンプルなtransformerアーキテクチャです。当社のデータで訓練されたSAM 2は、幅広いタスクで優れたパフォーマンスを発揮します。動画セグメンテーションでは、従来の手法よりも3分の1のインタラクション数で、より高い精度を実現しています。画像セグメンテーションでは、Segment Anything Model (SAM) よりも精度が高く、6倍速く動作します。当社のデータ、モデル、および知見は、動画セグメンテーションおよび関連する知覚タスクにとって重要なマイルストーンとなるものと確信しています。モデルのバージョン、データセット、およびインタラクティブなデモを公開します。
ヒント:
- Batch & Video Support: SAM2 はバッチ処理とシームレスな動画セグメンテーションをネイティブでサポートする一方、オリジナルの SAM は静的な画像と、1枚ずつ処理するシンプルなワークフロー向けに設計されています。
- Accuracy & Generalization: SAM2は、元のSAMと比較して、特に混合プロンプトを使用した場合に、セグメンテーションの品質、ロバストネス、および新しいドメインへのゼロショット汎化性能が向上しています。
このモデルは、sangbumchoi と yonigozlan によって提供されました。 元のコードはこちらで確認できます。
使用例
Pipelineによる自動マスク生成
SAM2は、mask-generationパイプラインを使用して画像内のすべてのオブジェクトをセグメントするための自動マスク生成に使用できます。
from transformers import pipeline
generator = pipeline("mask-generation", model="facebook/sam2.1-hiera-large", device=0)
image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg"
outputs = generator(image_url, points_per_batch=64)
len(outputs["masks"]) # Number of masks generated
39基本的な画像セグメンテーション
単一ポイントクリック
オブジェクトをセグメントするには、セグメントしたいオブジェクトに1回クリックするだけで分割できます:
from transformers import Sam2Processor, Sam2Model
import torch
from PIL import Image
import requests
model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-large", device_map="auto")
processor = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-large")
image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg"
raw_image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
input_points = [[[[500, 375]]]] # Single point click, 4 dimensions (image_dim, object_dim, point_per_object_dim, coordinates)
input_labels = [[[1]]] # 1 for positive click, 0 for negative click, 3 dimensions (image_dim, object_dim, point_label)
inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
# The model outputs multiple mask predictions ranked by quality score
print(f"Generated {masks.shape[1]} masks with shape {masks.shape}")
Generated 3 masks with shape torch.Size(1, 3, 1500, 2250)改善のための複数のポイント
セグメンテーションを微調整するために、複数の点を指定できます。
# Add both positive and negative points to refine the mask
input_points = [[[[500, 375], [1125, 625]]]] # Multiple points for refinement
input_labels = [[[1, 1]]] # Both positive clicks
inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]バウンディングボックス入力
SAM2は、セグメンテーションのためのバウンディングボックス入力もサポートしています:
# Define bounding box as [x_min, y_min, x_max, y_max]
input_boxes = [[[75, 275, 1725, 850]]]
inputs = processor(images=raw_image, input_boxes=input_boxes, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]複数オブジェクトのセグメンテーション
複数のオブジェクトを同時にセグメンテーションできます:
# Define points for two different objects
input_points = [[[[500, 375]], [[650, 750]]]] # Points for two objects in same image
input_labels = [[[1], [1]]] # Positive clicks for both objects
inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs, multimask_output=False)
# Each object gets its own mask
masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
print(f"Generated masks for {masks.shape[0]} objects")
Generated masks for 2 objectsバッチ推論
バッチ化された画像
効率を向上させるために、複数の画像を同時に処理します:
from transformers import Sam2Processor, Sam2Model
import torch
from PIL import Image
import requests
model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-large", device_map="auto")
processor = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-large")
# Load multiple images
image_urls = [
"https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg",
"https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/dog_sam.png"
]
raw_images = [Image.open(requests.get(url, stream=True).raw).convert("RGB") for url in image_urls]
# Single point per image
input_points = [[[[500, 375]]], [[[770, 200]]]] # One point for each image
input_labels = [[[1]], [[1]]] # Positive clicks for both images
inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs, multimask_output=False)
# Post-process masks for each image
all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
print(f"Processed {len(all_masks)} images, each with {all_masks[0].shape[0]} objects")
Processed 2 images, each with 1 objects画像ごとのバッチ化されたオブジェクト
バッチ推論を使用して、各画像内の複数のオブジェクトをセグメントします:
# Multiple objects per image - different numbers of objects per image
input_points = [
[[[500, 375]], [[650, 750]]], # Truck image: 2 objects
[[[770, 200]]] # Dog image: 1 object
]
input_labels = [
[[1], [1]], # Truck image: positive clicks for both objects
[[1]] # Dog image: positive click for the object
]
inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs, multimask_output=False)
all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])バッチ化された画像とバッチ化されたオブジェクト、および複数のポイント
1つのオブジェクトに複数の点を含む複雑なバッチシナリオを処理します:
# Add groceries image for more complex example
groceries_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/groceries.jpg"
groceries_image = Image.open(requests.get(groceries_url, stream=True).raw).convert("RGB")
raw_images = [raw_images[0], groceries_image] # Use truck and groceries images
# Complex batching: multiple images, multiple objects, multiple points per object
input_points = [
[[[500, 375]], [[650, 750]]], # Truck image: 2 objects with 1 point each
[[[400, 300]], [[630, 300], [550, 300]]] # Groceries image: obj1 has 1 point, obj2 has 2 points
]
input_labels = [
[[1], [1]], # Truck image: positive clicks
[[1], [1, 1]] # Groceries image: positive clicks for refinement
]
inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs, multimask_output=False)
all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])バッチ化されたバウンディングボックス
バウンディングボックス入力で複数の画像を処理します:
# Multiple bounding boxes per image (using truck and groceries images)
input_boxes = [
[[75, 275, 1725, 850], [425, 600, 700, 875], [1375, 550, 1650, 800], [1240, 675, 1400, 750]], # Truck image: 4 boxes
[[450, 170, 520, 350], [350, 190, 450, 350], [500, 170, 580, 350], [580, 170, 640, 350]] # Groceries image: 4 boxes
]
# Update images for this example
raw_images = [raw_images[0], groceries_image] # truck and groceries
inputs = processor(images=raw_images, input_boxes=input_boxes, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs, multimask_output=False)
all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
print(f"Processed {len(input_boxes)} images with {len(input_boxes[0])} and {len(input_boxes[1])} boxes respectively")
Processed 2 images with 4 and 4 boxes respectively以前のマスクを入力として使用
SAM2は、以前の予測から得られたマスクを入力として使用して、セグメンテーションを改善できます:
# Get initial segmentation
input_points = [[[[500, 375]]]]
input_labels = [[[1]]]
inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
# Use the best mask as input for refinement
mask_input = outputs.pred_masks[:, :, torch.argmax(outputs.iou_scores.squeeze())]
# Add additional points with the mask input
new_input_points = [[[[500, 375], [450, 300]]]]
new_input_labels = [[[1, 1]]]
inputs = processor(
input_points=new_input_points,
input_labels=new_input_labels,
original_sizes=inputs["original_sizes"],
return_tensors="pt",
).to(model.device)
with torch.no_grad():
refined_outputs = model(
**inputs,
input_masks=mask_input,
image_embeddings=outputs.image_embeddings,
multimask_output=False,
)Sam2Config
クラス transformers.Sam2Config
< source >( 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.02 )
パラメータ
- vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig]、任意) — ビジョンバックボーンの config オブジェクトまたは辞書です。 - prompt_encoder_config (Union[
dict,Sam2PromptEncoderConfig], 省略可) — Sam2PromptEncoderConfigを初期化するために使用される設定オプションの辞書。 - mask_decoder_config (Union[
dict,Sam2MaskDecoderConfig], 省略可) — Sam2MaskDecoderConfigを初期化するために使用される設定オプションの辞書です。 - initializer_range (
float、任意、デフォルトは0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
This is the configuration class to store the configuration of a Sam2Model. It is used to instantiate a Sam2 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/sam2.1-hiera-tiny
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
例:
>>> from transformers import (
... Sam2VisionConfig,
... Sam2PromptEncoderConfig,
... Sam2MaskDecoderConfig,
... Sam2Model,
... )
>>> # Initializing a Sam2Config with `"facebook/sam2.1_hiera_tiny"` style configuration
>>> configuration = Sam2Config()
>>> # Initializing a Sam2Model (with random weights) from the `"facebook/sam2.1_hiera_tiny"` style configuration
>>> model = Sam2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
>>> # We can also initialize a Sam2Config from a Sam2VisionConfig, Sam2PromptEncoderConfig, and Sam2MaskDecoderConfig
>>> # Initializing SAM2 vision encoder, memory attention, and memory encoder configurations
>>> vision_config = Sam2VisionConfig()
>>> prompt_encoder_config = Sam2PromptEncoderConfig()
>>> mask_decoder_config = Sam2MaskDecoderConfig()
>>> config = Sam2Config(vision_config, prompt_encoder_config, mask_decoder_config)Sam2HieraDetConfig
class transformers.Sam2HieraDetConfig
< source >( 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 = 96num_attention_heads: int = 1num_channels: int = 3image_size: int | list[int] | None = Nonepatch_kernel_size: int | list[int] | None = Nonepatch_stride: int | list[int] | None = Nonepatch_padding: int | list[int] | None = Nonequery_stride: int | list[int] | None = Nonewindow_positional_embedding_background_size: list[int] | None = Nonenum_query_pool_stages: int = 3blocks_per_stage: list[int] | None = Noneembed_dim_per_stage: list[int] | None = Nonenum_attention_heads_per_stage: list[int] | None = Nonewindow_size_per_stage: list[int] | None = Noneglobal_attention_blocks: list[int] | None = Nonemlp_ratio: float = 4.0hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06initializer_range: float = 0.02 )
パラメータ
- hidden_size (
int、任意、デフォルトは96) — 隠れ表現の次元数。 - num_attention_heads (
int、任意、デフォルトは1) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。 - num_channels (
int、任意、デフォルトは3) — 入力チャネル数。 - image_size (
Union[int, list[int]]、任意) — 各画像のサイズ(解像度)です。 - patch_kernel_size (
list[int]、任意、デフォルトは[7, 7]) — パッチのカーネルサイズです。 - patch_stride (
list[int]、任意、デフォルトは[4, 4]) — パッチのストライドです。 - patch_padding (
list[int]、省略可、デフォルトは[3, 3]) — パッチのpaddingです。 - query_stride (
list[int]、省略可、デフォルトは[2, 2]) — ステージ間のダウンサンプルのストライドです。 - window_positional_embedding_background_size (
list[int]、任意、デフォルトは[7, 7]) — グローバルアテンションを使用しない場合の、各ステージにおけるウィンドウサイズ。 - num_query_pool_stages (
int、任意、デフォルトは 3) — クエリプールのステージ数です。 - blocks_per_stage (
list[int]、任意、デフォルトは[1, 2, 7, 2]) — ステージごとのブロック数を指定します。 - embed_dim_per_stage (
list[int]、任意、デフォルトは[96, 192, 384, 768]) — ステージごとの埋め込み次元数。 - num_attention_heads_per_stage (
list[int]、任意、デフォルトは[1, 2, 4, 8]) — ステージごとのアテンションヘッド数です。 - window_size_per_stage (
list[int]、任意、デフォルトは[8, 4, 14, 7]) — ステージごとのウィンドウサイズです。 - global_attention_blocks (
list[int]、任意、デフォルトは[5, 7, 9]) — グローバルアテンションを使用するブロックです。 - mlp_ratio (
float、任意、デフォルトは4.0) — MLP の隠れ層の次元と埋め込み次元の比率です。 - hidden_act (
str、任意、デフォルトはgelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、"relu"、"silu"など。 - layer_norm_eps (
float、任意、デフォルトは1e-06) — レイヤーノーマル層で使用する epsilon です。 - initializer_range (
float、任意、デフォルトは0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
これは Sam2Model の設定を保存するための設定クラスです。指定された引数に基づいて Sam2 モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、facebook/sam2.1-hiera-tiny と同様の設定が得られます。
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
Sam2VisionConfig
class transformers.Sam2VisionConfig
< source >( 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 = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonebackbone_channel_list: list[int] | None = Nonebackbone_feature_sizes: list | None = Nonefpn_hidden_size: int = 256fpn_kernel_size: int = 1fpn_stride: int = 1fpn_padding: int = 0fpn_top_down_levels: list[int] | None = Nonenum_feature_levels: int = 3hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06initializer_range: float = 0.02 )
パラメータ
- backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig], 任意) — バックボーンモデルの設定です。 - backbone_channel_list (
List[int]、任意、デフォルトは[768, 384, 192, 96]) — backbone のチャネル次元のリストです。 - backbone_feature_sizes (
List[List[int]]、任意、デフォルトは[[256, 256], [128, 128], [64, 64]]) — backbone からの特徴マップの空間サイズです。 - fpn_hidden_size (
int, 任意、デフォルトは 256) — FPN の隠れ層の次元数です。 - fpn_kernel_size (
int、省略可、デフォルト値は 1) — Neck 内の畳み込みのカーネルサイズです。 - fpn_stride (
int、省略可能、デフォルト値は 1) — Neck 内の畳み込みのストライドです。 - fpn_padding (
int、任意、デフォルト値は 0) — Neck 内の畳み込みの padding です。 - fpn_top_down_levels (
List[int]、任意、デフォルトは[2, 3]) — トップダウン FPN 接続のレベルです。 - num_feature_levels (
int、省略可、デフォルトは 3) — 使用する FPN の特徴量レベルの数です。 - hidden_act (
str、任意、デフォルトはgelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、"relu"、"silu"など。 - layer_norm_eps (
float、任意、デフォルトは1e-06) — レイヤーノーマル層で使用する epsilon です。 - initializer_range (
float、任意、デフォルトは0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
This is the configuration class to store the configuration of a Sam2Model. It is used to instantiate a Sam2 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/sam2.1-hiera-tiny
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
Sam2MaskDecoderConfig
クラス transformers.Sam2MaskDecoderConfig
< source >( 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 = 'gelu'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 = 256dynamic_multimask_via_stability: bool = Truedynamic_multimask_stability_delta: float = 0.05dynamic_multimask_stability_thresh: float = 0.98 )
パラメータ
- hidden_size (
int、任意、デフォルトは256) — 隠れ表現の次元数。 - hidden_act (
str、任意、デフォルトはgelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、"relu"、"silu"など。 - mlp_dim (
int、任意、デフォルトは 2048) — 2 方向 Transformer における MLP の次元数です。 - num_hidden_layers (
int、任意、デフォルトは2) — Transformerデコーダーの隠れ層の数。 - num_attention_heads (
int、任意、デフォルトは8) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。 - attention_downsample_rate (
int、任意、デフォルトは 2) — アテンション層のダウンサンプル率です。 - num_multimask_outputs (
int、任意、デフォルトは 3) — マルチマスク出力の数です。 - iou_head_depth (
int、任意、デフォルト値は 3) — IoU ヘッドの深さです。 - iou_head_hidden_dim (
int、任意、デフォルトは 256) — IoU ヘッドの隠れ層の次元数です。 - dynamic_multimask_via_stability (
bool、省略可、デフォルトはTrue) — stability を用いた動的マルチマスクを使用するかどうかを指定します。 - dynamic_multimask_stability_delta (
float、任意、デフォルト値は 0.05) — 動的マルチマスクの安定性デルタです。 - dynamic_multimask_stability_thresh (
float、任意、デフォルト値は 0.98) — 動的マルチマスクの安定性しきい値です。
これは Sam2Model の設定を保存するための設定クラスです。指定された引数に基づいて Sam2 モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、facebook/sam2.1-hiera-tiny と同様の設定が得られます。
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
Sam2PromptEncoderConfig
クラス transformers.Sam2PromptEncoderConfig
< source >( 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-06scale: int = 1 )
パラメータ
- 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 です。 - scale (
float、任意、デフォルトは 1) — プロンプトエンコーダーのスケール係数です。
This is the configuration class to store the configuration of a Sam2Model. It is used to instantiate a Sam2 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/sam2.1-hiera-tiny
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
Sam2Processor
class transformers.Sam2Processor
< source >( image_processortarget_size: int | None = Nonepoint_pad_value: int = -10**kwargs )
パラメータ
- image_processor (
Sam2ImageProcessor) — 画像プロセッサは必須の入力です。 - target_size (
int, 任意) — 入力ポイントとバウンディングボックスを正規化するためのターゲットサイズ(ピクセル単位)です。指定されない場合、デフォルトでは画像プロセッサのサイズ設定が使用されます。すべての入力座標(ポイントとボックス)は、モデルに渡される前にこのサイズに正規化されます。これにより、元の画像の寸法に関係なく、座標の表現が常に一貫したものになります。 - point_pad_value (
int、任意、デフォルトは -10) — 長さの異なるシーケンスをバッチ処理する際に、入力ポイントのパディングに使用される値です。この値はパディングされた位置をマークするために使用され、座標正規化の間も保持されます。
Sam2Processor を構築し、画像プロセッサーを単一のプロセッサーにラップします。
Sam2Processor は Sam2ImageProcessor のすべての機能を提供します。詳細については、~Sam2ImageProcessor を参照してください。
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonesegmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Noneinput_points: typing.Union[list[list[list[list[float]]]], torch.Tensor, NoneType] = Noneinput_labels: typing.Union[list[list[list[int]]], torch.Tensor, NoneType] = Noneinput_boxes: typing.Union[list[list[list[float]]], torch.Tensor, NoneType] = Noneoriginal_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = None**kwargs ) → A BatchEncoding with the following fields
パラメータ
- 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、任意) — 処理対象のセグメンテーションマップです。 - input_points (
list[list[list[list[float]]]]、torch.Tensor、省略可) — フレームに追加する点です。 - input_labels (
list[list[list[int]]]、torch.Tensor、省略可) — ポイントのラベルです。 - input_boxes (
list[list[list[float]]]、torch.Tensor、省略可) — フレームに追加するバウンディングボックスです。 - original_sizes (
list[list[float]]、torch.Tensor、省略可) — 画像の元のサイズです。 - return_tensors (
Union[str, ~utils.generic.TensorType], 省略可能) — 設定すると、特定のフレームワークのテンソルを返します。受け入れられる値は以下の通りです:'pt': PyTorchのtorch.Tensorオブジェクトを返します。'np': NumPyのnp.ndarrayオブジェクトを返します。
戻り値
以下のフィールドを持つBatchEncoding
pixel_values(torch.Tensor): 処理された画像。original_sizes(list[list[float]]): 画像の元のサイズ。labels(torch.Tensor): 処理済みのセグメンテーションマップ(指定されている場合)。input_points(torch.Tensor): 処理済みのポイント。input_labels(torch.Tensor): 処理済みのラベル。input_boxes(torch.Tensor): 処理済みのバウンディングボックス。
post_process_masks
< source >( masksoriginal_sizesmask_threshold = 0.0binarize = Truemax_hole_area = 0.0max_sprinkle_area = 0.0apply_non_overlapping_constraints = False**kwargs ) → (torch.Tensor)
パラメータ
- masks (
Union[List[torch.Tensor], List[np.ndarray]]) — mask_decoder からのバッチ化されたマスク。形式は (batch_size, num_channels, height, width) です。 - original_sizes (
Union[torch.Tensor, List[Tuple[int,int]]]) — モデルが期待する入力形状にリサイズされる前の、各画像の元のサイズです。形式は (高さ, 幅) です。 - mask_threshold (
float、任意、デフォルト値は 0.0) — 二値化および後処理操作の閾値。 - binarize (
bool、省略可能、デフォルトはTrue) — マスクをバイナリ化するかどうかを指定します。 - max_hole_area (
float、任意、デフォルト値は 0.0)— 埋める穴の最大面積です。 - max_sprinkle_area (
float、任意、デフォルト値は 0.0) — 塗りつぶす sprinkle の最大面積です。 - apply_non_overlapping_constraints (
bool、省略可能、デフォルトはFalse) — マスクに非重複制約を適用するかどうか。
戻り値
(torch.Tensor)
batch_size, num_channels, height, width形式のバッチ化されたマスク。ここで、(height, width)はoriginal_sizeによって指定されます。
パディングを除去し、マスクを元の画像サイズにアップスケールします。
Sam2ImageProcessor
class transformers.Sam2ImageProcessor
< source >( **kwargs: *<class 'transformers.models.sam2.image_processing_sam2.Sam2ImageProcessorKwargs'> )
パラメータ
- 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、デフォルトは{'height' -- 1024, 'width': 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、デフォルトはNone) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせて行われるか、画像ごとに固定の正方形サイズに合わせて行われます。具体的なパディング戦略はモデルによって異なります。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults toNone) — The size in{"height": int, "width" int}to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_sizeis not provided, images will be padded to the largest height and width in the batch. Applied only whendo_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]、省略可) — セグメンテーションマップをリサイズするサイズ{"height": int, "width": int}。
Sam2ImageProcessor 画像プロセッサを構築します。
preprocess
< source >( 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.sam2.image_processing_sam2.Sam2ImageProcessorKwargs'> ) → ~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]、任意) — セグメンテーションマップをリサイズするサイズ{"height": int, "width": int}。
戻り値
~image_processing_base.BatchFeature
- data (
dict) — call メソッド(‘pixel_values’ など)によって返される、リスト/配列/テンソルの辞書。 - tensor_type (
Union[None, str, TensorType]、省略可) — 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。
Sam2HieraDetModel
forward
< source >( pixel_values: typing.Optional[torch.FloatTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )
Sam2VisionModel
class transformers.Sam2VisionModel
< source >( config: Sam2VisionConfig )
パラメータ
- config (Sam2VisionConfig) — モデルのパラメータをすべて含むモデル設定クラス。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
ヘッドや投影が上に乗せられていないSamのビジョンモデル。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( pixel_values: typing.Optional[torch.FloatTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )
Sam2Model
class transformers.Sam2Model
< source >( config: Sam2Config )
パラメータ
- config (Sam2Config) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
入力画像と、入力ポイントおよびラベル、ボックス、またはマスクを指定してセグメンテーションマスクを生成するためのSegment Anything Model 2 (SAM 2)。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( 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'> ) → Sam2ImageSegmentationOutput or tuple(torch.FloatTensor)
パラメータ
- pixel_values (
torch.FloatTensor、形状(batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は Sam2ImageProcessor を使用して取得できます。詳細については Sam2ImageProcessor.call() を参照してください(Sam2Processor は画像の処理に Sam2ImageProcessor を使用します)。 - 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で導入されたパーソナライゼーションに使用される場合、ターゲット意味プロンプティングのためにマスクデコーダーに提供されます。
戻り値
Sam2ImageSegmentationOutput または tuple(torch.FloatTensor)
Sam2ImageSegmentationOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(Sam2Config)や入力に応じて、さまざまな要素で構成されます。
Sam2Modelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
- iou_scores (
torch.FloatTensor、shape(batch_size, point_batch_size, num_masks)) — 予測されたマスクの Intersection over Union (IoU) スコア。 - pred_masks (
torch.FloatTensor、shape(batch_size, point_batch_size, num_masks, height, width)) — 予測された低解像度マスクです。これはlow_res_masksの別名です。これらのマスクは、プロセッサによって後処理を行うことで、元の画像サイズに拡大する必要があります。 - object_score_logits (
torch.FloatTensor、shape(batch_size, point_batch_size, 1)) — オブジェクトが存在するかどうかを示す、オブジェクトスコアの logits。 - image_embeddings (
tuple(torch.FloatTensor)) — FPN からの特徴量であり、マスクデコーダーで使用されます。これはtorch.FloatTensorのタプルで、各テンソルの形状は(batch_size, channels, height, width)です。 - vision_hidden_states (
tuple(torch.FloatTensor)、optional、output_hidden_states=Trueの場合のみ返却) — 各ステージの出力に対応するtorch.FloatTensorのタプルで、形状は(batch_size, height, width, hidden_size)です。 各ステージの出力におけるビジョンモデルの隠れ状態です。 - vision_attentions (
tuple(torch.FloatTensor)、optional、output_attentions=Trueの場合のみ返却) —torch.FloatTensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。 ビジョンモデルのアテンション重み。 - mask_decoder_attentions (
tuple(torch.FloatTensor)、optional、output_attentions=Trueの場合のみ返却) —torch.FloatTensorのタプル(各レイヤーごとに1つ)。形状は(batch_size, num_heads, sequence_length, sequence_length)です。 マスクデコーダーの注意重みです。
例:
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoModel, AutoProcessor
>>> model = AutoModel.from_pretrained("danelcsb/sam2.1_hiera_tiny")
>>> processor = AutoProcessor.from_pretrained("danelcsb/sam2.1_hiera_tiny")
>>> 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"]
... )get_image_features
< source >( pixel_values: FloatTensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sam2VisionEncoderOutput or tuple(torch.FloatTensor)
パラメータ
戻り値
Sam2VisionEncoderOutput または tuple(torch.FloatTensor)
Sam2VisionEncoderOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(Sam2Config)や入力に応じて、さまざまな要素で構成されます。
last_hidden_state (
torch.FloatTensor、shape(batch_size, height, width, hidden_size)) — モデルの最終層の出力における隠れ状態のシーケンス。pooler_output (
torch.FloatTensor、shape(batch_size, hidden_size)) — 補助事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン(分類トークン)の最終層の隠れ状態。例えば、BERT 系のモデルでは、線形層と tanh 活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次文予測(分類)目的から学習されます。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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
fpn_hidden_states (
tuple(torch.FloatTensor)) — 各特徴レベル(高解像度から低解像度へ)に対応するtorch.FloatTensorのタプルで、形状は(batch_size, hidden_size, height, width)です。Feature Pyramid Network のネック部からの特徴マップです。fpn_position_encoding (
tuple(torch.FloatTensor)) —torch.FloatTensorのタプル(解像度が高い順に各フィーチャーレベル分)。形状は(batch_size, hidden_size, height, width)。fpn_hidden_statesに対応する位置エンコーディングです。