# SAM2 Video

    
        
        
    

## 概要

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](https://ai.meta.com/research/publications/sam-2-segment-anything-in-images-and-videos/) で提案されました。

モデルは、入力画像または動画、および入力されたポイントまたはバウンディングボックスを指定することで、対象とする任意のオブジェクトのセグメンテーションマスクを予測するために使用できます。

![example image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam2_header.gif)

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

*画像および動画におけるプロンプト可能な視覚セグメンテーションの解決に向けた基盤モデルである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](https://github.com/SangbumChoi) と [yonigozlan](https://huggingface.co/yonigozlan) によって提供されました。元のコードは[こちら](https://github.com/facebookresearch/sam2/tree/main)で確認できます。

## 使用例

### Video Segmentation and Tracking

SAM2の最大の強みは、動画フレーム間でオブジェクトを追跡できる点です。動画セグメンテーションにSAM2を使用する方法は以下の通りです。

#### 基本的なビデオトラッキング

```python
from transformers import Sam2VideoModel, Sam2VideoProcessor
import torch

model = Sam2VideoModel.from_pretrained("facebook/sam2.1-hiera-tiny", device_map="auto")
processor = Sam2VideoProcessor.from_pretrained("facebook/sam2.1-hiera-tiny")

# 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
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 sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = video_res_masks

print(f"Tracked object through {len(video_segments)} frames")
Tracked object through 180 frames
```

#### マルチオブジェクト・ビデオトラッキング

動画フレーム間で複数のオブジェクトを同時にトラッキングします:

```python
# 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
outputs = model(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
)

# Propagate both objects through video
video_segments = {}
for sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_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
```

#### 動画セグメンテーションの洗練

任意のフレームに追加のクリックを追加して、トラッキングを微調整できます:

```python
# 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 sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = video_res_masks
```

### ストリーミング動画推論

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

```python
# 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
    sam2_video_output = model(inference_session=inference_session, frame=inputs.pixel_values[0])
...
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=inputs.original_sizes, binarize=False
    )[0]
    print(f"Frame {frame_idx}: mask shape {video_res_masks.shape}")
```

#### 複数のオブジェクト向けのビデオバッチ処理

をすべて一度に追加して、動画内の複数のオブジェクトを同時にトラッキングします:

```python
# 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 sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_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
```

## リソース

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

- [Demo notebook 🌎](https://colab.research.google.com/drive/1Z0NGLE7p8qnc9UpuI8KBETHd2xBbOEhv?usp=sharing)は、[Sangbum Choi](https://github.com/SangbumChoi) 氏によって提供された、このモデルの使用方法を示すノートブックです。

## Sam2VideoConfig[[transformers.Sam2VideoConfig]]

#### transformers.Sam2VideoConfig[[transformers.Sam2VideoConfig]]

```python
transformers.Sam2VideoConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, prompt_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, mask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, initializer_range: float = 0.02, num_maskmem: int = 7, image_size: int | list[int] | tuple[int, int] = 1024, 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, 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 = -1, 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 | int = 0.1, memory_attention_rope_feat_sizes: list[int] | None = None, memory_attention_rope_dropout: float | int = 0.1, memory_encoder_hidden_size: int = 256, memory_encoder_output_channels: int = 64, rope_parameters: dict | None = None, mask_downsampler_embed_dim: int = 256, mask_downsampler_kernel_size: int = 3, mask_downsampler_stride: int = 2, mask_downsampler_padding: int = 1, mask_downsampler_total_stride: int = 16, mask_downsampler_hidden_act: str = 'gelu', memory_fuser_num_layers: int = 2, memory_fuser_embed_dim: int = 256, memory_fuser_intermediate_dim: int = 1024, memory_fuser_kernel_size: int = 7, memory_fuser_padding: int = 3, memory_fuser_layer_scale_init_value: float = 1e-06, memory_fuser_hidden_act: str = 'gelu')
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/configuration_sam2_video.py#L96)

**パラメータ:**

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

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

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

initializer_range (`float`、*任意*、デフォルトは 0.02) : パラメータ初期化の標準偏差。

num_maskmem (`int`、*任意*、デフォルトは 7) : マスクメモリ用のメモリスロットの数。

image_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`1024`) : 各画像のサイズ（解像度）。

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`、*optional*、デフォルトは 1) : マルチマスク出力をトリガーする最大ポイント数。

multimask_output_for_tracking (`bool`、*任意*、デフォルトは `True`) : トラッキングにマルチマスク出力を使用するかどうか。

max_object_pointers_in_encoder (`int`、*optional*、デフォルトは 16) : エンコーダー内のオブジェクトポインタの最大数。

max_cond_frame_num (`int`、*optional*、デフォルトは -1) : メモリアテンションで使用する条件付けフレームの最大数です。すべての条件付けフレームを使用するには -1 を設定してください。

enable_temporal_pos_encoding_for_object_pointers (`bool`、*任意*、デフォルトは`True`) : オブジェクトポインタに対して時間的位置エンコーディングを有効にするかどうか。

memory_attention_hidden_size (`int`、*optional*、デフォルトは 256) : メモリアテンションの隠れ状態の次元数。

memory_attention_num_layers (`int`, *任意*, デフォルトは 4) : メモリアテンションモジュールの層数。

memory_attention_num_attention_heads (`int`、*任意*、デフォルトは 1) : メモリアテンションにおける各アテンション層のアテンションヘッド数。

memory_attention_downsample_rate (`int`、*optional*、デフォルトは 1) : attention レイヤーのダウンサンプル率です。

memory_attention_feed_forward_hidden_size (`int`、*任意*、デフォルトは 2048) : メモリアテンションモジュールにおけるフィードフォワードネットワークの次元です。

memory_attention_feed_forward_hidden_act (`str`、*任意*、デフォルトは `"relu"`) : メモリアテンションモジュール内のフィードフォワードネットワークで使用する非線形活性化関数。

memory_attention_dropout (`float`、*任意*、デフォルトは 0.1) : メモリ注意機構の dropout 率です。

memory_attention_rope_feat_sizes (`list[int]`、*optional*、デフォルトは`[64, 64]`) : Rope位置エンコーディングの機能サイズです。

memory_attention_rope_dropout (`float`、*任意*、デフォルトは 0.1) : Rope 位置エンコーディングの dropout レートです。

memory_encoder_hidden_size (`int`、*任意*、デフォルトは 256) : メモリエンコーダーの隠れ状態の次元数。

memory_encoder_output_channels (`int`、*optional*、デフォルトは 64) : メモリエンコーダーの出力チャネル数です。

rope_parameters (`dict`, *任意*) : RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には `rope_theta` の値が含まれており、より長い `max_position_embeddings` で RoPE を使用する場合にスケーリングに使用されるパラメータが任意で含まれます。

mask_downsampler_embed_dim (`int`、*optional*、デフォルトは 256) : マスクダウンサンプラーの埋め込みの次元数。

mask_downsampler_kernel_size (`int`、*optional*、デフォルトは 3) : マスクダウンサンプラーのカーネルサイズです。

mask_downsampler_stride (`int`、*optional*、デフォルトは 2) : マスクダウンサンプラーのストライドです。

mask_downsampler_padding (`int`、*optional*、デフォルトは 1) : マスクダウンサンプラーのパディング。

mask_downsampler_total_stride (`int`、*任意*、デフォルトは 16) : マスクダウンサンプラーの総ストライド。

mask_downsampler_hidden_act (`str`、*任意*、デフォルトは `"gelu"`) : マスクダウンサンプラーで使用する非線形活性化関数。

memory_fuser_num_layers (`int`、*optional*、デフォルトは 2) : メモリフューザーのレイヤー数。

memory_fuser_embed_dim (`int`、*任意*、デフォルトは 256) : メモリフューザーにおける埋め込み層の次元数。

memory_fuser_intermediate_dim (`int`, *optional*, デフォルトは 1024) : メモリフュージョンにおける中間層の次元数です。

memory_fuser_kernel_size (`int`、*optional*、デフォルトは 7) : メモリフューザーのカーネルサイズです。

memory_fuser_padding (`int`、*任意*、デフォルトは 3) : メモリフューザーの padding です。

memory_fuser_layer_scale_init_value (`float`、*任意*、デフォルト値は 1e-06) : メモリフュージョンにおけるレイヤースケールの初期値です。

memory_fuser_hidden_act (`str`、*任意*、デフォルトは`"gelu"`) : メモリフューザーで使用する非線形活性化関数。

これはSam2VideoModelの設定を保存するための設定クラスです。指定された引数に基づいてSam2 Videoモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[facebook/sam2.1-hiera-tiny](https://huggingface.co/facebook/sam2.1-hiera-tiny)と類似した設定が得られます。

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

例:

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

## Sam2VideoMaskDecoderConfig[[transformers.Sam2VideoMaskDecoderConfig]]

#### transformers.Sam2VideoMaskDecoderConfig[[transformers.Sam2VideoMaskDecoderConfig]]

```python
transformers.Sam2VideoMaskDecoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 256, hidden_act: str = 'gelu', mlp_dim: int = 2048, num_hidden_layers: int = 2, num_attention_heads: int = 8, attention_downsample_rate: int = 2, num_multimask_outputs: int = 3, iou_head_depth: int = 3, iou_head_hidden_dim: int = 256, dynamic_multimask_via_stability: bool = True, dynamic_multimask_stability_delta: float = 0.05, dynamic_multimask_stability_thresh: float = 0.98)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/configuration_sam2_video.py#L57)

**パラメータ:**

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

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

mlp_dim (`int`、*optional*、デフォルトは 2048) : 2-way transformer における MLP の次元数。

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

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

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

num_multimask_outputs (`int`、*任意*、デフォルトは 3) : マルチマスク出力の数。

iou_head_depth (`int`、*optional*、デフォルトは 3) : IoU ヘッドの深さ。

iou_head_hidden_dim (`int`、*optional*、デフォルトは 256) : IoU ヘッドの隠れ次元です。

dynamic_multimask_via_stability (`bool`、*任意*、デフォルトは `True`) : stability を用いた動的マルチマスクを使用するかどうか。

dynamic_multimask_stability_delta (`float`、*任意*、デフォルトは 0.05) : 動的マルチマスクの安定性デルタです。

dynamic_multimask_stability_thresh (`float`、*任意*、デフォルト値は 0.98) : 動的マルチマスクの安定性しきい値です。

これはSam2VideoModelの設定を保存するための設定クラスです。指定された引数に基づいてSam2 Videoモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[facebook/sam2_video.1-hiera-tiny](https://huggingface.co/facebook/sam2_video.1-hiera-tiny) と同様の設定が得られます。

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

## Sam2VideoPromptEncoderConfig[[transformers.Sam2VideoPromptEncoderConfig]]

#### transformers.Sam2VideoPromptEncoderConfig[[transformers.Sam2VideoPromptEncoderConfig]]

```python
transformers.Sam2VideoPromptEncoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 256, image_size: int | list[int] | tuple[int, int] = 1024, patch_size: int | list[int] | tuple[int, int] = 16, mask_input_channels: int = 16, num_point_embeddings: int = 4, hidden_act: str = 'gelu', layer_norm_eps: float = 1e-06, scale: int = 1)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/configuration_sam2_video.py#L32)

**パラメータ:**

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

image_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`1024`) : 各画像のサイズ（解像度）。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`16`) : 各パッチのサイズ（解像度）。

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

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

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

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

