# SAM2 视频

    
        
        
    

## 概述

SAM2 （Segment Anything Model 2）由 Nikhila Ravi、Valentin Gabeur、Yuan-Ting Hu、Ronghang Hu、Chaitanya Ryali、Tengyu Ma、Haitham Khedr、Roman Rädle、Chloe Rolland、Laura Gustafson、Eric Mintun、Junting Pan、Kalyan Vasudev Alwala、Nicolas Carion、Chao-Yuan Wu、Ross Girshick、Piotr Dollár 和 Christoph Feichtenhofer 在 [Segment Anything in Images and Videos](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 倍。在图像分割方面，我们的模型比 Segment Anything Model（SAM）更准确，速度快 6 倍。我们相信，我们的数据、模型和见解将成为视频分割及相关感知任务的重要里程碑。我们将发布我们模型的版本、数据集以及一个交互式演示。*

提示：

- 批量与视频支持：SAM2 原生支持批量处理和无缝视频分割，而原始 SAM 专为静态图像和更简单的单张图像处理工作流而设计。
- 准确性与泛化能力：与原始 SAM 相比，SAM2 在分割质量、鲁棒性以及针对新领域的零样本泛化能力方面均有提升，尤其是在使用混合提示时。

该模型由 [sangbumchoi](https://github.com/SangbumChoi) 和 [yonigozlan](https://huggingface.co/yonigozlan) 贡献。原始代码可在[此处](https://github.com/facebookresearch/sam2/tree/main)找到。

## 使用示例

### 视频分割与跟踪

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

## 资源

一份来自 Hugging Face 官方和社区（以 🌎 标识）的资源列表，帮助你快速上手 SAM。

- 由 [Sangbum Choi](https://github.com/SangbumChoi) 贡献的用于该模型的 [Demo notebook 🌎](https://colab.research.google.com/drive/1Z0NGLE7p8qnc9UpuI8KBETHd2xBbOEhv?usp=sharing)。

## 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/v5.23.0/src/transformers/models/sam2_video/configuration_sam2_video.py#L96)

**参数：**

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：视觉骨干网络的配置对象或字典。

prompt_encoder_config (Union[`dict`, `Sam2PromptEncoderConfig`], *可选*) : 用于初始化 [Sam2PromptEncoderConfig](/docs/transformers/v5.23.0/zh/model_doc/sam2#transformers.Sam2PromptEncoderConfig) 的配置选项字典。

mask_decoder_config (Union[`dict`, `Sam2MaskDecoderConfig`], *可选*) : 用于初始化 [Sam2MaskDecoderConfig](/docs/transformers/v5.23.0/zh/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 函数的缩放因子。

sigmoid_bias_for_mem_enc (`float`, *可选*, 默认值为 -10.0) : 内存编码器中 sigmoid 函数的偏置。

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`, *可选*，默认为 -1)：在内存注意力中使用的最大条件帧数。设置为 -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`, *可选*，默认为 0.1)：内存注意力模块的 dropout 率。

memory_attention_rope_feat_sizes (`list[int]`，*可选*，默认为 `[64, 64]`)：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)：掩码下采样器嵌入的维度。

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"`)：内存融合器中的非线性激活函数。

这是用于存储 Sam2VideoModel 配置的类。它根据指定的参数实例化 Sam2 Video 模型，并定义模型架构。使用默认值实例化配置将生成与 [facebook/sam2.1-hiera-tiny](https://huggingface.co/facebook/sam2.1-hiera-tiny) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/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/v5.23.0/src/transformers/models/sam2_video/configuration_sam2_video.py#L57)

**参数：**

hidden_size (`int`，*可选*，默认为 `256`)：隐藏表示的维度。

hidden_act (`str`，*可选*，默认为 `gelu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

mlp_dim (`int`, *可选*, 默认为 2048) : 双向 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`)：是否通过稳定性使用动态多掩码。

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/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/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/v5.23.0/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`)：每个 patch 的大小（分辨率）。

mask_input_channels (`int`，*可选*，默认为 16)：输入到 `MaskDecoder` 模块的通道数。

num_point_embeddings (`int`，*可选*，默认为 4)：要使用的点嵌入数量。

hidden_act (`str`，*可选*，默认为 `gelu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

layer_norm_eps (`float`, *可选*, 默认为 `1e-06`) : 层归一化层使用的 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/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/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/v5.23.0/src/transformers/models/sam2_video/processing_sam2_video.py#L37)

**参数：**

image_processor (`Sam2ImageProcessor`)：图像处理器是必需的输入。

video_processor (`Sam2VideoVideoProcessor`)：视频处理器是必需的输入。

target_size (`int`, *optional*) : 用于归一化输入点和边界框的目标尺寸（以像素为单位）。如果未提供，则默认使用图像处理器的大小配置。所有输入坐标（点和框）在传递给模型之前都会归一化到该尺寸。这确保了无论原始图像尺寸如何，坐标表示都保持一致。

point_pad_value (`int`, *可选*，默认为 -10) : 在对不同长度的序列进行批处理时，用于填充输入点的值。该值用于标记填充位置，并在坐标归一化过程中保留。

构造一个 Sam2VideoProcessor，它将图像处理器和视频处理器封装为单一处理器。

[Sam2VideoProcessor](/docs/transformers/v5.23.0/zh/model_doc/sam2_video#transformers.Sam2VideoProcessor) 提供了 [Sam2ImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/sam2#transformers.Sam2ImageProcessor) 和 [Sam2VideoVideoProcessor](/docs/transformers/v5.23.0/zh/model_doc/sam2_video#transformers.Sam2VideoVideoProcessor) 的所有功能。有关更多信息，请参阅 [~Sam2ImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/sam2#transformers.Sam2ImageProcessor) 和 [~Sam2VideoVideoProcessor](/docs/transformers/v5.23.0/zh/model_doc/sam2_video#transformers.Sam2VideoVideoProcessor)。

#### __调用__[[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/v5.23.0/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/v5.23.0/zh/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/v5.23.0/src/transformers/models/sam2_video/processing_sam2_video.py#L461)

**参数：**

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]]]`) : 每张图片在调整至模型预期输入形状之前的原始尺寸，格式为 (height, width)。

mask_threshold (`float`, *可选*，默认为 0.0)：用于二值化和后处理操作的阈值。

binarize (`bool`, *可选*, 默认为 `True`) : 是否将掩码二值化。

max_hole_area (`float`, *可选*，默认为 0.0)：要填充的孔洞的最大面积。

max_sprinkle_area (`float`, *可选*，默认为 0.0)：用于填充的 sprinkles 的最大面积。

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/v5.23.0/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`，*可选*，默认为 1)：要缓存的最大视觉特征数量。

dtype (`torch.dtype`，*可选*，默认为 `torch.float32`)：用于整个会话的 torch 数据类型。

初始化用于推理的视频会话。如果提供了视频（异步推理），该视频将被处理并存储在 `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/v5.23.0/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]`，*可选*)：视频的原始尺寸。在流式处理时提供。

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/v5.23.0/src/transformers/models/sam2_video/video_processing_sam2_video.py#L27)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `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*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.485, 0.456, 0.406]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.229, 0.224, 0.225]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

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*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

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*, *可选*) : 是否在处理前从视频中采样帧，还是处理整个视频。

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` 时，每秒采样的目标帧数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，要采样的最大帧数。

return_metadata (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([VideosKwargs](/docs/transformers/v5.23.0/zh/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/v5.23.0/src/transformers/models/sam2_video/video_processing_sam2_video.py#L58)

**参数：**

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]]]`) : 每张图片在调整至模型预期输入形状之前的原始尺寸，格式为 (height, width)。

