这是当前稳定版本 v1.4.0 的文档。早期版本仍可在版本菜单中找到。

支持 LibreYOLO

最好的支持方式就是给仓库点个 Star。遇到问题或有建议,欢迎提交 issue,也非常欢迎贡献代码

两份配套指南更深入地介绍专门主题。 LibreVLM 指南 介绍视觉语言模型层(Qwen3-VL、Florence-2),它生成文本,再由 LibreYOLO 解析成框。这与 开放词表检测 是两回事:后者使用以文本为条件的专用检测器,并在本页中说明。 实验性任务指南 介绍更多实验性工作流,包括 LoRA / DoRA 微调。

简介

v1.4.0 验证范围

经过充分测试的路径是 YOLO9 和 RF-DETR 的检测、训练与推理,包括 RF-DETR 分割。

其他模型系列和任务均可使用,但仍属实验性。多 GPU 训练在 v1.4.0 中经历了正确性大修,比 v1.3.x 可靠得多,但仍在已验证范围之外。

LibreYOLO 是一个采用 MIT 许可的计算机视觉工具包。v1.4.0 提供了涵盖检测、分割、分类、深度、图像修复、OCR 等的广泛模型目录,但其经过验证的支持范围是有意收窄的:

  • YOLO9 检测 - CNN 路径。
  • RF-DETR 检测 - transformer 路径。
  • RF-DETR 分割 - 经过充分测试的分割路径。

我们建议将这些路径作为新项目的默认选择,因为它们在检测、训练与推理方面经过了最充分的测试。其他受支持的系列和任务通过同一个统一的 LibreYOLO() 工厂工作,但在 v1.4.0 中属于实验性。如果你有特定理由,可以使用它们。

python
1from libreyolo import LibreYOLO, SAMPLE_IMAGE
2
3# Default: YOLO9 detection
4model = LibreYOLO("LibreYOLO9c.pt")
5result = model(SAMPLE_IMAGE, conf=0.25, save=True)
6
7print(f"Detected {len(result)} objects")
8print(result.boxes.xyxy)
9print(result.saved_path)

核心特性

  • 对 YOLO9 检测、RF-DETR 检测和 RF-DETR 分割进行了充分测试并作为推荐默认项
  • 统一的 LibreYOLO() 工厂,用于加载检查点、导出产物和运行时
  • 通过一致的 API 完成检测、实例 / 语义 / 全景分割、姿态、分类、深度、图像修复、背景移除、OCR、点定位和视线任务
  • 支持图像、目录和视频推理(大尺寸帧可选分块推理)
  • 内置多目标跟踪:ByteTrack、OC-SORT、BoT-SORT,以及带 ReID 的 Deep OC-SORT
  • 按系列细化的训练数据增强控制,配有声明式支持规范,参数被忽略时会发出警告
  • PyTorch 原生量化:fp16 / bf16 / fp8 / int8 / int4 配方,支持 QAT 与 QAD 精度恢复
  • ONNX、TorchScript、TensorRT、OpenVINO、NCNN、CoreML 和 TFLite 导出,内嵌元数据,并配有相应的运行时后端
  • 兼容 COCO 的验证,提供 mAP 指标,并包含分割、姿态、全景、抠图和 OCR 验证器
  • libreyolo 命令行工具,用于 predict / train / val / export / quantize
  • 接受任意图像格式:文件路径、URL、PIL、NumPy、PyTorch 张量、原始字节

v1.4.0 新特性

  • 15 个新模型系列,包括 SegFormer(语义分割)、SwinIR 和 Real-ESRGAN(超分辨率)、BiRefNet(背景移除)、ZipDepth 和 Depth Anything 3(深度)、PP-OCR(文字)、SigLIP2(零样本分类)、SAM 3、EdgeTAM 和 PicoSAM3(提示式分割),以及 OmDet-Turbo 和 OV-DEIM(开放词表检测)。
  • 三个新任务panopticmatteocr,各自拥有独立的结果类型和验证器。
  • 成体系的数据增强文档。每个训练增强参数现在都有按系列的支持规范,CLI 会在所选系列忽略你显式设置的参数时发出警告,并且本页终于有了完整的数据增强章节。
  • 量化栈model.quantize()libreyolo quantize,提供九种配方、基于仿真的可信精度、QAT / QAD 恢复,以及打包低比特权重的检查点。
  • 两个新跟踪器:BoT-SORT 和 Deep OC-SORT(外观 ReID),与 ByteTrack、OC-SORT 并列可选。
  • 多 GPU 正确性大修:所有系列的 DDP 分片都已修正,损失归一化因子做全局规约,BatchNorm 密集的系列默认开启 SyncBatchNorm,配置错误会在启动时大声报错而不是悄悄跑错。
  • YOLOv7 可训练(该系列在 v1.3.1 中仅支持推理),LoRA 微调扩展到七个新系列,新增 DINOv2 基础模型蒸馏教师和 TFLite 运行时后端。

v1.4.0 兼容性说明

  • 检查点只向前兼容。使用新任务字符串(panopticmatteocr)或已定型量化状态的检查点无法被 v1.3.1 加载。v1.3.x 写出的所有内容都能在 v1.4.0 中加载,且 ResultsLibreEoMT 完整保留 v1.3 的位置参数兼容性。
  • 部分微调默认值已修改,因为旧值有害:PicoDet(lr0 从 0.1 改为 0.01)和 DEIM(lr0 从 4e-4 改为 1e-4,min_lr_ratio 从 0.5 改为 0.05)。如需复现上游 COCO 配方,请显式传入旧值。
  • 训练结果可能有所偏移:语义分割训练现在默认应用 HSV 抖动,图像修复训练新增成对的垂直翻转和 rot90,AdamW 不再对 BatchNorm / bias 参数施加权重衰减。
  • model.train(profile=True) 在分析窗口结束后继续训练,而不再停止。传入 profile_then_stop=True 可恢复旧行为。
  • libreyolo models --json 的模式已变更(带任务后缀的 CLI 名称、新增键);formatsinfo 的 JSON 也增加了键。请更新解析它们的脚本。

兼容性

可将此矩阵作为 v1.4.0 的快速支持速查表。 表示受支持的路径, prev 表示研究预览,空白单元格表示当前不支持。YOLO9 和 RF-DETR 检测(外加 RF-DETR 分割)测试最充分,也是推荐的起点;其他系列同样受支持,如遇问题请提交 issue。

模型系列备注推理训练检测分割语义全景分类姿态OBB深度修复抠图OCR视线ONNXTorchScriptTensorRTOpenVINONCNNCoreMLTFLite
YOLO9推荐的 detect 路径;支持 int8 / fp8 量化Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
RF-DETR推荐的 detect + segment;pose / OBB 预览;支持 LoRA 与全部量化配方Not currently supportedNot currently supportedNot currently supportedprevprevNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
YOLOXNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
YOLOv7v1.4.0 起可训练(SimOTA);此前仅推理Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
YOLO9-E2ENot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
YOLO9-P2小目标;仅 VisDrone 权重(非商用)Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
YOLO-NASv1.4.0 新增多类别姿态训练Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
D-FINEv1.4.0 新增分割与动态验证尺寸;支持 LoRANot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
DEIMv1.4.0 修正微调默认值;支持 LoRANot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
DEIMv2支持 LoRANot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
RT-DETR支持 LoRANot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
RT-DETRv2支持 LoRANot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
RT-DETRv4v1.4.0 新增动态验证尺寸;支持 LoRANot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
PicoDetv1.4.0 修正微调默认值Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
RTMDetv1.4.0 新增 RTMDet-Ins 实例分割(仅推理与验证)Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
EC支持 LoRA(仅 detect)Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
EoMT语义 + 实例 + 全景;实例与全景为 v1.4.0 新增;仅推理与验证Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
SegFormerv1.4.0 新增;语义分割 b0-b5;ADE20K 权重非商用Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
PIDNet语义分割;仅推理与验证;v1.4.0 新增 ONNX 导出Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
DINOv2语义 / 分类 / 检测(需要 transformers)Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
MobileNetV4分类器(Apache-2.0)Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
ConvNeXt分类器(Apache-2.0);支持 LoRANot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
EfficientNetV2分类器(Apache-2.0)Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
ResNet分类器Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
CLIP零样本分类Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
SigLIP2v1.4.0 新增;零样本分类,仅推理Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
Depth Anything V2v1.4.0 新增 ONNX 导出(固定分辨率、batch 1)Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
Depth Anything 3v1.4.0 新增;l 尺寸、504 输入,Apache-2.0Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
ZipDepthv1.4.0 新增;b / bnpu、384 输入,MITNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
FOMO不自动下载;v1.4.0 新增 ONNX 导出Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
NAFNet图像修复(去噪 / 去模糊);提供 SIDD 去噪权重Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
SwinIRv1.4.0 新增;4 倍超分 s / m / l,Apache-2.0;仅推理与验证Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
Real-ESRGANv1.4.0 新增;x4 / x2 / x4t 超分;仅推理与验证Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
BiRefNetv1.4.0 新增;背景移除(matte)t / l,1024 输入Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
PP-OCRv1.4.0 新增;文本检测 + 识别;仅推理与验证Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
YOLO1 / YOLO2 / YOLO3 / YOLO4博物馆级历史基线,仅推理(YOLO1 为 v1.4.0 新增)Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported
L2CS仅推理Not currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supportedNot currently supported

导出各列汇总了 v1.4.0 内置的规范化导出支持矩阵;可用 libreyolo formats --family ... libreyolo info --model ... --json 精确查询(见导出)。 提示式分割层(SAM、SAM 2、SAM 3、MobileSAM、EdgeTAM、PicoSAM3)、开放词表层(Grounding DINO、OWLv2、OmDet-Turbo、OV-DEIM)和 VLM 层在 LibreYOLO() 工厂之外,不列入此表;请参见各自章节。CoreML 导出会生成 .mlpackage 包并需要 libreyolo[coreml]:仅限 macOS、不支持 INT8, 且对 RF-DETR、D-FINE、DEIM、DEIMv2 或 EC 不内嵌 NMS。

安装

环境要求

  • Python 3.10+
  • PyTorch 1.13+ 和 torchvision 0.11+

从 PyPI 安装

bash
1pip install libreyolo

v1.4.0 是 PyPI 上的当前版本,也是本文档所描述的版本。本页所有内容都可直接使用已发布的软件包,无需源码安装。

从源码安装

bash
1git clone https://github.com/LibreYOLO/libreyolo.git
2cd libreyolo
3pip install -e .

可选依赖

bash
1# ONNX export and inference
2pip install libreyolo[onnx]
3# or: pip install onnx onnxsim onnxruntime
4
5# RT-DETR compatibility extra (currently no extra packages)
6pip install libreyolo[rtdetr]
7
8# RF-DETR support
9pip install libreyolo[rfdetr]
10# or: pip install transformers
11
12# TensorRT export and inference (NVIDIA GPU)
13pip install libreyolo[tensorrt]
14# Installs TensorRT CUDA 12 Python packages on Linux/Windows.
15# Host driver/CUDA compatibility still matters.
16
17# OpenVINO export and inference (Intel CPU/GPU/VPU)
18pip install libreyolo[openvino]
19# INT8 export also needs: pip install nncf
20
21# NCNN export and inference
22pip install libreyolo[ncnn]
23# or: pip install pnnx ncnn
24
25# TFLite export + LiteRT runtime backend (Python 3.12+)
26pip install libreyolo[tflite]
27# "litert" is an alias extra: pip install libreyolo[litert]
28
29# Tracking API compatibility extra
30pip install libreyolo[tracking]
31# Tracking dependencies are part of the base install; Deep OC-SORT's ReID
32# embedder weights auto-download on first use.
33
34# CoreML export and inference (macOS only for runtime)
35pip install libreyolo[coreml]
36# or: pip install coremltools
37
38# L2CS gaze optional auto-download helper
39pip install libreyolo[gaze]
40
41# Promptable segmentation (LibreSAM: SAM-1, SAM-2, SAM 3, MobileSAM,
42# EdgeTAM, PicoSAM3)
43pip install libreyolo[sam]
44
45# Open-vocabulary detection (Grounding DINO, OWLv2, OmDet-Turbo, OV-DEIM)
46pip install libreyolo[openvocab]
47
48# LibreLabel AI assist (SAM click-to-mask)
49pip install libreyolo[label]
50
51# Zero-shot classification
52pip install libreyolo[clip] # CLIP
53pip install libreyolo[siglip2] # SigLIP2 tokenizer (SentencePiece)
54
55# LoRA fine-tuning (peft)
56pip install libreyolo[lora]
57
58# Experiment loggers
59pip install libreyolo[tensorboard] # or [mlflow], [wandb]
60
61# EoMT instance / panoptic segmentation
62pip install libreyolo[eomt]
63
64# Install every optional LibreYOLO extra
65pip install libreyolo[all]

如果使用 uv,最可靠的做法是为每个 extra 建立独立的 venv:

bash
1# ONNX environment
2uv venv .venv-onnx
3uv pip install --python .venv-onnx/bin/python -e '.[onnx]'
4
5# RT-DETR environment
6uv venv .venv-rtdetr
7uv pip install --python .venv-rtdetr/bin/python -e '.[rtdetr]'
8
9# Repeat with .[rfdetr], .[openvino], .[ncnn], .[coreml], .[gaze], .[tracking], or .[tensorrt] as needed

这样可以避免改动项目环境,并保持可选依赖相互隔离。TensorRT、OpenVINO、NCNN 和 CoreML 等特定厂商 extra 可能仍需平台相关的原生包。

快速开始

若要使用测试最充分的路径,请选择单 GPU 的 YOLO9 检测、RF-DETR 检测或 RF-DETR 分割。它们通过同一个工厂加载、接受相同的输入并返回相同的 Results 对象,因此你可以在它们之间切换而无需改动周边代码。

YOLO9 - CNN 旗舰

python
1from libreyolo import LibreYOLO, SAMPLE_IMAGE
2
3# Use the official checkpoint name and let the factory resolve the details
4model = LibreYOLO("LibreYOLO9c.pt")
5
6# Run on a single image (SAMPLE_IMAGE ships with the package)
7result = model(SAMPLE_IMAGE)
8
9print(f"Found {len(result)} objects")
10print(result.boxes.xyxy) # bounding boxes (N, 4)
11print(result.boxes.conf) # confidence scores (N,)
12print(result.boxes.cls) # class IDs (N,)

RF-DETR - transformer 旗舰

python
1from libreyolo import LibreYOLO, SAMPLE_IMAGE
2
3# Same factory, same call shape - just point at an RF-DETR checkpoint
4model = LibreYOLO("LibreRFDETRs.pt")
5result = model(SAMPLE_IMAGE)
6
7print(f"Found {len(result)} objects")
8print(result.boxes.xyxy)

保存标注后的输出

python
1result = model(SAMPLE_IMAGE, save=True)
2print(result.saved_path) # e.g. runs/detect/predict/parkour.jpg

处理目录

python
1results = model("images/", save=True, batch=4)
2for r in results:
3 print(f"{r.path}: {len(r)} detections")

可用模型

推荐的已验证路径:YOLO9 检测或 RF-DETR 检测 / 分割

这些模型的检测、训练与推理经过最充分的测试。在 v1.4.0 中,请将其他系列、任务以及多 GPU 工作流视为实验性。

LibreYOLO v1.4.0 提供两个已验证的旗舰系列,以及广泛的受支持模型目录:仅本次发布就新增了十五个系列。每个基于检查点的模型都通过同一个 LibreYOLO() 工厂加载,但只有下面的已验证路径才应被视为经过充分测试。

YOLO9 - CNN 旗舰

Recommended
默认:LibreYOLO9c.pt充分测试:检测、训练与推理v1.4.0 中仅检测可量化:int8 / fp8
尺寸代号输入尺寸适用场景检测检查点
Tiny"t"640快速推理LibreYOLO9t.pt
Small"s"640均衡LibreYOLO9s.pt
Medium"m"640更高精度LibreYOLO9m.pt
Compact"c"640最佳精度LibreYOLO9c.pt

在 v1.4.0 中 YOLO9 仅支持检测。非检测的旗舰变体(包括旧的 -seg 检查点)已在 v1.3.0 中移除;如需分割,请使用 RF-DETR 或下文的实验性分割系列。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreYOLO9c.pt") # detection

RF-DETR - transformer 旗舰

Recommended
推荐的 transformer 路径充分测试:检测、分割、训练与推理研究预览:pose、OBB支持 LoRA 与全部量化配方
尺寸代号输入尺寸适用场景检测检查点
Nano"n"384边缘端LibreRFDETRn.pt
Small"s"512均衡LibreRFDETRs.pt
Medium"m"576更高精度LibreRFDETRm.pt
Large"l"704最高精度LibreRFDETRl.pt

LibreYOLO 在 Hugging Face 组织上提供 Apache 干净授权的 RF-DETR 检测尺寸 N/S/M/L。XL/2XL 档位有意不提供。

充分测试 分割: LibreRFDETRn-seg.pt, LibreRFDETRs-seg.pt, LibreRFDETRm-seg.pt, LibreRFDETRl-seg.pt 更大的 -seg 尺寸(xxx) 使用上游 RF-DETR seg-XL / seg-2XL 权重,采用非商业许可:商用前请查看模型卡。请参见 分割 章节。

研究预览 姿态: LibreRFDETRx-pose.pt(移植自 RF-DETR 的 GroupPose)。 OBB: LibreRFDETRn-obb.pt, LibreRFDETRs-obb.pt, LibreRFDETRm-obb.pt, LibreRFDETRl-obb.pt (旋转框,使用检测的输入尺寸)。请将两者视为研究预览,而非已验证路径。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreRFDETRs.pt") # detect (validated)
4# model = LibreYOLO("LibreRFDETRs-seg.pt") # segment (validated)
5# model = LibreYOLO("LibreRFDETRx-pose.pt") # pose (research preview)
6# model = LibreYOLO("LibreRFDETRn-obb.pt") # obb (research preview)

其他检测系列

与已验证路径共享同一工厂和 API 接口的可检测系列。它们在 v1.4.0 中为实验性。每个检查点名称都链接到 LibreYOLO 组织上的模型卡; 将任意名称传给 LibreYOLO(),工厂会在首次使用时自动获取。

系列状态任务检查点
YOLOX实验性detectLibreYOLOXn.pt, LibreYOLOXt.pt, LibreYOLOXs.pt, LibreYOLOXm.pt, LibreYOLOXl.pt, LibreYOLOXx.pt
YOLOv7实验性detect(v1.4.0 起可训练)LibreYOLO7b.pt
YOLO9-E2E实验性detectLibreYOLO9E2Et.pt, LibreYOLO9E2Es.pt, LibreYOLO9E2Em.pt, LibreYOLO9E2Ec.pt
YOLO-NAS实验性detect, poseLibreYOLONASs.pt, LibreYOLONASm.pt, LibreYOLONASl.pt, LibreYOLONASn-pose.pt, LibreYOLONASs-pose.pt, LibreYOLONASm-pose.pt, LibreYOLONASl-pose.pt
D-FINE实验性detect, segment(v1.4.0 新增)LibreDFINEn.pt, LibreDFINEs.pt, LibreDFINEm.pt, LibreDFINEl.pt, LibreDFINEx.pt, LibreDFINEn-seg.pt, LibreDFINEs-seg.pt, LibreDFINEm-seg.pt, LibreDFINEl-seg.pt, LibreDFINEx-seg.pt
DEIM实验性detectLibreDEIMn.pt, LibreDEIMs.pt, LibreDEIMm.pt, LibreDEIMl.pt, LibreDEIMx.pt
DEIMv2实验性detectLibreDEIMv2atto.pt, LibreDEIMv2femto.pt, LibreDEIMv2pico.pt, LibreDEIMv2n.pt, LibreDEIMv2s.pt, LibreDEIMv2m.pt, LibreDEIMv2l.pt, LibreDEIMv2x.pt
RT-DETR实验性detectLibreRTDETRr18.pt, LibreRTDETRr34.pt, LibreRTDETRr50.pt, LibreRTDETRr50m.pt, LibreRTDETRr101.pt, LibreRTDETRl.pt, LibreRTDETRx.pt
RT-DETRv2实验性detectLibreRTDETRv2r18.pt, LibreRTDETRv2r34.pt, LibreRTDETRv2r50.pt, LibreRTDETRv2r50m.pt, LibreRTDETRv2r101.pt
RT-DETRv4实验性detectLibreRTDETRv4s.pt, LibreRTDETRv4m.pt, LibreRTDETRv4l.pt, LibreRTDETRv4x.pt
PicoDet实验性detectLibrePICODETs.pt, LibrePICODETm.pt, LibrePICODETl.pt
RTMDet实验性detect, segment(RTMDet-Ins,仅推理与验证)LibreRTMDett.pt, LibreRTMDets.pt, LibreRTMDetm.pt, LibreRTMDetl.pt, LibreRTMDetx.pt, LibreRTMDett-seg.pt, LibreRTMDets-seg.pt, LibreRTMDetm-seg.pt, LibreRTMDetl-seg.pt, LibreRTMDetx-seg.pt
EdgeCrafter实验性detect, pose, segmentLibreECs.pt, LibreECm.pt, LibreECl.pt, LibreECx.pt, LibreECs-pose.pt, LibreECm-pose.pt, LibreECl-pose.pt, LibreECx-pose.pt, LibreECs-seg.pt, LibreECm-seg.pt, LibreECl-seg.pt, LibreECx-seg.pt

