Transformers documentation
SAM3 Tracker Video
このモデルは2025年11月19日にHugging Face Transformersに貢献されました。
SAM3 Tracker Video
概要
SAM3 (Segment Anything Model 3) は、SAM 3: Segment Anything with Concepts で紹介されました。
Sam3TrackerVideo は動画に対して Promptable Visual Segmentation (PVS) を実行します。PVS は、インタラクティブな視覚プロンプト(点、ボックス、マスク)またはテキスト入力を受け取り、プロンプトごとに 特定のオブジェクトインスタンス を動画フレーム間でトラッキングします。
Sam3TrackerVideo は、SAM2 Video の更新版であり、同じ API を維持しながら、パフォーマンスと機能の向上を提供します。
論文の抄録は以下の通りです。
本稿では、Segment Anything Model (SAM) 3 を紹介します。SAM 3 は、概念プロンプトに基づいて画像および動画内のオブジェクトを検出・セグメンテーション・トラッキングを行う統合モデルです。ここでいう概念プロンプトとは、短い名詞句(例:「yellow school bus」)、画像のサンプル、またはそれらの組み合わせを指します。Promptable Concept Segmentation (PCS) は、こうしたプロンプトを受け取り、一致するすべてのオブジェクトインスタンスに対してセグメンテーションマスクと一意のIDを返します。PCS の発展を目的として、画像と動画にわたって困難なネガティブ例を含む 400 万のユニークな概念ラベルからなる高品質なデータセットを生成するスケーラブルなデータエンジンを構築しました。本モデルは、単一のバックボーンを共有する画像レベルの検出器と、メモリベースの動画トラッカーで構成されています。存在ヘッドによって認識と位置特定を分離することで、検出精度を向上させています。SAM 3 は、画像および動画の PCS において既存システムの精度を 2 倍に向上させ、視覚的セグメンテーションタスクにおける従来の SAM の機能も改善しています。SAM 3 と、プロンプタブル概念セグメンテーションのための新ベンチマーク Segment Anything with Concepts (SA-Co) をオープンソースとして公開します。
このモデルは、yonigozlan 氏と ronghanghu 氏によって提供されました。
使用例
Video Segmentation and Tracking
基本的なビデオトラッキング
from transformers import Sam3TrackerVideoModel, Sam3TrackerVideoProcessor
import torch
model = Sam3TrackerVideoModel.from_pretrained("facebook/sam3", device_map="auto")
processor = Sam3TrackerVideoProcessor.from_pretrained("facebook/sam3")
# Load video frames (example assumes you have a list of PIL Images)
# video_frames = [Image.open(f"frame_{i:05d}.jpg") for i in range(num_frames)]
# For this example, we'll use the video loading utility
from transformers.video_utils import load_video
video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4"
video_frames, _ = load_video(video_url)
# Initialize video inference session
inference_session = processor.init_video_session(
video=video_frames,
inference_device=device,
)
# Add click on first frame to select object
ann_frame_idx = 0
ann_obj_id = 1
points = [[[[210, 350]]]]
labels = [[[1]]]
processor.add_inputs_to_inference_session(
inference_session=inference_session,
frame_idx=ann_frame_idx,
obj_ids=ann_obj_id,
input_points=points,
input_labels=labels,
)
# Segment the object on the first frame (optional, you can also propagate the masks through the video directly)
outputs = model(
inference_session=inference_session,
frame_idx=ann_frame_idx,
)
video_res_masks = processor.post_process_masks(
[outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
print(f"Segmentation shape: {video_res_masks.shape}")
Segmentation shape: torch.Size([1, 1, 480, 854])
# Propagate through the entire video
video_segments = {}
for sam3_tracker_video_output in model.propagate_in_video_iterator(inference_session):
video_res_masks = processor.post_process_masks(
[sam3_tracker_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
video_segments[sam3_tracker_video_output.frame_idx] = video_res_masks
print(f"Tracked object through {len(video_segments)} frames")
Tracked object through 180 framesマルチオブジェクト・ビデオトラッキング
動画フレーム間で複数のオブジェクトを同時にトラッキングします:
# Reset for new tracking session
inference_session.reset_inference_session()
# Add multiple objects on the first frame
ann_frame_idx = 0
obj_ids = [2, 3]
input_points = [[[[200, 300]], [[400, 150]]]] # Points for two objects (batched)
input_labels = [[[1], [1]]]
processor.add_inputs_to_inference_session(
inference_session=inference_session,
frame_idx=ann_frame_idx,
obj_ids=obj_ids,
input_points=input_points,
input_labels=input_labels,
)
# Get masks for both objects on first frame (optional, you can also propagate the masks through the video directly)
outputs = model(
inference_session=inference_session,
frame_idx=ann_frame_idx,
)
# Propagate both objects through video
video_segments = {}
for sam3_tracker_video_output in model.propagate_in_video_iterator(inference_session):
video_res_masks = processor.post_process_masks(
[sam3_tracker_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
video_segments[sam3_tracker_video_output.frame_idx] = {
obj_id: video_res_masks[i]
for i, obj_id in enumerate(inference_session.obj_ids)
}
print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
Tracked 2 objects through 180 frames動画セグメンテーションの洗練
任意のフレームに追加のクリックを追加して、トラッキングを微調整できます:
# Add refinement click on a later frame
refine_frame_idx = 50
ann_obj_id = 2 # Refining first object
points = [[[[220, 280]]]] # Additional point
labels = [[[1]]] # Positive click
processor.add_inputs_to_inference_session(
inference_session=inference_session,
frame_idx=refine_frame_idx,
obj_ids=ann_obj_id,
input_points=points,
input_labels=labels,
)
# Re-propagate with the additional information
video_segments = {}
for sam3_tracker_video_output in model.propagate_in_video_iterator(inference_session):
video_res_masks = processor.post_process_masks(
[sam3_tracker_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
video_segments[sam3_tracker_video_output.frame_idx] = video_res_masksストリーミング動画推論
リアルタイムアプリケーション向けに、Sam3TrackerVideoは、フレームが到着するたびに処理を行うことをサポートしています:
# Initialize session for streaming
inference_session = processor.init_video_session(
inference_device=device,
)
# Process frames one by one
for frame_idx, frame in enumerate(video_frames[:10]): # Process first 10 frames
inputs = processor(images=frame, device=device, return_tensors="pt").to(model.device)
...
if frame_idx == 0:
# Add point input on first frame
processor.add_inputs_to_inference_session(
inference_session=inference_session,
frame_idx=0,
obj_ids=1,
input_points=[[[[210, 350], [250, 220]]]],
input_labels=[[[1, 1]]],
original_size=inputs.original_sizes[0], # need to be provided when using streaming video inference
)
...
# Process current frame
sam3_tracker_video_output = model(inference_session=inference_session, frame=inputs.pixel_values[0])
...
video_res_masks = processor.post_process_masks(
[sam3_tracker_video_output.pred_masks], original_sizes=inputs.original_sizes, binarize=False
)[0]
print(f"Frame {frame_idx}: mask shape {video_res_masks.shape}")複数のオブジェクト向けのビデオバッチ処理
をすべて一度に追加して、動画内の複数のオブジェクトを同時にトラッキングします:
# Initialize video session
inference_session = processor.init_video_session(
video=video_frames,
inference_device=device,
)
# Add multiple objects on the first frame using batch processing
ann_frame_idx = 0
obj_ids = [2, 3] # Track two different objects
input_points = [
[[[200, 300], [230, 250], [275, 175]], [[400, 150]]]
] # Object 2: 3 points (2 positive, 1 negative); Object 3: 1 point
input_labels = [
[[1, 1, 0], [1]]
] # Object 2: positive, positive, negative; Object 3: positive
processor.add_inputs_to_inference_session(
inference_session=inference_session,
frame_idx=ann_frame_idx,
obj_ids=obj_ids,
input_points=input_points,
input_labels=input_labels,
)
# Get masks for all objects on the first frame
outputs = model(
inference_session=inference_session,
frame_idx=ann_frame_idx,
)
video_res_masks = processor.post_process_masks(
[outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
print(f"Generated masks for {video_res_masks.shape[0]} objects")
Generated masks for 2 objects
# Propagate all objects through the video
video_segments = {}
for sam3_tracker_video_output in model.propagate_in_video_iterator(inference_session):
video_res_masks = processor.post_process_masks(
[sam3_tracker_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
video_segments[sam3_tracker_video_output.frame_idx] = {
obj_id: video_res_masks[i]
for i, obj_id in enumerate(inference_session.obj_ids)
}
print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
Tracked 2 objects through 180 framesSam3TrackerVideoConfig
クラス transformers.Sam3TrackerVideoConfig
< 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.02num_maskmem: int = 7sigmoid_scale_for_mem_enc: float = 20.0sigmoid_bias_for_mem_enc: float = -10.0enable_occlusion_spatial_embedding: bool = Truemultimask_output_in_sam: bool = Truemultimask_min_pt_num: int = 0multimask_max_pt_num: int = 1multimask_output_for_tracking: bool = Truemax_object_pointers_in_encoder: int = 16max_cond_frame_num: int = 4enable_temporal_pos_encoding_for_object_pointers: bool = Truememory_attention_hidden_size: int = 256memory_attention_num_layers: int = 4memory_attention_num_attention_heads: int = 1memory_attention_downsample_rate: int = 1memory_attention_feed_forward_hidden_size: int = 2048memory_attention_feed_forward_hidden_act: str = 'relu'memory_attention_dropout: float | int = 0.1memory_attention_rope_feat_sizes: list | None = Nonememory_attention_rope_dropout: float | int = 0.1memory_encoder_hidden_size: int = 256memory_encoder_output_channels: int = 64rope_parameters: dict | None = Nonemask_downsampler_embed_dim: int = 256mask_downsampler_kernel_size: int = 3mask_downsampler_stride: int = 2mask_downsampler_padding: int = 1mask_downsampler_total_stride: int = 16mask_downsampler_hidden_act: str = 'gelu'memory_fuser_num_layers: int = 2memory_fuser_embed_dim: int = 256memory_fuser_intermediate_dim: int = 1024memory_fuser_kernel_size: int = 7memory_fuser_padding: int = 3memory_fuser_layer_scale_init_value: float = 1e-06memory_fuser_hidden_act: str = 'gelu' )
パラメータ
- vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig]、任意) — ビジョンバックボーンの config オブジェクトまたは辞書です。 - prompt_encoder_config (Union[
dict,Sam3TrackerVideoPromptEncoderConfig], 省略可) — Sam3TrackerVideoPromptEncoderConfig を初期化するために使用される設定オプションの辞書。 - mask_decoder_config (Union[
dict,Sam3TrackerVideoMaskDecoderConfig], 省略可) — Sam3TrackerVideoMaskDecoderConfig を初期化するために使用される設定オプションの辞書。 - initializer_range (
float、任意、デフォルト値は 0.02) — パラメータ初期化の標準偏差。 - num_maskmem (
int、任意、デフォルト値は 7)— マスクメモリ用のメモリスロットの数。 - sigmoid_scale_for_mem_enc (
float、任意、デフォルト値は 20.0) — メモリエンコーダーにおけるシグモイド関数のスケール係数です。 - sigmoid_bias_for_mem_enc (
float、任意、デフォルト値は -10.0) — メモリエンコーダーにおけるシグモイド関数のバイアスです。 - enable_occlusion_spatial_embedding (
bool、任意、デフォルトはTrue) — オクルージョンに対して空間埋め込みを有効にするかどうか。 - multimask_output_in_sam (
bool、任意、デフォルトはTrue) — SAM ヘッドから複数のマスクを出力するかどうかを指定します。 - multimask_min_pt_num (
int、任意、デフォルト値は 0)— マルチマスク出力をトリガーするための最小ポイント数です。 - multimask_max_pt_num (
int、任意、デフォルト値は 1)— マルチマスク出力をトリガーする最大ポイント数です。 - multimask_output_for_tracking (
bool、任意、デフォルトはTrue) — トラッキングにマルチマスク出力を使用するかどうか。 - max_object_pointers_in_encoder (
int、任意、デフォルト値は 16)— エンコーダー内のオブジェクトポインタの最大数。 - max_cond_frame_num (
int、任意、デフォルトは 4)— メモリアテンションで使用される条件付けフレームの最大数。 - enable_temporal_pos_encoding_for_object_pointers (
bool、任意、デフォルトはTrue) — オブジェクトポインタに対して時間的位置エンコーディングを有効にするかどうか。 - memory_attention_hidden_size (
int、任意、デフォルトは 256) — メモリアテンションの隠れ状態の次元数です。 - memory_attention_num_layers (
int、任意、デフォルトは 4) — メモリアテンションモジュールの層数です。 - memory_attention_num_attention_heads (
int、任意、デフォルトは 1) — メモリアテンションにおける各アテンションレイヤーのアテンションヘッド数。 - memory_attention_downsample_rate (
int、任意、デフォルトは 1) — アテンション層のダウンサンプル率です。 - memory_attention_feed_forward_hidden_size (
int、任意、デフォルト値は 2048) — メモリアテンションモジュールにおけるフィードフォワードネットワークの次元数です。 - memory_attention_feed_forward_hidden_act (
str、任意、デフォルトは"relu") — メモリアテンションモジュール内のフィードフォワードネットワークで使用する非線形活性化関数です。 - memory_attention_dropout (
float、任意、デフォルトは 0.1) — メモリアテンションモジュールのドロップアウト率です。 - memory_attention_rope_feat_sizes (
list[int]、任意、デフォルトは[72, 72]) — Rope 位置エンコーディングのフィーチャーサイズです。 - memory_attention_rope_dropout (
float、任意、デフォルト値は 0.1) — Rope 位置エンコーディングの dropout 率です。 - memory_encoder_hidden_size (
int、任意、デフォルトは 256) — メモリエンコーダーの隠れ状態の次元数。 - memory_encoder_output_channels (
int, 任意、デフォルトは 64) — メモリエンコーダーの出力チャネル数です。 - rope_parameters (
dict, 任意) — RoPE 埋め込みの設定パラメータを含む辞書です。辞書にはrope_thetaの値が含まれており、より長いmax_position_embeddingsで RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。 - mask_downsampler_embed_dim (
int、任意、デフォルトは 256) — マスクダウンスAMPLERの埋め込みの次元数。 - mask_downsampler_kernel_size (
int、任意、デフォルトは 3) — マスクダウンスAMPLERのカーネルサイズです。 - mask_downsampler_stride (
int、任意、デフォルトは 2) — マスクダウンサンプラーのストライドです。 - mask_downsampler_padding (
int、任意、デフォルト値は 1) — マスクダウンサンプラーのパディングです。 - mask_downsampler_total_stride (
int、任意、デフォルト値は 16)— マスクダウンスAMPLERの総ストライドです。 - mask_downsampler_hidden_act (
str、任意、デフォルトは"gelu") — マスクダウンスAMPLERにおける非線形活性化関数です。 - memory_fuser_num_layers (
int、任意、デフォルトは 2)— memory fuser のレイヤー数です。 - memory_fuser_embed_dim (
int、任意、デフォルト値は 256) — memory fuser の埋め込み層の次元数です。 - memory_fuser_intermediate_dim (
int、任意、デフォルトは 1024) — memory fuser の中間層の次元数です。 - memory_fuser_kernel_size (
int、任意、デフォルトは 7) — memory fuser のカーネルサイズです。 - memory_fuser_padding (
int、任意、デフォルトは 3) — memory fuser のパディングです。 - memory_fuser_layer_scale_init_value (
float、任意、デフォルトは 1e-06) — memory fuser のレイヤースケールの初期値です。 - memory_fuser_hidden_act (
str、任意、デフォルトは"gelu") — メモリフューザーで使用する非線形活性化関数です。
これは Sam3TrackerVideoModel の設定を保存するための設定クラスです。指定された引数に基づいて Sam3 Tracker Video モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、facebook/sam3 と同様の設定が得られます。
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
例:
>>> from transformers import (
... Sam3VisionConfig,
... Sam3TrackerVideoPromptEncoderConfig,
... Sam3TrackerVideoMaskDecoderConfig,
... Sam3TrackerVideoModel,
... )
>>> # Initializing a Sam3TrackerVideoConfig with `"facebook/sam3"` style configuration
>>> configuration = Sam3TrackerVideoConfig()
>>> # Initializing a Sam3TrackerVideoModel (with random weights) from the `"facebook/sam3"` style configuration
>>> model = Sam3TrackerVideoModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
>>> # We can also initialize a Sam3TrackerVideoConfig from a Sam3TrackerVideoVisionConfig, Sam3TrackerVideoPromptEncoderConfig, and Sam3TrackerVideoMaskDecoderConfig
>>> # Initializing SAM3 tracker video vision encoder, memory attention, and memory encoder configurations
>>> vision_config = Sam3TrackerVideoVisionConfig()
>>> prompt_encoder_config = Sam3TrackerVideoPromptEncoderConfig()
>>> mask_decoder_config = Sam3TrackerVideoMaskDecoderConfig()
>>> config = Sam3TrackerVideoConfig(vision_config, prompt_encoder_config, mask_decoder_config)Sam3TrackerVideoMaskDecoderConfig
クラス transformers.Sam3TrackerVideoMaskDecoderConfig
< 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) — 動的マルチマスクの安定性しきい値です。
これは Sam3TrackerVideoModel の設定を保存するための設定クラスです。指定された引数に基づいて Sam3 Tracker Video モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、facebook/sam3 と同様の設定が得られます。
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
Sam3TrackerVideoPromptEncoderConfig
class transformers.Sam3TrackerVideoPromptEncoderConfig
< 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] = 1008patch_size: int | list[int] | tuple[int, int] = 14mask_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]]、任意、デフォルトは1008) — 各画像のサイズ(解像度)。 - patch_size (
Union[int, list[int], tuple[int, int]]、任意、デフォルトは14) — 各パッチのサイズ(解像度)です。 - 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) — プロンプトエンコーダーのスケール係数です。
これは Sam3TrackerVideoModel の設定を保存するための設定クラスです。指定された引数に基づいて Sam3 Tracker Video モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、facebook/sam3 と同様の設定が得られます。
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
Sam3TrackerVideoProcessor
class transformers.Sam3TrackerVideoProcessor
< source >( image_processorvideo_processortarget_size: int | None = Nonepoint_pad_value: int = -10**kwargs )
パラメータ
- image_processor (
Sam3ImageProcessor) — 画像プロセッサは必須の入力です。 - video_processor (
video_processor_class) — ビデオプロセッサは必須の入力です。 - target_size (
int, 任意) — 入力ポイントとバウンディングボックスを正規化するためのターゲットサイズ(ピクセル単位)です。指定されない場合、デフォルトでは画像プロセッサのサイズ設定が使用されます。すべての入力座標(ポイントとボックス)は、モデルに渡される前にこのサイズに正規化されます。これにより、元の画像の寸法に関係なく、座標の表現が常に一貫したものになります。 - point_pad_value (
int、任意、デフォルトは -10) — 長さの異なるシーケンスをバッチ処理する際に、入力ポイントのパディングに使用される値です。この値はパディングされた位置をマークするために使用され、座標正規化の間も保持されます。
画像プロセッサと動画プロセッサを単一のプロセッサにラップするSam3TrackerVideoProcessorを構築します。
Sam3TrackerVideoProcessor は、Sam3ImageProcessor と video_processor_class のすべての機能を提供します。詳細については、~Sam3ImageProcessor および ~video_processor_class を参照してください。
__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によって指定されます。
パディングを除去し、マスクを元の画像サイズにアップスケールします。
init_video_session
< source >( video: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneinference_device: typing.Union[str, ForwardRef('torch.device')] = 'cpu'inference_state_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Noneprocessing_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Nonevideo_storage_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Nonemax_vision_features_cache_size: int = 1dtype: dtype = torch.float32 )
パラメータ
- video (
VideoInput、任意) — 処理対象の動画です。ストリーミングの場合は指定する必要はありません。 - inference_device (
strまたはtorch.device、任意、デフォルトは “cpu”) — 推論に使用するデバイス。 - inference_state_device (
strまたはtorch.device、省略可) — 推論状態を保存するデバイス。 - processing_device (
strまたはtorch.device、省略可) — 動画処理に使用するデバイス。 - video_storage_device (
strまたはtorch.device、省略可) — 処理済みの動画フレームを保存するデバイス。 - max_vision_features_cache_size (
int、任意、デフォルト値は 1)— キャッシュするビジョン特徴の最大数です。 - dtype (
torch.dtype、任意、デフォルトはtorch.float32) — セッション全体で使用する torch の dtype。
推論用のビデオセッションを初期化します。
ビデオが提供されている場合(非同期推論)、そのビデオは処理され、video_storage_deviceに保存されます。
add_inputs_to_inference_session
< source >( inference_session: Sam3TrackerVideoInferenceSessionframe_idx: intobj_ids: list[int] | intinput_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] = Noneinput_masks: typing.Union[numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneoriginal_size: tuple[int, int] | None = Noneclear_old_inputs: bool = True )
パラメータ
- inference_session (
Sam3TrackerVideoInferenceSession) — 動画用の推論セッションです。 - frame_idx (
int) — 処理するフレームのインデックスです。 - obj_ids (
list[int]またはint) — 点またはボックスに関連付けるオブジェクト ID です。 任意の整数を指定でき、後でオブジェクトを特定するために再利用できます。 - 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、省略可) — フレームに追加するバウンディングボックスです。 - input_masks (
np.ndarray、torch.Tensor、list[np.ndarray]、またはlist[torch.Tensor]、任意) — フレームに追加するマスクです。 - original_size (
tuple[int, int]、省略可) — 動画の元のサイズです。ストリーミングを行う場合は指定してください。 - clear_old_inputs (
bool、省略可能、デフォルトはTrue) — オブジェクトの古い入力をクリアするかどうかを指定します。
動画フレームの新しい点、ボックス、またはマスクを処理し、推論セッションに追加します。
Sam3TrackerVideoInferenceSession
class transformers.Sam3TrackerVideoInferenceSession
< source >( video: typing.Optional[torch.FloatTensor] = Nonevideo_height: int | None = Nonevideo_width: int | None = Noneinference_device: typing.Union[torch.device, str] = 'cpu'inference_state_device: typing.Union[torch.device, str] = 'cpu'video_storage_device: typing.Union[torch.device, str] = 'cpu'dtype: typing.Union[torch.dtype, str] = 'float32'max_vision_features_cache_size: int = 1 )
パラメータ
- video (
torch.FloatTensor、任意) — 処理対象の動画です。ストリーミング時には指定する必要はありません。 - video_height (
int、任意) — 動画の高さ。 - video_width (
int、任意) — 動画の幅です。 - inference_device (
torch.device、任意、デフォルトは"cpu") — 推論に使用するデバイス。 - inference_state_device (
torch.device、任意、デフォルトは"cpu") — 推論状態を保存するデバイスです。 - video_storage_device (
torch.device、任意、デフォルトは"cpu") — 動画を保存するデバイスです。 - dtype (
torch.dtype、任意、デフォルトは"float32") — 動画に使用する dtype です。 - max_vision_features_cache_size (
int、任意、デフォルト値は 1)— キャッシュするビジョン特徴の最大数です。
動画推論セッションのパラメータ、状態、およびキャッシュを管理します。
自動的なデバイス配置を備えたマスク入力を追加します。
自動的なデバイス配置で新しいフレームを追加します。
自動的なデバイス配置を備えたポイント入力を追加します。
動画からフレームを取得します。
このセッションでこれまでに受信した一意のオブジェクトIDの総数を取得します。
get_output
< source >( obj_idx: intframe_idx: intoutput_key: stris_conditioning_frame: bool = True )
スマートなデバイス管理で出力を取得します。
必要に応じて新しいエントリを作成し、オブジェクトIDをインデックスにマッピングします。
モデル側のオブジェクトインデックスをクライアント側のオブジェクトIDにマッピングします。
マスク入力を削除します。
ポイント入力を削除します。
トラッキングデータとキャッシュをリセットします。
トラッキングデータをリセットしますが、キャッシュは保持します。
store_output
< source >( obj_idx: intframe_idx: intoutput_key: str | None = Noneoutput_value: typing.Union[torch.Tensor, dict, NoneType] = Noneis_conditioning_frame: bool = True )
スマートなデバイス管理により出力を保存します。 がNoneの場合、出力は辞書として保存されます。
Sam3TrackerVideoModel
class transformers.Sam3TrackerVideoModel
< source >( config: Sam3TrackerVideoConfigremove_vision_encoder: bool = False )
パラメータ
- config (Sam3TrackerVideoConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
- remove_vision_encoder (
bool、省略可、デフォルトはFalse) — ビジョンエンコーダーを削除するかどうか。True の場合、ビジョンエンコーダーは None に設定されます。
特定のヘッドを付加せずに、生のhidden-statesを出力する、素のSam3 Tracker Video Model。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( inference_session: Sam3TrackerVideoInferenceSessionframe_idx: int | None = Noneframe: typing.Optional[torch.Tensor] = Nonereverse: bool = Falserun_mem_encoder: bool = True**kwargs ) → Sam3TrackerVideoSegmentationOutput or tuple(torch.FloatTensor)
パラメータ
- inference_session (
~models.sam3_tracker_video.modeling_sam3_tracker_video.Sam3TrackerVideoInferenceSession) — 動画推論セッションオブジェクトです。 - frame_idx (
int, 任意) — 推論を実行するフレームのインデックスです。新しいストリームフレームに対して推論を行う場合は、指定する必要はありません。 - frame (
torch.Tensor, 任意) — 処理するフレーム。ストリーミング処理を行う場合に指定します。 - reverse (
bool、省略可能、デフォルトはFalse) — 逆方向に伝播するかどうか。 - run_mem_encoder (
bool、省略可、デフォルトはTrue) — 予測されたマスクに対してメモリエンコーダーを実行するかどうか。メモリエンコーダーは効率化のため、すべてのオブジェクトに対してバッチ処理されます。
戻り値
Sam3TrackerVideoSegmentationOutput または tuple(torch.FloatTensor)
Sam3TrackerVideoSegmentationOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(Sam3TrackerVideoConfig)や入力に応じて、さまざまな要素で構成されます。
ストリーミングされた動画フレームを通じてオブジェクトを伝播させます。
- object_ids (
list[int]、任意) — 現在のフレームで追跡されているオブジェクトの ID のリスト。 - pred_masks (
torch.FloatTensor、shape(batch_size, num_masks, height, width)) — モデルの解像度で保存された予測マスクです。 - object_score_logits (
torch.FloatTensor、shape(batch_size,)、任意) — オブジェクトが存在するかどうかを示す、オブジェクトスコアの logits。 - frame_idx (
int, 任意) — 動画のフレームインデックス。
propagate_in_video_iterator
< source >( inference_session: Sam3TrackerVideoInferenceSessionstart_frame_idx: int | None = Nonemax_frame_num_to_track: int | None = Nonereverse: bool = Falseshow_progress_bar: bool = False ) → Sam3TrackerVideoSegmentationOutput or tuple(torch.FloatTensor)
パラメータ
- inference_session (
~models.sam3_tracker_video.modeling_sam3_tracker_video.Sam3TrackerVideoInferenceSession) — 動画推論セッションオブジェクトです。 - start_frame_idx (
int, 任意) — 伝播の開始フレームインデックスです。forwardが新しい入力に対してまだ呼び出されていない場合は、指定する必要があります。 指定しない場合、開始フレームインデックスは入力ポイントを持つ最も早いフレームになります。 - max_frame_num_to_track (
int, 省略可) — 追跡するフレームの最大数。 - reverse (
bool、省略可能、デフォルトはFalse) — 逆方向に伝播するかどうか。 - show_progress_bar (
bool、省略可能、デフォルトはFalse) — 伝播中にプログレスバーを表示するかどうか。
戻り値
Sam3TrackerVideoSegmentationOutput または tuple(torch.FloatTensor)
Sam3TrackerVideoSegmentationOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(Sam3TrackerVideoConfig)や入力に応じて、さまざまな要素で構成されます。
…を動画フレーム全体に伝播します。動画全体で推論セッションを初期化する際に使用します。 各フレームに対してSam3TrackerVideoSegmentationOutputを生成します。
- object_ids (
list[int]、任意) — 現在のフレームで追跡されているオブジェクトの ID のリスト。 - pred_masks (
torch.FloatTensor、shape(batch_size, num_masks, height, width)) — モデルの解像度で保存された予測マスクです。 - object_score_logits (
torch.FloatTensor、shape(batch_size,)、任意) — オブジェクトが存在するかどうかを示す、オブジェクトスコアの logits。 - frame_idx (
int, 任意) — 動画のフレームインデックス。
get_image_features
< source >( pixel_values: FloatTensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sam3TrackerVideoVisionEncoderOutput or tuple(torch.FloatTensor)
パラメータ
戻り値
Sam3TrackerVideoVisionEncoderOutput または tuple(torch.FloatTensor)
Sam3TrackerVideoVisionEncoderOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(Sam3TrackerVideoConfig)と入力に応じて、さまざまな要素で構成されます。
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に対応する位置エンコーディングです。