scale (`float`、*任意*、デフォルトは 1) : プロンプトエンコーダーのスケール係数です。

これはSam2VideoModelの設定を保存するための設定クラスです。指定された引数に基づいてSam2 Videoモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[facebook/sam2_video.1-hiera-tiny](https://huggingface.co/facebook/sam2_video.1-hiera-tiny) と同様の設定が得られます。

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

## Sam2VideoProcessor[[transformers.Sam2VideoProcessor]]

#### transformers.Sam2VideoProcessor[[transformers.Sam2VideoProcessor]]

```python
transformers.Sam2VideoProcessor(image_processor, video_processor, target_size: int | None = None, point_pad_value: int = -10, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/processing_sam2_video.py#L37)

**パラメータ:**

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

video_processor (`Sam2VideoVideoProcessor`) : 動画プロセッサは必須の入力です。

target_size (`int`, *optional*) : 入力ポイントとバウンディングボックスを正規化するためのターゲットサイズ（ピクセル単位）です。指定されない場合、画像プロセッサのサイズ設定がデフォルトとして使用されます。すべての入力座標（ポイントとボックス）は、モデルに渡される前にこのサイズに正規化されます。これにより、元の画像の寸法に関係なく、座標の表現が常に一貫したものになります。

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

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

[Sam2VideoProcessor](/docs/transformers/main/ja/model_doc/sam2_video#transformers.Sam2VideoProcessor) は、[Sam2ImageProcessor](/docs/transformers/main/ja/model_doc/sam2#transformers.Sam2ImageProcessor) と [Sam2VideoVideoProcessor](/docs/transformers/main/ja/model_doc/sam2_video#transformers.Sam2VideoVideoProcessor) のすべての機能を提供します。詳細については、[~Sam2ImageProcessor](/docs/transformers/main/ja/model_doc/sam2#transformers.Sam2ImageProcessor) および [~Sam2VideoVideoProcessor](/docs/transformers/main/ja/model_doc/sam2_video#transformers.Sam2VideoVideoProcessor) を参照してください。

#### __call__[[transformers.Sam2VideoProcessor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, input_points: typing.Union[list[list[list[list[float]]]], torch.Tensor, NoneType] = None, input_labels: typing.Union[list[list[list[int]]], torch.Tensor, NoneType] = None, input_boxes: typing.Union[list[list[list[float]]], torch.Tensor, NoneType] = None, original_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/processing_sam2_video.py#L55)

**パラメータ:**

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](/docs/transformers/main/ja/main_classes/tokenizer#transformers.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[[transformers.Sam2VideoProcessor.post_process_masks]]

```python
post_process_masks(masks, original_sizes, mask_threshold = 0.0, binarize = True, max_hole_area = 0.0, max_sprinkle_area = 0.0, apply_non_overlapping_constraints = False, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/processing_sam2_video.py#L461)

**パラメータ:**

masks (`Union[List[torch.Tensor], List[np.ndarray]]`) : (batch_size, num_channels, height, width) 形式の、mask_decoder からのバッチ化されたマスク。

original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`) : モデルが期待する入力形状にリサイズされる前の、各画像の元のサイズ。(height, width)形式です。

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[[transformers.Sam2VideoProcessor.init_video_session]]

```python
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] = None, inference_device: typing.Union[str, ForwardRef('torch.device')] = 'cpu', inference_state_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = None, processing_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = None, video_storage_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = None, max_vision_features_cache_size: int = 1, dtype: dtype = torch.float32)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/processing_sam2_video.py#L512)

