# SAM3 视频

    
        
        
    

## 概述

SAM3 （Segment Anything Model 3）在 [SAM 3: Segment Anything with Concepts](https://ai.meta.com/research/publications/sam-3-segment-anything-with-concepts/) 中推出。

SAM3 Video 在视频上执行**可提示概念分割（PCS）**。PCS 以文本作为输入（例如，“黄色校车”），并为匹配该概念的**每一个对象**预测实例掩码和语义掩码，同时在视频帧之间保持对象身份的一致性。

该模型将检测模块（SAM3）与跟踪模块（SAM2 风格的跟踪器）相结合，利用文本提示在视频帧之间实现鲁棒的目标跟踪。

该论文的摘要如下：

*我们提出了 Segment Anything Model (SAM) 3，这是一个统一的模型，能够基于概念提示在图像和视频中对目标进行检测、分割和跟踪。我们将概念提示定义为短名词短语（例如，“yellow school bus”）、图像示例，或两者的组合。可提示概念分割（PCS）接收此类提示，并返回所有匹配目标实例的分割掩码和唯一标识。为了推动 PCS 的发展，我们构建了一个可扩展的数据引擎，生成了一个包含 400 万个唯一概念标签的高质量数据集，涵盖图像和视频，并包含困难负样本。我们的模型由一个图像级检测器和一个基于记忆的视频跟踪器组成，二者共享同一个骨干网络。通过一个存在头（presence head）将识别与定位解耦，从而提升了检测精度。SAM 3 在图像和视频 PCS 任务上的准确率是现有系统的两倍，并提升了先前 SAM 在视觉分割任务上的能力。我们开源了 SAM 3 以及用于可提示概念分割的新基准 Segment Anything with Concepts (SA-Co)。*

该模型由 [yonigozlan](https://huggingface.co/yonigozlan) 和 [ronghanghu](https://huggingface.co/ronghanghu) 贡献。

## 使用示例

### 视频分割与跟踪

#### 预加载视频推理

使用文本提示词处理所有帧均已可用的视频：

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

你还可以通过提供多个提示来同时跟踪多个对象类别。该模型会高效地跨所有提示复用视觉特征：

```python
# 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 支持在视频帧到达时进行处理：

```python
# 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 分辨率使用。

如需更快的推理速度或更低的内存占用：

```python
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[[transformers.Sam3VideoConfig]]

#### transformers.Sam3VideoConfig[[transformers.Sam3VideoConfig]]

```python
transformers.Sam3VideoConfig(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, detector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, tracker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, initializer_range: float = 0.02, low_res_mask_size: int = 288, score_threshold_detection: float = 0.5, det_nms_thresh: float = 0.1, assoc_iou_thresh: float = 0.1, trk_assoc_iou_thresh: float = 0.5, new_det_thresh: float = 0.7, recondition_on_trk_masks: bool = True, hotstart_delay: int = 15, hotstart_unmatch_thresh: int = 8, hotstart_dup_thresh: int = 8, suppress_unmatched_only_within_hotstart: bool = True, init_trk_keep_alive: int = 30, max_trk_keep_alive: int = 30, min_trk_keep_alive: int = -1, suppress_overlapping_based_on_recent_occlusion_threshold: float = 0.7, decrease_trk_keep_alive_for_empty_masklets: bool = False, fill_hole_area: int = 16, max_num_objects: int = 10000, recondition_every_nth_frame: int = 16, high_conf_thresh: float = 0.8, high_iou_thresh: float = 0.8)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/configuration_sam3_video.py#L28)

**参数：**

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（非极大值抑制）的 IoU 阈值。

assoc_iou_thresh (`float`, *可选*，默认为 0.1)：用于检测与轨迹匹配的 IoU 阈值。如果检测框与轨迹片段的重叠度高于此阈值，则该检测被视为与该轨迹片段“匹配”。通常使用 0.1 这样的宽松阈值。

trk_assoc_iou_thresh (`float`, *可选*，默认为 0.5)：用于检测与轨迹匹配的 IoU 阈值，用于确定某个 masklet 是否未被任何检测匹配。通常使用更严格的阈值，例如 0.5。

new_det_thresh (`float`, *可选*，默认为 0.7)：检测被添加为新对象的概率阈值。

recondition_on_trk_masks (`bool`, *可选*，默认为 `True`) : 是否使用跟踪掩码（True）或检测掩码（False）进行再条件化。当跟踪掩码质量更高，且检测器作为验证信号以增强记忆并防止漂移时，请使用 True。

hotstart_delay (`int`，*可选*，默认为 15)：在热启动期间缓冲输出的帧数。我们会将输出延迟 `hotstart_delay` 帧，并根据热启动启发式规则移除 tracklet。

hotstart_unmatch_thresh (`int`，*可选*，默认为 8)：在热启动期间，移除 tracklet 所需的未匹配帧数。

hotstart_dup_thresh (`int`，*可选*，默认为 8)：在热启动期间，用于移除重复 tracklet 所需的重叠帧数。

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)：最小保活计数器值。与未匹配检测关联的跟踪器，其计数器值将被降低至该值。

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)：用于重条件化的高置信度阈值。只有高于此阈值的检测结果才能对 tracklet 进行重条件化。