托管说明: YOLO-NAS 检查点(上方纯文本)托管在 Deci 的 CDN 上,采用其专有权重许可, 而非 LibreYOLO 的 Hugging Face 组织。工厂仍会在首次使用时自动下载它们。 DAMO-YOLO 已在 v1.3.0 中移除,不再可加载。

v1.4.0 中的新模型系列

v1.4.0 新增了十五个模型系列。基于检查点的系列通过同一个 LibreYOLO() 工厂加载;提示式分割和开放词表条目则直接构造 (见各自章节)。它们全部为实验性。

系列任务尺寸检查点 / 加载方式
SegFormersemanticb0-b5(512;b5 为 640)LibreSegformerb0-sem.pt, LibreSegformerb1-sem.pt, LibreSegformerb2-sem.pt, LibreSegformerb3-sem.pt, LibreSegformerb4-sem.pt, LibreSegformerb5-sem.pt
SwinIRrestore(4 倍超分)s / m / lLibreSwinIRs-restore.pt, LibreSwinIRm-restore.pt, LibreSwinIRl-restore.pt
Real-ESRGANrestore(超分辨率)x4 / x2 / x4tLibreRealESRGANx4-restore.pt, LibreRealESRGANx2-restore.pt, LibreRealESRGANx4t-restore.pt
BiRefNetmatte(背景移除)t / l(1024)LibreBiRefNetl-matte.pt;t 权重暂未重新托管
ZipDepthdepthb / bnpu(384)LibreZipDepthb-depth.pt, LibreZipDepthbnpu-depth.pt
Depth Anything 3depthl(504)LibreDepthAnything3l-depth.pt
PP-OCR (v5)ocrt / l(960)LibrePPOCRt-ocr.pt, LibrePPOCRl-ocr.pt
SigLIP2零样本 classifyb16 / so400mLibreSigLIP2b16-cls.pt, LibreSigLIP2so400m-cls.pt
YOLOv1detect(博物馆级)t / b(448,VOC-20)LibreYOLO1b.pt;tiny 权重已在上游遗失
SAM 3提示式分割large(1008)LibreSAM3():Hugging Face 门控权重,Meta SAM 许可
EdgeTAM提示式分割edge(1024)LibreEdgeTAM():仅图像推理,Apache-2.0
PicoSAM3提示式 ROI 分割96 pxLibrePicoSAM3():原生移植,仅支持 ONNX 导出
OmDet-Turbo开放词表检测tLibreOpenVocab("omdet-turbo")
OV-DEIM开放词表检测(无 NMS)s / m / lLibreOpenVocab("ov-deim");权重为 CC BY-NC 4.0
SenseNova Vision七任务多模态预览7B实验性:尚未进入 CLI、UI 或模型清单;权重为 CC BY-NC 4.0
  • 既有系列也扩展了任务:EoMT 新增实例分割和全景分割检查点,RTMDet 新增 RTMDet-Ins 实例分割(推理与验证),D-FINE 新增实验性分割并发布了权重。
  • 许可因系列而异。SwinIR、EdgeTAM 和 Depth Anything 3 从代码到权重都是 Apache-2.0。SegFormer 代码为 Apache-2.0,但转换自 NVIDIA 的 ADE20K 权重为非商业许可(下载前会显示许可提示)。OV-DEIM 和 SenseNova 权重为 CC BY-NC 4.0。SAM 3 权重在 Hugging Face 上门控,采用 Meta SAM 许可。商用前请查看模型卡。

检测之外的任务系列

这些系列沿袭自早期版本,各自在对应任务章节中有完整说明。DINOv2 需要 pip install libreyolo[rfdetr](transformers)。

系列任务文档位置
MobileNetV4 / ConvNeXt / EfficientNetV2 / ResNetclassify分类
CLIP / SigLIP2零样本 classify分类
DINOv2semantic, classify, detect语义分割
PIDNet / EoMT / SegFormersemantic语义分割
EoMTpanoptic全景分割
Depth Anything V2 / Depth Anything 3 / ZipDepthdepth深度估计
NAFNet / SwinIR / Real-ESRGANrestore图像修复与超分
BiRefNetmatte背景移除
PP-OCRocr文字识别(OCR)
FOMOpoint点定位

提示式、开放词表与 VLM 档位: LibreSAM(提示式分割,libreyolo[sam])、 LibreOpenVocab(开放词表检测,libreyolo[openvocab]) 和 LibreVLM 视觉语言检测器档位 (libreyolo[vlm])是单独的类别,它们加载 Hugging Face 快照,且不通过 LibreYOLO() 检查点工厂路由。它们的权重继承 各上游模型的许可。

专用模型

系列状态任务检查点
L2CS实验性gaze(仅推理)- 参见 视线估计LibreL2CSr50.pt

L2CS 架构尺寸包括 r18、r34、r50、r101 和 r152,但上游发布的 Gaze360 检查点为 ResNet-50。安装 libreyolo[gaze] 以获取可选的下载助手, 或为其他尺寸传入本地检查点路径。L2CS 权重不由 LibreYOLO 托管(Gaze360 数据集 许可禁止再分发)。

工厂函数

对每个模型和运行时都使用 LibreYOLO() 工厂。给它一个官方检查点名称或导出产物路径, 然后让它选择正确的模型系列、任务、类别数和运行时:

python
1from libreyolo import LibreYOLO
2
3# Default: YOLO9 detection
4model = LibreYOLO("LibreYOLO9c.pt")
5
6# Flagship transformer: RF-DETR
7model = LibreYOLO("LibreRFDETRs.pt")
8model = LibreYOLO("LibreRFDETRs-seg.pt") # validated segmentation
9
10# The task suffix selects the task
11model = LibreYOLO("LibreMobileNetV4s-cls.pt") # classification (Apache, ImageNet-1k)
12model = LibreYOLO("LibreDINOv2n.pt") # semantic segmentation
13model = LibreYOLO("LibreDepthAnythingV2s-depth.pt") # monocular depth
14model = LibreYOLO("LibreFOMOs-point.pt") # point localization (local weights)
15
16# New in v1.4.0
17model = LibreYOLO("LibreSegformerb2-sem.pt") # semantic segmentation
18model = LibreYOLO("LibreEoMTb-panoptic.pt") # panoptic segmentation
19model = LibreYOLO("LibreSwinIRm-restore.pt") # 4x super-resolution
20model = LibreYOLO("LibreBiRefNetl-matte.pt") # background removal
21model = LibreYOLO("LibrePPOCRt-ocr.pt") # OCR (text detection + recognition)
22model = LibreYOLO("LibreZipDepthb-depth.pt") # depth
23
24# Exported deployment formats
25model = LibreYOLO("model.onnx") # ONNX Runtime
26model = LibreYOLO("model.engine") # TensorRT
27model = LibreYOLO("model.mlpackage") # CoreML (macOS)
28model = LibreYOLO("model_openvino/") # OpenVINO (directory)
29model = LibreYOLO("model_ncnn/") # NCNN (directory)
30model = LibreYOLO("model.tflite") # TFLite / LiteRT (new in v1.4.0)

对于可识别的官方检查点文件名,LibreYOLO 可以自动下载缺失的权重。对于自定义文件名,请指向明确的本地路径。 新项目请保持使用 YOLO9 检测或 RF-DETR 检测 / 分割; 其他系列、任务以及新增系列在 v1.4.0 中为实验性。

任务与文件名

LibreYOLO 使用统一的文件名约定,因此工厂仅凭检查点名称即可识别系列、尺寸和任务:

text
1Libre<FAMILY><size>[-<task>].pt

任务后缀

任务规范名称文件名后缀所属系列
检测"detect"(无 - 隐式)大多数系列(默认)
实例分割"segment"-segRF-DETR、EdgeCrafter、RTMDet-Ins、D-FINE、EoMT
语义分割"semantic"-semDINOv2、PIDNet、EoMT、SegFormer
全景分割"panoptic"-panopticEoMT(v1.4.0 新增)
姿态估计"pose"-poseYOLO-NAS、EdgeCrafter、RF-DETR(预览)
旋转框"obb"-obbRF-DETR(预览)
分类"classify"-clsMobileNetV4、ConvNeXt、EfficientNetV2、ResNet、DINOv2;CLIP 与 SigLIP2 零样本
单目深度"depth"-depthDepth Anything V2 / 3、ZipDepth
图像修复"restore"-restoreNAFNet、SwinIR、Real-ESRGAN
背景移除"matte"-matteBiRefNet(v1.4.0 新增)
文字识别"ocr"-ocrPP-OCR(v1.4.0 新增)
点定位"point"-pointFOMO
视线估计"gaze"-gazeL2CS

检测是隐式的(无后缀),遵循常见的 YOLO 约定。 工厂在 API 边界接受别名 ("detection""seg""keypoints""cls" 等); 只有上面的规范名称才会出现在文件名中。只有当某个任务在该系列的 受支持任务集中时,它才可用。

解析优先级

加载模型时,任务按以下顺序解析:

text
1explicit task= → checkpoint["task"] → filename suffix → family default
python
1from libreyolo import LibreYOLO
2
3# 1. Filename suffix decides → segment
4model = LibreYOLO("LibreRFDETRs-seg.pt")
5
6# 2. Override regardless of filename
7model = LibreYOLO("custom_weights.pt", task="segment")
8
9# 3. Detection is implicit
10model = LibreYOLO("LibreYOLO9c.pt") # task="detect"

各系列任务支持

系列v1.4.0 状态默认受支持任务
YOLO9单 GPU detect 充分测试;多 GPU 实验性detectdetect
RF-DETR单 GPU detect 和 segment 充分测试;pose 和 OBB 研究预览detectdetect, segment, pose, obb
YOLOX实验性detectdetect
YOLOv7实验性;v1.4.0 起可训练detectdetect
YOLO9-E2E实验性detectdetect
YOLO-NAS实验性;v1.4.0 新增多类别姿态训练detectdetect, pose
D-FINE实验性;segment 为 v1.4.0 新增detectdetect, segment
DEIM / DEIMv2实验性detectdetect
RT-DETR / RT-DETRv2 / RT-DETRv4实验性detectdetect
PicoDet实验性detectdetect
RTMDet实验性;RTMDet-Ins segment(仅推理与验证)为 v1.4.0 新增detectdetect, segment
EdgeCrafter (EC)实验性detectdetect, pose, segment
YOLO1 / YOLO2 / YOLO3 / YOLO4博物馆级(仅推理);YOLO1 为 v1.4.0 新增detectdetect
PIDNet实验性semanticsemantic(仅推理与验证)
EoMT实验性;实例与全景为 v1.4.0 新增semanticsemantic, segment, panoptic(仅推理与验证)
SegFormerv1.4.0 新增,实验性semanticsemantic
DINOv2实验性semanticsemantic, classify, detect
MobileNetV4 / ConvNeXt / EfficientNetV2 / ResNet实验性classifyclassify
CLIP / SigLIP2实验性;SigLIP2 为 v1.4.0 新增classify零样本 classify(仅推理)
Depth Anything V2 / Depth Anything 3 / ZipDepth实验性;DA3 与 ZipDepth 为 v1.4.0 新增depthdepth(仅推理与验证)
NAFNet实验性restorerestore
SwinIR / Real-ESRGANv1.4.0 新增,实验性restorerestore(仅推理与验证)
BiRefNetv1.4.0 新增,实验性mattematte(仅推理与验证)
PP-OCRv1.4.0 新增,实验性ocrocr(仅推理与验证)
FOMO实验性pointpoint
L2CS实验性gazegaze(仅推理)

有三个档位位于 LibreYOLO() 工厂之外,需要直接导入:LibreSAM(提示式分割,现已包含 SAM 3、EdgeTAM 和 PicoSAM3)、LibreOpenVocab(开放词表检测,现已包含 OmDet-Turbo 和 OV-DEIM)和 LibreVLM。它们不是检查点系列,因此 LibreYOLO("sam_b") 之类的写法不会解析。

示例

text
1# Detection (implicit)
2LibreYOLO9c.pt
3LibreRFDETRs.pt
4LibreRTDETRr50.pt
5
6# Instance segmentation (-seg)
7LibreRFDETRs-seg.pt
8LibreECm-seg.pt
9
10# Semantic segmentation (-sem)
11LibreDINOv2n.pt # semantic is DINOv2's default; -sem optional
12LibreSegformerb0-sem.pt # SegFormer requires the -sem suffix
13
14# Panoptic segmentation (-panoptic)
15LibreEoMTs-panoptic.pt
16
17# Pose (-pose)
18LibreYOLONASn-pose.pt
19LibreECs-pose.pt
20LibreRFDETRx-pose.pt # preview
21
22# Oriented boxes (-obb)
23LibreRFDETRn-obb.pt # preview
24
25# Classification (-cls)
26LibreMobileNetV4s-cls.pt
27LibreConvNeXtt-cls.pt
28LibreEfficientNetV2b0-cls.pt
29LibreDINOv2n-cls.pt # DINOv2 linear probe
30LibreSigLIP2b16-cls.pt # zero-shot
31
32# Depth (-depth)
33LibreDepthAnythingV2s-depth.pt
34LibreZipDepthb-depth.pt
35
36# Restoration / super-resolution (-restore)
37LibreNAFNetl-restore-sidd.pt
38LibreSwinIRm-restore.pt
39LibreRealESRGANx4-restore.pt
40
41# Background removal (-matte)
42LibreBiRefNetl-matte.pt
43
44# OCR (-ocr)
45LibrePPOCRt-ocr.pt
46
47# Point (-point)
48LibreFOMOs-point.pt
49
50# Gaze (-gaze optional; only task for L2CS)
51LibreL2CSr50.pt

已弃用别名

LibreYOLORTDETRLibreYOLORFDETR 分别是 LibreRTDETRLibreRFDETR 的旧名称。它们仍可解析,但会发出 DeprecationWarning - 方便时请更新导入。

预测

单 GPU 预测路径在 YOLO9 检测、RF-DETR 检测和 RF-DETR 分割上经过充分测试。其他系列和任务使用相同的 API,但在 v1.4.0 中为实验性。

基础预测

python
1result = model("image.jpg")

全部预测参数

python
1result = model(
2 "image.jpg",
3 conf=0.25, # confidence threshold (default: 0.25)
4 iou=0.45, # NMS IoU threshold (default: 0.45)
5 imgsz=640, # input size override (default: model's native)
6 device="auto", # "auto", "cpu", "mps", "0", "cuda:0", ...
7 classes=[0, 2, 5], # filter to specific class IDs (default: all)
8 max_det=300, # max detections per image (default: 300)
9 augment=False, # test-time augmentation where implemented
10 save=True, # save annotated image (default: False)
11 batch=4, # directory batch size
12 stream=False, # video only: yield frame results instead of a list
13 vid_stride=1, # video only: process every N-th frame
14 show=False, # video only: display annotated frames
15 tiling=False, # large-image tiled detection
16 overlap_ratio=0.2, # tile overlap ratio
17 output_path="out/", # where to save (default: runs/detect/predict*/)
18 color_format="auto", # "auto", "rgb", or "bgr"
19 output_file_format="png", # output format: "jpg", "png", "webp"
20)

model.predict(...)model(...) 的别名。

支持的输入格式

LibreYOLO 接受以下任意格式的图像:

python
1# File path (string or pathlib.Path)
2result = model("photo.jpg")
3result = model(Path("photo.jpg"))
4
5# URL
6result = model("https://example.com/image.jpg")
7result = model("s3://bucket/image.jpg")
8result = model("gs://bucket/image.jpg")
9
10# PIL Image
11from PIL import Image
12img = Image.open("photo.jpg")
13result = model(img)
14
15# NumPy array (HWC or CHW, RGB or BGR, uint8 or float32)
16import numpy as np
17arr = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
18result = model(arr)
19
20# OpenCV (BGR) - specify color_format
21import cv2
22frame = cv2.imread("photo.jpg")
23result = model(frame, color_format="bgr")
24
25# PyTorch tensor (CHW or NCHW)
26import torch
27tensor = torch.randn(3, 640, 640)
28result = model(tensor)
29
30# Raw bytes
31with open("photo.jpg", "rb") as f:
32 result = model(f.read())
33
34# BytesIO
35from io import BytesIO
36result = model(BytesIO(open("photo.jpg", "rb").read()))
37
38# Directory of images
39results = model("images/", batch=4)

处理结果

每次预测都返回一个 Results 对象(对目录则返回它们的列表):

python
1result = model("image.jpg")
2
3# Number of detections
4len(result) # e.g., 5
5
6# Bounding boxes in xyxy format (x1, y1, x2, y2)
7result.boxes.xyxy # tensor of shape (N, 4)
8
9# Bounding boxes in xywh format (center_x, center_y, width, height)
10result.boxes.xywh # tensor of shape (N, 4)
11
12# Confidence scores
13result.boxes.conf # tensor of shape (N,)
14
15# Class IDs
16result.boxes.cls # tensor of shape (N,)
17
18# Combined data: [x1, y1, x2, y2, conf, cls]
19# Tracking adds a track_id column before conf/cls.
20result.boxes.data # shape (N, 6), or (N, 7) when tracked
21
22# Metadata
23result.orig_shape # (height, width) of original image
24result.path # source file path (or None)
25result.names # {0: "person", 1: "bicycle", ...}
26
27# Move to CPU / convert to numpy
28result_cpu = result.cpu()
29boxes_np = result.boxes.numpy()

类别过滤

将检测结果过滤到特定类别 ID:

python
1# Only detect people (class 0) and cars (class 2)
2result = model("image.jpg", classes=[0, 2])

内存中的批量推理

model.predict() 接受由内存中图像组成的列表或元组 (NumPy 数组、PIL 图像或张量),并将它们作为真正的堆叠前向批次运行。设置 batch > 1 可在支持的系列上 真正批处理前向计算;返回结果列表,每个输入对应一个。

python
1import numpy as np
2from libreyolo import LibreYOLO
3
4model = LibreYOLO("LibreYOLO9c.pt")
5
6frames = [
7 np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8),
8 np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8),
9 np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8),
10]
11
12results = model(frames, batch=4) # list/tuple -> true batched inference
13for r in results:
14 print(len(r), r.boxes.xyxy.shape)

模型信息

model.info() 返回一个 JSON 友好的字典,包含 系列、尺寸、任务、参数量、输入尺寸和类别名称,并在 verbose=True 时 打印可读的摘要。

python
1meta = model.info(detailed=False, verbose=True)
2# meta -> {"family": ..., "size": ..., "task": ..., "params": ..., "imgsz": ..., "names": {...}, ...}

分块推理

对于远大于模型输入尺寸的图像(如卫星影像、无人机画面),分块推理会将图像切分为重叠的分块,对每个分块运行检测,再合并结果。

在 v1.4.0 中分块仅支持检测。它会拒绝分割掩码,且不能与 augment=True 组合使用。

python
1result = model(
2 "large_aerial_image.jpg",
3 tiling=True,
4 overlap_ratio=0.2, # 20% overlap between tiles (default)
5 save=True,
6)
7
8# Extra metadata on tiled results
9result.tiled # True
10result.num_tiles # number of tiles used
11result.saved_path # output directory when save=True
12result.tiles_path # directory containing per-tile crops
13result.grid_path # grid visualization image

在分块时设置 save=True,LibreYOLO 会保存:

  • final_image.jpg - 绘制了所有合并检测的完整图像
  • grid_visualization.jpg - 显示分块网格叠加的图像
  • tiles/ - 各个分块裁剪图
  • metadata.json - 分块参数和检测数量

如果图像已经小于模型的输入尺寸,则会自动跳过分块。

视频推理

将任意视频文件传给旗舰模型,LibreYOLO 会根据扩展名自动检测格式。支持:.mp4.avi.mov.mkv.webm.gif 以及其他常见容器。

保存标注后的视频

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreYOLO9c.pt")
4results = model("clip.mp4", save=True)
5# Saved under runs/detect/predict*/clip.mp4

流式结果(内存平稳)

对于长视频,传入 stream=True 可获得一个生成器。每次迭代产出一帧的 Results - 不会在内存中缓存完整列表。

python
1for result in model("long_clip.mp4", stream=True):
2 print(f"frame {result.frame_idx}: {len(result)} detections")

帧抽样

python
1# Process every 2nd frame (halves compute and saved fps)
2results = model("clip.mp4", vid_stride=2, save=True)

实时预览

python
1# Display annotated frames in an OpenCV window while processing
2results = model("clip.mp4", show=True)

用于自定义流水线的 VideoSource / VideoWriter

当你需要完全控制解码和编码时 - 自定义帧变换、混入跟踪输出、写入非默认编解码器 - 可直接使用这些构建块:

