Transformers documentation

SAM3 Video

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

このモデルは2025年11月19日にHugging Face Transformersに貢献されました。

SAM3 Video

SDPA FlashAttention

概要

SAM3 (Segment Anything Model 3) は、SAM 3: Segment Anything with Concepts で紹介されました。

SAM3 Video は、動画に対してPromptable Concept Segmentation (PCS)を実行します。PCS はテキストを入力として受け取り(例: “yellow school bus”)、その概念に一致するすべてのオブジェクトについて、インスタンスマスクとセマンティックマスクを予測します。また、動画フレーム間でオブジェクトのアイデンティティを維持します。

このモデルは、検出モジュール(SAM3)とトラッキングモジュール(SAM2スタイルのトラッカー)を組み合わせることで、テキストプロンプトを用いた動画フレーム間の堅牢なオブジェクトトラッキングを可能にします。

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

本稿では、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 Sam3VideoModel, Sam3VideoProcessor
import torch

model = Sam3VideoModel.from_pretrained("facebook/sam3", device_map="auto")
processor = Sam3VideoProcessor.from_pretrained("facebook/sam3")

# Load video frames
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,
    processing_device="cpu",
    video_storage_device="cpu",
)

# Add text prompt to detect and track objects
text = "person"
inference_session = processor.add_text_prompt(
    inference_session=inference_session,
    text=text,
)

# Process all frames in the video
outputs_per_frame = {}
# Pass show_progress_bar=True to display a tqdm progress bar.
for model_outputs in model.propagate_in_video_iterator(
    inference_session=inference_session, max_frame_num_to_track=50
):
    processed_outputs = processor.postprocess_outputs(inference_session, model_outputs)
    outputs_per_frame[model_outputs.frame_idx] = processed_outputs

print(f"Processed {len(outputs_per_frame)} frames")
Processed 51 frames

# Access results for a specific frame
frame_0_outputs = outputs_per_frame[0]
print(f"Detected {len(frame_0_outputs['object_ids'])} objects")
print(f"Object IDs: {frame_0_outputs['object_ids'].tolist()}")
print(f"Scores: {frame_0_outputs['scores'].tolist()}")
print(f"Boxes shape (XYXY format, absolute coordinates): {frame_0_outputs['boxes'].shape}")
print(f"Masks shape: {frame_0_outputs['masks'].shape}")

複数のプロンプトを指定することで、複数のオブジェクトカテゴリを同時にトラッキングすることもできます。モデルは、すべてのプロンプト間でビジョン特徴を効率的に再利用します:

# Add multiple text prompts (or use a list in add_text_prompt)
multi_prompt_session = processor.init_video_session(
    video=video_frames,
    inference_device=device,
    processing_device="cpu",
    video_storage_device="cpu",
)
>>>
prompts = ["person", "bed", "lamp"]
processor.add_text_prompt(multi_prompt_session, prompts)
>>>
# Process video - detects objects from ALL prompts in a single pass
multi_outputs_per_frame = {}
# Pass show_progress_bar=True to display a tqdm progress bar.
for model_outputs in model.propagate_in_video_iterator(
    inference_session=multi_prompt_session, max_frame_num_to_track=50
):
    processed_outputs = processor.postprocess_outputs(multi_prompt_session, model_outputs)
    multi_outputs_per_frame[model_outputs.frame_idx] = processed_outputs
>>>
# Check which objects were detected by each prompt
frame_0_outputs = multi_outputs_per_frame[0]
prompt_to_obj_ids = frame_0_outputs["prompt_to_obj_ids"]
for prompt, obj_ids in prompt_to_obj_ids.items():
    print(f"{prompt}: {len(obj_ids)} objects")
person: 2 objects
bed: 1 objects
lamp: 1 objects

ストリーミング動画推論