**パラメータ:**

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`、*optional*、デフォルトは 1) : キャッシュするビジョン特徴の最大数。

dtype (`torch.dtype`、*任意*、デフォルトは`torch.float32`) : セッション全体で使用するtorchのdtype。

推論用のビデオセッションを初期化します。ビデオが提供されている場合（非同期推論）、そのビデオは処理され、`video_storage_device`に保存されます。

#### add_inputs_to_inference_session[[transformers.Sam2VideoProcessor.add_inputs_to_inference_session]]

```python
add_inputs_to_inference_session(inference_session: Sam2VideoInferenceSession, frame_idx: int, obj_ids: list[int] | int, input_points: typing.Union[list[list[list[list[float]]]], torch.Tensor, NoneType] = None, input_labels: typing.Union[list[list[list[int]]], torch.Tensor, NoneType] = None, input_boxes: typing.Union[list[list[list[float]]], torch.Tensor, NoneType] = None, input_masks: typing.Union[numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], NoneType] = None, original_size: tuple[int, int] | None = None, clear_old_inputs: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/processing_sam2_video.py#L565)

**パラメータ:**

inference_session (`Sam2VideoInferenceSession`) : 動画用の推論セッションです。

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]`、*optional*) : 元の動画のサイズ。ストリーミング時に指定します。

clear_old_inputs (`bool`、*任意*、デフォルトは`True`) : オブジェクトの古い入力をクリアするかどうか。

動画フレームの新しい点、ボックス、またはマスクを処理し、推論セッションに追加します。

## Sam2VideoVideoProcessor[[transformers.Sam2VideoVideoProcessor]]

#### transformers.Sam2VideoVideoProcessor[[transformers.Sam2VideoVideoProcessor]]

```python
transformers.Sam2VideoVideoProcessor(**kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/video_processing_sam2_video.py#L27)

**パラメータ:**

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 が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

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

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

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

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

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

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

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

do_sample_frames (`bool`, *kwargs*, *optional*) : 処理前に動画からフレームをサンプリングするか、動画全体を処理するかを指定します。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 動画のメタデータ。総再生時間、fps、総フレーム数などの情報を含みます。動画からのフレームサンプリングやタイムスタンプの計算に使用されます。動画を処理する前に手動でデコードしようとしている場合を除き、メタデータは渡さないでください。

fps (`Annotated[int | float | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、1 秒あたりにサンプリングするターゲットフレーム数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、サンプリングするフレームの最大数。

return_metadata (`bool`, *kwargs*, *任意*、デフォルトは `False`) : ビデオメタデータを返すかどうかを指定します。ビデオメタデータは、ビデオの長さ、fps、デコードバックエンドなどの情報を含むオブジェクトです。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 設定されている場合、特定のフレームワークのテンソルを返します。許可される値は以下の通りです。 - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

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

Sam2VideoVideoProcessorのビデオプロセッサを構築します。

#### post_process_masks[[transformers.Sam2VideoVideoProcessor.post_process_masks]]

```python
post_process_masks(masks, original_sizes, reshaped_input_sizes, mask_threshold = 0.0, binarize = True, pad_size = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/video_processing_sam2_video.py#L58)

**パラメータ:**

masks (`Union[List[torch.Tensor], List[np.ndarray]]`) : (batch_size, num_channels, height, width) 形式の、mask_decoder からのバッチ化されたマスク。

original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`) : モデルが期待する入力形状にリサイズされる前の、各画像の元のサイズ。(height, width)形式です。

reshaped_input_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`) : モデルに与えられる各画像のサイズ。(height, width)形式です。パディングの除去に使用されます。

mask_threshold (`float`、*optional*、デフォルトは 0.0) : マスクをバイナリ化する際に使用する閾値。

binarize (`bool`、*任意*、デフォルトは`True`) : マスクをバイナリ化するかどうか。

pad_size (`int`、*任意*、デフォルトは`self.pad_size`) : モデルに渡される前に画像がパディングされた後のターゲットサイズです。None の場合、ターゲットサイズはプロセッサの`pad_size`であると仮定されます。

**戻り値:** (`torch.Tensor`)

batch_size, num_channels, height, width形式のバッチ化されたマスク。ここで、(height, width)はoriginal_sizeによって指定されます。

パディングを除去し、マスクを元の画像サイズにアップスケールします。

## Sam2VideoInferenceSession[[transformers.Sam2VideoInferenceSession]]

#### transformers.Sam2VideoInferenceSession[[transformers.Sam2VideoInferenceSession]]

```python
transformers.Sam2VideoInferenceSession(video: typing.Optional[torch.FloatTensor] = None, video_height: int | None = None, video_width: int | None = None, inference_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)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L109)

**パラメータ:**

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`、*optional*、デフォルトは 1) : キャッシュするビジョン特徴の最大数。

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

#### add_mask_inputs[[transformers.Sam2VideoInferenceSession.add_mask_inputs]]

```python
add_mask_inputs(obj_idx: int, frame_idx: int, inputs: Tensor)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L229)

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

#### add_new_frame[[transformers.Sam2VideoInferenceSession.add_new_frame]]

```python
add_new_frame(pixel_values: Tensor, frame_idx: int | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L304)

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

#### add_point_inputs[[transformers.Sam2VideoInferenceSession.add_point_inputs]]

```python
add_point_inputs(obj_idx: int, frame_idx: int, inputs: dict)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L215)

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

#### get_frame[[transformers.Sam2VideoInferenceSession.get_frame]]

```python
get_frame(frame_idx: int)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L320)

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