python
1from libreyolo import LibreYOLO
2from libreyolo.utils.video import VideoSource, VideoWriter
3
4model = LibreYOLO("LibreYOLO9c.pt")
5
6with VideoSource("clip.mp4", vid_stride=1) as src, \
7 VideoWriter("out.mp4", fps=src.fps, width=src.width, height=src.height) as out:
8 for frame_bgr, frame_idx in src:
9 result = model(frame_bgr, color_format="bgr")
10 # ... draw, transform, etc.
11 out.write_frame(frame_bgr)

跟踪

LibreYOLO 提供四种运动跟踪器,它们消费任意检测器的 Results 并添加持久的轨迹 ID:ByteTrack(默认)、OC-SORT(对遮挡和非线性运动更鲁棒),以及 v1.4.0 新增的 BoT-SORT(相机运动补偿)和 Deep OC-SORT(在 OC-SORT 之上加入外观 ReID)。在 model.track() 上用 tracker="bytetrack" / "ocsort" / "botsort" / "deepocsort" 选择。 跟踪在单 GPU 的 YOLO9 检测和 RF-DETR 检测上测试最充分;其他检测系列在 v1.4.0 中为实验性。

安装

bash
1pip install libreyolo[tracking] # compatibility extra; tracking deps ship in base dev install

视频跟踪助手

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreYOLO9c.pt")
4
5for result in model.track(
6 "clip.mp4",
7 track_conf=0.25,
8 iou=0.45,
9 save=True, # writes runs/track/<video_stem>.mp4 by default
10 vid_stride=1,
11):
12 print(result.frame_idx, result.track_id)

model.track() 是用于视频文件的生成器。它逐帧运行检测,内部使用较低的 ByteTrack 置信度进行恢复,并产出已填充 result.track_idresult.boxes.idResults

基础循环

python
1from libreyolo import LibreYOLO, ByteTracker
2from libreyolo.utils.video import VideoSource
3
4model = LibreYOLO("LibreYOLO9c.pt")
5tracker = ByteTracker()
6
7with VideoSource("clip.mp4") as src:
8 for frame_bgr, frame_idx in src:
9 result = model(frame_bgr, color_format="bgr", conf=0.1)
10 tracked = tracker.update(result)
11
12 for i in range(len(tracked.boxes)):
13 track_id = int(tracked.boxes.id[i])
14 xyxy = tracked.boxes.xyxy[i].tolist()
15 cls = int(tracked.boxes.cls[i])
16 print(f"frame {frame_idx} - id {track_id} cls {cls} {xyxy}")

调用 tracker.update() 之后,result.boxes.id 保存轨迹 ID,且 result.boxes.is_trackTrue

TrackConfig 参数

python
1from libreyolo import ByteTracker, TrackConfig
2
3cfg = TrackConfig(
4 track_high_thresh=0.25, # first-stage match threshold
5 track_low_thresh=0.1, # second-stage (low-conf recovery)
6 new_track_thresh=0.25, # minimum conf to start a new track
7 match_thresh=0.8, # IoU cost cutoff (stage 1)
8 match_thresh_low=0.5, # IoU cost cutoff (stage 2)
9 match_thresh_unconfirmed=0.7, # IoU cost cutoff for unconfirmed tracks
10 track_buffer=30, # frames to keep lost tracks before removal
11 frame_rate=30, # scales track_buffer
12 fuse_score=True, # multiply IoU by detection score
13 minimum_consecutive_frames=1, # frames to confirm a new track
14)
15tracker = ByteTracker(config=cfg)

片段之间重置

python
1tracker.reset() # clears tracked / lost / removed lists and the ID counter

OC-SORT(抗遮挡)

model.track() 上用 tracker="ocsort" 选择 OC-SORT。ByteTrack 仍为默认。使用 OC-SORT 时, track_conf 映射到跟踪器的 det_thresh(在 ByteTrack 中它映射到 track_high_thresh)。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreYOLO9c.pt")
4
5for result in model.track(
6 "clip.mp4",
7 tracker="ocsort", # "bytetrack" (default) or "ocsort"
8 track_conf=0.25, # maps to OC-SORT det_thresh
9 iou=0.45,
10 save=True,
11):
12 print(result.frame_idx, result.track_id)

传入 OCSortConfig 以完全控制。提供配置实例会按类型选择跟踪器, 因此此时会忽略 tracker= 字符串。

python
1from libreyolo import LibreYOLO, OCSortConfig
2
3cfg = OCSortConfig(
4 det_thresh=0.25, # boxes above this drive association and spawn new tracks
5 max_age=30, # frames a track survives without an observation
6 min_hits=3, # consecutive hits before a track is reported
7 iou_threshold=0.3, # minimum IoU for a valid association
8 delta_t=3, # frame span used to estimate velocity direction
9 inertia=0.2, # weight of the velocity-direction (momentum) term
10 use_byte=False, # enable the BYTE low-score recovery pass
11)
12
13model = LibreYOLO("LibreYOLO9c.pt")
14for result in model.track("clip.mp4", tracker_config=cfg, save=True):
15 print(result.frame_idx, result.track_id)

BoT-SORT(相机运动补偿)

v1.4.0 新增

BoT-SORT 在 ByteTrack 的关联框架上加入相机运动补偿(CMC):用稀疏光流估计整帧的全局运动,并在匹配前对轨迹预测位置做相应的变换。当移动的是相机本身时(手持拍摄、无人机、车载相机),优先尝试它。LibreYOLO 的移植是纯运动版(不含 ReID 分支)。

python
1from libreyolo import LibreYOLO, BoTSortConfig
2
3model = LibreYOLO("LibreYOLO9c.pt")
4
5# Select by name with defaults
6for result in model.track("drone.mp4", tracker="botsort", save=True):
7 print(result.frame_idx, result.track_id)
8
9# Or configure it: a config instance selects the tracker by type
10cfg = BoTSortConfig(
11 track_high_thresh=0.25,
12 track_buffer=30,
13 enable_cmc=True, # camera-motion compensation on (default)
14 cmc_method="sparseOptFlow", # the shipped CMC estimator
15 cmc_downscale=2, # estimate flow at half resolution
16)
17for result in model.track("drone.mp4", tracker_config=cfg, save=True):
18 print(result.frame_idx, result.track_id)

BoTSortTrackerBoTSortConfig ByteTracker 一样从顶层导出,可用于手动的 tracker.update(result) 循环。

Deep OC-SORT(外观 ReID)

v1.4.0 新增

Deep OC-SORT 在 OC-SORT 之上加入外观嵌入分支:被遮挡后消失的目标可以按长相重新识别,而不只是按运动轨迹外推。默认嵌入器是 OSNet-AIN,首次使用时从 LibreYOLO/LibreReID-osnet 自动下载,并运行在与检测器相同的设备上。额外的前向计算使 Deep OC-SORT 成为四者中最慢的:当你的问题是 ID 切换而非速度时再选它。

python
1from libreyolo import LibreYOLO
2from libreyolo.tracking import DeepOCSortConfig
3
4model = LibreYOLO("LibreYOLO9c.pt")
5
6# Defaults: OSNet-AIN embedder, auto-downloaded
7for result in model.track("mall.mp4", tracker="deepocsort", save=True):
8 print(result.frame_idx, result.track_id)
9
10# Tune the appearance term, or plug in your own embedder
11cfg = DeepOCSortConfig(
12 det_thresh=0.25,
13 embedder="osnet_ain_x0_25", # or a callable: (frame, boxes_xyxy) -> (N, D) features
14 w_association_emb=0.75, # weight of appearance vs motion in matching
15 alpha_fixed_emb=0.95, # EMA smoothing of per-track embeddings
16)
17for result in model.track("mall.mp4", tracker_config=cfg, save=True):
18 print(result.frame_idx, result.track_id)

DeepOCSortTrackerDeepOCSortConfig 位于 libreyolo.tracking(不是顶层导出)。支持自定义嵌入器可调用对象:任何把一帧图像和 (N, 4) 框映射为 (N, D) 特征的函数都可以。

如何选择跟踪器

跟踪器选择方式优势开销
ByteTracktracker="bytetrack"快速、简单、默认最低
OC-SORTtracker="ocsort"遮挡与非线性运动
BoT-SORTtracker="botsort"移动相机(CMC)中(每帧光流)
Deep OC-SORTtracker="deepocsort"ID 切换、长时间遮挡后重识别最高(嵌入器前向)

模型集成

仅检测仅 Python API

LibreEnsemble 同时运行两个或更多检测模型,并把它们的检测结果融合成一个普通的 Results。融合发生在检测层面,而不是张量层面,因此每个成员都保留自己的输入尺寸、归一化和 NMS。这正是你可以把网格检测器与 DETR、或把 .pt 检查点与已导出后端混在同一个集成里的原因。

类别空间不必一致。成员按类别名称统一:名称映射相同则直接通过,否则 LibreYOLO 会构建并集并把每个成员重映射进去。只有属于同一统一类别的框才会相互融合。

python
1from libreyolo import LibreEnsemble
2
3# 加权框融合(WBF,默认),只保留两个模型都找到的框
4ens = LibreEnsemble(["LibreYOLO9s.pt", "LibreRFDETRs.pt"], min_votes=2)
5
6result = ens("image.jpg", conf=0.25)
7print(result.boxes.xyxy)
8print(result.names) # 统一后的(并集)类别表
python
1ens = LibreEnsemble(
2 ["LibreYOLO9s.pt", "LibreRFDETRs.pt"],
3 weights=[1.0, 1.4], # 让融合结果更偏向第二个成员
4 fusion="wbf", # "wbf" | "wbf_seeded" | "nms" | 自定义可调用对象
5 fusion_iou=0.55, # 用于聚类的 IoU,不是成员的 NMS
6 min_votes=1,
7)
8
9result = ens("image.jpg", conf=[0.25, 0.4]) # 每个成员单独的置信度阈值

限制

  • 只支持检测成员。任何非 detect 任务的成员都会报错,分割与姿态模型无法集成。
  • 至少需要两个成员。
  • min_votes 大于 1 时必须使用投票式融合,配合 fusion="nms" 会报错,请改用 wbf
  • 仅支持图像与图像目录。视频源与 stream=True 会报错,请分别对每个成员单独处理视频。
  • ens.val()ens.export() 都会报错,请对成员单独验证与导出。

实例分割

v1.4.0 验证范围

经过充分测试的路径是 YOLO9 和 RF-DETR 的检测、训练与推理,包括 RF-DETR 分割。

其他模型系列和任务均可使用,但仍属实验性。多 GPU 训练在 v1.4.0 中经历了正确性大修,比 v1.3.x 可靠得多,但仍在已验证范围之外。

RF-DETR 分割是 v1.4.0 中经过充分测试的分割路径。它周围还有四个实验性选项:EdgeCrafter(-seg),以及 v1.4.0 新增的 RTMDet-Ins、EoMT 实例分割和 D-FINE 分割。YOLO9 不提供分割头:它仅支持检测。

运行分割

python
1from libreyolo import LibreYOLO
2
3# RF-DETR segmentation, the heavily tested segmentation path
4model = LibreYOLO("LibreRFDETRs-seg.pt")
5result = model("photo.jpg")
6
7# EdgeCrafter segmentation is also available but experimental
8# model = LibreYOLO("LibreECs-seg.pt")
9
10# Segmentation returns boxes + masks
11print(result.boxes.xyxy) # bounding boxes (N, 4)
12print(result.boxes.cls) # class IDs (N,)
13print(result.masks.data.shape) # (N, H, W) tensor of binary masks

掩码表示

python
1# Raw bitmasks
2result.masks.data # tensor (N, H, W) - original image resolution
3
4# Polygon contours (one ndarray of (M, 2) per instance)
5result.masks.xy # absolute pixel coords
6result.masks.xyn # normalized to [0, 1]
7
8# Move / convert like Boxes
9result.masks.cpu()
10result.masks.numpy()

保存标注后的输出

save=True 会自动绘制框和半透明掩码叠加。

python
1model("photo.jpg", save=True)

v1.4.0 中的新分割系列

v1.4.0 有三个系列获得了实例分割能力,全部为实验性,且都返回同样的 boxes + masks 结果:

系列检查点支持范围
RTMDet-InsLibreRTMDett-seg.pt, LibreRTMDets-seg.pt, LibreRTMDetm-seg.pt, LibreRTMDetl-seg.pt, LibreRTMDetx-seg.pt推理与验证;训练未实现
EoMT(实例)LibreEoMTl-seg.pt, LibreEoMTl-seg-1280.pt推理与验证;-1280 变体以速度换取高分辨率掩码
D-FINELibreDFINEn-seg.pt, LibreDFINEs-seg.pt, LibreDFINEm-seg.pt, LibreDFINEl-seg.pt, LibreDFINEx-seg.pt推理、验证与实验性训练;CLI 训练会自动把 detect 权重迁移到 segment

D-FINE 分割与其 ONNX 和 TensorRT 导出已验证一致。注意分块推理(tiling=True)会对分割模型直接报错,而不是悄悄丢掉掩码。

训练分割

RF-DETR 分割使用 RF-DETR 的 COCO 格式训练流水线,属于经过充分测试的单 GPU 范围。EdgeCrafter 与 D-FINE 分割训练可用,但为实验性。分割专用的增强(copy-paste)见数据增强

语义分割

实验性SegFormer 与 TTA 为 v1.4.0 新增

语义分割为每个像素赋予一个类别。它与实例分割是不同的任务:没有目标实例,也没有检测框,只有一张稠密的类别图。使用 task="semantic",并从 result.semantic_mask 读取结果。对语义模型而言,result.boxesresult.masks 均为 None

系列检查点主干训练数据类别数可训练?
LibrePIDNetLibrePIDNet{s,m,l}-sem.ptPIDNet 三分支 CNNCityscapes19
LibreEoMTLibreEoMTl-sem.ptDINOv2 ViT-LADE20K150
LibreSegformer(v1.4.0 新增)LibreSegformer{b0..b5}-sem.ptMiT 分层 transformerADE20K150是(可微调)
LibreDINOv2未发布权重:需自行训练DINOv2 + 稠密头你的数据自定义

各系列差别很大,请有意识地选择。LibrePIDNet 是快速的实时 CNN,携带 Cityscapes 街景类别;LibreEoMT 携带 ADE20K 的 150 个通用场景类别。两者都提供预训练权重,但无法在 LibreYOLO 内训练:请在上游微调后再转换权重。

v1.4.0 新增的 LibreSegformer 走中间路线:SegFormer 架构的逐位一致移植,六个尺寸(b0 到 b5,512 px;b5 为 640),带 ADE20K 预训练权重,并且提供微调训练器,可以从 150 个通用类别出发适配你自己的数据。许可上有一点要注意:代码为 Apache-2.0,但转换自 NVIDIA 的 ADE20K 权重为非商业许可,下载前会先显示许可提示。

LibreDINOv2 是不带预训练头的微调系列:没有发布任何 LibreDINOv2 语义检查点。你需要基于预训练的 DINOv2 主干加一个全新的稠密头,用自己的掩码训练它。当你的类别既不是 Cityscapes 也不是 ADE20K,又想在全新头下用最强的特征时,就选它。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibrePIDNets-sem.pt") # Cityscapes,19 类
4result = model.predict("street.jpg")
5
6sm = result.semantic_mask # SemanticMask
7print(sm.data.shape) # (H, W) 整数类别 id,位于原图尺寸上
8print(sm.classes) # 出现过的类别 id,已排除 255(忽略)
9car = sm.class_mask(13) # (H, W) 布尔掩码
10
11result.plot().save("out.png")
12print(result.boxes, result.masks) # None None:语义分割没有实例

验证

python
1metrics = model.val(data="cityscapes.yaml")
2print(metrics["metrics/mIoU"])
3print(metrics["metrics/pixel_accuracy"])

训练(仅 LibreDINOv2)

掩码是单通道无损图像,像素值即类别 id,按文件名与图像配对。255 表示忽略,不参与损失与指标。

