> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/shi-jue-mo-xing/sam2-video.md).

# SAM2 视频

在 Clore.ai 上使用 Meta 的 SAM2 跟踪并分割视频中的对象

借助 Meta 的 SAM2.1 跟踪并分割视频中的任意对象——SAM2 的改进版，具备更高的视频精度。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

{% hint style="info" %}
本指南中的所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace) 市场。
{% endhint %}

## 在 CLORE.AI 上租用

1. 访问 [CLORE.AI 市场](https://clore.ai/marketplace)
2. 按 GPU 类型、VRAM 和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价）
4. 配置你的订单：
   * 选择 Docker 镜像
   * 设置端口（SSH 用 TCP，Web UI 用 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问你的服务器

* 在以下位置查找连接信息 **我的订单**
* Web 界面：使用 HTTP 端口 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 SAM2？

Meta AI 的 SAM2（Segment Anything Model 2）可实现：

* 实时视频对象分割
* 点击即可跟踪任意对象
* 在遮挡情况下保持一致跟踪
* 内存高效的视频处理

## SAM2.1 有哪些新特性

与原始 SAM2 相比，SAM2.1 带来了显著改进：

* **提升的视频精度** — 在遮挡和快速运动下具有更好的跟踪能力
* **增强的记忆模块** — 更一致的长距离跟踪
* **新检查点** — `sam2.1_hiera_*` 系列，性能更好
* **官方 pip 包** — 使用以下命令安装 `pip install sam-2` （无需手动构建）
* **更快的推理** — 优化的 CUDA 内核

## 资源

* **GitHub：** [facebookresearch/sam2](https://github.com/facebookresearch/sam2)
* **论文：** [SAM2 论文](https://arxiv.org/abs/2408.00714)
* **演示：** [SAM2 演示](https://sam2.metademolab.com/)
* **模型权重：** [SAM2.1 检查点](https://github.com/facebookresearch/sam2#model-checkpoints)

## 推荐硬件

| 组件  | 最低            | 推荐            | 最佳            |
| --- | ------------- | ------------- | ------------- |
| GPU | RTX 3060 12GB | RTX 4080 16GB | RTX 4090 24GB |
| 显存  | 8GB           | 16GB          | 24GB          |
| CPU | 4 核           | 8 核           | 16 核          |
| 内存  | 16GB          | 32GB          | 64GB          |
| 存储  | 30GB SSD      | 50GB NVMe     | 100GB NVMe    |
| 网络  | 100 Mbps      | 500 Mbps      | 1 Gbps        |

## 在 CLORE.AI 上快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
```

**端口：**

```
22/tcp
7860/http
```

**命令：**

```bash
cd /workspace && \
pip install sam-2 && \
python -c "from sam2.build_sam import build_sam2; print('SAM2.1 已就绪！')"
```

## 访问你的服务

部署后，找到你的 `http_pub` URL 在 **我的订单**:

1. 前往 **我的订单** 页面
2. 点击你的订单
3. 找到 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 替代 `localhost` 在下面的示例中。

## 安装

```bash
# 官方 pip 包（推荐用于 SAM2.1）
pip install sam-2

# 下载 SAM2.1 检查点
python -c "
from sam2.utils.misc import download_file_with_progress

checkpoints = [
    ('https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_tiny.pt', 'checkpoints/sam2.1_hiera_tiny.pt'),
    ('https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_small.pt', 'checkpoints/sam2.1_hiera_small.pt'),
    ('https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_base_plus.pt', 'checkpoints/sam2.1_hiera_base_plus.pt'),
    ('https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_large.pt', 'checkpoints/sam2.1_hiera_large.pt'),
]
"

# 或使用下载脚本
mkdir -p checkpoints && cd checkpoints
wget https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_large.pt
```

### 替代方案：从源代码构建（用于开发）

```bash
git clone https://github.com/facebookresearch/sam2.git
cd sam2
pip install -e ".[demo]"

# 下载 SAM2.1 检查点
cd checkpoints
bash download_ckpts.sh
```

## 你可以创建什么

### 视频编辑

* 从视频中移除对象
* 无缝替换背景
* 用于合成的视频遮罩

### 体育分析

* 跟踪比赛中的球员
* 分析运动模式
* 生成精彩集锦

### 医疗影像

* 在 CT/MRI 视频中分割器官
* 跟踪显微镜下的细胞运动
* 测量随时间的增长

### 监控与安全

* 跨摄像头跟踪对象
* 统计人数/车辆
* 异常检测

### 创意项目

* 用于 VFX 的转描
* 交互式视频装置
* AR/VR 内容创作

## 基础用法

### 图像分割

```python
import torch
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor
from PIL import Image
import numpy as np

# 加载 SAM2.1 模型（比 SAM2 具有更高精度）
checkpoint = "./checkpoints/sam2.1_hiera_large.pt"
model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"

sam2 = build_sam2(model_cfg, checkpoint, device="cuda")
predictor = SAM2ImagePredictor(sam2)

# 加载图像
image = np.array(Image.open("image.jpg"))
predictor.set_image(image)

# 使用点提示进行分割
point_coords = np.array([[500, 375]])  # x, y 坐标
point_labels = np.array([1])  # 1 = 前景

masks, scores, logits = predictor.predict(
    point_coords=point_coords,
    point_labels=point_labels,
    multimask_output=True
)

# 获取最佳遮罩
best_mask = masks[scores.argmax()]
```

### 视频对象跟踪

```python
import torch
from sam2.build_sam import build_sam2_video_predictor
import numpy as np

# 初始化 SAM2.1 视频预测器（提高跟踪精度）
checkpoint = "./checkpoints/sam2.1_hiera_large.pt"
model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"

predictor = build_sam2_video_predictor(model_cfg, checkpoint, device="cuda")

# 使用视频初始化
video_path = "./video_frames"  # 帧图像目录
inference_state = predictor.init_state(video_path=video_path)

# 在第一帧上添加点
predictor.reset_state(inference_state)
frame_idx = 0
obj_id = 1  # 跟踪对象 ID

points = np.array([[400, 300]], dtype=np.float32)
labels = np.array([1], dtype=np.int32)

# 添加要跟踪的对象
_, out_obj_ids, out_mask_logits = predictor.add_new_points_or_box(
    inference_state=inference_state,
    frame_idx=frame_idx,
    obj_id=obj_id,
    points=points,
    labels=labels
)

# 在视频中传播
video_segments = {}
for out_frame_idx, out_obj_ids, out_mask_logits in predictor.propagate_in_video(inference_state):
    video_segments[out_frame_idx] = {
        obj_id: (out_mask_logits[i] > 0.0).cpu().numpy()
        for i, obj_id in enumerate(out_obj_ids)
    }
```

## 多对象跟踪

```python
import torch
from sam2.build_sam import build_sam2_video_predictor
import numpy as np

predictor = build_sam2_video_predictor(
    "configs/sam2.1/sam2.1_hiera_l.yaml",
    "./checkpoints/sam2.1_hiera_large.pt",
    device="cuda"
)

video_path = "./video_frames"
inference_state = predictor.init_state(video_path=video_path)

# 跟踪多个对象
objects_to_track = [
    {"id": 1, "point": [200, 150], "frame": 0},  # 人物 1
    {"id": 2, "point": [400, 200], "frame": 0},  # 人物 2
    {"id": 3, "point": [600, 300], "frame": 0},  # 球
]

for obj in objects_to_track:
    predictor.add_new_points_or_box(
        inference_state=inference_state,
        frame_idx=obj["frame"],
        obj_id=obj["id"],
        points=np.array([obj["point"]], dtype=np.float32),
        labels=np.array([1], dtype=np.int32)
    )

# 传播所有对象
all_masks = {}
for frame_idx, obj_ids, mask_logits in predictor.propagate_in_video(inference_state):
    all_masks[frame_idx] = {}
    for i, obj_id in enumerate(obj_ids):
        all_masks[frame_idx][obj_id] = (mask_logits[i] > 0.0).cpu().numpy()
```

## 框提示分割

```python
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor
import numpy as np
from PIL import Image

sam2 = build_sam2(
    "configs/sam2.1/sam2.1_hiera_l.yaml",
    "./checkpoints/sam2.1_hiera_large.pt",
    device="cuda"
)
predictor = SAM2ImagePredictor(sam2)

image = np.array(Image.open("image.jpg"))
predictor.set_image(image)

# 使用边界框进行分割
box = np.array([100, 100, 400, 400])  # x1, y1, x2, y2

masks, scores, _ = predictor.predict(
    box=box,
    multimask_output=False
)
```

## Gradio 界面

```python
import gradio as gr
import numpy as np
from PIL import Image
import torch
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor

sam2 = build_sam2(
    "configs/sam2.1/sam2.1_hiera_l.yaml",
    "./checkpoints/sam2.1_hiera_large.pt",
    device="cuda"
)
predictor = SAM2ImagePredictor(sam2)

def segment_image(image, x, y):
    predictor.set_image(np.array(image))

    masks, scores, _ = predictor.predict(
        point_coords=np.array([[x, y]]),
        point_labels=np.array([1]),
        multimask_output=True
    )

    best_mask = masks[scores.argmax()]

    # 创建叠加层
    overlay = np.array(image).copy()
    overlay[best_mask] = overlay[best_mask] * 0.5 + np.array([255, 0, 0]) * 0.5

    return Image.fromarray(overlay.astype(np.uint8))

demo = gr.Interface(
    fn=segment_image,
    inputs=[
        gr.Image(type="pil", label="输入图像"),
        gr.Number(label="X 坐标"),
        gr.Number(label="Y 坐标")
    ],
    outputs=gr.Image(label="分割后的图像"),
    title="SAM2 - Segment Anything",
    description="点击坐标以分割对象。在 CLORE.AI GPU 服务器上运行。"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## 将遮罩导出为视频

```python
import cv2
import numpy as np
from sam2.build_sam import build_sam2_video_predictor

predictor = build_sam2_video_predictor(
    "configs/sam2.1/sam2.1_hiera_l.yaml",
    "./checkpoints/sam2.1_hiera_large.pt",
    device="cuda"
)

# ...（上面的跟踪代码）

# 导出为视频
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output_masks.mp4', fourcc, 30.0, (width, height))

for frame_idx in sorted(video_segments.keys()):
    frame = cv2.imread(f"./video_frames/{frame_idx:05d}.jpg")

    # 应用遮罩叠加
    for obj_id, mask in video_segments[frame_idx].items():
        color = [0, 255, 0] if obj_id == 1 else [0, 0, 255]
        frame[mask.squeeze()] = frame[mask.squeeze()] * 0.5 + np.array(color) * 0.5

    out.write(frame.astype(np.uint8))

out.release()
```

## 性能

| 任务     | 分辨率       | GPU      | 速度   |
| ------ | --------- | -------- | ---- |
| 图像分割   | 1024x1024 | RTX 3090 | 50ms |
| 图像分割   | 1024x1024 | RTX 4090 | 30毫秒 |
| 视频（每帧） | 720p      | RTX 4090 | 45毫秒 |
| 视频（每帧） | 1080p     | A100     | 35ms |

## 模型变体（SAM2.1）

SAM2.1 引入了新的 `sam2.1_hiera_*` 检查点，其视频跟踪精度有所提升：

| 模型                        | 参数       | 显存       | 速度     | 质量     | 检查点                          |
| ------------------------- | -------- | -------- | ------ | ------ | ---------------------------- |
| sam2.1\_hiera\_tiny       | 38M      | 4GB      | 最快     | 好      | sam2.1\_hiera\_tiny.pt       |
| sam2.1\_hiera\_small      | 46M      | 5GB      | 快      | 更好     | sam2.1\_hiera\_small.pt      |
| sam2.1\_hiera\_base\_plus | 80M      | 8GB      | 中等     | 很高     | sam2.1\_hiera\_base\_plus.pt |
| **sam2.1\_hiera\_large**  | **224M** | **12GB** | **较慢** | **最佳** | **sam2.1\_hiera\_large.pt**  |

> **注意：** 在视频基准测试中，SAM2.1 模型始终优于其 SAM2 对应模型，尤其是在快速移动对象和长时间遮挡方面。

## 常见问题与解决方案

### 内存不足

**问题：** 长视频出现 CUDA 显存不足

**解决方案：**

```python

# 分块处理
chunk_size = 100  # 每个分块的帧数

for start_frame in range(0, total_frames, chunk_size):
    end_frame = min(start_frame + chunk_size, total_frames)
    # 处理分块...
    torch.cuda.empty_cache()  # 在分块之间清理内存
```

### 跟踪丢失

**问题：** 对象跟踪在视频中途失败

**解决方案：**

* 当跟踪漂移时添加修正点
* 使用框提示以获得更好的初始分割
* 选择更清晰的初始帧

```python

# 添加修正点
predictor.add_new_points_or_box(
    inference_state=inference_state,
    frame_idx=lost_frame,
    obj_id=obj_id,
    points=np.array([[new_x, new_y]], dtype=np.float32),
    labels=np.array([1], dtype=np.int32)
)
```

### 处理缓慢

**问题：** 视频处理太慢

**解决方案：**

* 使用更小的模型变体（tiny/small）
* 降低视频分辨率
* 启用半精度（fp16）
* 在 A100 GPU 上处理

```python

# 使用更小的 SAM2.1 模型以提速
predictor = build_sam2_video_predictor(
    "configs/sam2.1/sam2.1_hiera_t.yaml",
    "./checkpoints/sam2.1_hiera_tiny.pt",
    device="cuda"
)
```

### 遮罩质量较差

**问题：** 分割边缘较粗糙

**解决方案：**

* 使用更大的模型（large 代替 tiny）
* 添加更多点提示
* 结合点提示和框提示

## 故障排查

### 分割不准确

* 更精确地点击目标对象
* 添加多个正/负点
* 对大型对象使用框提示

### 视频内存错误

* 一次处理更少的帧
* 降低视频分辨率
* 长视频使用流式模式

### 跟踪丢失

* 对象变化时添加更多提示
* 使用记忆库功能
* 检查对象是否被遮挡

### 处理缓慢

* SAM2 计算量很大
* 长视频请使用 A100
* 可考虑跳帧

## 成本估算

CLORE.AI 市场常见费率（截至 2024 年）：

| GPU       | 小时费率    | 日费率     | 4 小时会话  |
| --------- | ------- | ------- | ------- |
| RTX 3060  | \~$0.03 | \~$0.70 | \~$0.12 |
| RTX 3090  | \~$0.06 | \~$1.50 | \~$0.25 |
| RTX 4090  | \~$0.10 | \~$2.30 | \~$0.40 |
| A100 40GB | \~$0.17 | \~$4.00 | \~$0.70 |
| A100 80GB | \~$0.25 | \~$6.00 | \~$1.00 |

*价格因提供商和需求而异。请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

**节省费用：**

* 使用 **竞价** 可中断工作市场——约三分之一的服务器将现货价格定得低于按需价格（中位数约优惠 13%），其余则与按需价格持平
* 使用 **CLORE** 代币支付
* 比较不同提供商的价格

## 下一步

* [GroundingDINO](/guides/guides_v2-zh/shi-jue-mo-xing/groundingdino.md) - 自动检测要分割的对象
* [Florence-2](/guides/guides_v2-zh/shi-jue-mo-xing/florence2.md) - 视觉语言理解
* [Depth Anything](/guides/guides_v2-zh/tu-xiang-chu-li/depth-anything.md) - 深度估计


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/shi-jue-mo-xing/sam2-video.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