⚠️ **ストリーミング推論の品質に関する注意**: ストリーミング推論では、一致しないオブジェクトや重複したオブジェクトを除去するホットスタートのヒューリスティックが無効になります。これらの処理には、適切な判断を行うために将来のフレームへのアクセスが必要だからです。そのため、事前読み込み済み動画の推論と比較して、誤検出や重複したオブジェクトトラッキングが増える可能性があります。すべてのフレームが利用可能な場合は、最適な結果を得るために事前読み込み済み動画の推論を使用してください。

リアルタイムアプリケーション向けに、SAM3 Videoは、動画フレームが到着するたびにそれらを処理することをサポートしています。

# Initialize session for streaming
streaming_inference_session = processor.init_video_session(
    inference_device=device,
    processing_device="cpu",
    video_storage_device="cpu",
)

# Add text prompt
text = "person"
streaming_inference_session = processor.add_text_prompt(
    inference_session=streaming_inference_session,
    text=text,
)

# Process frames one by one (streaming mode)
streaming_outputs_per_frame = {}
for frame_idx, frame in enumerate(video_frames[:50]):  # Process first 50 frames
    # First, process the frame using the processor
    inputs = processor(images=frame, device=device, return_tensors="pt").to(model.device)
...
    # Process frame using streaming inference - pass the processed pixel_values
    model_outputs = model(
        inference_session=streaming_inference_session,
        frame=inputs.pixel_values[0],  # Provide processed frame - this enables streaming mode
        reverse=False,
    )
...
    # Post-process outputs with original_sizes for proper resolution handling
    processed_outputs = processor.postprocess_outputs(
        streaming_inference_session,
        model_outputs,
        original_sizes=inputs.original_sizes,  # Required for streaming inference
    )
    streaming_outputs_per_frame[frame_idx] = processed_outputs
...
    if (frame_idx + 1) % 10 == 0:
        print(f"Processed {frame_idx + 1} frames...")

print(f"✓ Streaming inference complete! Processed {len(streaming_outputs_per_frame)} frames")
✓ Streaming inference complete! Processed 50 frames

# Access results
frame_0_outputs = streaming_outputs_per_frame[0]
print(f"Detected {len(frame_0_outputs['object_ids'])} objects in first frame")
print(f"Boxes are in XYXY format (absolute pixel coordinates): {frame_0_outputs['boxes'].shape}")
print(f"Masks are at original video resolution: {frame_0_outputs['masks'].shape}")

カスタム解像度推論

⚠️ **パフォーマンスに関する注意**: カスタム解像度を使用すると、精度が低下する可能性があります。このモデルは1008pxの解像度で使用することを前提としています。

より高速な推論や、メモリ使用量の削減のために:

config = Sam3VideoConfig.from_pretrained("facebook/sam3")
config.image_size = 560
model = Sam3VideoModel.from_pretrained("facebook/sam3", config=config, device_map="auto")
processor = Sam3VideoProcessor.from_pretrained("facebook/sam3", size={"height": 560, "width": 560})

Sam3VideoConfig

class transformers.Sam3VideoConfig

< >

( 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 = Nonedetector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetracker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinitializer_range: float = 0.02low_res_mask_size: int = 288score_threshold_detection: float = 0.5det_nms_thresh: float = 0.1assoc_iou_thresh: float = 0.1trk_assoc_iou_thresh: float = 0.5new_det_thresh: float = 0.7recondition_on_trk_masks: bool = Truehotstart_delay: int = 15hotstart_unmatch_thresh: int = 8hotstart_dup_thresh: int = 8suppress_unmatched_only_within_hotstart: bool = Trueinit_trk_keep_alive: int = 30max_trk_keep_alive: int = 30min_trk_keep_alive: int = -1suppress_overlapping_based_on_recent_occlusion_threshold: float = 0.7decrease_trk_keep_alive_for_empty_masklets: bool = Falsefill_hole_area: int = 16max_num_objects: int = 10000recondition_every_nth_frame: int = 16high_conf_thresh: float = 0.8high_iou_thresh: float = 0.8 )