bash
1dataset/
2 images/train/*.jpg
3 masks/train/*.png # 与图像同名;像素值 = 类别 id
python
1from libreyolo import LibreDINOv2
2
3model = LibreDINOv2(model_path=None, size="s", task="semantic", nb_classes=19)
4model.train(data="cityscapes.yaml", epochs=100, batch_size=4, lr=1e-4)

测试时增强(v1.4.0 新增)

语义模型现在在 predict()val() 上都接受 augment=True(v1.3.1 中会报错)。TTA 额外运行一次水平翻转前向并对 logits 取平均,用约 2 倍的推理开销换取小而稳定的 mIoU 提升。PIDNet、SegFormer、EoMT 和 DINOv2 语义分割均已实现。

python
1model = LibreYOLO("LibreSegformerb2-sem.pt")
2result = model.predict("street.jpg", augment=True) # flip-TTA
3metrics = model.val(data="ade20k.yaml", augment=True)

限制

  • 导出大多仍被拦截。v1.4.0 中 PIDNet 获得了固定分辨率契约下的 ONNX 导出;SegFormer、EoMT 与 DINOv2 语义分割的所有格式仍会报错。用 libreyolo formats --family ... 查询当前档位。
  • 只有 LibreDINOv2 和 LibreSegformer 可训练。LibrePIDNet.train()LibreEoMT.train() 都会报错。
  • 语义分割训练现在默认应用 HSV 颜色抖动(v1.4.0 新增),重新训练的 mIoU 可能与 v1.3.1 略有偏移。该开关来自系列本身而非 hsv_prob;见数据增强
  • EoMT 语义分割仅有 l 尺寸,且 imgsz 固定为 512(其检查点使用固定位置编码),并且不支持批处理。
  • imgsz 的整除要求因系列而异:PIDNet 需被 8 整除,EoMT 为 16,DINOv2 为 14。
  • 语义模型不支持跟踪。
  • Cityscapes、ADE20K 与 COCO-Stuff 均需手动下载,LibreYOLO 只提供数据集 YAML。

全景分割

v1.4.0 新增仅推理与验证

全景分割同时回答两个问题:每个像素都有类别(像语义分割),可数目标又被拆成独立实例(像实例分割)。道路和天空作为单个 "stuff" 段返回;每辆车、每个人作为独立的 "thing" 段返回。结果是一张段 id 图加一份逐段信息列表,从 result.panoptic 读取。

v1.4.0 中由一个系列提供该任务:LibreEoMT 的 COCO-panoptic 检查点(133 类,640 px),共三个尺寸: LibreEoMTs-panoptic.pt, LibreEoMTb-panoptic.pt, LibreEoMTl-panoptic.pt

运行全景分割

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreEoMTb-panoptic.pt") # task resolved from the -panoptic suffix
4result = model.predict("street.jpg")
5
6pan = result.panoptic # PanopticSegmentation
7print(pan.data.shape) # (H, W) integer segment ids, original canvas
8for seg in pan.segments_info: # one dict per segment
9 print(seg["id"], seg["category_id"], model.names[seg["category_id"]])
10
11car_mask = pan.segment_mask(3) # (H, W) bool mask for one segment id
12result.plot().save("panoptic.png")
13
14# Flip-TTA works here too (new in v1.4.0)
15result = model.predict("street.jpg", augment=True)

PanopticSegmentation API

python
1pan = result.panoptic
2pan.data # (H, W) int segment-id map at original resolution
3pan.segments_info # list of {"id", "category_id", ...} dicts
4pan.segment_ids # ids present in the map
5pan.segment_mask(sid) # (H, W) bool mask for one segment
6
7pan.cpu(); pan.numpy()

用 Panoptic Quality 验证

验证通过 PanopticValidator 运行,报告 Panoptic Quality(PQ):这一标准指标把分割质量(匹配段的平均 IoU)与识别质量(段级 F1)相乘。augment=True 可启用翻转 TTA。

python
1metrics = model.val(data="coco_panoptic.yaml")
2print(metrics["metrics/PQ"])

限制

  • 仅推理与验证。v1.4.0 中全景分割的训练与导出都会报错。
  • 使用 panoptic 任务字符串写出的检查点无法被 v1.3.1 加载。
  • 对全景模型而言,result.boxesresult.masks 均为 None:一切都在 result.panoptic 里。

可提示分割

仅 Python API仅推理SAM 3、EdgeTAM、PicoSAM3 为 v1.4.0 新增

LibreSAM 是独立于检测器工厂的一层,因为可提示分割器的调用契约不同:它先运行一次重量级图像编码器,随后用廉价的空间提示(点击、框)换取掩码。没有固定的类别表。安装:pip install "libreyolo[sam]"

有两点常令人意外。其一,LibreSAM工厂函数而非类,并且刻意不在 LibreYOLO() 加载器之内,因此 LibreYOLO("sam_b") 无效,请直接导入。其二,整个层仅支持 Python,没有任何 CLI 入口。

系列传给 LibreSAM()编码器备注
SAM-1"base"(默认), "large", "huge"ViT-B / L / HApache-2.0
SAM-2.1"sam2-tiny", "sam2-small", "sam2-base-plus", "sam2-large"Hiera仅图像,不支持视频
MobileSAM"mobilesam"TinyViT最快

v1.4.0 新增:SAM 3、EdgeTAM、PicoSAM3

三个新成员覆盖了从最高质量到最小体积的光谱。它们直接构造,快照在首次使用时自动下载。

模型构造方式工作尺寸备注
SAM 3LibreSAM3()1008质量最高;基于 transformers。权重在 Hugging Face 上门控,采用 Meta SAM 许可:首次使用前需接受条款并登录。
EdgeTAMLibreEdgeTAM()1024面向边缘端;仅图像推理;从代码到权重均为 Apache-2.0。
PicoSAM3LibrePicoSAM3()96面向极小裁剪图的原生 ROI 分割移植;SAM 层中唯一支持导出的模型(仅 ONNX)。
python
1from libreyolo import LibreSAM3, LibreEdgeTAM, LibrePicoSAM3
2
3model = LibreSAM3() # gated HF weights (Meta SAM license)
4r = model.predict("img.jpg", points=[640, 360], labels=[1])
5
6model = LibreEdgeTAM() # Apache-2.0, edge-friendly
7r = model.predict("img.jpg", bboxes=[100, 100, 500, 500])
8
9model = LibrePicoSAM3() # 96 px ROI segmenter, ONNX-exportable
10r = model.predict("crop.jpg", points=[48, 48], labels=[1])
python
1from libreyolo import LibreSAM
2
3model = LibreSAM("base")
4
5# 一次点击
6r = model.predict("img.jpg", points=[640, 360], labels=[1])
7print(r.masks.data.shape) # (1, H, W) 布尔掩码,原图分辨率
8print(r.boxes.conf) # SAM 预测的掩码质量,不是检测置信度
9
10# 框提示
11r = model.predict("img.jpg", bboxes=[100, 100, 500, 500])

编码一次,多次提示

python
1model.set_image("img.jpg") # 重量级编码器只运行一次
2a = model.predict(points=[500, 375], labels=[1]) # 廉价:只跑解码器
3b = model.predict(bboxes=[100, 100, 200, 200]) # 廉价:复用图像嵌入
4model.reset_image()

提示的形状

嵌套层级是有含义的,这是最容易出错的地方。标签 1 表示包含,0 表示排除。

你传入含义
points=[x, y]一个目标,一个点
points=[[x, y], [x, y]]两个目标,各一个点
points=[[[x, y], [x, y]]]一个目标,两个点

限制

  • 整层仅支持图像。v1.4.0 没有视频分割,也没有跨帧记忆传播(SAM 2、SAM 3 和 EdgeTAM 亦然),track() 会报错,请逐帧调用 predict()
  • 不支持训练与验证,所有 SAM 系列均如此。导出除 PicoSAM3(仅 ONNX)外全部报错。
  • 不支持掩码提示(masks=),请使用点或框。
  • 全程使用 fp32,即便在 CUDA 上也是如此。这是有意为之:半精度会在 SAM 的 1024px 工作尺度上把提示坐标舍入若干像素,悄悄挪动你点击的位置。

开放词表检测

仅 Python APIOmDet-Turbo 与 OV-DEIM 为 v1.4.0 新增

用文本给出类别名列表,就能得到真实的检测框。无需训练,也无需标注数据。改变列表,就改变它检测的东西。安装:pip install "libreyolo[openvocab]"

它与 LibreVLM 不同,这一点很关键。这些是以文本为条件的专用检测器:检测头直接输出带真实模型分数的框;而 VLM 是生成文本,再由 LibreYOLO 解析成框。经验法则:要“给已命名类别画框”就用开放词表;要“描述或指令”就用 VLM。许可请按系列核对:Grounding DINO、OWLv2 和 OmDet-Turbo 的权重为 Apache-2.0,但 OV-DEIM 的权重为 CC BY-NC 4.0(非商用,已与上游作者确认)。

传给 LibreOpenVocab()主干默认 conf
"grounding-dino"(默认,tiny)LibreGroundingDINOSwin-T + BERT0.25
"grounding-dino-base"LibreGroundingDINOSwin-B + BERT0.25
"owlv2"LibreOWLv2ViT-B/160.1
"owlv2-large"LibreOWLv2ViT-L/140.1
"omdet-turbo"(v1.4.0 新增)LibreOMDetTurboSwin-T,基于 transformers0.25
"ov-deim" / "-m" / "-l"(v1.4.0 新增)LibreOVDEIMDEIM,原生无 NMS 移植0.25

词表设置在模型上,通过 set_classes(),并且会在后续调用中保持。predict()没有 prompts=text= 参数。

python
1from libreyolo import LibreOpenVocab
2
3model = LibreOpenVocab("grounding-dino")
4model.set_classes(["person", "dog", "skateboard"]) # 持久词表
5
6result = model.predict("street.jpg", conf=0.25, text_threshold=0.25)
7print(result.names) # {0: 'person', 1: 'dog', 2: 'skateboard'}
8
9result = model.predict("another.jpg") # 词表仍然有效

小心同名陷阱。predict(classes=...) 不是文本接口,它是标准的整数类别 id 过滤器。文本词表只能通过 set_classes() 设置。

实用提示

  • 简短的名词短语效果最好,"remote control" 优于 "remote"。无法明确映射回你类别名的短语会被丢弃,因此漏检有时是映射被丢弃,而不是检测器没看到。
  • 类别数量没有上限。Grounding DINO 会自动把长词表切分成多个块,每块跑一次前向,因此开销随词表增大而增长,这是你能控制的主要延迟因素。
  • text_threshold 仅适用于 Grounding DINO,传给其他系列会报错。
  • 各系列的打分尺度不同,请分别调 conf,不要复用同一个数值。
  • OV-DEIM 是值得关注的速度选项:原生的无 NMS 移植(不是 transformers 流水线),提供三个尺寸。它的文本特征按词表缓存,v1.4.0 修复了该缓存在设备切换时的崩溃。注意权重为非商用许可。
  • OmDet-Turbo 基于 transformers,并会遵循 iou=(v1.4.0 之前会被忽略)。
  • 它比 LibreYOLO 检测器慢得多。务实的用法:先用开放词表探索或自动标注,再训练一个快速检测器。

限制

  • 没有 CLI。libreyolo predict model=grounding-dino 无效,本层只能从 Python 使用。
  • 不支持训练、验证、导出与跟踪,四者都会报错。
  • imgszaugment=True 会被拒绝;iou 会被接受但忽略。
  • 批处理不会带来加速,且全程 fp32。

姿态估计

姿态(关键点)估计可在 YOLO-NAS (-pose) EdgeCrafter (-pose) 以及 RF-DETR (-pose) 预览上运行。已发布的检查点都是单类别 ("person"),具有 17 个 COCO 关键点。v1.4.0 新增:YOLO-NAS 姿态支持多类别关键点训练, 并且多类别检查点会以真实的类别数加载、返回真实的类别 id(此前会被强制视为单类别 person)。

运行姿态

python
1from libreyolo import LibreYOLO
2
3# YOLO-NAS pose
4model = LibreYOLO("LibreYOLONASs-pose.pt")
5result = model("people.jpg")
6
7# EdgeCrafter pose
8# model = LibreYOLO("LibreECs-pose.pt")
9
10# Per-person bbox + 17 keypoints
11print(result.boxes.xyxy) # person boxes (N, 4)
12print(result.keypoints.xy.shape) # (N, 17, 2) pixel coordinates

预览 RF-DETR 姿态(移植自 GroupPose)在 v1.4.0 中仍是研究预览。

python
1# RF-DETR pose preview
2model = LibreYOLO("LibreRFDETRx-pose.pt")
3result = model("people.jpg")
4print(result.keypoints.xy.shape) # (N, 17, 2)

关键点 API

python
1result.keypoints.xy # (N, K, 2) absolute pixel coords
2result.keypoints.xyn # (N, K, 2) normalized to [0, 1]
3result.keypoints.conf # (N, K) per-keypoint confidence (None if model doesn't emit it)
4result.keypoints.has_visible # (N, K) bool - conf > 0
5
6result.keypoints.cpu()
7result.keypoints.numpy()

保存标注后的输出

python
1model("people.jpg", save=True) # draws boxes + skeleton

YOLO-NAS 支持姿态训练(v1.4.0 起包括多类别数据集);EdgeCrafter 姿态目前仅推理。RF-DETR 姿态为预览。YOLO9 仅检测,不提供姿态检查点。多 GPU DDP 下的姿态验证已在 v1.4.0 修复(各 rank 互相覆盖文件与集合通信死锁)。

视线估计

视线方向估计由 LibreL2CS 系列提供,它是 L2CS-Net 的移植,具有 ResNet 主干和两个角度分箱分类头。这是一个两阶段模型:上游的人脸检测器定位人脸,然后视线头以弧度预测每张人脸的 pitch 和 yaw。它在 v1.4.0 中仅推理且为实验性。(v1.4.0 还通过加入 YuNet 检测器修复了 OpenCV 5 上的人脸检测。)

安装

bash
1pip install libreyolo[gaze] # optional Google Drive helper for Gaze360 weights

已发布的 L2CS ResNet-50 权重在 Gaze360 上训练,LibreYOLO 不做镜像。在没有可选助手的情况下,请传入本地检查点路径,或按照 LibreL2CS 打印的手动下载说明操作。

两阶段推理

python
1from libreyolo import LibreYOLO
2from libreyolo.models.l2cs.face import resolve_face_detector
3
4# Gaze head
5gaze = LibreYOLO("LibreL2CSr50.pt")
6
7# Wire any LibreYOLO detector trained on faces
8face = LibreYOLO("path/to/face-detector.pt")
9gaze.face_detector = resolve_face_detector(face)
10
11result = gaze("portrait.jpg")
12print(result.boxes.xyxy) # face boxes
13print(result.gaze.data) # (N, 2) tensor - pitch, yaw in radians

解码角度

python
1import math
2
3for i in range(len(result.gaze)):
4 pitch_rad, yaw_rad = result.gaze.data[i].tolist()
5 pitch_deg = pitch_rad * 180.0 / math.pi
6 yaw_deg = yaw_rad * 180.0 / math.pi
7 print(f"face {i}: pitch={pitch_deg:.1f} deg, yaw={yaw_deg:.1f} deg")

在命令行中:libreyolo predict model=LibreL2CSr50.pt source=portrait.jpg --face-detector path/to/face.pt

分类

整图分类覆盖两条监督路径和一条零样本路径。LibreMobileNetV4 是生产级分类器(Apache-2.0 ImageNet-1k 权重,可导出为 ONNX),LibreConvNeXtLibreEfficientNetV2LibreResNet 提供同一 API 下的替代选择。LibreDINOv2 配合 task=classify 是 DINOv2 主干加线性探针,非常适合迁移学习,但其发布的权重为演示级,且暂不支持导出。零样本分类(无需训练,标签即文本)请用 CLIP 或 v1.4.0 新增的 SigLIP2。分类训练在 v1.4.0 中获得了自己的增强参数包auto_augmenterasingmixupcutmix

系列检查点输入权重微调ONNX 导出
LibreMobileNetV4LibreMobileNetV4{s,m,l}-cls.pt224 / 224 / 256Apache-2.0 ImageNet-1k(生产级)交叉熵支持
LibreDINOv2(classify)LibreDINOv2{n,s,m,l}-cls.pt224Imagenette 演示级(10 类)线性探针不支持

LibreMobileNetV4(生产级分类器)

Apache-2.0 ImageNet-1k 权重

原生 MobileNetV4-conv 移植(源自 timm),其 1000 类 ImageNet-1k 权重可逐比特一致地加载。尺寸 s / m 在 224 运行,l 在 256 运行。检查点:

LibreMobileNetV4s-cls.pt, LibreMobileNetV4m-cls.pt, LibreMobileNetV4l-cls.pt

加载并预测。单张图像返回一个 Results;直接从中读取 .probs(传入列表则返回列表)。

python
1from libreyolo import LibreYOLO
2
3# MobileNetV4-conv-Small, Apache-2.0 ImageNet-1k weights (auto-downloaded if missing)
4model = LibreYOLO("LibreMobileNetV4s-cls.pt")
5result = model("cat.jpg") # single image -> one Results
6
7probs = result.probs # whole-image class vector, length = num classes
8print(probs.top1, probs.top1conf) # top-1 class id (int) and its confidence
9print(probs.top5, probs.top5conf) # 5 class ids and 5 confidences
10print(result.names[probs.top1]) # human-readable class name

微调到自定义类别集(ImageFolder 布局)。分类头会自动按数据集类别数重建;ImageNet 预训练主干可干净地迁移。

python
1from libreyolo import LibreMobileNetV4
2
3model = LibreMobileNetV4(size="s") # ImageNet-pretrained backbone
4model.train(
5 data="imagenette160", # known name, dataset root, or .zip URL
6 epochs=5,
7 batch=64,
8 lr0=1e-3, # AdamW + cosine, 1-epoch warmup
9 imgsz=224,
10)

验证(top-1 / top-5 精度):

python
1model = LibreYOLO("LibreMobileNetV4s-cls.pt")
2metrics = model.val(data="imagenette160")
3print(metrics["metrics/accuracy_top1"])
4print(metrics["metrics/accuracy_top5"])

导出为 ONNX(已验证与 eager 模式逐比特一致)。ONNX 图输出单个 logits 张量。

python
1model = LibreYOLO("LibreMobileNetV4s-cls.pt")
2path = model.export(format="onnx", imgsz=224) # single output: logits [batch, num_classes]
3
4# Interop note: the ONNX output is RAW LOGITS, not softmaxed. The PyTorch
5# predict path applies softmax for you; non-Python consumers must apply it
6# themselves before reading probabilities.

LibreDINOv2 分类(线性探针 / 迁移)

演示级权重(Imagenette)不支持导出

冻结风格的 DINOv2-S 编码器加可训练线性头,在 224 运行。n / s / m / l 尺寸只控制投影头宽度:四者共享同一个 DINOv2-S 编码器,因此发布的检查点精度几乎相同。随附的 -cls 权重为演示级(在 Imagenette 上训练,10 类),因此请将该系列视为迁移学习选项,而非可直接替换的 1000 类分类器。检查点:

LibreDINOv2n-cls.pt, LibreDINOv2s-cls.pt, LibreDINOv2m-cls.pt, LibreDINOv2l-cls.pt

加载并预测(与 MobileNetV4 相同的 Probs 接口):

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreDINOv2s-cls.pt") # DINOv2-S backbone + linear probe (224)
4result = model("springer.jpg")
5print(result.probs.top1, result.probs.top1conf)

微调用于迁移。用 task="classify" 构建全新模型以获得全新分类头,或加载随附的 -cls 检查点继续训练。为获得最佳精度,请从随附检查点而非全新分类头开始微调,并保持默认的 lr=1e-4(更高的学习率收敛更差)。

python
1from libreyolo import LibreDINOv2
2
3# Fresh DINOv2 backbone + random linear head, sized to the dataset
4model = LibreDINOv2(size="s", task="classify", nb_classes=3)
5model.train(data="path/to/imagefolder", epochs=5, lr=1e-4, batch=4)
6
7# Validate the same way (top-1 / top-5)
8metrics = model.val(data="path/to/imagefolder")
9print(metrics["metrics/accuracy_top1"])

LibreDINOv2 未实现导出。如果你需要可导出的分类器,请使用 LibreMobileNetV4。

python
1model = LibreYOLO("LibreDINOv2s-cls.pt")
2model.export(format="onnx")
3# raises NotImplementedError: Export is not yet implemented for LibreDINOv2.

数据集布局(两个系列)

分类使用 ImageNet 风格的 ImageFolder 目录树(按文件夹组织,而非标签文件)。类别索引按文件夹名称排序分配。data= 接受数据集根目录、已知名称(如 imagenette160)或 .zip URL。

text
1dataset_root/
2 train/ # required; one subfolder per class
3 class_a/img001.jpg
4 class_a/img002.jpg
5 class_b/img003.jpg
6 val/ # required for validation; same class folders as train
7 class_a/img010.jpg
8 class_b/img011.jpg

Results.probs 参考

python
1probs = result.probs # Probs payload, 1-D vector of length = num classes
2probs.data # raw tensor / ndarray of class probabilities
3probs.top1 # int - argmax class id
4probs.top5 # list - 5 class ids, highest first
5probs.top1conf # float - confidence of the top-1 class
6probs.top5conf # 5 confidences, aligned with probs.top5

零样本分类:SigLIP2 与 CLIP

SigLIP2 为 v1.4.0 新增仅推理

零样本分类器把图像与运行时给定的文本标签逐一打分:无需训练,也没有固定类别表。v1.4.0 在原有 CLIP 系列之外新增了 LibreSigLIP2(尺寸 b16 so400m,原生 torch 移植)。两者都通过工厂加载,并用 set_classes() 设置词表;SigLIP2 的 SentencePiece 分词器需要 pip install "libreyolo[siglip2]"

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreSigLIP2b16-cls.pt")
4model.set_classes(["a forklift", "an empty aisle", "a spill"])
5
6result = model.predict("warehouse.jpg")
7print(model.names[result.probs.top1], float(result.probs.top1conf))
8
9# Independent per-label probabilities (sigmoid) instead of softmax
10result = model.predict("warehouse.jpg", multi_label=True)

SigLIP2 的 sigmoid 训练目标让 multi_label=True 的分数本身就有意义(CLIP 式 softmax 分数则不然):当多个标签可能同时为真时用它。两种零样本系列的 train() 都会报错。

  • MobileNetV4 权重为生产级(Apache-2.0 ImageNet-1k,逐比特一致加载)。DINOv2 分类权重为演示级(Imagenette,10 类)。
  • 自 v1.3.0 起不再有 LibreRFDETR 分类器。分类已迁移到专门的分类器系列;旧的 LibreRFDETR*-cls 检查点在加载时会被拒绝。
  • 使用默认配方从头微调 DINOv2 在 Imagenette 上的 top-1 上限约为 0.93,低于随附的 0.976。从随附的 -cls 检查点开始微调以恢复精度。
  • ONNX 分类输出为原始 logits。请在非 Python 消费方中自行应用 softmax。
  • 预测单张图像返回一个 Results。直接读取 result.probs,或传入列表并对列表取索引:model(["a.jpg"])[0].probs。
  • v1.4.0 新增:square_resizeaugment 同时使用现在会直接报错而不是悄悄出错,并且分类器系列支持 spawn 路径的多 GPU 训练。

深度估计

ZipDepth 与 Depth Anything 3 为 v1.4.0 新增仅推理与验证

单目深度估计预测一张密集的相对逆深度图:值越大越靠近相机,不隐含任何度量单位。v1.4.0 在同一 API 下提供三个深度系列,主要差别在体量、许可和目标硬件:

系列尺寸(输入)许可检查点
LibreDepthAnythingV2s / b / l / g(518)s 为 Apache-2.0;b / l / g 为 CC-BY-NC-4.0LibreDepthAnythingV2s-depth.pt, LibreDepthAnythingV2b-depth.pt, LibreDepthAnythingV2l-depth.pt;g 需从上游转换
LibreDepthAnything3(新增)l(504)Apache-2.0LibreDepthAnything3l-depth.pt
LibreZipDepth(新增)b / bnpu(384)MITLibreZipDepthb-depth.pt, LibreZipDepthbnpu-depth.pt

LibreDepthAnything3 是与 V2 并列的独立系列(不是原地升级),只有一个 Apache-2.0 的 large 检查点:在意许可时的质量之选。LibreZipDepth 是效率之选:MIT 许可、384 px,其 bnpu 变体的解码器避开了对 NPU 不友好的算子,适合边缘加速器。

运行深度估计

输入 imgsz 必须能被 14 整除(DINOv2 的 patch 网格)。深度图在原始图像画布上返回。

python
1from libreyolo import LibreYOLO
2
3# ViT-S encoder, Apache-2.0 weights (commercial use OK)
4model = LibreYOLO("LibreDepthAnythingV2s-depth.pt")
5result = model("street.jpg")
6
7depth = result.depth_map # DepthMap payload, (H, W) float on the original canvas
8print(depth.data.shape) # (H, W)
9print(depth.min, depth.max, depth.mean) # relative inverse depth: higher = closer
10norm = depth.normalized() # rescaled to [0, 1] over finite values

DepthMap API

python
1depth = result.depth_map
2depth.data # (H, W) float tensor / ndarray, relative inverse depth
3depth.min # min over finite values
4depth.max # max over finite values
5depth.mean # mean over finite values
6depth.normalized() # (H, W) rescaled to [0, 1]; non-finite pixels become 0
7
8depth.cpu()
9depth.numpy()

零样本验证

验证通过共享的深度验证器以零样本方式运行,并报告标准深度指标(AbsRel、RMSE 和 delta 阈值)。验证器会信箱填充到固定正方形并排除填充像素;由于预测使用 Depth Anything 原生的保持纵横比缩放,非正方形的验证指标是预测的有据近似。

python
1metrics = model.val(data="depth_dataset.yaml")
2print(metrics["metrics/abs_rel"]) # absolute relative error (lower is better)
3print(metrics["metrics/rmse"]) # root mean squared error
4print(metrics["metrics/delta1"]) # fraction within a 1.25x ratio (higher is better)

导出(v1.4.0 新增)

v1.4.0 为 Depth Anything V2 和 ZipDepth 解锁了深度导出,采用固定分辨率、batch 1 的契约:导出的图固定一个输入尺寸,没有动态轴。Depth Anything 3 暂不支持导出。

python
1model = LibreYOLO("LibreZipDepthb-depth.pt")
2model.export(format="onnx") # fixed resolution, batch 1

不支持

python
1model.train(data="...") # raises NotImplementedError - all depth families are inference + val only
  • Depth Anything V2 的许可是分开的:尺寸 s 为 Apache-2.0,可商用;b / l / g 为 CC-BY-NC-4.0(非商业)。商用请选择 V2 的尺寸 s、Depth Anything 3 或 ZipDepth。
  • 深度为相对逆深度,没有度量单位。如果你需要以米为单位,请自行标定。
  • Depth Anything V2 的 imgsz 必须能被 14 整除(DINOv2 patch 网格)。批量预测被禁用,因为保持纵横比缩放会导致每张图像尺寸不一。
  • v1.4.0 起深度模型支持视频输入(v1.3.1 中会崩溃)。

图像修复与超分

SwinIR 与 Real-ESRGAN 为 v1.4.0 新增NAFNet 可训练

restore 任务接收退化的图像,返回更好的图像。与这里的多数任务不同,它没有要检测的东西:输出就是一张图像,通过 result.restored 获取。在 v1.4.0 中该任务覆盖两类工作:清理(去噪 / 去模糊,输出与输入同分辨率)和新增的超分辨率(每个方向放大 2 倍或 4 倍;result.restore_scale 会告诉你倍数)。

系列工作尺寸输出倍数可训练?
LibreNAFNet去噪 / 去模糊s / l1x
LibreSwinIR(新增)超分辨率s / m / l4x
LibreRealESRGAN(新增)超分辨率x4 / x2 / x4t4x / 2x / 4x(快速)

清理模型究竟修复什么(去噪还是去模糊)取决于它训练所用的权重,而不是模型尺寸。超分模型的倍数则固化在检查点里:预测时没有倍数参数。

检查点

NAFNet 发布了一个检查点:LibreNAFNetl-restore-sidd.pt,一个基于 SIDD 训练的真实图像去噪模型,从上游 NAFNet 逐位精确转换而来,MIT 许可。去模糊没有已发布的检查点:请用 weights/convert_nafnet_weights.py 自行转换上游 GoPro 权重。注意 LibreNAFNets-restore.ptLibreNAFNetl-restore.pt 这两个名字并未托管,请求它们会下载失败。

超分辨率则全部托管:SwinIR LibreSwinIRs-restore.pt, LibreSwinIRm-restore.pt, LibreSwinIRl-restore.pt(代码与权重均为 Apache-2.0)以及 Real-ESRGAN LibreRealESRGANx4-restore.pt, LibreRealESRGANx2-restore.pt, LibreRealESRGANx4t-restore.ptx4t 是紧凑的 SRVGG 变体:快得多,也明显更软。

清理一张图像

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreNAFNetl-restore-sidd.pt") # SIDD 去噪
4result = model("noisy.jpg")
5
6img = result.restored # RestoredImage
7print(img.array.shape) # (H, W, 3) uint8 RGB,原始分辨率
8print(result.restore_scale) # 清理模型为 1
9img.save("clean.png") # 无损保存

清理在图像的原生分辨率上进行:输入会先填充到 16 的倍数,之后再裁回原尺寸,因此输出与输入尺寸一致。

放大一张图像(v1.4.0 新增)

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreSwinIRm-restore.pt") # 4x super-resolution
4result = model("small.jpg")
5print(result.restore_scale) # 4
6result.restored.save("big.png") # 4x height, 4x width
7
8# Real-ESRGAN: seam-free tiled upscaling for large inputs
9model = LibreYOLO("LibreRealESRGANx4-restore.pt")
10result = model("photo.jpg", tile=512) # process in 512px tiles, bounded VRAM

务必无损保存

这一点最容易出错。libreyolo predict --save 默认写出 JPEG,会把压缩伪影重新引入你刚刚花模型清理干净的图像。请显式要求 PNG。

bash
1libreyolo predict model=LibreNAFNetl-restore-sidd.pt source=noisy.jpg \
2 save=true output-file-format=png

训练与验证(NAFNet)

NAFNet 训练使用成对的退化 / 干净图像;SwinIR 与 Real-ESRGAN 仅支持推理与验证。验证报告 PSNR 与 SSIM。v1.4.0 新增:修复训练默认应用成对的垂直翻转和 90 度旋转(输入与目标一起变换),因此重新训练的结果与 v1.3.1 会略有差异;见数据增强

python
1model.train(data="gopro.yaml", epochs=100)
2
3metrics = model.val(data="gopro.yaml")
4print(metrics["metrics/psnr"], metrics["metrics/ssim"])
  • 训练时有两处显示上的怪癖:控制台会把 PSNR 打印在 mAP50 这一列标题下(标签错误,数值确实是 PSNR);并且 PSNR/SSIM 计算时不做边界裁剪,因此不能直接与公开的 NAFNet 基准数字对比。
  • 导出(NAFNet):支持 ONNX(仅静态尺寸,且 imgsz 必须是 16 的倍数)与 TorchScript;TFLite 与 CoreML 会报错。SwinIR 与 Real-ESRGAN 在 v1.4.0 中不支持导出。

背景移除

v1.4.0 新增仅推理与验证

matte 任务为每个像素预测一个 [0, 1] 区间的 alpha 值:该像素属于前景主体的程度。与二值分割掩码不同,matte 能保留柔和的边缘(发丝、毛发、运动模糊),抠图效果的好坏正取决于此。v1.4.0 提供 LibreBiRefNet,BiRefNet 的 1024 px 移植,尺寸为 tlLibreBiRefNetl-matte.pt 权重已托管;t(lite)权重在许可确认前暂未重新托管,如需小模型请自行转换。

抠出主体

python
1from libreyolo import LibreYOLO
2from PIL import Image
3
4model = LibreYOLO("LibreBiRefNetl-matte.pt")
5result = model("portrait.jpg")
6
7matte = result.matte # Matte payload
8print(matte.data.shape) # (H, W) float32 alpha in [0, 1], original canvas
9
10# RGBA cutout: original pixels with the matte as the alpha channel
11rgba = result.cutout() # (H, W, 4) uint8
12Image.fromarray(rgba).save("subject.png") # transparent background
13
14# Or composite yourself
15alpha = matte.array[..., None] # (H, W, 1)

save=True 会写出 matte 叠加图;对视频源则逐帧渲染(matte 视频叠加自 v1.4.0 起可用)。验证通过 MatteValidator 与真值 alpha 图对比。

限制

  • 仅推理与验证。v1.4.0 中 matte 的训练与导出都会报错。
  • 使用 matte 任务字符串写出的检查点无法被 v1.3.1 加载。
  • 抠图请保存为 PNG 或 WebP。JPEG 没有 alpha 通道,存成 JPEG 会悄悄拍平透明度。

文字识别(OCR)

v1.4.0 新增仅推理与验证

ocr 任务读取文字:检测阶段以四点多边形找出文本区域,识别阶段逐一转写。v1.4.0 提供 LibrePPOCR,PP-OCRv5 的 960 px 移植,尺寸为 tlLibrePPOCRt-ocr.pt, LibrePPOCRl-ocr.pt。结果通过 result.ocr 获取,这是一个 OCRRegions 负载,把每个多边形与其文本和两个置信度(检测一个、识别一个)配对。

从图像读取文字

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibrePPOCRt-ocr.pt")
4result = model("receipt.jpg")
5
6ocr = result.ocr # OCRRegions
7print(ocr.polygons.shape) # (N, 4, 2) quad corners in pixels
8for text, conf in zip(ocr.texts, ocr.confidence):
9 print(f"{conf:.2f} {text}")
10
11ocr.det_confidence # (N,) detector scores, separate from recognition
12result.plot().save("read.png") # polygons + transcriptions drawn on the image

CLI 与验证

libreyolo predict --json 会输出一个 ocr 数组(每个区域的多边形、文本与置信度),让 CLI 可以直接用于文档处理流水线。验证通过 OCRValidator 运行,它先用最优一对一匹配把预测与真值配对,再计分。

bash
1libreyolo predict model=LibrePPOCRt-ocr.pt source=receipt.jpg --json | jq .ocr

限制

  • 仅推理与验证。v1.4.0 中 OCR 的训练与导出都会报错。
  • 使用 ocr 任务字符串写出的检查点无法被 v1.3.1 加载。
  • 对 OCR 模型而言 result.boxesNone:区域是 result.ocr 中的多边形,不是轴对齐的框。

点定位

实验性

LibreFOMO 是 FOMO 风格的点定位器(尺寸 s / m / l),用于质心式检测:每个检测不是框,而是一个图像坐标。预测以 result.points 形式返回。预训练的 LibreFOMO 权重不会自动下载,因此请传入本地检查点路径(或从头训练,这属于实验性,需要 allow_experimental=True)。v1.4.0 新增:FOMO 支持固定分辨率契约下的 ONNX 导出,训练好的点模型可以离开 Python 部署到边缘端。

python
1from libreyolo import LibreYOLO
2
3# LibreFOMO weights are not hosted by LibreYOLO - pass a local checkpoint
4model = LibreYOLO("path/to/LibreFOMOm-point.pt")
5result = model("scene.jpg")
6
7points = result.points # Points payload, (N, 4) rows: x, y, class, confidence
8print(points.xy) # (N, 2) absolute pixel coords
9print(points.xyn) # (N, 2) normalized to [0, 1]
10print(points.cls, points.conf)

标注(LibreLabel)

libreyolo label 启动一个本地的、基于浏览器的标注工具。它把 LibreYOLO 原生格式的标签文件直接写到训练器已经会读取的位置,因此一个图像文件夹无需任何转换就能变成可训练的数据集,不需要云账号,也不需要数据库。服务端只用 Python 标准库,全程在你自己的机器上运行。

bash
1# 打开已有数据集
2libreyolo label data=path/to/data.yaml
3
4# 也可以直接给一个图像文件夹
5libreyolo label data=path/to/images
6
7# 从项目主页开始,在浏览器里创建项目
8libreyolo label
选项默认值作用
data(无)数据集 YAML 或文件夹。省略则打开项目主页。
host127.0.0.1绑定的网卡地址。修改前请先看下面的共享说明。
port8000绑定端口,被占用时自动向后顺延最多 19 个端口。
deviceautoAI 辅助功能使用的设备。
no_assistfalse彻底关闭所有 AI 辅助。
no_browserfalse不自动打开浏览器。
sharefalse绑定 0.0.0.0,让局域网内的同事一起标注。

可以标注什么

检测框(detect)、多边形(segment)与旋转框(obb,带旋转手柄)。关键点、掩码与深度文件以只读方式打开,这样保存时绝不会悄悄丢掉它不理解的字段。分类标注尚不可用。

AI 辅助,以及它绝不打破的一条规则

LibreLabel 可以用你自己的检测器预标注、用 SAM 把一次点击变成掩码、审计已有标签中可能的错误、找出近似重复的图像,并检测训练/验证集泄漏。任何 AI 路径都不会写入标签文件。所有建议都只存在内存中,直到人工确认。AI 辅助也绝不会下载权重:如果检查点不在本地,它会拒绝并提示你,而不是在背后拉取数百 MB。

导出

在浏览器的导出对话框中可导出为 YOLO、COCO 或 VOC(也可一次导出多种),并提供可复现的训练/验证/测试划分。注意这是浏览器里的操作,没有对应的 CLI 参数。导入仅支持 YOLO,因此 COCO 与 VOC 只是导出格式,不是入口。

共享,以及一个值得注意的陷阱

这里完全没有任何身份认证,访问控制纯粹依赖网络位置,因此只在你信任的网络上共享。

反直觉的地方在于:share=true 才是让同事加入的安全方式。它绑定通配地址,而管理员权限要求来自回环连接,因此你在本机保留管理员权限,同事只得到一个仅供标注的视图。反过来,绑定具体地址(host=192.168.1.50)会让你的机器与同事无法区分,从而把完整管理员权限交给局域网内的每一个客户端。请优先使用 share=true

训练

v1.4.0 验证范围

经过充分测试的路径是 YOLO9 和 RF-DETR 的检测、训练与推理,包括 RF-DETR 分割。

其他模型系列和任务均可使用,但仍属实验性。多 GPU 训练在 v1.4.0 中经历了正确性大修,比 v1.3.x 可靠得多,但仍在已验证范围之外。

经过充分测试的训练路径是单 GPU 的 YOLO9 检测、RF-DETR 检测和 RF-DETR 分割。其他模型系列的训练器和多 GPU 工作流可用,但为实验性。YOLO9 仅检测,因此没有 YOLO9 分割或姿态训练。v1.4.0 新增:YOLOv7 可训练(SimOTA 损失)、SegFormer 可微调,并且每个增强参数都在数据增强章节中按系列写明。

YOLO9 - CNN 旗舰训练

python
1from libreyolo import LibreYOLO
2
3# Fine-tune from a pretrained checkpoint (recommended)
4model = LibreYOLO("LibreYOLO9c.pt")
5
6results = model.train(
7 data="coco128.yaml", # path to data.yaml (required)
8
9 # Schedule
10 epochs=300, # default: 300
11 batch=16,
12 imgsz=640,
13
14 # Optimizer
15 lr0=0.01, # initial learning rate
16 optimizer="SGD", # "SGD", "Adam", "AdamW"
17
18 # System
19 device="0", # "" | "cpu" | "cuda" | "0" | "0,1"
20 workers=8,
21 seed=0,
22
23 # Output
24 project="runs/train",
25 name="yolo9_exp",
26 exist_ok=False,
27
28 # Training features
29 amp=True, # automatic mixed precision
30 patience=50, # early stopping patience
31 resume=False, # resume from loaded checkpoint
32 pretrained=True, # transfer-learning init (True, a path, or None)
33 cache="disk", # cache decoded images: False | True/"ram" | "disk"
34 freeze=10, # freeze first N groups, or a list of indices / module names
35 save_plots=True, # write final validation plots to the run dir
36)
37
38print(f"Best mAP50-95: {results['best_mAP50_95']:.3f}")
39print(f"Best checkpoint: {results['best_checkpoint']}")

训练完成后,模型实例会自动以最优权重重新加载,因此你可以立即调用 model(...)freezecachepretrainedsave_plots 在所有基于训练器的系列中受支持。

RF-DETR - transformer 旗舰训练

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreRFDETRs.pt")
4
5results = model.train(
6 data="path/to/data.yaml",
7 epochs=100,
8 batch_size=4, # NOTE: RF-DETR uses batch_size, not batch
9 lr=1e-4,
10 output_dir="runs/train/rfdetr_exp",
11)

RF-DETR 有自己的训练签名(batch_sizelroutput_dir),但共用 LibreYOLO 的数据集加载器。为检测或分割传入 data.yaml,可采用 YOLO TXT 或原生 COCO JSON 布局,参见 数据集格式

LoRA 微调

实验性 lora=True 注入 LoRA 适配器进行低显存微调:只有适配器 (加上必须保持可训练的部分,如检测头)接收梯度。它需要可选的 peft 依赖(pip install "libreyolo[lora]")。 v1.4.0 把 LoRA 扩展到 RF-DETR 之外:受支持的系列为 RF-DETR、D-FINE、DEIM、DEIMv2、RT-DETR v1 / v2 / v4、EC 和 ConvNeXt(D-FINE 与 EC 仅限 detect)。不支持的系列仍会抛出明确错误,而不是忽略该标志。export() 时适配器会合并进稠密权重,部署产物在运行时不需要 peft。

python
1model = LibreYOLO("LibreRFDETRs.pt")
2results = model.train(data="data.yaml", epochs=50, lora=True)
3
4# Works the same on the newly supported families
5model = LibreYOLO("LibreDEIMs.pt")
6results = model.train(data="data.yaml", epochs=50, lora=True)

实验日志记录器

传入 loggers= 可将指标流式发送到 TensorBoard、 MLflow 或 Weights & Biases。接受名称("tensorboard" "mlflow""wandb")、已配置的日志记录器 实例,或两者混合的可迭代对象。每个后端都是可选 extra (libreyolo[tensorboard][mlflow] [wandb])。

python
1from libreyolo import LibreYOLO
2from libreyolo.training.loggers import MLflowLogger
3
4model = LibreYOLO("LibreYOLO9c.pt")
5
6# By name
7model.train(data="coco128.yaml", loggers="tensorboard")
8
9# Mix configured instances and names
10model.train(
11 data="coco128.yaml",
12 loggers=[MLflowLogger(experiment_name="my-exp"), "tensorboard"],
13)

日志记录器仅为 Python API 功能。命令行没有相应标志;其余新增的训练参数 (--task--cache --lora--freeze --save-plots)在命令行中可用。

训练结果字典

python
1{
2 "final_loss": 2.31,
3 "best_mAP50": 0.682,
4 "best_mAP50_95": 0.451,
5 "best_epoch": 87,
6 "save_dir": "runs/train/yolo9_exp",
7 "best_checkpoint": "runs/train/yolo9_exp/weights/best.pt",
8 "last_checkpoint": "runs/train/yolo9_exp/weights/last.pt",
9}

恢复训练

python
1# Load the checkpoint with the factory, then resume
2model = LibreYOLO("runs/train/yolo9_exp/weights/last.pt")
3results = model.train(data="coco128.yaml", resume=True)

自定义数据集 YAML 格式

data.yaml
1path: /path/to/dataset
2train: images/train
3val: images/val
4test: images/test # optional
5
6nc: 3
7names: ["cat", "dog", "bird"]

其他训练路径

其他系列也有训练器钩子,但在 v1.4.0 中它们不是推荐路径。新工作请保持使用 YOLO9 检测或 RF-DETR 检测/分割;仅出于兼容性、基准复现或针对性研究使用实验性训练器。PicoDet、RTMDet 和 EC 训练需要显式的 allow_experimental=True 确认。注意 v1.4.0 修正了有害的微调默认值:PicoDet(lr0 从 0.1 改为 0.01)和 DEIM(lr0 从 4e-4 改为 1e-4);如需复现上游 COCO 配方,请显式传入旧值。

从 YAML 配置训练

每个 model.train(...) 都接受 cfg="train.yaml",以从文件加载全部参数。显式 kwargs 仍优先于 yaml 中的值,因此你可以用 yaml 作为基线,并按运行覆盖单个字段。

python
1model = LibreYOLO("LibreYOLO9c.pt")
2results = model.train(cfg="configs/yolo9_finetune.yaml")
3# Override individual fields:
4# results = model.train(cfg="configs/yolo9_finetune.yaml", epochs=50)

梯度累积

传入 nbs(名义批大小)以启用梯度累积。训练器每 nbs / batch 次前向后步进一次优化器,从而让你在较小硬件上以配方的参考批大小进行训练。

python
1# Effective batch 64 on a single GPU that only fits batch=8
2model.train(data="coco128.yaml", batch=8, nbs=64)

分布式训练(DDP,v1.4.0 大修)

多 GPU 训练在 v1.4.0 经历了正确性大修。它仍在充分测试范围之外,但失败模式从“悄悄跑错”变成了“大声报错”:

  • 所有系列的分片都已修正。DEIM、D-FINE 和 YOLO-NAS 姿态此前每个 rank 都在用完整批大小训练完整数据集(多买 GPU 毫无收益);现在它们正确分片,损失归一化因子做全局 all-reduce,梯度与单 GPU 训练一致。
  • SyncBatchNorm 默认开启:BatchNorm 密集的系列(YOLO9、YOLOX、YOLOv7、YOLO-NAS、PicoDet、RTMDet、FOMO)在 DDP 下默认同步 BN 统计,修复了各 rank 独立统计导致的真实收敛退化。
  • 启动时硬性报错:全局批大小不能被卡数整除、AutoBatch 之后每 rank 批大小小于 1、自定义加载器不分片,这些情况现在都会在启动时报错。
  • spawn 路径的多 GPU 覆盖到分类器系列(ResNet、ConvNeXt、EfficientNetV2、MobileNetV4)和 NAFNet:传入 device="0,1" 即自动派生工作进程,无需 torchrun。
python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreYOLO9c.pt")
4# Two GPUs: the global batch is split per rank (16 -> 8 + 8)
5model.train(data="coco128.yaml", epochs=300, batch=16, device="0,1")

device="0,1"(或列表 [0, 1])即选择多 GPU。在 torchrun 之下由启动器管理进程组;在它之外,LibreYOLO 会自行派生 DDP 工作进程。两条路径运行同一个训练器。

bash
1# Explicit torchrun launch also works
2torchrun --nproc_per_node=2 train_yolo9.py

数据增强

v1.4.0 完成文档化并由规范测试保障

训练时的数据增强直接在 model.train() 上配置:mosaic、MixUp、HSV 抖动、翻转,以及仿射变换(旋转、平移、缩放、错切、透视)都是普通的关键字参数。同样的参数在 libreyolo train 上以 key=value 形式可用,其中 mosaic=mixup= mosaic_probmixup_prob 的 CLI 简写。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreYOLO9c.pt")
4model.train(
5 data="coco128.yaml",
6 epochs=100,
7
8 # Augmentation knobs (defaults shown in the table below)
9 mosaic_prob=1.0, # 4-image mosaic
10 mixup_prob=0.5, # blend in a second sample
11 hsv_prob=1.0, # HSV color jitter
12 flip_prob=0.5, # horizontal flip
13 flipud=0.1, # vertical flip (good for aerial imagery)
14 degrees=10.0, # random rotation range for the affine warp
15 translate=0.1, # random translation fraction
16 shear=2.0, # random shear, degrees
17 perspective=0.0005, # projective warp magnitude (0 = pure affine)
18 no_aug_epochs=15, # final epochs with strong augmentation off
19)
bash
1libreyolo train model=yolo9-c data=coco128.yaml epochs=100 \
2 mosaic=1.0 mixup=0.5 hsv_prob=1.0 flip_prob=0.5 degrees=10 translate=0.1

增强参数一览

以下是基础 TrainConfig 字段。表中是基类默认值:各系列会用调优过的配方覆盖它们(例如 YOLO9 默认 degrees=0shear=0 且关闭 mixup,而 YOLOX 三者全开)。用 libreyolo cfg 可打印你的模型实际解析出的默认值。

参数基类默认值作用
mosaic_prob1.0把 4 张图拼成一张 mosaic 样本的概率。
mixup_prob1.0混入第二个样本(MixUp)的概率。
hsv_prob1.0HSV 颜色抖动的概率。
flip_prob0.5水平翻转概率。
flipud0.0垂直翻转概率。默认关闭;适合没有固定上下方向的场景(航拍、显微镜)。
degrees10.0仿射变换的随机旋转范围(度)。
translate0.1仿射变换的随机平移比例。
mosaic_scale(0.1, 2.0)仿射变换的随机缩放范围。
shear2.0仿射变换的随机错切范围(度)。
perspective0.0透视变换幅度,在 [-p, +p] 内采样;0.0005 左右是典型值。0 表示纯仿射。
mixup_scale(0.5, 1.5)施加在 MixUp 伙伴图像上的缩放抖动范围。
no_aug_epochs15最后若干个 epoch 关闭强增强,让模型在干净图像上收敛。

哪些系列使用哪些参数

并非每个系列都运行所有增强:每个系列都沿用其配方自带的流水线。v1.4.0 用一份声明式规范 (libreyolo/data/augment/spec.py)把这一点显式化,并用测试钉在真实流水线上。每个参数在每个系列下有三种状态之一,并且 CLI 现在会在你显式设置了所选系列忽略的参数时发出警告:手误或错误假设不会再无声失败。

状态含义
used参数进入训练流水线并改变样本。
gated by mosaic参数只作用于走了 mosaic 分支的样本;mosaic_prob=0 时它永远不会生效。
ignored参数不会进入该系列的流水线;设置它没有任何效果(CLI 会警告)。
流水线系列实际发生的事
YOLOX 式 mosaicYOLO9、YOLO9-E2E、YOLO9-P2、YOLOX、YOLOv7、RTMDet、PicoDet、RT-DETR、RT-DETRv2、FOMOHSV 抖动与翻转逐样本运行。仿射变换(degrees / translate / mosaic_scale / shear / perspective)与 MixUp 只在 mosaic 画布上运行,因此受 mosaic_prob 门控。RTMDet、PicoDet、RT-DETR、RT-DETRv2 和 FOMO 没有垂直翻转;FOMO 还去掉了 perspective。
YOLO-NASYOLO-NAS没有 mosaic(mosaic_prob 被忽略),取而代之的是常开的逐样本仿射,因此 degrees / translate / shear / perspective 直接生效,且 MixUp 独立于 mosaic。
DETR 式直通D-FINE、DEIM、DEIMv2、RT-DETRv4、EC只有 flip_prob 和 no_aug_epochs 可调。颜色抖动、zoom-out 和 IoU 裁剪是固定的配方常量,没有 mosaic、MixUp 或仿射。例外:EC 姿态通过关键点感知仿射使用 hsv_prob、degrees 和 translate。
RF-DETR 原生RF-DETR原生配方中的翻转、尺度抖动与随机裁剪;flip_prob 与 no_aug_epochs 可配置,HSV 不可。
分类ResNet、ConvNeXt、MobileNetV4、EfficientNetV2、DINOv2(classify)检测参数一律不生效(水平翻转固定为 0.5)。请使用下面的分类增强包。
语义SegFormer(及共享的语义流水线)尺度抖动与 HSV 来自系列属性而非 TrainConfig 参数;翻转固定为 0.5。v1.4.0 起 HSV 抖动默认开启。
修复NAFNet输入 / 目标成对的裁剪、翻转与 rot90,概率固定(垂直翻转 + rot90 为 v1.4.0 新增)。TrainConfig 参数被忽略。

mosaic 门控的含义

在 YOLOX 式流水线中,MixUp 与仿射变换搭乘在 mosaic 分支内部:样本先(以 mosaic_prob 的概率)拼成 4 图 mosaic,然后才对 mosaic 画布做仿射并可选地与另一个样本混合。两个实际后果:

  • mosaic_prob=0 会连带关闭这些系列的 MixUp 与仿射,无论其他参数写了什么。v1.4.0 会在 mixup_prob > 0mosaic_prob=0(mixup 永远无法生效)时于训练开始时发出警告。
  • 想减弱增强又保留一些几何变换时,调低 mosaic_prob 而不是归零,或者用 degrees=0 translate=0 shear=0 显式关掉几何部分。
python
1# Minimal augmentation: flips only
2model.train(
3 data="data.yaml",
4 mosaic_prob=0.0, # also disables mixup + affine in mosaic-gated families
5 mixup_prob=0.0,
6 hsv_prob=0.0,
7 flip_prob=0.5,
8 no_aug_epochs=0,
9)

分类增强包(v1.4.0 新增)

分类的 ImageFolder 流水线有自己的四个参数,默认全部关闭。每个 batch 最多运行 MixUp / CutMix 之一:先以 mixup 的概率尝试 MixUp,否则以 cutmix 的概率尝试 CutMix,因此两者之和不应超过 1。

参数默认值作用
auto_augmentNone策略名:"randaugment"、"autoaugment" 或 "augmix"。
erasing0.0RandomErasing 概率。
mixup0.0batch 级 MixUp 概率(软标签)。仅限 Python API:CLI 上的 --mixup 是检测的 mixup_prob 别名。
cutmix0.0batch 级 CutMix 概率(软标签)。
python
1from libreyolo import LibreMobileNetV4
2
3model = LibreMobileNetV4(size="s")
4model.train(
5 data="imagenette160",
6 epochs=20,
7 auto_augment="randaugment",
8 erasing=0.25,
9 mixup=0.2,
10 cutmix=0.2,
11)

任务专属参数

少数参数位于各系列的 TrainConfig 子类而非基础配置上,可从 Python 或训练 YAML 使用(CLI 不暴露它们):

参数系列作用
copy_pasteRF-DETR(segment)、YOLO9 系分割训练的 copy-paste 实例增强概率:把实例剪出并粘贴到样本中。
copy_paste_mode同上粘贴实例的来源:"flip" 镜像同一样本;"mixup" 抽取第二个样本(RF-DETR 仅支持 "flip")。
rot90YOLO9 系(OBB 路径)旋转框训练的随机 90 度旋转概率;对轴对齐检测忽略。
crop_resize_probRF-DETR、D-FINE(segment)、EC(segment)原生流水线中的随机裁剪缩放概率。
brightness_contrast_probYOLO-NAS(pose)、EC(pose)关键点训练的亮度 / 对比度抖动概率。
affine_probYOLO-NAS(pose)、EC(pose)关键点感知仿射的概率。

训练增强与测试时增强

以上一切都发生在 train() 期间。测试时增强(TTA)是另一回事: predict(augment=True) / val(augment=True) 在推理时额外运行增强过的前向并合并输出。v1.4.0 中 TTA 覆盖已实现的检测系列、四个语义分割系列 (PIDNet、SegFormer、EoMT、DINOv2)以及 EoMT 全景分割。

知识蒸馏

学生仅限 YOLO9 与 YOLOXDINOv2 教师为 v1.4.0 新增

知识蒸馏让小模型(学生)在自身标签之外,额外向一个更大的冻结教师模型的中间特征学习。你会得到一个以学生速度运行、却找回部分教师精度的模型。把 distill_model 指向一个教师检查点即可开启蒸馏。

python
1from libreyolo import LibreYOLO
2
3student = LibreYOLO("LibreYOLO9t.pt") # 小学生模型
4
5student.train(
6 data="coco.yaml",
7 epochs=100,
8 distill_model="LibreYOLO9c.pt", # 冻结的教师:这一项开启蒸馏
9 distill_loss_type="mgd", # "mgd"(默认)或 "cwd"
10 dis=2e-5, # 全局权重;省略则使用各损失的默认值
11)
bash
1libreyolo train model=LibreYOLO9t.pt data=coco.yaml epochs=100 \
2 distill-model=LibreYOLO9c.pt distill-loss-type=mgd dis=2e-5
参数默认值含义
distill_modelNone教师检查点路径。设置即开启蒸馏。
disNone蒸馏损失的全局权重。默认回退为 MGD 的 2e-5、CWD 的 1.0。
distill_loss_type"mgd"特征损失:"mgd" 或 "cwd"。
distill_mask_ratio0.65仅 MGD:被遮蔽的空间位置比例。仅 Python API。
distill_tau1.0仅 CWD:softmax 温度。仅 Python API。

注意参数名很短:权重参数叫 dis,而不是 distill_loss_weight

基础模型蒸馏教师:DINOv2(v1.4.0 新增)

除了检查点教师,v1.4.0 新增 distill_model="dinov2":学生主干的特征以 feat_mse 损失向一个冻结的 DINOv2 基础编码器回归。不需要你自己的教师检查点,这是给 YOLO9 主干的训练加上蒸馏信号最省事的方式。

python
1student = LibreYOLO("LibreYOLO9s.pt")
2student.train(
3 data="coco128.yaml",
4 epochs=100,
5 distill_model="dinov2", # frozen foundation teacher
6 distill_loss_type="feat_mse", # feature regression against DINOv2
7 distill_normalize=True, # normalize features before the loss
8)

教师内部以 DINOv2 兼容的分辨率运行;v1.4.0 修复了非 14 倍数尺寸下的边缘裁剪 bug,奇数输入尺寸也能正确蒸馏。

MGD 还是 CWD

MGD(掩码生成式蒸馏,默认)随机遮蔽学生特征的空间位置,并要求它重建教师的特征。由于它回归的是原始特征幅值,默认权重很小:2e-5

CWD(逐通道蒸馏)把每个通道变成一个空间分布,再用 KL 散度对齐。逐通道归一化使它对尺度不敏感,因此在师生特征幅值差距很大时表现更稳。默认权重为 1.0

限制

  • 学生只能是 YOLO9 与 YOLOX 系列。其他系列会在 setup 阶段报错,因为蒸馏需要只有这两个系列声明的特征抽取点。DINOv2 基础教师面向 YOLO9 主干。
  • 师生的 stride 必须完全一致。两个支持的系列都使用 8/16/32,因此实际做法是在同一系列内跨尺寸蒸馏。通道宽度可以自由不同,会由 1x1 适配层桥接。
  • 多卡、混合精度与梯度累积都可与蒸馏同时使用。
  • 支持断点续训并恢复适配层状态,但教师不会存入检查点:续训时请重新传入 distill_model

训练监控

每一次训练、每一个模型系列,都会把机器可读的进度文件写入运行目录,无需任何开关。libreyolo monitor 把它们展示为实时看板;由于它只读取文件,对正在运行、已完成、甚至已崩溃的任务同样有效。

bash
1libreyolo monitor # 在 http://127.0.0.1:8420 监视 runs/
2libreyolo monitor runs/train/exp # 直接打开某一次运行
3libreyolo monitor --port 9000 --no-browser
文件内容
status.json本次运行的当前状态,每个 epoch 原子性重写。
metrics.jsonl仅追加,每个 epoch 一个 JSON 对象,完整指标历史。
train.log运行日志。

status.json 始终包含 staterunningcompletedfailed)、pidprogresseta_seconds,以及当前与最佳指标。如果任务崩溃,它会记录 state: "failed" 以及包含异常类型与信息的 error 对象,因此崩溃会留在文件里,而不是只出现在你已经关掉的终端里。

python
1import json, time
2
3def wait_for_run(run_dir):
4 while True:
5 status = json.load(open(f"{run_dir}/status.json"))
6 if status["state"] != "running":
7 return status
8 print(f'{status["progress"]:.0%} eta {status["eta_seconds"]:.0f}s')
9 time.sleep(30)
10
11final = wait_for_run("runs/train/exp")
12if final["state"] == "failed":
13 print(final["error"]["type"], final["error"]["message"])

性能分析

libreyolo profile 测量时间究竟花在哪里,训练与推理都支持。它刻意只做测量:绝不修改你的配置,也不替你调参。它只告诉你什么慢,决定权留给你。

v1.4.0 行为变化:model.train(profile=True) 现在会在分析窗口结束后继续训练而不是停止(也不再破坏断点续训状态)。传入 profile_then_stop=True 可恢复旧的“采集完即退出”行为。

bash
1# 训练:GPU 真的在忙,还是被数据加载卡住了?
2libreyolo profile run coco128 --weights LibreYOLO9t.pt --batch 16 --repeat 3
3
4# 推理:延迟分位数,以及时间花在哪一段
5libreyolo profile infer bus.jpg --weights LibreYOLO9t.pt --runs 200

profile infer 报告 p50、p90、p99 延迟、吞吐,以及在预处理 / 前向 / 后处理(NMS)之间的耗时拆分。这个拆分往往才是重点:一个看起来很慢的模型,时间常常花在 NMS 或预处理上,而不是网络本身。

子命令回答什么问题
summary总体诊断:利用率、瓶颈在哪、kernel 构成。
phases时间去向:前向、反向、数据加载、优化器。
kernels哪些 GPU kernel 占主导。
ops框架视角:哪些算子最耗 CPU 时间。
compare对比两份 profile,看改动前后。
what-if在动手改代码之前,先估算收益。

两点提示:每个子命令都支持 --json,便于放进自动化的优化循环;而 compare 只有在两份 profile 都用 --repeat 2 或更高采集时才会报告统计显著性,单次运行的噪声足以误导你。

验证

在验证集上运行 COCO 标准评估。经过充分测试的验证路径是单 GPU 的 YOLO9 检测、RF-DETR 检测和 RF-DETR 分割。

python
1results = model.val(
2 data="coco128.yaml", # dataset config
3 batch=16,
4 imgsz=640,
5 conf=0.001, # low conf for mAP calculation
6 iou=0.6, # NMS IoU threshold
7 split="val", # "val", "test", or "train"
8 save_json=False, # save predictions as COCO JSON
9 verbose=True, # print per-class metrics
10 plots=True, # save validation plots (metrics, per-class AP, confusion matrix); alias for save_plots
11)
12
13print(f"mAP50: {results['metrics/mAP50']:.3f}")
14print(f"mAP50-95: {results['metrics/mAP50-95']:.3f}")

验证结果字典

默认情况下,LibreYOLO 使用 COCO 评估,返回精确率、召回率、AP/AR 指标以及每张图像的耗时:

python
1{
2 "metrics/mAP50-95": 0.489, # COCO primary metric (AP@[.5:.95])
3 "metrics/mAP50": 0.721, # AP@0.5 (PASCAL VOC style)
4 "metrics/mAP75": 0.534, # AP@0.75 (strict)
5 "metrics/precision": 0.68,
6 "metrics/recall": 0.61,
7 "metrics/precision(B)": 0.68, # bbox aliases
8 "metrics/recall(B)": 0.61,
9 "metrics/mAP50(B)": 0.721,
10 "metrics/mAP50-95(B)": 0.489,
11 "metrics/mAP_small": 0.291,
12 "metrics/mAP_medium": 0.532,
13 "metrics/mAP_large": 0.648,
14 "metrics/AR1": 0.362, # Average Recall (max 1 det)
15 "metrics/AR10": 0.571,
16 "metrics/AR100": 0.601,
17 "metrics/AR_small": 0.387,
18 "metrics/AR_medium": 0.641,
19 "metrics/AR_large": 0.739,
20 "speed/preprocess_ms": 1.2,
21 "speed/inference_ms": 6.8,
22 "speed/postprocess_ms": 0.9,
23 "speed/total_ms": 8.9,
24 "speed/total_s": 12.3,
25 "speed/images_seen": 1382,
26}

分割验证返回带 (M) 后缀的掩码指标,以及带 (B) 后缀的 框指标;OBB 验证会添加 (OBB) 指标。姿态验证通过 PoseValidator 返回 COCO 关键点指标。除此之外还有分类(top-1 / top-5)、 语义(mIoU / 像素精度)、点定位和深度(零样本)验证器,以及 v1.4.0 新增的全景 (PanopticValidator,Panoptic Quality 指标)、抠图 (MatteValidator)和 OCR(OCRValidator, 最优一对一匹配)验证器。语义与全景验证自 v1.4.0 起接受 augment=True 启用翻转 TTA(此前会报错)。传入 plots=True(或命令行的 --save-plots)可将 指标图、各类 AP、混淆矩阵和样本图写入运行目录。

模型量化

v1.4.0 新增YOLO9 与 RF-DETR

LibreYOLO 直接在 PyTorch 中量化模型。量化后的模型保持正常的 predict / val / train / save 契约,因此精度用与浮点模型相同的验证器测量;精度恢复就是在量化模型上直接 train()(QAT),或再加上现有的蒸馏参数(QAD)。

语法:先量化,可选恢复

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreYOLO9s.pt")
4
5# Step 1: quantize. calib is a small UNLABELED image set, used forward-only
6# to derive activation ranges and scales.
7qmodel = model.quantize(recipe="int8", calib="coco128.yaml", samples=128)
8
9qmodel.val(data="coco8.yaml") # honest accuracy, same validators
10qmodel.predict("bus.jpg")
11qmodel.save("LibreYOLO9s-int8.pt") # manifest-carrying checkpoint
12
13# Step 2 (optional): QAT is plain train() on the quantized model
14qmodel.train(data="coco.yaml", epochs=5)
15
16# QAD: same, plus the existing distillation kwargs
17qmodel.train(data="coco.yaml", epochs=5, distill_model="LibreYOLO9m.pt")
bash
1libreyolo quantize --model LibreYOLO9s.pt --recipe int8 --calib coco8.yaml
2libreyolo train model=LibreYOLO9s-int8.pt data=coco.yaml epochs=5

LibreYOLO("LibreYOLO9s-int8.pt") 会自动恢复量化结构和缩放系数:检查点携带 quant 清单,QAT / QAD 期间训练器写出的检查点同样携带,因此 QAT 跑出的 best.pt 本身就是量化检查点。model.quant_info() 报告配方、模块数量、校准状态和执行层级;model.dequantize() 原地恢复浮点模块。

配方

配方做什么系列校准
fp16半精度转换,保持 float32 输入输出契约。仅推理。yolo9, rfdetr不需要
bf16bfloat16 转换:以一半存储保留 fp32 的指数范围;DETR 式模型 fp16 溢出时的解法。仅推理。yolo9, rfdetr不需要
fp8E4M3 权重 + 激活仿真,作用于 Conv2d 与 Linear。yolo9, rfdetr需要
int8W8A8:逐通道 INT8 权重、逐张量仿射 INT8 激活。yolo9, rfdetr需要(calib=None 时仅量化权重)
w4a16分组 INT4 权重、浮点激活,仅 Linear。rfdetr不需要
w4a8分组 INT4 权重 + INT8 激活;对应 NPU 的 W4A8 部署。rfdetr需要
nvfp4NVFP4 W4A4:E2M1 元素、16 元素块、FP8 块缩放。rfdetr不需要(动态)
mxfp4OCP MXFP4:E2M1 元素、32 元素块、二的幂次缩放。rfdetr不需要(动态)
int2研究预览:分组 2 比特权重 + INT8 激活。仅 PTQ 不可用;必须 QAT / QAD。rfdetr需要

这样划分是有意的:当前硬件上低于 8 比特的加速只在 GEMM 上成立,因此仅作用于 Linear 的配方会对 YOLO9 这类以卷积为主的系列直接拒绝(它们用 int8fp8);4 比特配方的目标是 transformer 系列(RF-DETR)。各系列的 keep_high_precision 默认值保护第一层和各个头;确有把握时可用 quantize(..., keep_high_precision=("head.",)) 覆盖。

校准数据不是训练数据

  • calib= 是几百张图像,不读标签、只做前向。它的工作是激活范围与缩放系数。默认 coco128.yaml(自动下载);多个 batch 很重要,因为范围是跨 batch 估计的。
  • train / val 上的 data= 才是带标签的数据集,负责梯度和指标。参数不同,职责不同。
  • 默认的范围估计是 minmaxalgorithm="percentile" 存在但实测处处更差,还会让 DETR 系精度崩塌,因为 transformer 的激活离群值是承重的。真正解决小模型 int8 敏感性的是用足够多的 batch 校准:用 coco128 默认值时,YOLO9-t 与 fp32 的差距约在 1 个 mAP 点以内。

诚实的数字:先仿真

v1.4.0 以仿真执行量化算术(fake-quantize 加直通梯度,在 fp32 岛内计算)。仿真在数值上是真实的:任何设备上的 val() 分数都是对量化算术的真实断言。但它不是速度断言;打包的低比特 kernel 属于部署层面。fp16bf16 转换是例外:它们原生执行。

部署量化模型

python
1# Finalize: pack real low-bit weights, strip fp32 masters
2qmodel.export(format="pt") # -> <name>-final.pt
3
4# int8 exports straight to QDQ ONNX with the model's own calibrated scales
5qmodel = LibreYOLO("LibreYOLO9s-int8.pt")
6qmodel.export(format="onnx") # ONNX Runtime / TensorRT consume real INT8 kernels
  • 定型后的检查点存储真实打包权重并相应变小(实测:YOLO9-s int8 从 29.5 降到 9.6 MB;RF-DETR-n nvfp4 从 122 降到 26 MB),在定型设备上解包与仿真逐比特一致。加载即得到可推理的模型,对它 train() 会自动重新准备主权重。
  • fp16 / bf16 请先 dequantize() 再走浮点导出器(half=True 得到 fp16 ONNX)。
  • 低于 8 比特的 Linear 配方与 fp8 目前没有可部署的 ONNX 形式:它们在 PyTorch 中执行,通过 format="pt" 定型。
  • 仿真由内置 Triton kernel 支撑,带可插拔注册表和 LIBREYOLO_QUANT_KERNELS 覆盖开关。
  • 携带定型量化状态的检查点无法被 v1.3.1 加载。

导出

将 PyTorch 模型导出为 ONNX、TorchScript、TensorRT、OpenVINO、NCNN、CoreML 或 TFLite 以进行部署。经过充分测试的导出路径仍是单 GPU 的 YOLO9 检测、RF-DETR 检测和 RF-DETR 分割。

支持矩阵是权威依据(v1.4.0 新增)

v1.4.0 用一份规范化的导出支持矩阵取代了猜测。每个系列 / 任务 / 格式组合都有一个档位: validated(已测试,放心用)、 experimental(可导出,带警告)或 blocked(预先报错,而不是产出坏产物)。在围绕某个格式搭建流水线之前先查询它:

bash
1# Formats and tiers for one family / task
2libreyolo formats --family yolo9
3libreyolo formats --family rfdetr --task segment
4
5# Everything about one model, including its export_support map
6libreyolo info --model LibreYOLO9s.pt --json | jq .export_support

v1.4.0 还在固定分辨率、batch 1 的契约下解锁了整组任务的导出:PIDNet(语义)、FOMO(点定位)、ZipDepth / Depth Anything V2(深度)现在都能导出 ONNX。伴随矩阵还有两条行为保证:在请求被接受之前,导出绝不修改活动模型(LoRA 适配器折叠与量化模型重准备只在格式查询和选项预检通过之后发生);LoRA 适配器在导出时合并进稠密权重,部署产物运行时不需要 peft。

快速导出

python
1# ONNX (default)
2model.export()
3
4# TorchScript
5model.export(format="torchscript")
6
7# TensorRT (requires NVIDIA GPU + TensorRT)
8model.export(format="tensorrt")
9
10# OpenVINO (optimized for Intel hardware)
11model.export(format="openvino")
12
13# NCNN (via PNNX)
14model.export(format="ncnn")
15
16# CoreML (.mlpackage, macOS runtime)
17model.export(format="coreml")
18
19# TFLite (needs Python 3.12+); "litert" is an accepted alias
20model.export(format="tflite")
21
22# Quantized checkpoints: pack low-bit weights, or emit QDQ INT8 ONNX
23qmodel.export(format="pt") # finalized packed checkpoint
24qmodel.export(format="onnx") # int8 -> QDQ ONNX (see Quantization)

全部导出参数

python
1path = model.export(
2 format="onnx", # "onnx", "torchscript", "tensorrt", "openvino", "ncnn", "coreml", or "tflite"
3 output_path="model.onnx", # output file (auto-generated if None)
4 imgsz=640, # input resolution (default: model's native); also accepts (h, w) for rectangular
5 opset=None, # ONNX opset (auto: 13, or 17 for wrappers that need it)
6 simplify=True, # run onnxsim graph simplification
7 dynamic=True, # enable dynamic batch axis (ONNX); TFLite requires static shapes
8 half=False, # export in FP16
9 batch=1, # batch size for static graph
10 device=None, # device to trace on (default: model's current device)
11 int8=False, # INT8 quantization: TensorRT, OpenVINO, or ONNX (YOLO9 detection only)
12 data=None, # calibration dataset for INT8
13 fraction=1.0, # fraction of calibration data to use
14 allow_download_scripts=False, # allow data.yaml download hooks during calibration
15 workspace=4.0, # TensorRT workspace size (GB)
16 min_batch=1, # TensorRT dynamic profile minimum batch
17 opt_batch=1, # TensorRT dynamic profile optimal batch
18 max_batch=8, # TensorRT dynamic profile maximum batch
19 hardware_compatibility="none", # TensorRT compatibility mode
20 gpu_device=0, # GPU device index for TensorRT
21 trt_config=None, # optional TensorRT YAML config path
22 compute_units="all", # CoreML routing: all, cpu_only, cpu_and_gpu, cpu_and_ne
23 nms=False, # embed NMS in the graph (ONNX YOLO9 detection, or CoreML)
24 iou=0.45, # embedded-NMS IoU threshold
25 conf=0.25, # embedded-NMS confidence threshold
26 max_det=300, # embedded-NMS max detections (ONNX only)
27 verbose=False, # verbose logging
28)

OpenVINO INT8 导出额外需要 nncf。NCNN 导出会写出一个目录,包含 model.ncnn.parammodel.ncnn.binmetadata.yaml。CoreML 导出会写出 .mlpackage 包,需要 coremltools,且不支持 INT8。

ONNX 内嵌 NMS(YOLO9 检测)

传入 nms=True 可将 NMS 烘焙进导出的 ONNX 图,使模型直接输出最终框。目前仅限 detect 任务上的 yolo9 系列(其他系列/任务会报错)。它会强制固定的 batch-1 图 (dynamic=False),并在 ONNX 元数据中记录 nms / nms_conf / nms_iou / max_det

python
1model = LibreYOLO("LibreYOLO9c.pt")
2model.export(format="onnx", nms=True, conf=0.25, iou=0.45, max_det=300)

int8=True 现在也支持 ONNX(除 TensorRT 和 OpenVINO 之外), 同样仅限 YOLO9 检测;它需要一个用于标定的 data= 数据集。

TFLite (LiteRT) 导出

运行时后端为 v1.4.0 新增 LibreYOLO 提供基于 onnx2tf 的 TFLite 导出路径。TFLite 是 Google LiteRT 运行时的格式(TensorFlow Lite 于 2024 年更名为 LiteRT,.tflite 文件格式不变)。它已在 RF-DETR detect / segment / pose 和 YOLO9 detect 上验证。它需要 Python 3.12+ onnx2tf 2.4.x wheels 不面向更老的 Python),以及 可选 extra libreyolo[tflite](别名 libreyolo[litert])。导出 为 FP32 且仅静态形状(暂不支持 half int8dynamic)。

bash
1pip install "libreyolo[tflite]" # Python 3.12+; [litert] is the same extra
python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreRFDETRs-seg.pt")
4model.export(format="tflite") # writes a .tflite file; format="litert" also works

对于 RF-DETR,导出器会将每个 GridSample 节点改写为 TFLite 安全的双线性 子图,因为 onnx2tf 的默认 lowering 在数值上有问题。

TFLite 不再只是导出格式。 v1.4.0 新增:LibreYOLO("model.tflite") 会通过 LiteRT 运行时后端(ai-edge-litert)加载该文件,运行 ONNX 与 TensorRT 产物的同一个工厂现在也能运行 TFLite;见 TFLite 推理

ONNX 元数据

导出的 ONNX 文件包含内嵌元数据:

示例值
libreyolo_version"1.4.0"
model_family"yolox"
model_size"s"
nb_classes"80"
names'{"0": "person", "1": "bicycle", ...}'
imgsz"640"
dynamic"True"
half"False"

使用 LibreYOLO("model.onnx") 加载导出文件时,会自动读回该元数据。

TorchScript 推理

通过相同的运行时后端预测 API 运行导出的 .torchscript 模型。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("model.torchscript")
4
5result = model("image.jpg", conf=0.25, iou=0.45, save=True)
6print(result.boxes.xyxy)

ONNX 推理

使用 ONNX Runtime 而非 PyTorch 运行推理。适用于没有 PyTorch 的部署环境。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("model.onnx")
4
5result = model("image.jpg", conf=0.25, iou=0.45, save=True)
6print(result.boxes.xyxy)

自动元数据

如果 ONNX 文件由 LibreYOLO 导出,类别名称和类别数会自动从内嵌元数据中读取:

python
1# Export with metadata
2model.export(format="onnx", output_path="model.onnx")
3
4# Load - names and nb_classes auto-populated
5onnx_model = LibreYOLO("model.onnx")
6print(onnx_model.names) # {0: "person", 1: "bicycle", ...}
7print(onnx_model.nb_classes) # 80

对于没有元数据的 ONNX 文件(例如由其他工具导出),请手动指定 nb_classes

python
1model = LibreYOLO("external_model.onnx", nb_classes=20)

设备选择

python
1# Auto-detect (CUDA if available, else CPU)
2model = LibreYOLO("model.onnx", device="auto")
3
4# Force CPU
5model = LibreYOLO("model.onnx", device="cpu")
6
7# Force CUDA
8model = LibreYOLO("model.onnx", device="cuda")

预测参数

通过 LibreYOLO() 加载的运行时产物支持共享的运行时预测 API:

python
1result = model(
2 "image.jpg",
3 conf=0.25,
4 iou=0.45,
5 imgsz=640,
6 classes=[0, 2],
7 max_det=300,
8 save=True,
9 output_path="output/annotated.jpg", # final file path when save=True
10 color_format="auto",
11)

运行时后端不暴露仅 PyTorch 的选项,如 tilingoverlap_ratiooutput_file_format

运行时后端在保存方面与 PyTorch 包装器略有不同:如果你设置 output_path,请传入最终文件路径,而非目录。如果省略它,当前后端默认保存在 runs/detections/ 下。

TensorRT 推理

使用 TensorRT 在 NVIDIA GPU 上获得最大吞吐。需要 CUDA 以及 TensorRT 的 Python 绑定。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("model.engine")
4
5result = model("image.jpg", conf=0.25, iou=0.45, save=True)
6print(result.boxes.xyxy)

通过 LibreYOLO() 加载的 TensorRT 产物支持与 ONNX 和 OpenVINO 相同的核心运行时预测 API,包括 save=True 时同样仅接受文件路径的 output_path 行为。

OpenVINO 推理

使用 OpenVINO 运行推理,针对 Intel CPU、GPU 和 VPU 优化。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("model_openvino/")
4
5result = model("image.jpg", conf=0.25, iou=0.45, save=True)
6print(result.boxes.xyxy)

通过 LibreYOLO() 加载的 OpenVINO 目录会在存在时读取 metadata.yaml,并支持相同的核心运行时预测 API。

NCNN 推理

使用 NCNN 运行推理,用于在 CPU 或支持 Vulkan 的 GPU 目标上进行轻量部署。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("model_ncnn/")
4
5result = model("image.jpg", conf=0.25, iou=0.45, save=True)
6print(result.boxes.xyxy)

NCNN 导出目录包含 model.ncnn.parammodel.ncnn.bin,通常还有 metadata.yaml

CoreML 推理

在 macOS 上通过 CoreML 运行导出的 .mlpackage。CoreML 使用 compute_units 而非 PyTorch 设备字符串来路由执行。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("model.mlpackage", compute_units="all")
4
5result = model("image.jpg", conf=0.25, iou=0.45, save=True)
6print(result.boxes.xyxy)

支持的 compute_units 取值为 allcpu_onlycpu_and_gpucpu_and_ne

TFLite 推理

v1.4.0 新增

通过 Google 的 LiteRT 解释器(即原 TensorFlow Lite 运行时)运行导出的 .tflite 文件。需要 Python 3.12+ 与 pip install "libreyolo[tflite]"(或别名 [litert]),它会安装 ai-edge-litert

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("model.tflite")
4
5result = model("image.jpg", conf=0.25, iou=0.45, save=True)
6print(result.boxes.xyxy)

TFLite 产物支持与其他后端相同的核心运行时预测 API,包括 save=True output_path 只接受文件路径的行为。导出的计算图为静态形状,请以导出时的 imgsz 运行。

命令行(CLI)

安装 LibreYOLO 会在你的 PATH 中注册一个 libreyolo 命令(入口点在 pyproject.toml 中)。命令行镜像 Python API,并接受 key=value 语法。

子命令

命令用途
predict对图像、目录或视频运行推理
train在数据集上训练模型
val在数据集上评估模型
export导出为 ONNX / TorchScript / TensorRT / OpenVINO / NCNN / CoreML / TFLite
quantize用配方 + 校准集量化模型(v1.4.0 新增)
label启动 LibreLabel 本地浏览器标注工具
monitor为训练任务提供实时看板
profile分析训练或推理性能,并解读结果
ui启动本地拖放 / 粘贴的浏览器推理界面
doctor运行训练前的数据集健康检查(YOLO 检测格式)
checks打印 Python、torch、CUDA、GPU 和可选包信息
models列出已注册的模型系列和命令行简称(v1.4.0 内容更丰富;--json 模式已变更)
formats列出导出格式;--family / --task 按支持档位过滤(v1.4.0 新增)
cfg打印默认的训练配置 YAML
info加载模型并打印系列、尺寸、任务、设备、类别及其 export_support 映射
metadata检查 .pt 文件中的原始检查点元数据
version打印 LibreYOLO + Python + torch 版本

模型名称简称

命令行接受简称(yolo9-c),它们会解析为权重文件名(LibreYOLO9c.pt)- 可通过 libreyolo models 查看。你也可以传入任意明确的检查点路径。

常用选项

命令重要选项
predictconf, iou, imgsz, classes, max_det, half, batch, tiling, overlap_ratio, output_file_format, project, name, exist_ok, face_detector
trainepochs, batch, imgsz, lr0, optimizer, scheduler, workers, seed, resume, amp, task, cache, lora, freeze, save_plots, allow_download_scripts, dry_run,以及各增强参数mosaic, mixup, hsv_prob, flip_prob, degrees, ...)
valsplit, batch, imgsz, conf, iou, max_det, half, save_plots, data_dir, use_coco_eval, project, name, exist_ok, save_json, allow_download_scripts
exportformat, imgsz, batch, half, int8, dynamic, simplify, nms, conf, iou, max_det, opset, data, fraction, device, allow_download_scripts, verbose

预测

bash
1# Flagship: YOLO9
2libreyolo predict model=yolo9-c source=image.jpg conf=0.25 save=true
3
4# Flagship: RF-DETR
5libreyolo predict model=rfdetr-s source=image.jpg save=true
6
7# Video - saved under runs/detect/predict*/
8libreyolo predict model=yolo9-c source=clip.mp4 save=true
9
10# Tiled inference for very large images
11libreyolo predict model=yolo9-c source=aerial.jpg tiling=true save=true
12
13# Gaze (requires a face detector)
14libreyolo predict model=LibreL2CSr50.pt source=portrait.jpg \
15 --face-detector path/to/face.pt save=true

