# YOLOv9/v10 检测

> **最先进的实时目标检测 — 在 GPU 上训练和部署最新的 YOLO 模型**

YOLO（You Only Look Once）仍然是实时目标检测的金标准。YOLOv9 引入了可编程梯度信息（PGI）和广义高效层聚合网络（GELAN），而 YOLOv10 带来了无 NMS 的检测与双标签分配。两者在 NVIDIA GPU 上都在精度/速度权衡上表现出顶级水平。

* **YOLOv9 GitHub：** [WongKinYiu/yolov9](https://github.com/WongKinYiu/yolov9) — 8K+ ⭐
* **YOLOv10 GitHub：** [THU-MIG/yolov10](https://github.com/THU-MIG/yolov10) — 10K+ ⭐
* **Ultralytics（统一版）：** [ultralytics/ultralytics](https://github.com/ultralytics/ultralytics) — 32K+ ⭐

***

## YOLOv9 vs YOLOv10 vs YOLOv8 — 快速比较

| 模型       | mAP50-95 | 速度（A100） | 参数量   | NMS    |
| -------- | -------- | -------- | ----- | ------ |
| YOLOv8x  | 53.9     | 14.2ms   | 68.2M | 需要     |
| YOLOv9e  | 55.6     | 16.8ms   | 57.3M | 需要     |
| YOLOv10x | 54.4     | 10.7ms   | 29.5M | **无需** |
| YOLOv10b | 53.0     | 8.8ms    | 19.1M | **无需** |
| YOLOv10s | 46.8     | 4.2ms    | 7.2M  | **无需** |

{% hint style="success" %}
**YOLOv10 是无 NMS 的** — 无后处理的非极大值抑制步骤。这使得端到端部署成为可能，对边缘/嵌入式场景和 TensorRT 部署尤其有利。
{% endhint %}

***

## 使用场景

* **安防与监控** — 实时人员/车辆/物体检测
* **自动驾驶车辆** — 行人与障碍物检测
* **制造质检** — 生产线缺陷检测
* **零售分析** — 客流与商品检测
* **医学影像** — X 光和扫描中的异常检测
* **体育分析** — 球员与球的跟踪
* **农业** — 作物病害与虫害检测

***

## 先决条件

* Clore.ai 账户并租用 GPU
* 训练数据（用于自定义模型训练）或使用 COCO 预训练权重
* 基本的 Python 和命令行知识

***

## 步骤 1 — 在 Clore.ai 上租用 GPU

1. 前往 [clore.ai](https://clore.ai) → **市场**
2. 根据任务选择 GPU：
   * **仅推理：** RTX 3080/3090 或 RTX 4080 — 优秀的性价比
   * **训练小型模型：** RTX 4090 24GB
   * **训练大型模型（YOLOv9e/YOLOv10x）：** A100 40/80GB

{% hint style="info" %}
**用于实时推理** （视频流），RTX 3090 或 RTX 4090 可根据模型变体提供 100–500 FPS。即使是最小的 YOLOv10n 在 4090 上配合 TensorRT 也能达到 1000+ FPS。
{% endhint %}

***

## 第 2 步 — 部署 Ultralytics 容器

官方 Ultralytics Docker 镜像通过统一 API 支持 YOLOv8、YOLOv9 和 YOLOv10：

**Docker 镜像：**

```
ultralytics/ultralytics:latest
```

**端口：**

```
22
8000
```

**环境变量：**

```
NVIDIA_VISIBLE_DEVICES=all
NVIDIA_DRIVER_CAPABILITIES=compute,utility
```

**磁盘：** 至少 20GB（预训练权重 + 你的数据集）

***

## 第 3 步 — 连接并验证

```bash
ssh root@<server-ip> -p <ssh-port>

# 检查 GPU
nvidia-smi

# 检查 Ultralytics 安装
python3 -c "import ultralytics; ultralytics.checks()"

# 应显示 GPU 信息、CUDA 版本和模型可用性
```

***

## 第 4 步 — 使用预训练模型快速推理

### YOLOv10 推理（无 NMS）

```python
from ultralytics import YOLO
import cv2

# 加载 YOLOv10 模型（若不存在将自动下载）
model = YOLO("yolov10x.pt")  # 可选项：n, s, m, b, l, x

# 在图像上运行推理
results = model("https://ultralytics.com/images/bus.jpg")

# 显示结果
for result in results:
    boxes = result.boxes
    print(f"Detected {len(boxes)} objects")
    for box in boxes:
        cls = int(box.cls[0])
        conf = float(box.conf[0])
        xyxy = box.xyxy[0].tolist()
        print(f"  {model.names[cls]}: {conf:.2f} at {[int(x) for x in xyxy]}")

# 保存带标注的图像
results[0].save("output.jpg")
```

### YOLOv9 推理

```python
from ultralytics import YOLO

# 加载 YOLOv9 模型
model = YOLO("yolov9e.pt")  # 可选项：t, s, m, c, e

# 批量推理以获得最大吞吐量
results = model(
    source=[
        "image1.jpg",
        "image2.jpg",
        "image3.jpg",
    ],
    batch=8,        # 并行处理 8 张图像
    device="cuda",
    conf=0.25,      # 置信度阈值
    iou=0.45,       # NMS IoU 阈值（v10 不需要）
    imgsz=640,
    half=True       # FP16 可实现 2 倍速度提升
)
```

### 实时视频流推理

```python
from ultralytics import YOLO
import cv2

model = YOLO("yolov10s.pt")

# 用于摄像头（device=0）或视频文件
cap = cv2.VideoCapture("input_video.mp4")

# 获取视频属性
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# 输出写入器
out = cv2.VideoWriter(
    "output_video.mp4",
    cv2.VideoWriter_fourcc(*"mp4v"),
    fps,
    (width, height)
)

frame_count = 0
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    
    results = model(frame, conf=0.25, verbose=False)
    annotated = results[0].plot()
    out.write(annotated)
    frame_count += 1
    
    if frame_count % 100 == 0:
        print(f"Processed {frame_count} frames")

cap.release()
out.release()
print("完成！输出已保存到 output_video.mp4")
```

***

## 第 5 步 — 训练自定义模型

### 准备你的数据集

YOLO 使用特定的目录结构和标签格式：

```
dataset/
├── images/
│   ├── train/          # 训练图像（.jpg/.png）
│   ├── val/            # 验证图像
│   └── test/           # 测试图像（可选）
└── labels/
    ├── train/          # 标签文件（.txt）
    ├── val/
    └── test/
```

每个标签文件（与图像同名， `.txt` 扩展名）包含：

```
# class_id center_x center_y width height（均归一化为 0-1）
0 0.512 0.334 0.256 0.412
1 0.123 0.654 0.089 0.123
```

### 创建数据集配置

```bash
cat > /workspace/custom_dataset.yaml << 'EOF'
# 数据集配置
path: /workspace/dataset
train: images/train
val: images/val
test: images/test

# 类别数量
nc: 3

# 类别名称
names:
  0: person
  1: car
  2: bicycle
EOF
```

### 从 Roboflow 导入（推荐）

```python
# 安装 Roboflow
pip install roboflow

from roboflow import Roboflow
rf = Roboflow(api_key="YOUR_API_KEY")
project = rf.workspace("your-workspace").project("your-project")
version = project.version(1)
dataset = version.download("yolov9")

# 数据集现在位于 ./your-project-1/
```

### 训练 YOLOv10

```python
from ultralytics import YOLO

# 加载预训练 YOLOv10 模型（迁移学习）
model = YOLO("yolov10m.pt")  # 中等变体 — 平衡性良好

results = model.train(
    data="/workspace/custom_dataset.yaml",
    epochs=100,
    imgsz=640,
    batch=16,               # 根据你的 GPU 显存调整
    device="cuda",
    workers=8,
    project="/workspace/runs",
    name="yolov10_custom",
    patience=50,            # 提前停止
    save=True,
    save_period=10,         # 每 10 个 epoch 保存一次检查点
    plots=True,
    val=True,
    augment=True,           # 数据增强
    degrees=10.0,
    flipud=0.0,
    fliplr=0.5,
    mosaic=1.0,
    mixup=0.1,
    copy_paste=0.1,
    lr0=0.01,
    lrf=0.01,
    momentum=0.937,
    weight_decay=0.0005,
    warmup_epochs=3.0,
    amp=True                # 自动混合精度（FP16）
)

print(f"训练完成！最佳 mAP: {results.results_dict['metrics/mAP50-95(B)']:.3f}")
```

### 训练 YOLOv9

```python
from ultralytics import YOLO

model = YOLO("yolov9e.pt")

results = model.train(
    data="/workspace/custom_dataset.yaml",
    epochs=100,
    imgsz=640,
    batch=8,               # v9e 更大，需要更小的 batch
    device="cuda",
    workers=8,
    project="/workspace/runs",
    name="yolov9_custom",
    amp=True,
    optimizer="SGD",
    momentum=0.937,
    weight_decay=0.0005
)
```

{% hint style="info" %}
**训练提示：**

* **批量大小：** 从以下开始 `batch=16` 对于 RTX 4090， `batch=32` 对于 A100 40GB
* **图像尺寸：** `imgsz=640` 是标准；对高分辨率任务使用 1280
* **训练周期（Epochs）：** 100 个 epoch 通常用于微调，300+ 用于从头训练
* **AMP（混合精度）：** 始终启用 `amp=True` 可获得 1.5–2 倍的速度提升
  {% endhint %}

***

## 第 6 步 — 导出到 TensorRT 以获得最大速度

```python
from ultralytics import YOLO

# 加载训练好的模型
model = YOLO("/workspace/runs/yolov10_custom/weights/best.pt")

# 导出到 TensorRT（FP16 可获得最佳速度/精度平衡）
model.export(
    format="engine",        # TensorRT 引擎
    device="cuda",
    half=True,              # FP16
    dynamic=False,          # 使用静态形状以获得最大 TRT 优化
    batch=1,                # 为批量大小 1 优化（实时）
    imgsz=640,
    workspace=4             # TRT 工作区，单位为 GB
)
# 保存为：best.engine

# 加载并运行 TRT 引擎
trt_model = YOLO("best.engine")
results = trt_model("image.jpg")
```

### 导出为 ONNX

```python
# 导出为 ONNX 以提高部署灵活性
model.export(
    format="onnx",
    opset=17,
    half=True,              # FP16 权重
    dynamic=True,           # 动态批量大小
    simplify=True
)
```

***

## 第 7 步 — 作为 REST API 提供服务

```bash
pip install fastapi uvicorn python-multipart

cat > /workspace/yolo_api.py << 'EOF'
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse, FileResponse
from ultralytics import YOLO
from PIL import Image
import io
import uuid
import os

app = FastAPI(title="YOLOv10 Detection API")
model = YOLO("yolov10x.pt")

@app.get("/health")
async def health():
    return {"status": "ok", "model": "yolov10x", "device": "cuda"}

@app.post("/detect")
async def detect(
    file: UploadFile = File(...),
    conf: float = 0.25,
    iou: float = 0.45,
    return_image: bool = False
):
    # 读取上传的图像
    image_data = await file.read()
    img = Image.open(io.BytesIO(image_data)).convert("RGB")
    
    # 运行检测
    results = model(img, conf=conf, iou=iou, verbose=False)
    result = results[0]
    
    # 构建响应
    detections = []
    for box in result.boxes:
        detections.append({
            "class": model.names[int(box.cls[0])],
            "confidence": round(float(box.conf[0]), 4),
            "bbox": [round(x, 2) for x in box.xyxy[0].tolist()],
            "class_id": int(box.cls[0])
        })
    
    response = {
        "count": len(detections),
        "detections": detections,
        "image_size": list(result.orig_shape)
    }
    
    if return_image:
        output_path = f"/tmp/{uuid.uuid4()}.jpg"
        result.save(filename=output_path)
        return FileResponse(output_path, media_type="image/jpeg")
    
    return JSONResponse(response)

@app.post("/detect/batch")
async def detect_batch(files: list[UploadFile] = File(...)):
    results = []
    for file in files:
        data = await file.read()
        img = Image.open(io.BytesIO(data)).convert("RGB")
        res = model(img, verbose=False)[0]
        results.append({
            "filename": file.filename,
            "count": len(res.boxes),
            "detections": [
                {"class": model.names[int(b.cls[0])], "conf": float(b.conf[0])}
                for b in res.boxes
            ]
        })
    return JSONResponse({"results": results})

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
EOF

python3 /workspace/yolo_api.py &

# 测试 API
curl -X POST "http://localhost:8000/detect" \
    -F "file=@test_image.jpg" | python3 -m json.tool
```

***

## 第 8 步 — 验证并基准测试你的模型

```python
from ultralytics import YOLO

model = YOLO("yolov10x.pt")

# 在 COCO 数据集上验证
metrics = model.val(
    data="coco.yaml",
    imgsz=640,
    batch=32,
    device="cuda",
    half=True
)

print(f"mAP50:    {metrics.box.map50:.3f}")
print(f"mAP50-95: {metrics.box.map:.3f}")
print(f"Precision: {metrics.box.mp:.3f}")
print(f"Recall:    {metrics.box.mr:.3f}")

# 基准测试速度
model.benchmark(
    format="engine",   # 比较多种导出格式
    imgsz=640,
    half=True,
    device="cuda"
)
```

***

## 下载结果

```bash
# 从本地机器：
scp -P <ssh-port> root@<server-ip>:/workspace/runs/yolov10_custom/weights/best.pt ./
scp -P <ssh-port> root@<server-ip>:/workspace/output_video.mp4 ./

# 下载整个训练运行
rsync -avz -e "ssh -p <ssh-port>" \
    root@<server-ip>:/workspace/runs/ \
    ./yolo_training_runs/
```

***

## 故障排除

### 训练期间 CUDA 内存不足

```python
# 减小批量大小
model.train(data="data.yaml", batch=4, imgsz=640)

# 或启用梯度检查点
model.train(data="data.yaml", batch=8, imgsz=640, cache=False)
```

### 训练速度慢

```python
# 启用缓存（将数据集加载到 RAM/GPU）
model.train(data="data.yaml", cache=True)  # 缓存到 RAM
model.train(data="data.yaml", cache="disk")  # 缓存到磁盘

# 增加 workers（小心：过多可能会变慢）
model.train(data="data.yaml", workers=8)
```

### mAP 较低 / 检测效果差

```bash
# 验证标签是否正确（已归一化，位于 0-1 范围内）
python3 -c "
from ultralytics.data.utils import check_det_dataset
check_det_dataset('custom_dataset.yaml')
"

# 可视化训练样本
python3 -c "
from ultralytics import YOLO
model = YOLO('yolov10m.pt')
model.train(data='data.yaml', epochs=1, batch=4, plots=True)
# 检查 /workspace/runs/train/exp/train_batch*.jpg
"
```

***

## 性能参考（Clore.ai GPU）

| 模型           | GPU      | 批次（Batch） | FPS（推理） | mAP50-95 |
| ------------ | -------- | --------- | ------- | -------- |
| YOLOv10n     | RTX 3090 | 1         | 1,200   | 38.5     |
| YOLOv10s     | RTX 3090 | 1         | 780     | 46.8     |
| YOLOv10m     | RTX 4090 | 1         | 950     | 51.3     |
| YOLOv10x     | RTX 4090 | 1         | 380     | 54.4     |
| YOLOv9e      | A100 40G | 1         | 720     | 55.6     |
| YOLOv10x TRT | RTX 4090 | 1         | 920     | 54.2     |

***

## 附加资源

* [Ultralytics 文档](https://docs.ultralytics.com/)
* [YOLOv9 论文](https://arxiv.org/abs/2402.13616)
* [YOLOv10 论文](https://arxiv.org/abs/2405.14458)
* [Roboflow 资源库](https://universe.roboflow.com/) — 100K+ 公共数据集
* [Ultralytics HUB](https://hub.ultralytics.com/) — 云端训练平台
* [COCO 数据集](https://cocodataset.org/) — 标准基准数据集

***

*在 Clore.ai GPU 租用上运行 YOLOv9 和 YOLOv10，为训练自定义目标检测模型并部署实时推理管道提供了经济的途径 — 无需 AWS SageMaker 或 Google Vertex AI 的额外开销。*

***

## Clore.ai 的 GPU 建议

| 在 Clore.ai 上的预估费用 | 开发/测试             | RTX 3090（24GB） |
| ----------------- | ----------------- | -------------- |
| \~$0.12/每 GPU/每小时 | 生产                | RTX 4090（24GB） |
| 生产级推理             | 大规模               | A100 80GB      |
| 大批量训练             | 💡 本指南中的所有示例均可部署在 | Clore.ai       |

> GPU 服务器上。浏览可用 GPU 并按小时租用 — 无需承诺，提供完整的 root 访问权限。 [Clore.ai](https://clore.ai/marketplace) GPU 服务器。浏览可用 GPU 并按小时租用 — 无需承诺，提供完整的 root 访问权限。


---

# Agent Instructions: 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:

```
GET https://docs.clore.ai/guides/guides_v2-zh/ji-suan-ji-shi-jue/yolov9-v10.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