パラメータ

  • detector_config (dict または Sam3Config、省略可) — Sam3 デテクターモデルの設定です。指定しない場合、デフォルトの Sam3Config が使用されます。
  • tracker_config (dict または Sam2VideoConfig、省略可) — Sam2Video トラッカーモデルの設定です。指定しない場合、デフォルトの Sam2VideoConfig が使用されます。
  • initializer_range (float、任意、デフォルト値は 0.02)— 重み行列の初期化に使用する truncated_normal_initializer の標準偏差です。
  • low_res_mask_size (int、任意、デフォルトは 288) — トラッカーが動画解像度にアップサンプリングする前の、低解像度マスク出力のサイズ(高さおよび幅)。
  • score_threshold_detection (float、任意、デフォルト値は 0.5) — 検出出力の確率閾値。この閾値を超える検出のみを保持します。
  • det_nms_thresh (float、任意、デフォルト値は 0.1)— 検出 NMS (Non-Maximum Suppression) の IoU しきい値。
  • assoc_iou_thresh (float、任意、デフォルト値は 0.1) — 検出とトラッキングのマッチングに使用する IoU 閾値。検出がこの閾値以上でトラクレットと重複する場合、その検出はトラクレットに「マッチした」とみなされます。通常は 0.1 のような緩やかな閾値が使用されます。
  • trk_assoc_iou_thresh (float、任意、デフォルト値は 0.5)— 検出とトラッキングのマッチングに使用される IoU しきい値。マスクレットがどの検出にも「未マッチ」であるかを判定するために用いられます。通常は 0.5 のようなより厳しめのしきい値が使用されます。
  • new_det_thresh (float、任意、デフォルト値 0.7) — 検出が新しいオブジェクトとして追加されるための確率の閾値。
  • recondition_on_trk_masks (bool、任意、デフォルトは True) — リコンディショニングにトラッキングマスク(True)を使用するか、検出マスク(False)を使用するかを指定します。トラッキングマスクの品質が高く、検出器を検証シグナルとして用いてメモリを強化しドリフトを防ぐ場合は True を使用します。
  • hotstart_delay (int、任意、デフォルトは 15) — ホットスタート中にバッファリングする出力のフレーム数です。hotstart_delay フレーム分の出力を保持し、ホットスタートのヒューリスティックに基づいてトラクレットを削除します。
  • hotstart_unmatch_thresh (int、任意、デフォルト値は 8)— hotstart 期間中に tracklet を削除するために必要な未一致フレームの数。
  • hotstart_dup_thresh (int、任意、デフォルト値は 8)— ホットスタート期間中に重複トラックレットを除去するために必要な重複フレーム数。
  • suppress_unmatched_only_within_hotstart (bool、任意、デフォルトはTrue) — マスクの抑制をホットスタート期間内に限定するかどうか。False の場合、ホットスタート期間より前に始まるマスクも抑制できます。
  • init_trk_keep_alive (int、任意、デフォルトは 30)— 新規トラックの初期 keep-alive カウンター。
  • max_trk_keep_alive (int、任意、デフォルト値は 30)— 最大キープアライブカウンタ値です。検出結果とマッチしたトラッカーは、この値までカウンタが増加します。
  • min_trk_keep_alive (int、省略可、デフォルトは -1) — 最小の keep-alive カウンター値です。検出とマッチングしないトラッカーは、そのカウンターがこの値まで減少します。
  • suppress_overlapping_based_on_recent_occlusion_threshold (float、任意、デフォルト値は 0.7)— 最近の遮蔽に基づいて重複するオブジェクトを抑制するための閾値です。この閾値を超える IoU を持つ重複するマスクは、最も最近遮蔽されたものに基づいて抑制されます。
  • decrease_trk_keep_alive_for_empty_masklets (bool、省略可、デフォルトはFalse) — SAM2 の予測において、面積がゼロの masklet に対して keep-alive カウンターを減少させるかどうかを指定します。
  • fill_hole_area (int、任意、デフォルト値は 16) — マスク内の穴を埋め、小さなノイズを除去するための最小面積(ピクセル単位)。
  • max_num_objects (int, 任意、デフォルトは 10000) — 追跡するオブジェクトの最大数です。デフォルトの 10000 は、実質的にこの制限を無効にします。
  • recondition_every_nth_frame (int、任意、デフォルト値は 16)— マスクの再条件付けの頻度(フレーム数)。再条件付けを無効にするには 0 を設定してください。
  • high_conf_thresh (float、任意、デフォルト値は 0.8) — リコンディショニング用の高信頼度閾値です。この閾値を超える検出のみが、トラックレットのリコンディショニングに使用できます。
  • high_iou_thresh (float、任意、デフォルト値は 0.8) — リコンディショニング用の高IoU閾値。この閾値を超えるIoUを持つ検出のみが、トラクレットのリコンディショニングに使用できます。

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

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

