Transformers documentation

SAM3 视频

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2025-11-19 贡献至 Hugging Face Transformers。

SAM3 视频

SDPA FlashAttention

概述

SAM3(Segment Anything Model 3)在 SAM 3: Segment Anything with Concepts 中提出。

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

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

该论文的摘要如下:

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

该模型由 yonigozlan 和 ronghanghu 贡献。

使用示例

视频分割与跟踪

预加载视频推理

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

from transformers import Sam3VideoModel, Sam3VideoProcessor
import torch

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

# Load video frames
from transformers.video_utils import load_video
video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4"
video_frames, _ = load_video(video_url)

# Initialize video inference session
inference_session = processor.init_video_session(
    video=video_frames,
    inference_device=device,
    processing_device="cpu",
    video_storage_device="cpu",
)

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

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

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

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

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

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

流式视频推理

⚠️ **关于流式推理质量的说明**:流式推理会禁用热启动启发式策略,该策略用于移除未匹配和重复的对象,因为这类决策需要访问未来帧才能做出。与预加载视频推理相比,这可能会导致更多的误检和重复的对象轨迹。为了获得最佳效果,当所有帧均可用时,请使用预加载视频推理。

对于实时应用,SAM3 Video 支持在视频帧到达时进行处理:

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

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

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

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

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

自定义分辨率推理

⚠️ **性能说明**:自定义分辨率可能会降低精度。该模型旨在以 1008px 分辨率使用。

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

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

Sam3VideoConfig

class transformers.Sam3VideoConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonedetector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetracker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinitializer_range: float = 0.02low_res_mask_size: int = 288score_threshold_detection: float = 0.5det_nms_thresh: float = 0.1assoc_iou_thresh: float = 0.1trk_assoc_iou_thresh: float = 0.5new_det_thresh: float = 0.7recondition_on_trk_masks: bool = Truehotstart_delay: int = 15hotstart_unmatch_thresh: int = 8hotstart_dup_thresh: int = 8suppress_unmatched_only_within_hotstart: bool = Trueinit_trk_keep_alive: int = 30max_trk_keep_alive: int = 30min_trk_keep_alive: int = -1suppress_overlapping_based_on_recent_occlusion_threshold: float = 0.7decrease_trk_keep_alive_for_empty_masklets: bool = Falsefill_hole_area: int = 16max_num_objects: int = 10000recondition_every_nth_frame: int = 16high_conf_thresh: float = 0.8high_iou_thresh: float = 0.8 )

参数

  • detector_config (dict 或 Sam3Config,可选) — Sam3 检测器模型的配置。如果未提供,将使用默认的 Sam3Config。
  • tracker_config (dict 或 Sam2VideoConfig,可选) — Sam2Video 跟踪器模型的配置。如果未提供,将使用默认的 Sam2VideoConfig。
  • initializer_range (float,可选,默认值为 0.02) — 用于初始化权重矩阵的 truncated_normal_initializer 的标准差。
  • low_res_mask_size (int,可选,默认为 288) — 跟踪器在上采样至视频分辨率之前,低分辨率掩码输出的尺寸(高度和宽度)。
  • score_threshold_detection (float,可选,默认为 0.5) — 检测输出的概率阈值 - 仅保留高于此阈值的检测结果。
  • det_nms_thresh (float,可选,默认值为 0.1) — 检测 NMS(非极大值抑制)的 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) — 是否仅在 hotstart 期间内抑制掩码。如果为 False,即使掩码在 hotstart 期间之前开始,也可以抑制它们。
  • 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) — 基于最近遮挡情况来抑制重叠对象的阈值。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 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import Sam3VideoConfig, Sam3VideoModel

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

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

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

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

Sam3VideoProcessor

class transformers.Sam3VideoProcessor

< >

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

参数

  • image_processor (Sam3ImageProcessor) — 图像处理器是必需的输入。
  • video_processor (video_processor_class) — 视频处理器是必需的输入。
  • tokenizer (CLIPTokenizer) — 分词器是必需的输入。
  • target_size (int, 可选) — 图像将被调整到的目标尺寸 (target_size, target_size)。

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

Sam3VideoProcessor 提供了 Sam3ImageProcessor、video_processor_class 和 CLIPTokenizer 的所有功能。有关更多信息,请参阅 ~Sam3ImageProcessor、~video_processor_class 和 ~CLIPTokenizer。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonesegmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Noneoriginal_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = None**kwargs ) → A BatchEncoding with the following fields