#### get_obj_num[[transformers.Sam2VideoInferenceSession.get_obj_num]]

```python
get_obj_num()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L210)

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

#### get_output[[transformers.Sam2VideoInferenceSession.get_output]]

```python
get_output(obj_idx: int, frame_idx: int, output_key: str, is_conditioning_frame: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L277)

**パラメータ:**

obj_idx (int) : オブジェクトのインデックス。

frame_idx (int) : フレームのインデックス。

output_key (str) : 出力のキー。

is_conditioning_frame (bool) : 出力が条件付けフレーム用かどうかを示します。

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

#### obj_id_to_idx[[transformers.Sam2VideoInferenceSession.obj_id_to_idx]]

```python
obj_id_to_idx(obj_id: int)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L184)

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

#### obj_idx_to_id[[transformers.Sam2VideoInferenceSession.obj_idx_to_id]]

```python
obj_idx_to_id(obj_idx: int)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L206)

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

#### remove_mask_inputs[[transformers.Sam2VideoInferenceSession.remove_mask_inputs]]

```python
remove_mask_inputs(obj_idx: int, frame_idx: int)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L235)

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

#### remove_point_inputs[[transformers.Sam2VideoInferenceSession.remove_point_inputs]]

```python
remove_point_inputs(obj_idx: int, frame_idx: int)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L225)

