Transformers documentation
SAM2 视频
该模型于 2025-08-14 贡献至 Hugging Face Transformers。
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 中提出。
给定输入图像或视频以及输入点或边界框,该模型可用于预测任意感兴趣对象的分割掩码。

该论文的摘要如下:
我们提出了 Segment Anything Model 2(SAM 2),这是一个旨在解决图像和视频中的可提示视觉分割问题的基础模型。我们构建了一个数据引擎,通过用户交互来改进模型和数据,从而收集了迄今为止规模最大的视频分割数据集。我们的模型采用了一种简单的 Transformer 架构,并配备了用于实时视频处理的流式内存。在我们数据上训练的 SAM 2 在广泛的任务中均表现出强劲的性能。在视频分割方面,我们观察到其精度更高,且所需的交互次数比先前方法减少了 3 倍。在图像分割方面,我们的模型比 Segment Anything Model(SAM)更准确,速度快 6 倍。我们相信,我们的数据、模型和见解将成为视频分割及相关感知任务的重要里程碑。我们将发布我们模型的版本、数据集以及一个交互式演示。
提示:
- 批量与视频支持:SAM2 原生支持批量处理和无缝视频分割,而原始 SAM 专为静态图像和更简单的单张图像处理工作流而设计。
- 准确性与泛化能力:与原始 SAM 相比,SAM2 在分割质量、鲁棒性以及针对新领域的零样本泛化能力方面均有提升,尤其是在使用混合提示时。
该模型由 sangbumchoi 和 yonigozlan 贡献。 原始代码可在此处找到。
使用示例
视频分割与跟踪
SAM2 的核心优势在于其跨视频帧跟踪对象的能力。以下是如何使用它进行视频分割:
基础视频跟踪
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多目标视频跟踪
在视频帧中同时跟踪多个对象:
# 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优化视频分割
您可以在任意帧上添加额外的点击以优化跟踪:
# 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 支持在视频帧到达时进行处理:
# 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}")多对象视频批量处理
通过一次性添加所有对象,在视频中同时跟踪多个对象:
# 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 贡献的用于该模型的 Demo notebook 🌎。
Sam2VideoConfig
class transformers.Sam2VideoConfig
< source >( 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 = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprompt_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonemask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinitializer_range: float = 0.02num_maskmem: int = 7image_size: int | list[int] | tuple[int, int] = 1024sigmoid_scale_for_mem_enc: float = 20.0sigmoid_bias_for_mem_enc: float = -10.0enable_occlusion_spatial_embedding: bool = Truemultimask_output_in_sam: bool = Truemultimask_min_pt_num: int = 0multimask_max_pt_num: int = 1multimask_output_for_tracking: bool = Truemax_object_pointers_in_encoder: int = 16max_cond_frame_num: int = -1enable_temporal_pos_encoding_for_object_pointers: bool = Truememory_attention_hidden_size: int = 256memory_attention_num_layers: int = 4memory_attention_num_attention_heads: int = 1memory_attention_downsample_rate: int = 1memory_attention_feed_forward_hidden_size: int = 2048memory_attention_feed_forward_hidden_act: str = 'relu'memory_attention_dropout: float | int = 0.1memory_attention_rope_feat_sizes: list[int] | None = Nonememory_attention_rope_dropout: float | int = 0.1memory_encoder_hidden_size: int = 256memory_encoder_output_channels: int = 64rope_parameters: dict | None = Nonemask_downsampler_embed_dim: int = 256mask_downsampler_kernel_size: int = 3mask_downsampler_stride: int = 2mask_downsampler_padding: int = 1mask_downsampler_total_stride: int = 16mask_downsampler_hidden_act: str = 'gelu'memory_fuser_num_layers: int = 2memory_fuser_embed_dim: int = 256memory_fuser_intermediate_dim: int = 1024memory_fuser_kernel_size: int = 7memory_fuser_padding: int = 3memory_fuser_layer_scale_init_value: float = 1e-06memory_fuser_hidden_act: str = 'gelu' )
参数
- vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。 - prompt_encoder_config (Union[
dict,Sam2PromptEncoderConfig], 可选) — 用于初始化 Sam2PromptEncoderConfig 的配置选项字典。 - mask_decoder_config (Union[
dict,Sam2MaskDecoderConfig], 可选) — 用于初始化 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的值,并且如果希望使用 RoPE 处理更长的max_position_embeddings,则可选地包含用于缩放的参数。 - 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 中间层的维度。 - memory_fuser_kernel_size (
int,可选,默认为 7) — 内存融合器的卷积核大小。 - memory_fuser_padding (
int, 可选,默认为 3) — 内存融合器的填充值。 - memory_fuser_layer_scale_init_value (
float, 可选,默认为 1e-06) — memory fuser 中层缩放的初始值。 - memory_fuser_hidden_act (
str,可选,默认为"gelu") — 内存融合器中的非线性激活函数。
这是用于存储 Sam2VideoModel 配置的类。它根据指定的参数实例化 Sam2 Video 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/sam2.1-hiera-tiny 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> 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
< source >( 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 = Nonehidden_size: int = 256hidden_act: str = 'gelu'mlp_dim: int = 2048num_hidden_layers: int = 2num_attention_heads: int = 8attention_downsample_rate: int = 2num_multimask_outputs: int = 3iou_head_depth: int = 3iou_head_hidden_dim: int = 256dynamic_multimask_via_stability: bool = Truedynamic_multimask_stability_delta: float = 0.05dynamic_multimask_stability_thresh: float = 0.98 )
参数
- 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 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Sam2VideoPromptEncoderConfig
类 transformers.Sam2VideoPromptEncoderConfig
< source >( 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 = Nonehidden_size: int = 256image_size: int | list[int] | tuple[int, int] = 1024patch_size: int | list[int] | tuple[int, int] = 16mask_input_channels: int = 16num_point_embeddings: int = 4hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06scale: int = 1 )
参数
- 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 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
Sam2VideoProcessor
class transformers.Sam2VideoProcessor
< source >( image_processorvideo_processortarget_size: int | None = Nonepoint_pad_value: int = -10**kwargs )
参数
- image_processor (
Sam2ImageProcessor) — 图像处理器是必需的输入。 - video_processor (
Sam2VideoVideoProcessor) — 视频处理器是必需的输入。 - target_size (
int, 可选) — 用于归一化输入点和边界框的目标尺寸(以像素为单位)。如果未提供,则默认使用图像处理器的大小配置。所有输入坐标(点和框)在传递给模型之前都会归一化到该尺寸。这确保了无论原始图像尺寸如何,坐标表示都保持一致。 - point_pad_value (
int,可选,默认为 -10) — 在对不同长度的序列进行批处理时,用于填充输入点的值。该值用于标记填充位置,并在坐标归一化过程中保持不变。
构造一个 Sam2VideoProcessor,它将图像处理器和视频处理器封装为单一处理器。
Sam2VideoProcessor 提供了 Sam2ImageProcessor 和 Sam2VideoVideoProcessor 的所有功能。有关更多信息,请参阅 ~Sam2ImageProcessor 和 ~Sam2VideoVideoProcessor。
__call__
< source >( 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] = Noneinput_points: typing.Union[list[list[list[list[float]]]], torch.Tensor, NoneType] = Noneinput_labels: typing.Union[list[list[list[int]]], torch.Tensor, NoneType] = Noneinput_boxes: typing.Union[list[list[list[float]]], 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 (
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':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
返回值
一个包含以下字段的 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
< source >( masksoriginal_sizesmask_threshold = 0.0binarize = Truemax_hole_area = 0.0max_sprinkle_area = 0.0apply_non_overlapping_constraints = False**kwargs ) → (torch.Tensor)
参数
- 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) — 用于填充的 sprinkle 的最大面积。 - apply_non_overlapping_constraints (
bool,可选,默认为False) — 是否对掩码应用非重叠约束。
返回值
(torch.Tensor)
格式为 batch_size, num_channels, height, width 的批量掩码,其中 (height, width) 由 original_size 指定。
移除填充并将掩码上采样至原始图像尺寸。
init_video_session
< source >( 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_inputs_to_inference_session
< source >( inference_session: Sam2VideoInferenceSessionframe_idx: intobj_ids: list[int] | intinput_points: typing.Union[list[list[list[list[float]]]], torch.Tensor, NoneType] = Noneinput_labels: typing.Union[list[list[list[int]]], torch.Tensor, NoneType] = Noneinput_boxes: typing.Union[list[list[list[float]]], torch.Tensor, NoneType] = Noneinput_masks: typing.Union[numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneoriginal_size: tuple[int, int] | None = Noneclear_old_inputs: bool = True )
参数
- 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
class transformers.Sam2VideoVideoProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.VideosKwargs'> )
参数
- 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 为 int 时,是否在调整大小时默认使用正方形图像。 - 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':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (VideosKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
构建一个 Sam2VideoVideoProcessor 视频处理器。
post_process_masks
< source >( masksoriginal_sizesreshaped_input_sizesmask_threshold = 0.0binarize = Truepad_size = None ) → (torch.Tensor)
参数
- 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
class transformers.Sam2VideoInferenceSession
< source >( 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) — 要缓存的视觉特征的最大数量。
管理视频推理会话的参数、状态和缓存。
添加掩码输入,并自动进行设备放置。
添加新帧并自动进行设备放置。
添加点输入,并自动进行设备放置。
从视频中获取帧。
获取当前会话中已接收到的唯一对象 ID 总数。
get_output
< source >( obj_idx: intframe_idx: intoutput_key: stris_conditioning_frame: bool = True )
通过智能设备管理获取输出。
将对象 ID 映射到索引,如有必要则创建新条目。
将模型端的对象索引映射到客户端的对象 ID。
移除 mask 输入。
移除点输入。
重置跟踪数据和缓存。
重置跟踪数据,但保留缓存。
store_output
< source >( obj_idx: intframe_idx: intoutput_key: str | None = Noneoutput_value: typing.Union[torch.Tensor, dict, NoneType] = Noneis_conditioning_frame: bool = True )
使用智能设备管理来存储输出。 如果 output_key 为 None,则输出将以字典形式存储。
Sam2VideoModel
class transformers.Sam2VideoModel
< source >( config: Sam2VideoConfig )
参数
- config (Sam2VideoConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Sam2 Video Model,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( inference_session: Sam2VideoInferenceSessionframe_idx: int | None = Noneframe: typing.Optional[torch.Tensor] = Nonereverse: bool = Falserun_mem_encoder: bool = True**kwargs ) → Sam2VideoSegmentationOutput or tuple(torch.Tensor)
参数
- 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)和输入。
通过流式视频帧传播对象。
- 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
< source >( inference_session: Sam2VideoInferenceSessionstart_frame_idx: int | None = Nonemax_frame_num_to_track: int | None = Nonereverse: bool = Falseshow_progress_bar: bool = False ) → Sam2VideoSegmentationOutput or tuple(torch.Tensor)
参数
- 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)和输入。
将对象传播到视频帧中。在初始化包含完整视频的推理会话时使用。 为每一帧生成 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
< source >( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sam2VideoVisionEncoderOutput or tuple(torch.Tensor)
参数
返回值
Sam2VideoVisionEncoderOutput 或 tuple(torch.Tensor)
Sam2VideoVisionEncoderOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Sam2VideoConfig)和输入。
last_hidden_state(形状为
(batch_size, height, width, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 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对应的位置编码。