训练

bash
1libreyolo train model=yolo9-c data=coco128.yaml epochs=300 batch=16 device=0
2
3# Dry-run prints the resolved config without launching training
4libreyolo train model=yolo9-c data=coco128.yaml --dry-run

验证

bash
1libreyolo val model=runs/train/exp/weights/best.pt data=coco128.yaml split=val

导出

bash
1libreyolo export model=runs/train/exp/weights/best.pt format=onnx dynamic=true
2libreyolo export model=best.pt format=tensorrt half=true
3libreyolo export model=best.pt format=openvino int8=true data=coco128.yaml
4libreyolo export model=best.pt format=coreml

导出内嵌 NMS 与矩形尺寸

bash
1# Embed NMS into an ONNX YOLO9 detection graph
2libreyolo export model=yolo9-c format=onnx nms=true conf=0.25 iou=0.45 max_det=300
3
4# Rectangular export size (imgsz accepts a single value or two comma-separated dims)
5libreyolo export model=yolo9-c format=onnx imgsz=640,480
6
7# TFLite (Python 3.12+, libreyolo[tflite])
8libreyolo export model=rfdetr-s format=tflite

量化(v1.4.0 新增)

bash
1# PTQ: int8 with a small calibration set
2libreyolo quantize --model LibreYOLO9s.pt --recipe int8 --calib coco8.yaml --samples 128
3
4# Write to an explicit path, machine-readable output
5libreyolo quantize --model LibreRFDETRn.pt --recipe nvfp4 --out rfdetr-nvfp4.pt --json