ポイント入力を削除します。

#### reset_inference_session[[transformers.Sam2VideoInferenceSession.reset_inference_session]]

```python
reset_inference_session()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L336)

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

#### reset_tracking_data[[transformers.Sam2VideoInferenceSession.reset_tracking_data]]

```python
reset_tracking_data()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L324)

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

#### store_output[[transformers.Sam2VideoInferenceSession.store_output]]

```python
store_output(obj_idx: int, frame_idx: int, output_key: str | None = None, output_value: typing.Union[torch.Tensor, dict, NoneType] = None, is_conditioning_frame: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L240)

**パラメータ:**

obj_idx (int) : オブジェクトのインデックス。

frame_idx (int) : フレームのインデックス。

output_key (Optional[str]) : 出力のキー。None の場合、出力は辞書として保存されます。

output_value (Optional[Union[torch.Tensor, dict]]) : 出力の値。

is_conditioning_frame (bool) : 出力が条件付けフレーム用かどうかを示します。

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

## Sam2VideoModel[[transformers.Sam2VideoModel]]

#### transformers.Sam2VideoModel[[transformers.Sam2VideoModel]]

```python
transformers.Sam2VideoModel(config: Sam2VideoConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L1643)

**パラメータ:**

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

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

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

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

#### forward[[transformers.Sam2VideoModel.forward]]