参数

  • images(ImageInput,可选)— 要处理的图像。
  • segmentation_maps (ImageInput,可选) — 要处理的分割图(可选,用于图像处理器)。
  • original_sizes (list[list[float]]、torch.Tensor、可选) — 图像的原始尺寸。仅在未提供 images 时使用。
  • return_tensors (Union[str, ~utils.generic.TensorType], 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。

返回值

一个包含以下字段的 BatchEncoding

  • pixel_values (torch.Tensor):处理后的图像。
  • original_sizes (list[list[float]]):图像的原始尺寸。
  • labels(torch.Tensor,可选):处理后的分割掩码(如果已提供)。

postprocess_outputs

< >

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

参数

  • inference_session (Sam3VideoInferenceSession) — 推理会话对象。
  • model_outputs (Sam3VideoSegmentationOutput) — Sam3VideoModel.forward() 的原始模型输出。
  • original_sizes (list[list[float]] 或 torch.Tensor,可选) — 可选的原始帧尺寸 [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

< >

( video: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneinference_device: typing.Union[str, ForwardRef('torch.device')] = 'cpu'inference_state_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Noneprocessing_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Nonevideo_storage_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Nonemax_vision_features_cache_size: int = 1dtype: dtype = torch.float32 )

参数

  • video (VideoInput,可选) — 要处理的视频。在流式处理时无需提供。
  • inference_device(str 或 torch.device,可选,默认为 “cpu”)— 用于推理的设备。
  • inference_state_device (str 或 torch.device,可选) — 用于存储推理状态的设备。
  • processing_device (str 或 torch.device,可选) — 用于视频处理的设备。
  • video_storage_device (str 或 torch.device,可选) — 用于存储处理后视频帧的设备。
  • max_vision_features_cache_size (int,可选,默认为 1) — 要缓存的视觉特征的最大数量。
  • dtype(torch.dtype,可选,默认为 torch.float32)— 用于整个会话的 torch dtype。

初始化用于推理的视频会话。 如果提供了视频(异步推理),该视频将被处理并存储在 video_storage_device 上。

add_text_prompt

< >

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

参数

  • inference_session (Sam3VideoInferenceSession) — 推理会话。
  • text (str 或 list[str]) — 要添加的文本提示。

返回值

Sam3VideoInferenceSession

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

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

Sam3VideoInferenceSession

class transformers.Sam3VideoInferenceSession

< >

( video: typing.Optional[torch.Tensor] = Nonevideo_height: int | None = Nonevideo_width: int | None = Noneinference_device: typing.Union[torch.device, str] = 'cpu'inference_state_device: typing.Union[torch.device, str] = 'cpu'video_storage_device: typing.Union[torch.device, str] = 'cpu'dtype: typing.Union[torch.dtype, str] = 'float32'max_vision_features_cache_size: int = 1 )

参数

  • video (torch.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

< >

( obj_idx: intframe_idx: intinputs: Tensor )

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

add_new_frame

< >

( pixel_values: Tensorframe_idx: int | None = None )

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

add_prompt

< >

( prompt_text: str )

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

get_frame

< >

( frame_idx: int )

从视频中获取帧。

get_obj_num

< >

( )

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

get_output

< >

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

参数

  • obj_idx (int) — 对象的索引。
  • frame_idx (int) — 帧的索引。
  • output_key (str) — 输出的键。
  • is_conditioning_frame (bool) — 输出是否用于条件帧。

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

obj_id_to_idx

< >

( obj_id: int )

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

obj_idx_to_id

< >

( obj_idx: int )

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

remove_mask_inputs

< >

( obj_idx: intframe_idx: int )

移除 mask 输入。

remove_object

< >

( obj_id: intstrict: bool = False )

参数

  • obj_id (int) — 要删除的对象 ID。
  • strict(bool,可选,默认为 False)—— 如果对象不存在,是否抛出错误。

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

reset_inference_session

< >

( )

重置跟踪数据和缓存。

reset_state

< >

( )

重置推理会话状态。

reset_tracking_data

< >

( )

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

store_output

< >

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

参数

  • obj_idx (int) — 对象的索引。
  • frame_idx (int) — 帧的索引。
  • output_key (Optional[str]) — 输出的键。如果为 None,输出将存储为字典。
  • output_value (Optional[Union[torch.Tensor, dict]]) — 输出的值。
  • is_conditioning_frame (bool) — 输出是否用于条件帧。

使用智能设备管理来存储输出。 如果 output_key 为 None,则输出将以字典形式存储。

Sam3VideoSegmentationOutput

class transformers.Sam3VideoSegmentationOutput

< >

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

参数

  • object_ids (list[int], 可选) — 当前帧中正在跟踪的对象 ID 列表。
  • obj_id_to_mask (dict[int, torch.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

class transformers.Sam3VideoModel

< >

( config: Sam3VideoConfig )

参数

  • config (Sam3VideoConfig) — 模型的配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

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

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

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

参数

  • inference_session (~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession) — 视频推理会话对象。
  • frame_idx (int, 可选) — 用于执行推理的帧索引。在对新的流式帧进行推理时无需提供。
  • frame (torch.Tensor, 可选) — 要处理的帧。在流式处理时提供。
  • reverse (bool,可选,默认为 False) — 是否反向传播。

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

propagate_in_video_iterator

< >

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

参数

  • inference_session (~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession) — 视频推理会话对象。
  • start_frame_idx (int,可选,默认为 0) — 用于传播的起始帧索引。
  • max_frame_num_to_track (int, 可选) — 要跟踪的最大帧数。如果未提供,将跟踪视频中的所有帧。
  • reverse (bool,可选,默认为 False) — 是否反向传播。
  • show_progress_bar (bool,可选,默认为 False) — 是否在传播过程中显示进度条。

返回值

Sam3VideoSegmentationOutput 或 tuple(torch.Tensor)

一个 Sam3VideoSegmentationOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Sam3VideoConfig)和输入。

将提示传播以获取整个视频的定位结果。在初始化包含完整视频的推理会话时使用。 为每一帧生成 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, 可选) — 视频的帧索引。
Update on GitHub