量化后的检查点接入常规命令:libreyolo val 得到可信精度、 libreyolo train 做 QAT、libreyolo export 做部署。见模型量化

本地推理界面

libreyolo ui 提供一个本地浏览器页面,你可以在其中拖放、粘贴 或选择图像、选择模型并查看结果。它默认绑定 127.0.0.1:8000,若端口被占用会自动递增。

bash
1libreyolo ui # opens http://127.0.0.1:8000
2libreyolo ui --port 9000 --no-browser --device 0

数据集健康检查

libreyolo doctor 对 YOLO 检测格式的数据集运行训练前检查, 发现错误时以非零退出 (--strict 还会在出现警告时失败),因此可用于门控 CI。

bash
1libreyolo doctor coco8.yaml
2libreyolo doctor --data coco8.yaml --strict --json
3libreyolo doctor coco8.yaml --fast --only labels # skip image decoding, run one check family

机器可读输出

每个命令都接受 --json(结构化的标准输出,便于管道传入脚本或智能体)和 --quiet(抑制 stderr 进度行)。核心的 predicttrainvalexport 命令还接受 --help-json,可将其参数 schema 以 JSON 形式输出。

bash
1libreyolo predict model=yolo9-c source=img.jpg --json | jq .
2
3libreyolo train --help-json > train_schema.json