```python
forward(inference_session: Sam2VideoInferenceSession, frame_idx: int | None = None, frame: typing.Optional[torch.Tensor] = None, reverse: bool = False, run_mem_encoder: bool = True, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L1776)

**パラメータ:**

inference_session (`~models.sam2_video.modeling_sam2_video.Sam2VideoInferenceSession`) : 動画推論セッションオブジェクト。

frame_idx (`int`, *optional*) : 推論を実行するフレームのインデックスです。新しいストリームされたフレームに対して推論を行う場合は、指定する必要はありません。

frame (`torch.Tensor`, *任意*) : 処理するフレーム。ストリーミングの場合に指定します。

reverse (`bool`、*任意*、デフォルトは`False`) : 逆方向に伝播するかどうか。

run_mem_encoder (`bool`, *任意*, デフォルトは `True`) : 予測されたマスクに対してメモリエンコーダーを実行するかどうか。メモリエンコーダーは効率化のため、すべてのオブジェクトに対してバッチ処理されます。

**戻り値:** `Sam2VideoSegmentationOutput` または `tuple(torch.FloatTensor)`

`Sam2VideoSegmentationOutput`、または`torch.FloatTensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[Sam2VideoConfig](/docs/transformers/main/ja/model_doc/sam2_video#transformers.Sam2VideoConfig)）と入力に応じて、さまざまな要素で構成されます。

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

- **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[[transformers.Sam2VideoModel.propagate_in_video_iterator]]

```python
propagate_in_video_iterator(inference_session: Sam2VideoInferenceSession, start_frame_idx: int | None = None, max_frame_num_to_track: int | None = None, reverse: bool = False, show_progress_bar: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L2797)

**パラメータ:**

inference_session (`~models.sam2_video.modeling_sam2_video.Sam2VideoInferenceSession`) : 動画推論セッションオブジェクト。

start_frame_idx (`int`, *optional*) : 伝播の開始フレームインデックスです。`forward` が新しい入力に対してまだ呼び出されていない場合は、この値を指定する必要があります。指定しない場合、開始フレームインデックスは入力ポイントを持つ最も早いフレームになります。

max_frame_num_to_track (`int`, *任意*) : 追跡するフレームの最大数。

reverse (`bool`、*任意*、デフォルトは`False`) : 逆方向に伝播するかどうか。

show_progress_bar (`bool`, *任意*, デフォルトは `False`) : 伝播中にプログレスバーを表示するかどうか。

**戻り値:** `Sam2VideoSegmentationOutput` または `tuple(torch.FloatTensor)`

`Sam2VideoSegmentationOutput`、または`torch.FloatTensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[Sam2VideoConfig](/docs/transformers/main/ja/model_doc/sam2_video#transformers.Sam2VideoConfig)）と入力に応じて、さまざまな要素で構成されます。

動画フレーム全体を通じてオブジェクトを伝播させます。動画全体で推論セッションを初期化する際に使用します。各フレームに対してSam2VideoSegmentationOutputを生成します。

- **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[[transformers.Sam2VideoModel.get_image_features]]

```python
get_image_features(pixel_values: FloatTensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2_video/modeling_sam2_video.py#L1901)

**パラメータ:**

pixel_values (`torch.FloatTensor`) : 形状が `(batch_size, num_channels, height, width)` の入力ピクセル値。

**戻り値:** `Sam2VideoVisionEncoderOutput` または `tuple(torch.FloatTensor)`

`Sam2VideoVisionEncoderOutput`、または`torch.FloatTensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[Sam2VideoConfig](/docs/transformers/main/ja/model_doc/sam2_video#transformers.Sam2VideoConfig)）や入力に応じて、さまざまな要素で構成されます。

- **last_hidden_state** (`torch.FloatTensor`、形状 `(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` に対応する位置エンコーディングです。

