> 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/ji-suan-ji-shi-jue/yolov9-v10.md).

# 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   | 6820 万 | 必需     |
| 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 光和扫描中的异常检测
* **体育分析** —— 球员和球跟踪
* **农业** —— 作物病害和害虫检测

***

## 前提条件

* 带 GPU 租赁的 Clore.ai 账户
* 训练数据（用于自定义模型训练）或使用 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"检测到 {len(boxes)} 个目标")
    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}，位置为 {[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"已处理 {frame_count} 帧")

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
* **轮数：** 微调通常使用 100 轮，从头训练则使用 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,                # 针对 batch size 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,           # 动态 batch 大小
    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 检测 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"精确率： {metrics.box.mp:.3f}")
print(f"召回率：    {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
# 减小 batch 大小
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 GPUs）

| 模型           | GPU      | 批次 | 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 Universe](https://universe.roboflow.com/) — 10万+ 个公开数据集
* [Ultralytics HUB](https://hub.ultralytics.com/) — 云端训练平台
* [COCO 数据集](https://cocodataset.org/) — 标准基准数据集

***

*Clore.ai 上的 YOLOv9 和 YOLOv10 GPU 租赁，为训练自定义目标检测模型和部署实时推理管线提供了一条经济实惠的路径——无需 AWS SageMaker 或 Google Vertex AI 的额外开销。*

***

## Clore.ai GPU 推荐

| 使用场景   | 推荐 GPU         | Clore.ai 预计成本                     |
| ------ | -------------- | --------------------------------- |
| 开发/测试  | RTX 3090（24GB） | $0.07–0.21/gpu/hr                 |
| 生产环境推理 | RTX 4090（24GB） | $0.14–0.42/gpu/hr                 |
| 大批量训练  | A100 80GB      | [裸机](https://clore.ai/bare-metal) |

> 💡 本指南中的所有示例都可以部署在 [Clore.ai](https://clore.ai/marketplace) GPU 服务器上。浏览可用 GPU 并按小时租用——无需承诺，拥有完整 root 访问权限。


---

# 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/ji-suan-ji-shi-jue/yolov9-v10.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.