API 参考

LibreYOLO(工厂)

python
1LibreYOLO(
2 model_path: str,
3 *,
4 device: str = "auto",
5 task: str | None = None, # override only when a custom artifact is ambiguous
6 nb_classes: int | None = None, # mainly for external exported artifacts
7 compute_units: str = "all", # CoreML only: all, cpu_only, cpu_and_gpu, cpu_and_ne
8) -> model wrapper or runtime backend

优先使用官方检查点文件名和导出产物路径,然后让工厂解析细节。它可处理 PyTorch 检查点、.onnx.torchscript.engine.tensorrt.mlpackage、包含 model.xml 的 OpenVINO 目录,以及包含 model.ncnn.parammodel.ncnn.bin 的 NCNN 目录。task 参数用于有歧义的自定义产物;否则解析来自检查点元数据、文件名后缀和系列默认值。

预测(PyTorch 模型包装器)

python
1model(
2 source, # image input (see supported formats)
3 *,
4 conf: float = 0.25,
5 iou: float = 0.45,
6 imgsz: int = None,
7 device: str = "auto",
8 classes: list[int] = None,
9 max_det: int = 300,
10 augment: bool = False,
11 save: bool = False,
12 batch: int = 1,
13 stream: bool = False,
14 vid_stride: int = 1,
15 show: bool = False,
16 output_path: str = None,
17 color_format: str = "auto",
18 tiling: bool = False,
19 overlap_ratio: float = 0.2,
20 output_file_format: str = None,
21) -> Results | list[Results] | Generator[Results, None, None]

预测(运行时后端)

python
1backend(
2 source,
3 *,
4 conf: float = 0.25,
5 iou: float = 0.45,
6 imgsz: int = None,
7 classes: list[int] = None,
8 max_det: int = 300,
9 save: bool = False,
10 batch: int = 1,
11 output_path: str = None, # final file path when save=True
12 color_format: str = "auto",
13) -> Results | list[Results]

如果运行时后端省略了 output_path,当前默认保存位置是 runs/detections/

Results