例:

>>> from transformers import Sam3VideoConfig, Sam3VideoModel

>>> # Initializing a SAM3 Video configuration with default detector and tracker
>>> configuration = Sam3VideoConfig()

>>> # Changing image size for custom resolution inference (automatically propagates to all nested configs)
>>> configuration.image_size = 560

>>> # Initializing a model from the configuration
>>> model = Sam3VideoModel(configuration)

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

Sam3VideoProcessor

class transformers.Sam3VideoProcessor

< >

( image_processorvideo_processortokenizertarget_size: int | None = None**kwargs )

パラメータ

  • image_processor (Sam3ImageProcessor) — 画像プロセッサは必須の入力です。
  • video_processor (video_processor_class) — ビデオプロセッサは必須の入力です。
  • tokenizer (CLIPTokenizer) — トークナイザーは必須の入力です。
  • target_size (int, 任意) — 画像をリサイズする対象サイズ (target_size, target_size)。

画像プロセッサ、動画プロセッサ、トークナイザーを単一のプロセッサにラップするSam3VideoProcessorを構築します。

Sam3VideoProcessor は、Sam3ImageProcessor、video_processor_class、および CLIPTokenizer のすべての機能を提供します。詳細については、~Sam3ImageProcessor、~video_processor_class、および ~CLIPTokenizer を参照してください。

__call__

< >

( 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] = 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 (ImageInput、任意) — 処理対象の画像です。
  • segmentation_maps (ImageInput、任意) — 処理対象のセグメンテーションマップ(任意、画像プロセッサ用)。
  • original_sizes (list[list[float]], torch.Tensor, optional) — The original sizes of the images. Only used when images is not provided.
  • 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、任意): 提供された場合の、処理済みセグメンテーションマップ。

postprocess_outputs

< >

( inference_sessionmodel_outputsoriginal_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = None ) → dict

パラメータ

  • inference_session (Sam3VideoInferenceSession) — 推論セッションオブジェクトです。
  • model_outputs (Sam3VideoSegmentationOutput) — Sam3VideoModel.forward()からの生のモデル出力です。
  • original_sizes (list[list[float]] または torch.Tensor、任意) — 元のフレームサイズ [高さ, 幅] を指定します。セッションで video_height/video_width が設定されていない場合、ストリーミング推論では必須です。

戻り値

dict