reshaped_input_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`) : 图像输入模型时的尺寸，格式为 (height, width)。用于移除填充。

mask_threshold (`float`, *可选*，默认为 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.Tensor] = 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/v5.23.0/src/transformers/models/sam2_video/modeling_sam2_video.py#L109)

**参数：**

video (`torch.Tensor`, *可选*) : 要处理的视频。流式处理时无需提供。

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[[transformers.Sam2VideoInferenceSession.add_mask_inputs]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/src/transformers/models/sam2_video/modeling_sam2_video.py#L235)

移除 mask 输入。

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

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/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/v5.23.0/src/transformers/models/sam2_video/modeling_sam2_video.py#L1643)

**参数：**

config ([Sam2VideoConfig](/docs/transformers/v5.23.0/zh/model_doc/sam2_video#transformers.Sam2VideoConfig))：包含模型所有参数的模型配置类。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

未添加任何特定头部的裸 Sam2 Video Model，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/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/v5.23.0/src/transformers/models/sam2_video/modeling_sam2_video.py#L1776)

**参数：**

inference_session (`~models.sam2_video.modeling_sam2_video.Sam2VideoInferenceSession`)：视频推理会话对象。

frame_idx (`int`, *可选*) : 用于运行推理的帧索引。在对新的流式帧进行推理时无需提供。

frame (`torch.Tensor`, *可选*) : 要处理的帧。在流式处理时提供。

reverse (`bool`，*可选*，默认为 `False`)：是否反向传播。

run_mem_encoder (`bool`, *可选*，默认为 `True`) : 是否对预测的掩码运行内存编码器。内存编码器会对所有对象进行批处理以提高效率。

**返回：** `Sam2VideoSegmentationOutput` 或 `tuple(torch.Tensor)`

`Sam2VideoSegmentationOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Sam2VideoConfig](/docs/transformers/v5.23.0/zh/model_doc/sam2_video#transformers.Sam2VideoConfig)）和输入。

通过流式视频帧传播对象。

- **object_ids** (`list[int]`，*可选*) -- 当前帧中正在跟踪的对象 ID 列表。
- **pred_masks**（形状为 `(batch_size, num_masks, height, width)` 的 `torch.Tensor`）-- 以模型分辨率存储的预测掩码。
- **object_score_logits** (`torch.Tensor`，形状为 `(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/v5.23.0/src/transformers/models/sam2_video/modeling_sam2_video.py#L2797)

**参数：**

inference_session (`~models.sam2_video.modeling_sam2_video.Sam2VideoInferenceSession`)：视频推理会话对象。

start_frame_idx (`int`, *可选*) : 传播的起始帧索引。如果尚未对新输入调用 `forward`，则必须提供此参数。如果未提供，起始帧索引将为具有输入点的最早帧。

max_frame_num_to_track (`int`, *可选*) : 要跟踪的最大帧数。

reverse (`bool`，*可选*，默认为 `False`)：是否反向传播。

show_progress_bar (`bool`，*可选*，默认为 `False`)：是否在传播过程中显示进度条。

**返回：** `Sam2VideoSegmentationOutput` 或 `tuple(torch.Tensor)`

`Sam2VideoSegmentationOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Sam2VideoConfig](/docs/transformers/v5.23.0/zh/model_doc/sam2_video#transformers.Sam2VideoConfig)）和输入。

将对象传播到视频帧中。在初始化包含整个视频的推理会话时使用。为每一帧生成 Sam2VideoSegmentationOutput。

- **object_ids** (`list[int]`，*可选*) -- 当前帧中正在跟踪的对象 ID 列表。
- **pred_masks**（形状为 `(batch_size, num_masks, height, width)` 的 `torch.Tensor`）-- 以模型分辨率存储的预测掩码。
- **object_score_logits** (`torch.Tensor`，形状为 `(batch_size,)`，*可选*) -- 对象分数的 logits，用于指示是否存在对象。
- **frame_idx** (`int`, *可选*) -- 视频的帧索引。

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

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam2_video/modeling_sam2_video.py#L1901)

**参数：**

pixel_values (`torch.Tensor`) : 形状为 `(batch_size, num_channels, height, width)` 的输入像素值。

**返回：** `Sam2VideoVisionEncoderOutput` 或 `tuple(torch.Tensor)`

`Sam2VideoVisionEncoderOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Sam2VideoConfig](/docs/transformers/v5.23.0/zh/model_doc/sam2_video#transformers.Sam2VideoConfig)）和输入。

- **last_hidden_state**（形状为 `(batch_size, height, width, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。
- **fpn_hidden_states** (`tuple(torch.Tensor)`) -- 一个 `torch.Tensor` 元组（每个特征层一个，从高分辨率到低分辨率），形状为 `(batch_size, hidden_size, height, width)`。来自特征金字塔网络（Feature Pyramid Network）颈部的特征图。
- **fpn_position_encoding** (`tuple(torch.Tensor)`) -- 一个 `torch.Tensor` 元组（每个特征层一个，从高分辨率到低分辨率），形状为 `(batch_size, hidden_size, height, width)`。与 `fpn_hidden_states` 对应的位置编码。