python
1result = Results(
2 boxes: Boxes | None,
3 orig_shape: tuple[int, int], # (height, width)
4 path: str | None,
5 names: dict[int, str],
6 masks: Masks | None = None,
7 keypoints: Keypoints | None = None,
8 probs: Probs | None = None,
9 obb: OBB | None = None,
10 gaze: Gaze | None = None,
11 speed: dict[str, float] | None = None,
12 track_id = None,
13 frame_idx: int | None = None,
14 semantic_mask: SemanticMask | None = None,
15 depth_map: DepthMap | None = None,
16 points: Points | None = None,
17 restored: RestoredImage | None = None,
18 # New in v1.4.0 (placed after the complete v1.3 signature, so
19 # positional v1.3 call sites keep working):
20 panoptic: PanopticSegmentation | None = None,
21 matte: Matte | None = None,
22 ocr: OCRRegions | None = None,
23 restore_scale: int = 1,
24)
25
26len(result) # number of detections
27result.cpu() # copy with tensors on CPU
28result.cuda() # copy with tensors on CUDA
29result.numpy() # copy with numpy arrays
30result.summary() # list[dict] with the payloads present
31result.to_json() # JSON string from summary()
32result.cutout() # (H, W, 4) RGBA ndarray; matte results only

Boxes

python
1boxes = Boxes(boxes, conf, cls)
2
3boxes.xyxy # (N, 4) tensor - x1, y1, x2, y2
4boxes.xywh # (N, 4) tensor - cx, cy, w, h
5boxes.conf # (N,) tensor - confidence scores
6boxes.cls # (N,) tensor - class IDs
7boxes.id # (N,) track IDs when tracking, else None
8boxes.is_track # True when track IDs are attached
9boxes.data # (N, 6) [xyxy, conf, cls], or (N, 7) with track IDs
10
11len(boxes) # number of boxes
12boxes.cpu() # copy on CPU
13boxes.numpy() # copy as numpy arrays

任务载荷

python
1result.masks.data # segmentation masks, (N, H, W)
2result.masks.xy # list of mask contours in pixel coordinates
3result.masks.xyn # normalized mask contours
4
5result.keypoints.xy # pose keypoint coordinates
6result.keypoints.xyn # normalized keypoint coordinates
7result.keypoints.conf # keypoint confidence when present
8
9result.gaze.data # (N, 2): pitch, yaw in radians
10result.gaze.pitch_deg # pitch in degrees
11result.gaze.yaw_deg # yaw in degrees
12result.gaze.direction_3d # approximate 3D direction vectors
13
14result.semantic_mask.data # (H, W) class-id map (semantic)
15result.depth_map.data # (H, W) relative inverse depth
16result.points.xy # (N, 2) point detections (FOMO)
17result.restored.array # (H, W, 3) uint8 restored image
18result.restore_scale # int upscale factor; 1 unless super-resolution
19
20# New in v1.4.0
21result.panoptic.data # (H, W) segment-id map
22result.panoptic.segments_info # per-segment {"id", "category_id", ...}
23result.matte.data # (H, W) float32 alpha in [0, 1]
24result.ocr.polygons # (N, 4, 2) text-region quads
25result.ocr.texts # list[str] transcriptions
26result.ocr.confidence # (N,) recognition scores
27result.ocr.det_confidence # (N,) detection scores

model.track()

python
1model.track(
2 source, # video file path
3 *,
4 track_conf: float = 0.25,
5 iou: float = 0.45,
6 imgsz: int = None,
7 classes: list[int] = None,
8 max_det: int = 300,
9 save: bool = False,
10 show: bool = False,
11 vid_stride: int = 1,
12 output_path: str = None,
13 tracker: str = "bytetrack", # "bytetrack" | "ocsort" | "botsort" | "deepocsort"
14 tracker_config = None, # a config instance selects the tracker by type
15 augment: bool = False,
16 **tracker_kwargs,
17) -> Generator[Results, None, None]

model.quantize()(v1.4.0 新增)

python
1model.quantize(
2 recipe: str, # "fp16" | "bf16" | "fp8" | "int8" | "w4a16"
3 # | "w4a8" | "nvfp4" | "mxfp4" | "int2"
4 calib: str = "coco128.yaml", # unlabeled calibration images (forward-only)
5 samples: int = 128,
6 batch: int = 8,
7 algorithm: str = "auto", # "auto" (minmax) | "minmax" | "percentile"
8 keep_high_precision = None, # module-name substrings to keep in float
9 verbose: bool = True,
10) -> model # quantized in place
11
12model.quant_info() # dict describing the quant state, or None
13model.dequantize() # restore float modules in place

model.export()

python
1model.export(
2 format: str = "onnx", # "onnx", "torchscript", "tensorrt", "openvino",
3 # "ncnn", "coreml", "tflite" (alias "litert"), or "pt"
4 *,
5 output_path: str | None = None,
6 imgsz: int | None = None,
7 opset: int | None = None, # auto: 13, or 17 for wrappers that need it
8 simplify: bool = True,
9 dynamic: bool = True,
10 half: bool = False,
11 batch: int = 1,
12 device: str | None = None,
13 int8: bool = False,
14 data: str | None = None, # calibration data for INT8
15 fraction: float = 1.0, # fraction of calibration data
16 allow_download_scripts: bool = False,
17 workspace: float = 4.0, # TensorRT workspace (GB)
18 min_batch: int = 1, # TensorRT dynamic profile minimum batch
19 opt_batch: int = 1, # TensorRT dynamic profile optimal batch
20 max_batch: int = 8, # TensorRT dynamic profile maximum batch
21 hardware_compatibility: str = "none",
22 gpu_device: int = 0,
23 trt_config = None, # optional TensorRT YAML config path
24 compute_units: str = "all", # CoreML only
25 nms: bool = False, # CoreML embedded NMS where supported
26 iou: float = 0.45, # CoreML embedded NMS IoU threshold
27 conf: float = 0.25, # CoreML embedded NMS confidence threshold
28 verbose: bool = False,
29) -> str # path to exported file or directory

model.val()

python
1model.val(
2 data: str = None, # path to data.yaml
3 batch: int = 16,
4 imgsz: int = None,
5 conf: float = 0.001,
6 iou: float = 0.6,
7 workers: int = 4,
8 allow_download_scripts: bool = False,
9 device: str = None,
10 split: str = "val", # "val", "test", or "train"
11 augment: bool = False,
12 save_json: bool = False,
13 verbose: bool = True,
14) -> dict

返回(COCO 评估,默认):

python
1{
2 "metrics/mAP50-95": float, # COCO primary metric
3 "metrics/mAP50": float,
4 "metrics/mAP75": float,
5 "metrics/mAP_small": float,
6 "metrics/mAP_medium": float,
7 "metrics/mAP_large": float,
8 "metrics/AR1": float,
9 "metrics/AR10": float,
10 "metrics/AR100": float,
11 "metrics/AR_small": float,
12 "metrics/AR_medium": float,
13 "metrics/AR_large": float,
14}

model.train()(YOLO9)

python
1model.train(
2 data: str, # path to data.yaml (required)
3 *,
4 epochs: int = 300,
5 batch: int = 16,
6 imgsz: int = 640,
7 lr0: float = 0.01,
8 optimizer: str = "SGD",
9 device: str = "",
10 workers: int = 8,
11 seed: int = 0,
12 project: str = "runs/train",
13 name: str = "yolo9_exp",
14 exist_ok: bool = False,
15 resume: bool = False,
16 amp: bool = True,
17 patience: int = 50,
18 allow_download_scripts: bool = False,
19 callbacks = None,
20) -> dict

返回标准的 LibreYOLO 训练字典,包含 final_lossbest_mAP50best_mAP50_95best_epochsave_dirbest_checkpointlast_checkpoint

model.train()(RF-DETR)

python
1model.train(
2 data: str, # path to data.yaml
3 epochs: int = 100,
4 batch_size: int = 4,
5 lr: float = 1e-4,
6 output_dir: str = "runs/train",
7 resume: str = None,
8 **kwargs, # additional RF-DETR training args
9) -> dict

YOLO-NAS、D-FINE、DEIM、DEIMv2、EC、PicoDet、RT-DETRv2/v4 和 RTMDet 还有额外的实验性训练器,外加新增的分类(MobileNetV4、ConvNeXt、EfficientNetV2、DINOv2)、语义分割(DINOv2)和点定位(FOMO)系列。它们遵循相同的 model.train(data="...yaml", ...) 形式,但默认值和实验性门控因系列而异。

运行时产物加载

通过 LibreYOLO() 加载导出产物,方式与加载 PyTorch 检查点相同。工厂会根据路径选择 ONNX Runtime、TorchScript、TensorRT、OpenVINO、NCNN 或 CoreML:

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("model.onnx")
4model = LibreYOLO("model.torchscript")
5model = LibreYOLO("model.engine")
6model = LibreYOLO("model_openvino/")
7model = LibreYOLO("model_ncnn/")
8model = LibreYOLO("model.mlpackage", compute_units="all")

高级集成可以触及更底层的运行时模块,但普通应用代码应保持使用工厂路径。

ValidationConfig

python
1from libreyolo import ValidationConfig
2
3config = ValidationConfig(
4 data="coco128.yaml",
5 data_dir=None, # override dataset root directory
6 split="val", # "val", "test", or "train"
7 batch_size=16,
8 imgsz=640,
9 conf_thres=0.001,
10 iou_thres=0.6,
11 max_det=300,
12 iou_thresholds=( # mAP IoU sweep
13 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95,
14 ),
15 device="auto",
16 save_dir=None,
17 save_json=False,
18 verbose=True,
19 num_workers=4,
20 half=False,
21 augment=False, # test-time augmentation (TTA)
22 allow_download_scripts=False,
23 # Pose-only fields (PoseValidator)
24 keypoints_json=None,
25 images_dir=None,
26 oks_sigmas=None,
27)
28
29# Load/save YAML
30config = ValidationConfig.from_yaml("config.yaml")
31config.to_yaml("config.yaml")

架构指南

本节面向希望了解代码库内部机制的贡献者。

基类设计

PyTorch 模型系列继承自 libreyolo/models/base/model.py 中的 BaseModel。子类实现以下抽象方法:

方法用途
_init_model()构建并返回 nn.Module
_get_available_layers()返回层名到模块的映射
_get_preprocess_numpy()返回用于导出 / 标定的 NumPy 预处理器
_preprocess()图像到张量的转换
_forward()模型前向传播
_postprocess()原始输出到检测字典

BaseModel 提供共享的包装行为:预测、导出、验证、尺寸/名称元数据和训练辅助。实际的单图、批量和分块推理流程位于 libreyolo/models/base/inference.py,而部署运行时位于 libreyolo/backends/ 下。

包结构

text
1libreyolo/
2 __init__.py # Public API exports + deprecated-alias resolver
3 tasks.py # Task types, suffix conventions, resolution rules
4 assets/parkour.jpg # SAMPLE_IMAGE
5 models/
6 __init__.py # LibreYOLO() factory + model registry bootstrap
7 base/
8 model.py # BaseModel - shared wrapper behaviour
9 inference.py # Shared prediction pipeline (image/dir/video/tiled)
10 yolox/ # LibreYOLOX (detect)
11 yolo9/ # LibreYOLO9 (detect)
12 yolo9_e2e/ # LibreYOLO9E2E (detect)
13 yolonas/ # LibreYOLONAS (detect, pose)
14 dfine/ # LibreDFINE (detect)
15 deim/ # LibreDEIM (detect)
16 deimv2/ # LibreDEIMv2 (detect)
17 rtdetr/ # LibreRTDETR (detect)
18 rtdetrv2/ # LibreRTDETRv2 (detect)
19 rtdetrv4/ # LibreRTDETRv4 (detect)
20 rfdetr/ # LibreRFDETR (detect, segment, pose, obb) - lazy-loaded
21 ec/ # LibreEC / EdgeCrafter (detect, pose, segment)
22 picodet/ # LibrePICODET (detect)
23 rtmdet/ # LibreRTMDet (detect)
24 dinov2/ # LibreDINOv2 (semantic, classify) - lazy-loaded
25 mobilenetv4/ # LibreMobileNetV4 (classify)
26 convnext/ # LibreConvNeXt (classify)
27 efficientnetv2/ # LibreEfficientNetV2 (classify)
28 depth_anything/ # LibreDepthAnythingV2 (depth)
29 fomo/ # LibreFOMO (point)
30 l2cs/ # LibreL2CS (gaze, inference-only)
31 backends/
32 base.py
33 onnx.py # ONNX Runtime loader
34 torchscript.py # TorchScript loader
35 tensorrt.py # TensorRT loader
36 openvino.py # OpenVINO loader
37 ncnn.py # NCNN loader
38 coreml.py # CoreML loader
39 export/
40 exporter.py # BaseExporter and format registry
41 onnx.py / torchscript.py / tensorrt.py / openvino.py / ncnn.py / coreml.py
42 config.py / calibration.py
43 training/
44 trainer.py # Shared trainer scaffolding
45 config.py # TrainConfig dataclass (single source of truth)
46 augment.py / callbacks.py / distributed.py / ema.py / scheduler.py
47 artifacts.py / train_config.yaml
48 # Per-family trainers live in models/<family>/trainer.py
49 validation/
50 config.py # ValidationConfig
51 base.py / preprocessors.py
52 detection_validator.py # DetectionValidator, SegmentationValidator
53 pose_validator.py # PoseValidator
54 coco_evaluator.py # COCOEvaluator
55 tracking/
56 tracker.py # ByteTracker
57 config.py # TrackConfig
58 kalman_filter.py / matching.py / strack.py
59 cli/
60 __init__.py # libreyolo entrypoint (Typer app)
61 commands/ # predict / train / val / export / special
62 aliases.py / config.py / parsing.py / output.py / errors.py
63 utils/
64 results.py # Results, Boxes, Masks, Keypoints, Probs, OBB, Gaze
65 image_loader.py # Unified image loading
66 video.py # VideoSource, VideoWriter, video inference loop
67 general.py # Path helpers, NMS, tiling utilities
68 download.py / drawing.py / logging.py / predict_args.py
69 serialization.py / box_ops.py
70 data/
71 dataset.py / pose_dataset.py / utils.py / yolo_coco_api.py
72 config/
73 datasets/ # Built-in dataset YAML configs (coco8, coco128, coco5000, coco, etc.)
74 export/ # TensorRT default YAML

添加新的模型系列

  1. 1创建 libreyolo/models/newmodel/model.py,其中包含一个继承 BaseModel 的类
  2. 2按需设置 FAMILYFILENAME_PREFIXINPUT_SIZESSUPPORTED_TASKSDEFAULT_TASK
  3. 3实现注册表钩子,如 can_load()detect_size()detect_nb_classes()detect_size_from_filename()
  4. 4实现该系列所需的模型初始化、预处理、前向、后处理、训练和验证钩子
  5. 5libreyolo/models/newmodel/ 下创建配套的网络和工具
  6. 6将导入添加到 libreyolo/models/__init__.py;子类注册会在导入运行时发生
  7. 7libreyolo/__init__.py 导出该类
  8. 8(可选)如果验证预处理与标准路径不同,覆盖 val_preprocessor_class

导出架构

用户代码应通过 model.export(...) 导出。在内部,libreyolo/export/exporter.py 中的 BaseExporter 拥有格式注册表,具体的导出器通过子类注册来注册自身。

python
1from libreyolo import LibreYOLO
2
3model = LibreYOLO("LibreYOLO9c.pt")
4model.export(format="onnx")

要添加新的导出格式,请实现一个具有唯一 format_name 的新 BaseExporter 子类,并从 libreyolo/export/exporter.py 导入它,以填充注册表。

数据集格式

每个任务都通过一个 data.yaml 加载。检测、实例分割和 OBB 接受两种可互换的标签格式(YOLO TXT 或原生 COCO JSON),加载器会根据配置自动选择。姿态、语义分割、深度和分类各自增加一个小型格式。下表将每个任务映射到其布局。

按任务划分的格式

任务数据布局标签
检测data.yaml + labels/*.txt,或 COCO JSON每行一个框
实例分割data.yaml + 多边形 .txt,或 COCO JSON每行一个多边形(TXT)/ 多边形 + RLE(COCO)
OBBdata.yaml + 旋转框 .txt,或 COCO JSON每行一个旋转框
姿态data.yaml + .txt + kpt_shape/flip_idx每行一个框 + 关键点
语义分割data.yaml + masks_dir/ PNG逐像素类别 ID(255 = 忽略)
深度data.yaml + depths_dir/ 深度图逐像素深度(0 = 无效)
分类ImageFolder(train/<class>/文件夹名 = 类别

data.yaml 结构

检测、分割、OBB 和姿态的通用契约。train/val/test 可以是目录、.txt 文件列表(每行一个图像路径)或路径列表。nc 可选:省略时从 names 推断。

data.yaml
1path: /absolute/path/to/dataset # dataset root
2train: images/train # dir, .txt file list, or list of paths
3val: images/val
4test: images/test # optional
5
6nc: 80 # optional; inferred from names if absent
7names: ["person", "bicycle", "car", "..."]

配置按以下顺序解析:明确路径、当前工作目录,然后是 libreyolo/config/datasets/ 下的内置配置。根目录默认在 ~/datasets 下;用 LIBREYOLO_DATASETS_DIR 覆盖。

YOLO TXT 标签

默认布局:每张图像在 labels/ 下有一个 .txt,镜像 images/ 树并使用相同的文件名主干。所有坐标都归一化到 [0, 1]。

text
1dataset/
2 images/train/img001.jpg
3 labels/train/img001.txt # same stem as the image
text
1# Detection one box per line
2<class_id> <cx> <cy> <w> <h>
3
4# Segmentation one polygon per line (box derived from the vertices)
5<class_id> <x1> <y1> <x2> <y2> ... <xn> <yn>
6
7# Pose box, then K keypoints (needs kpt_shape / flip_idx below)
8<class_id> <cx> <cy> <w> <h> <kx1> <ky1> <v1> ... <kxK> <kyK> <vK>
9
10# OBB four rotated-box corners
11<class_id> <x1> <y1> <x2> <y2> <x3> <y3> <x4> <y4>
data.yaml (pose)
1kpt_shape: [17, 3] # K keypoints, 3 values each: x, y, visibility
2flip_idx: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]

原生 COCO JSON

检测、分割和 OBB 也可直接加载 COCO JSON:添加一个 annotations: 块,将每个划分映射到其 JSON 文件。此时 train/val 指向图像目录(而非 .txt 列表)。需要 pycocotools;类别名来自 JSON 的 categories,因此 nc/names 可选。

data.yaml (COCO)
1path: dataset
2train: images/train # image directory
3val: images/val
4annotations:
5 train: annotations/train.json # COCO instances JSON
6 val: annotations/val.json

同一套切换逻辑服务于 YOLO9、RF-DETR、DEIM 和 D-FINE 训练,以及检测、OBB 和姿态验证器。磁盘上带有 annotations/instances_train2017.json 的 COCO 布局也会被自动识别,无需 annotations: 键。

选择哪种分割格式? 一个 YOLO 多边形行是每个实例一个环,无法表示带孔或分离(多部分)的掩码。COCO JSON 会保留实例的每个多边形并解码 RLE 掩码(含孔)。当实例带孔或存在不相连的部分时使用 COCO JSON;简单的单块掩码用任一格式均可。人群标注(iscrowd: 1)会被跳过。

语义分割掩码

为每张图像配一张单通道掩码,其像素值为类别 ID;255 标记被忽略的像素。masks_dir 会替换每个路径中的 images(默认 masks),掩码必须是无损(PNG)且与其图像同名主干。可选的 label_mapping 将源 ID 重映射为训练 ID(未映射的值变为忽略)。省略 masks_dir 则在加载时从 YOLO 多边形标签栅格化掩码,并追加一个 background 类。

text
1dataset/
2 images/train/scene001.jpg
3 masks/train/scene001.png # single-channel class IDs, 255 = ignore
data.yaml (semantic)
1path: /path/to/dataset
2train: images/train
3val: images/val
4masks_dir: masks
5nc: 3
6names: ["road", "building", "vegetation"]

深度图

为每张图像配一张单通道深度图,放在 depths_dir 下(默认 depths)。16 位 PNG/TIF 会除以 depth_scale(默认 256.0);.npy 浮点文件按原样使用。零、负值和非有限像素为无效。可选的 depth_stem_suffix*_mask 有效性掩码会被自动识别。深度仅支持验证。

data.yaml (depth)
1path: /path/to/dataset
2val: images/val
3depths_dir: depths
4depth_scale: 256.0 # 16-bit PNG encoding: value / 256 = depth

分类

分类使用 ImageNet 风格的 ImageFolder 树,而非 data.yaml,布局参见 分类data= 接受数据集根目录、.zip URL 或已知名称。

内置数据集

配置位于 libreyolo/config/datasets/ 下。下载行为因配置而异:基于 URL 的数据集在首次使用时获取,基于脚本的数据集需要 allow_download_scripts=True,少数需要在本地放置。

配置任务下载
coco8检测(8 张)自动
coco128检测(128 张)自动
coco5000检测脚本:allow_download_scripts=True
coco / coco-val-only检测(完整)脚本:allow_download_scripts=True
coco8-pose / coco-pose姿态脚本:allow_download_scripts=True
cocostuff语义(182 类)手动:本地放置
python
1results = model.val(data="coco8.yaml") # auto-downloads
2results = model.train(data="coco128.yaml", epochs=10) # auto-downloads
3model.train(data="coco8-pose.yaml", allow_download_scripts=True) # script config