high_iou_thresh (`float`, *可选*，默认为 0.8)：用于重新条件化的高 IoU 阈值。只有 IoU 高于此阈值的检测才能重新条件化 tracklet。

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

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：
```python
>>> 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[[transformers.Sam3VideoProcessor]]

#### transformers.Sam3VideoProcessor[[transformers.Sam3VideoProcessor]]

```python
transformers.Sam3VideoProcessor(image_processor, video_processor, tokenizer, target_size: int | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/processing_sam3_video.py#L39)

**参数：**

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

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

tokenizer (`CLIPTokenizer`)：分词器是必需的输入。

target_size (`int`, *可选*) : 图像将被调整到的目标尺寸 (target_size, target_size)。

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

[Sam3VideoProcessor](/docs/transformers/main/zh/model_doc/sam3_video#transformers.Sam3VideoProcessor) 提供了 [Sam3ImageProcessor](/docs/transformers/main/zh/model_doc/sam3#transformers.Sam3ImageProcessor)、`video_processor_class` 和 [CLIPTokenizer](/docs/transformers/main/zh/model_doc/clip#transformers.CLIPTokenizer) 的所有功能。有关更多信息，请参阅 [~Sam3ImageProcessor](/docs/transformers/main/zh/model_doc/sam3#transformers.Sam3ImageProcessor)、`~video_processor_class` 和 [~CLIPTokenizer](/docs/transformers/main/zh/model_doc/clip#transformers.CLIPTokenizer)。

#### __调用__[[transformers.Sam3VideoProcessor.__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, 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/sam3_video/processing_sam3_video.py#L55)

**参数：**

images (`ImageInput`, *可选*) : 要处理的图像。

segmentation_maps (`ImageInput`，*可选*)：要处理的分割图（可选，用于图像处理器）。

original_sizes (`list[list[float]]`、`torch.Tensor`、*可选*)：图像的原始尺寸。仅在未提供 images 时使用。

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

**返回：** 一个包含以下字段的 [BatchEncoding](/docs/transformers/main/zh/main_classes/tokenizer#transformers.BatchEncoding)

- `pixel_values` (`torch.Tensor`)：处理后的图像。
- `original_sizes` (`list[list[float]]`)：图像的原始尺寸。
- `labels`（`torch.Tensor`，*可选*）：处理后的分割掩码（如果已提供）。

#### postprocess_outputs[[transformers.Sam3VideoProcessor.postprocess_outputs]]

```python
postprocess_outputs(inference_session, model_outputs, original_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/processing_sam3_video.py#L247)

**参数：**

inference_session (`Sam3VideoInferenceSession`)：推理会话对象。

model_outputs (`Sam3VideoSegmentationOutput`)：`Sam3VideoModel.forward()` 的原始模型输出。

original_sizes (`list[list[float]]` 或 `torch.Tensor`，*可选*)：可选的原始帧尺寸 [height, width]。当会话中未设置 video_height/video_width 时，流式推理需要此参数。

**返回：** `dict`

包含以下键的字典：
- **object_ids**（形状为 `(num_objects,)` 的 `torch.Tensor`）：每个检测到的对象的 ID。
- **scores**（形状为 `(num_objects,)` 的 `torch.Tensor`）：每个检测对象的置信度分数。
- **boxes**（形状为 `(num_objects, 4)` 的 `torch.Tensor`）：XYXY 格式的边界框（top_left_x, top_left_y, bottom_right_x, bottom_right_y）。
- **masks**（形状为 `(num_objects, height, width)` 的 `torch.Tensor`）：原始视频分辨率下每个对象的二值分割掩码。
- **prompt_to_obj_ids** (`dict[str, list[int]]`)：从提示文本到该提示检测到的对象 ID 列表的映射。

对模型输出进行后处理，以获取最终的掩码、边界框和分数。

#### init_video_session[[transformers.Sam3VideoProcessor.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/sam3_video/processing_sam3_video.py#L133)

**参数：**

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_text_prompt[[transformers.Sam3VideoProcessor.add_text_prompt]]

```python
add_text_prompt(inference_session: Sam3VideoInferenceSession, text: str | list[str])
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/processing_sam3_video.py#L101)

**参数：**

inference_session (`Sam3VideoInferenceSession`)：推理会话。

text (`str` 或 `list[str]`) : 要添加的文本提示。

**返回：** `Sam3VideoInferenceSession`

添加了文本提示的推理会话。

向推理会话添加文本提示。

## Sam3VideoInferenceSession[[transformers.Sam3VideoInferenceSession]]

#### transformers.Sam3VideoInferenceSession[[transformers.Sam3VideoInferenceSession]]

```python
transformers.Sam3VideoInferenceSession(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/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L119)

**参数：**

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.Sam3VideoInferenceSession.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/sam3_video/modeling_sam3_video.py#L255)

添加掩码输入，并自动进行设备放置。

#### add_new_frame[[transformers.Sam3VideoInferenceSession.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/sam3_video/modeling_sam3_video.py#L384)

添加新帧并自动进行设备放置。

#### add_prompt[[transformers.Sam3VideoInferenceSession.add_prompt]]

```python
add_prompt(prompt_text: str)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L215)

向会话添加文本提示并返回其唯一 ID。如果该提示已存在，则返回现有的 ID。

#### get_frame[[transformers.Sam3VideoInferenceSession.get_frame]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L400)

从视频中获取帧。

#### get_obj_num[[transformers.Sam3VideoInferenceSession.get_obj_num]]

```python
get_obj_num()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L251)

获取当前会话中已接收到的唯一对象 ID 总数。

#### get_output[[transformers.Sam3VideoInferenceSession.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/sam3_video/modeling_sam3_video.py#L357)

**参数：**

obj_idx (int)：对象的索引。

frame_idx (int)：帧的索引。

output_key (str) : 输出的键。

is_conditioning_frame (bool) : 输出是否用于条件帧。

通过智能设备管理获取输出。

#### obj_id_to_idx[[transformers.Sam3VideoInferenceSession.obj_id_to_idx]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L229)

将对象 ID 映射到索引，如有必要则创建新条目。

#### obj_idx_to_id[[transformers.Sam3VideoInferenceSession.obj_idx_to_id]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L247)

将模型端的对象索引映射到客户端的对象 ID。

#### remove_mask_inputs[[transformers.Sam3VideoInferenceSession.remove_mask_inputs]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L261)

移除 mask 输入。

#### remove_object[[transformers.Sam3VideoInferenceSession.remove_object]]

```python
remove_object(obj_id: int, strict: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L265)

**参数：**

obj_id (`int`) : 要移除的对象 ID。

strict (`bool`，*可选*，默认为 `False`)：如果对象不存在，是否引发错误。

从推理会话中移除一个对象。这将把该对象从视频的所有帧中移除。

#### reset_inference_session[[transformers.Sam3VideoInferenceSession.reset_inference_session]]

```python
reset_inference_session()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L416)

重置跟踪数据和缓存。

#### reset_state[[transformers.Sam3VideoInferenceSession.reset_state]]

```python
reset_state()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L428)

重置推理会话状态。

#### reset_tracking_data[[transformers.Sam3VideoInferenceSession.reset_tracking_data]]

```python
reset_tracking_data()
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L404)

重置跟踪数据，但保留缓存。

#### store_output[[transformers.Sam3VideoInferenceSession.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/sam3_video/modeling_sam3_video.py#L320)

**参数：**

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，则输出将以字典形式存储。

## Sam3VideoSegmentationOutput[[transformers.Sam3VideoSegmentationOutput]]

#### transformers.Sam3VideoSegmentationOutput[[transformers.Sam3VideoSegmentationOutput]]

```python
transformers.Sam3VideoSegmentationOutput(object_ids: list[int] | None = None, obj_id_to_mask: dict[int, torch.Tensor] | None = None, obj_id_to_score: dict[int, float] | None = None, obj_id_to_tracker_score: dict[int, float] | None = None, removed_obj_ids: set[int] | None = None, suppressed_obj_ids: set[int] | None = None, frame_idx: int | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L462)

**参数：**

object_ids (`list[int]`, *可选*) : 当前帧中正在跟踪的对象 ID 列表。

obj_id_to_mask (`dict[int, torch.Tensor]`, *可选*) : 将对象 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[[transformers.Sam3VideoModel]]

#### transformers.Sam3VideoModel[[transformers.Sam3VideoModel]]

```python
transformers.Sam3VideoModel(config: Sam3VideoConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L507)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.Sam3VideoModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L1693)

**参数：**

inference_session (`~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession`)：视频推理会话对象。

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

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

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

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

#### propagate_in_video_iterator[[transformers.Sam3VideoModel.propagate_in_video_iterator]]

```python
propagate_in_video_iterator(inference_session: Sam3VideoInferenceSession, start_frame_idx: int = 0, 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/sam3_video/modeling_sam3_video.py#L1784)

**参数：**

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](/docs/transformers/main/zh/model_doc/sam3_video#transformers.Sam3VideoSegmentationOutput) 或 `tuple(torch.Tensor)`

一个 [Sam3VideoSegmentationOutput](/docs/transformers/main/zh/model_doc/sam3_video#transformers.Sam3VideoSegmentationOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[Sam3VideoConfig](/docs/transformers/main/zh/model_doc/sam3_video#transformers.Sam3VideoConfig)）和输入。

将提示传播以获取整个视频的 grounding 结果。在初始化包含完整视频的推理会话时使用。为每一帧生成 Sam3VideoSegmentationOutput。

- **object_ids** (`list[int]`，*可选*) -- 当前帧中正在跟踪的对象 ID 列表。
- **obj_id_to_mask** (`dict[int, torch.Tensor]`, *可选*) -- 将对象 ID 映射到其预测的低分辨率掩码的字典。每个掩码的形状为 `(1, H_low, W_low)`。
- **obj_id_to_score** (`dict[int, float]`，*可选*) -- 将对象 ID 映射到其检测分数的字典。
- **obj_id_to_tracker_score** (`dict[int, float]`, *optional*) -- Dictionary mapping object IDs to their tracker scores for the current frame.
- **removed_obj_ids** (`set[int]`，*可选*) -- 已移除的对象 ID 集合（例如，通过热启动启发式方法移除）。
- **suppressed_obj_ids** (`set[int]`，*可选*) -- 当前帧中已被抑制的对象 ID 集合。
- **frame_idx** (`int`, *可选*) -- 视频的帧索引。