以下のキーを含む辞書:

  • object_ids (torch.Tensor、shape (num_objects,)): 検出された各オブジェクトのオブジェクト ID。
  • scores (torch.Tensor、形状 (num_objects,)): 各オブジェクトの検出スコア。
  • boxes(torch.Tensor、形状 (num_objects, 4)): XYXY 形式のバウンディングボックス(top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
  • masks(torch.Tensor、形状 (num_objects, height, width)): 元の動画解像度における、各オブジェクトのバイナリセグメンテーションマスク
  • prompt_to_obj_ids (dict[str, list[int]]): プロンプトのテキストから、そのプロンプトによって検出されたオブジェクト ID のリストへのマッピング。

モデルの出力を後処理して、最終的なマスク、ボックス、スコアを取得します。

init_video_session

< >

( 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_text_prompt

< >

( inference_session: Sam3VideoInferenceSessiontext: str | list[str] ) → Sam3VideoInferenceSession

パラメータ

  • inference_session (Sam3VideoInferenceSession) — 推論セッションです。
  • text (str または list[str]) — 追加するテキストプロンプト。

戻り値

Sam3VideoInferenceSession

追加されたテキストプロンプトを含む推論セッション。

推論セッションにテキストプロンプトを追加します。

Sam3VideoInferenceSession

class transformers.Sam3VideoInferenceSession

< >

( 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)— キャッシュするビジョン特徴の最大数です。

動画推論セッションのパラメータ、状態、およびキャッシュを管理します。

add_mask_inputs

< >

( obj_idx: intframe_idx: intinputs: Tensor )

自動的なデバイス配置を備えたマスク入力を追加します。

add_new_frame

< >

( pixel_values: Tensorframe_idx: int | None = None )

自動的なデバイス配置で新しいフレームを追加します。

add_prompt

< >

( prompt_text: str )

セッションにテキストプロンプトを追加し、その一意のIDを返します。 プロンプトが既に存在する場合は、既存のIDを返します。

get_frame

< >

( frame_idx: int )

動画からフレームを取得します。

get_obj_num

< >

( )

このセッションでこれまでに受信した一意のオブジェクトIDの総数を取得します。

get_output

< >

( obj_idx: intframe_idx: intoutput_key: stris_conditioning_frame: bool = True )

パラメータ

  • obj_idx (int) — オブジェクトのインデックス。
  • frame_idx (int) — フレームのインデックス。
  • output_key (str) — 出力のキー。
  • is_conditioning_frame (bool) — 出力が条件付けフレーム用であるかどうかを示します。

スマートなデバイス管理で出力を取得します。

obj_id_to_idx

< >

( obj_id: int )

必要に応じて新しいエントリを作成し、オブジェクトIDをインデックスにマッピングします。

obj_idx_to_id

< >

( obj_idx: int )

モデル側のオブジェクトインデックスをクライアント側のオブジェクトIDにマッピングします。

remove_mask_inputs

< >

( obj_idx: intframe_idx: int )

マスク入力を削除します。

remove_object

< >

( obj_id: intstrict: bool = False )

パラメータ

  • obj_id (int) — 削除するオブジェクトの ID。
  • strict (bool、省略可、デフォルトはFalse) — オブジェクトが存在しない場合にエラーを送出するかどうか。

推論セッションからオブジェクトを削除します。これにより、動画のすべてのフレームからそのオブジェクトが削除されます。

reset_inference_session

< >

( )

トラッキングデータとキャッシュをリセットします。

reset_state

< >

( )

推論セッションの状態をリセットします。

reset_tracking_data

< >

( )

トラッキングデータをリセットしますが、キャッシュは保持します。

store_output

< >

( obj_idx: intframe_idx: intoutput_key: str | None = Noneoutput_value: typing.Union[torch.Tensor, dict, NoneType] = Noneis_conditioning_frame: bool = True )

パラメータ

  • obj_idx (int) — オブジェクトのインデックス。
  • frame_idx (int) — フレームのインデックス。
  • output_key (Optional[str]) — 出力のキーです。None の場合、出力は辞書として保存されます。
  • output_value (Optional[Union[torch.Tensor, dict]]) — 出力の値。
  • is_conditioning_frame (bool) — 出力が条件付けフレーム用であるかどうかを示します。

スマートなデバイス管理により出力を保存します。 がNoneの場合、出力は辞書として保存されます。

Sam3VideoSegmentationOutput

class transformers.Sam3VideoSegmentationOutput

< >

( object_ids: list[int] | None = Noneobj_id_to_mask: dict[int, torch.FloatTensor] | None = Noneobj_id_to_score: dict[int, float] | None = Noneobj_id_to_tracker_score: dict[int, float] | None = Noneremoved_obj_ids: set[int] | None = Nonesuppressed_obj_ids: set[int] | None = Noneframe_idx: int | None = None )

パラメータ

  • object_ids (list[int]、任意) — 現在のフレームで追跡されているオブジェクトの ID のリスト。
  • obj_id_to_mask (dict[int, torch.FloatTensor]、任意) — オブジェクト ID を予測された低解像度マスクにマッピングする辞書です。 各マスクの形状は (1, H_low, W_low) です。
  • obj_id_to_score (dict[int, float], 省略可) — オブジェクト ID をその検出スコアにマッピングする辞書。
  • obj_id_to_tracker_score (dict[int, float], 省略可) — 現在のフレームにおける、オブジェクト ID とトラッカースコアの対応を表す辞書。
  • removed_obj_ids (set[int]、省略可) — 削除されたオブジェクト ID のセット(例:ホットスタートのヒューリスティックによる削除)。
  • suppressed_obj_ids (set[int]、省略可) — 現在のフレームで抑制されているオブジェクト ID のセットです。
  • frame_idx (int, 任意) — 動画のフレームインデックスです。

Sam3Video モデルの出力の基底クラスです。

Sam3VideoModel

class transformers.Sam3VideoModel

< >

( config: Sam3VideoConfig )

パラメータ

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

特定のヘッドを上に載せずに、生のhidden-statesを出力する素のSam3 Video Model。

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

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

forward

< >

( inference_session: Sam3VideoInferenceSessionframe_idx: int | None = Noneframe: typing.Optional[torch.Tensor] = Nonereverse: bool = False**kwargs )

パラメータ

  • inference_session (~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession) — 動画推論セッションオブジェクトです。
  • frame_idx (int, 任意) — 推論を実行するフレームのインデックスです。新しいストリームフレームに対して推論を行う場合は、指定する必要はありません。
  • frame (torch.Tensor, 任意) — 処理するフレーム。ストリーミング処理を行う場合に指定します。
  • reverse (bool、省略可能、デフォルトは False) — 逆方向に伝播するかどうか。

ストリーミングされた動画フレームを通じてオブジェクトを伝播させます。

propagate_in_video_iterator

< >

( inference_session: Sam3VideoInferenceSessionstart_frame_idx: int = 0max_frame_num_to_track: int | None = Nonereverse: bool = Falseshow_progress_bar: bool = False ) → Sam3VideoSegmentationOutput or tuple(torch.FloatTensor)

パラメータ

  • inference_session (~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession) — 動画推論セッションオブジェクトです。
  • start_frame_idx (int、任意、デフォルトは0) — 伝播の開始フレームインデックスです。
  • max_frame_num_to_track (int, 省略可) — トラッキングするフレームの最大数です。指定しない場合、動画内のすべてのフレームがトラッキングされます。
  • reverse (bool、省略可能、デフォルトは False) — 逆方向に伝播するかどうか。
  • show_progress_bar (bool、省略可能、デフォルトは False) — 伝播中にプログレスバーを表示するかどうか。

戻り値

Sam3VideoSegmentationOutput または tuple(torch.FloatTensor)

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

プロンプトを伝播して、動画全体についてグラウンディング結果を取得します。動画全体で推論セッションを初期化する際に使用します。 各フレームに対してSam3VideoSegmentationOutputを生成します。

  • object_ids (list[int]、任意) — 現在のフレームで追跡されているオブジェクトの ID のリスト。
  • obj_id_to_mask (dict[int, torch.FloatTensor]、optional) — オブジェクト ID を予測された低解像度マスクにマッピングする辞書。 各マスクの形状は (1, H_low, W_low) です。
  • obj_id_to_score (dict[int, float]、省略可) — オブジェクト ID をその検出スコアにマッピングする辞書。
  • obj_id_to_tracker_score (dict[int, float]、optional) — 現在のフレームにおける、オブジェクトIDとトラッカースコアの対応を示す辞書。
  • removed_obj_ids (set[int]、任意) — 削除されたオブジェクト ID のセット(例:ホットスタートのヒューリスティックによる削除)。
  • suppressed_obj_ids (set[int]、任意) — 現在のフレームで抑制されているオブジェクト ID のセット。
  • frame_idx (int, 任意) — 動画のフレームインデックス。
Update on GitHub