如何不转换格式直接使用 COCO JSON 训练 YOLO#
Annotations 采用 COCO JSON 格式,可直接用于 Ultralytics YOLO 训练,无需先转换为 .txt 文件。其工作原理是通过继承 YOLODataset 来动态解析 COCO JSON,并通过自定义训练器将其接入训练流程。
为什么要直接在 COCO JSON 上进行训练#
这种方法让 COCO JSON 保持为唯一的真实数据源——无需调用 convert_coco()、无需重新组织目录、也无需中间标签文件。支持 YOLO26 及所有其他 Ultralytics YOLO 检测模型。分割和姿态模型需要额外的标签字段(参见常见问题)。
有关标准的 convert_coco() 工作流,请参阅 COCO to YOLO Conversion guide。
架构概述#
需要两个类:
COCODataset— 在训练期间读取 COCO JSON 并将边界框在内存中转换为 YOLO 格式COCOTrainer— 覆盖build_dataset(),使用COCODataset代替默认的YOLODataset
该实现的模式与内置的 GroundingDataset 相同,后者同样直接读取 JSON 标注。重写了三个方法:get_img_files()、cache_labels() 和 get_labels()。
构建 COCO JSON 数据集类#
COCODataset 类继承自 YOLODataset 并覆盖了标签加载逻辑。它不从标签目录中读取 .txt 文件,而是打开 COCO JSON 文件,遍历按图像分组的标注,并将每个边界框从 COCO 像素格式 [x_min, y_min, width, height] 转换为 YOLO 归一化中心格式 [x_center, y_center, width, height]。人群标注(iscrowd: 1)和零面积边界框会被自动跳过。
get_img_files() 方法会返回一个空列表,因为图像路径是从 cache_labels() 内的 JSON file_name 字段解析出来的。类别 ID 会经过排序并重新映射为从零开始的类索引,因此基于 1 的 ID(标准 COCO)和非连续 ID 方案都能正常工作。
import json
from collections import defaultdict
from pathlib import Path
import numpy as np
from ultralytics.data.dataset import DATASET_CACHE_VERSION, YOLODataset
from ultralytics.data.utils import get_hash, load_dataset_cache_file, save_dataset_cache_file
from ultralytics.utils import TQDM
class COCODataset(YOLODataset):
"""Dataset that reads COCO JSON annotations directly without conversion to .txt files."""
def __init__(self, *args, json_file="", **kwargs):
"""Initialize the dataset with a COCO JSON annotation file."""
self.json_file = json_file
super().__init__(*args, data={"channels": 3}, **kwargs)
def get_img_files(self, img_path):
"""Image paths are resolved from the JSON file, not from scanning a directory."""
return []
def cache_labels(self, path=Path("./labels.cache")):
"""Parse COCO JSON and convert annotations to YOLO format. Results are saved to a .cache file."""
x = {"labels": []}
with open(self.json_file) as f:
coco = json.load(f)
# Sort categories by ID and map to 0-indexed classes
categories = {cat["id"]: i for i, cat in enumerate(sorted(coco["categories"], key=lambda c: c["id"]))}
img_to_anns = defaultdict(list)
for ann in coco["annotations"]:
img_to_anns[ann["image_id"]].append(ann)
for img_info in TQDM(coco["images"], desc="reading annotations"):
h, w = img_info["height"], img_info["width"]
im_file = Path(self.img_path) / img_info["file_name"]
if not im_file.exists():
continue
self.im_files.append(str(im_file))
bboxes = []
for ann in img_to_anns.get(img_info["id"], []):
if ann.get("iscrowd", False):
continue
# COCO: [x, y, w, h] top-left in pixels -> YOLO: [cx, cy, w, h] center normalized
box = np.array(ann["bbox"], dtype=np.float32)
box[:2] += box[2:] / 2 # top-left to center
box[[0, 2]] /= w # normalize x
box[[1, 3]] /= h # normalize y
if box[2] <= 0 or box[3] <= 0:
continue
cls = categories[ann["category_id"]]
bboxes.append([cls, *box.tolist()])
lb = np.array(bboxes, dtype=np.float32) if bboxes else np.zeros((0, 5), dtype=np.float32)
x["labels"].append(
{
"im_file": str(im_file),
"shape": (h, w),
"cls": lb[:, 0:1],
"bboxes": lb[:, 1:],
"segments": [],
"normalized": True,
"bbox_format": "xywh",
}
)
x["hash"] = get_hash([self.json_file, str(self.img_path)])
save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
return x
def get_labels(self):
"""Load labels from .cache file if available, otherwise parse JSON and create the cache."""
cache_path = Path(self.json_file).with_suffix(".cache")
try:
cache = load_dataset_cache_file(cache_path)
assert cache["version"] == DATASET_CACHE_VERSION
assert cache["hash"] == get_hash([self.json_file, str(self.img_path)])
self.im_files = [lb["im_file"] for lb in cache["labels"]]
except (FileNotFoundError, AssertionError, AttributeError, KeyError, ModuleNotFoundError):
cache = self.cache_labels(cache_path)
cache.pop("hash", None)
cache.pop("version", None)
return cache["labels"]解析后的标签会保存在 JSON 旁边的 .cache 文件中(例如 instances_train.cache)。在后续的训练运行中,缓存会被直接加载,从而跳过 JSON 解析。如果 JSON 文件发生更改,哈希检查将失败并自动重建缓存。
将数据集连接到训练流水线#
训练器中唯一需要的修改是重写 build_dataset()。默认的 DetectionTrainer 会构建一个 YOLODataset 来扫描 .txt 标签文件。通过将其替换为 COCODataset,训练器改为从 COCO JSON 读取。
JSON 文件路径取自数据配置中的自定义 train_json / val_json 字段(参见配置 dataset.yaml)。在训练期间,mode="train" 解析为 train_json;在验证期间,mode="val" 解析为 val_json。如果未设置 val_json,则回退到 train_json。
from ultralytics.models.yolo.detect import DetectionTrainer
from ultralytics.utils import colorstr
class COCOTrainer(DetectionTrainer):
"""Trainer that uses COCODataset for direct COCO JSON training."""
def build_dataset(self, img_path, mode="train", batch=None):
"""Build a COCODataset for the given split using the JSON file from the data config."""
json_file = self.data["train_json"] if mode == "train" else self.data.get("val_json", self.data["train_json"])
return COCODataset(
img_path=img_path,
json_file=json_file,
imgsz=self.args.imgsz,
batch_size=batch,
augment=mode == "train",
hyp=self.args,
rect=self.args.rect or mode == "val",
cache=self.args.cache or None,
single_cls=self.args.single_cls or False,
stride=int(self.model.stride.max()) if hasattr(self, "model") and self.model else 32,
pad=0.0 if mode == "train" else 0.5,
prefix=colorstr(f"{mode}: "),
task=self.args.task,
classes=self.args.classes,
fraction=self.args.fraction if mode == "train" else 1.0,
)配置用于 COCO JSON 的 dataset.yaml#
dataset.yaml 使用标准的 path、train 和 val 字段来定位图像目录。另外两个字段 train_json 和 val_json 指定了 COCOTrainer 读取的 COCO 标注文件。nc 和 names 字段定义了类别数量及其名称,与 JSON 中 categories 的排序顺序相匹配。
path: /path/to/my_dataset/images # root with train/ and val/ image subfolders
train: train
val: val
# COCO JSON annotation files (use absolute paths; these custom keys are not resolved against `path`)
train_json: /path/to/my_dataset/annotations/instances_train.json
val_json: /path/to/my_dataset/annotations/instances_val.json
nc: 80
names:
0: person
1: bicycle
# ... remaining class names预期的目录结构:
my_dataset/
images/
train/
img_001.jpg
...
val/
img_100.jpg
...
annotations/
instances_train.json
instances_val.json
dataset.yaml在 COCO JSON 上运行训练#
在准备好数据集类、训练器类和 YAML 配置后,即可通过标准的 model.train() 调用进行训练。与常规训练运行唯一的区别是 trainer=COCOTrainer 参数,它告诉 Ultralytics 使用自定义数据集加载器而不是默认加载器。
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
model.train(data="dataset.yaml", epochs=100, imgsz=640, trainer=COCOTrainer)完整的训练流水线会按预期运行,包括验证、检查点保存和指标记录。
完整实现#
为方便起见,完整实现作为单个可复制粘贴的脚本在下方提供。它包含自定义数据集、自定义训练器以及训练调用。将其与你的 dataset.yaml 保存在一起并直接运行。
import json
from collections import defaultdict
from pathlib import Path
import numpy as np
from ultralytics import YOLO
from ultralytics.data.dataset import DATASET_CACHE_VERSION, YOLODataset
from ultralytics.data.utils import get_hash, load_dataset_cache_file, save_dataset_cache_file
from ultralytics.models.yolo.detect import DetectionTrainer
from ultralytics.utils import TQDM, colorstr
class COCODataset(YOLODataset):
"""Dataset that reads COCO JSON annotations directly without conversion to .txt files."""
def __init__(self, *args, json_file="", **kwargs):
"""Initialize the dataset with a COCO JSON annotation file."""
self.json_file = json_file
super().__init__(*args, data={"channels": 3}, **kwargs)
def get_img_files(self, img_path):
"""Image paths are resolved from the JSON file, not from scanning a directory."""
return []
def cache_labels(self, path=Path("./labels.cache")):
"""Parse COCO JSON and convert annotations to YOLO format. Results are saved to a .cache file."""
x = {"labels": []}
with open(self.json_file) as f:
coco = json.load(f)
categories = {cat["id"]: i for i, cat in enumerate(sorted(coco["categories"], key=lambda c: c["id"]))}
img_to_anns = defaultdict(list)
for ann in coco["annotations"]:
img_to_anns[ann["image_id"]].append(ann)
for img_info in TQDM(coco["images"], desc="reading annotations"):
h, w = img_info["height"], img_info["width"]
im_file = Path(self.img_path) / img_info["file_name"]
if not im_file.exists():
continue
self.im_files.append(str(im_file))
bboxes = []
for ann in img_to_anns.get(img_info["id"], []):
if ann.get("iscrowd", False):
continue
box = np.array(ann["bbox"], dtype=np.float32)
box[:2] += box[2:] / 2
box[[0, 2]] /= w
box[[1, 3]] /= h
if box[2] <= 0 or box[3] <= 0:
continue
cls = categories[ann["category_id"]]
bboxes.append([cls, *box.tolist()])
lb = np.array(bboxes, dtype=np.float32) if bboxes else np.zeros((0, 5), dtype=np.float32)
x["labels"].append(
{
"im_file": str(im_file),
"shape": (h, w),
"cls": lb[:, 0:1],
"bboxes": lb[:, 1:],
"segments": [],
"normalized": True,
"bbox_format": "xywh",
}
)
x["hash"] = get_hash([self.json_file, str(self.img_path)])
save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
return x
def get_labels(self):
"""Load labels from .cache file if available, otherwise parse JSON and create the cache."""
cache_path = Path(self.json_file).with_suffix(".cache")
try:
cache = load_dataset_cache_file(cache_path)
assert cache["version"] == DATASET_CACHE_VERSION
assert cache["hash"] == get_hash([self.json_file, str(self.img_path)])
self.im_files = [lb["im_file"] for lb in cache["labels"]]
except (FileNotFoundError, AssertionError, AttributeError, KeyError, ModuleNotFoundError):
cache = self.cache_labels(cache_path)
cache.pop("hash", None)
cache.pop("version", None)
return cache["labels"]
class COCOTrainer(DetectionTrainer):
"""Trainer that uses COCODataset for direct COCO JSON training."""
def build_dataset(self, img_path, mode="train", batch=None):
"""Build a COCODataset for the given split using the JSON file from the data config."""
json_file = self.data["train_json"] if mode == "train" else self.data.get("val_json", self.data["train_json"])
return COCODataset(
img_path=img_path,
json_file=json_file,
imgsz=self.args.imgsz,
batch_size=batch,
augment=mode == "train",
hyp=self.args,
rect=self.args.rect or mode == "val",
cache=self.args.cache or None,
single_cls=self.args.single_cls or False,
stride=int(self.model.stride.max()) if hasattr(self, "model") and self.model else 32,
pad=0.0 if mode == "train" else 0.5,
prefix=colorstr(f"{mode}: "),
task=self.args.task,
classes=self.args.classes,
fraction=self.args.fraction if mode == "train" else 1.0,
)
model = YOLO("yolo26n.pt")
model.train(data="dataset.yaml", epochs=100, imgsz=640, trainer=COCOTrainer)你现在拥有了一个最小的数据集和训练器,可以直接在 COCO JSON 上训练 Ultralytics YOLO,标注保持为单一真实数据源,且无需中间的 .txt 文件。通过 segments 或 keypoints 扩展 cache_labels() 方法以支持分割和姿态,并参阅 Model Training Tips 指南获取超参数调整建议。
常见问题解答#
convert_coco()将.txt标签文件写入磁盘作为一次性转换。此方法在每次训练运行开始时解析 JSON 并在内存中转换标注。当偏好永久的 YOLO 格式标签时,请使用convert_coco();若想在不生成额外文件的情况下将 COCO JSON 保持为唯一真实数据源,请使用本方法。目前的 Ultralytics 流水线默认期望 YOLO
.txt标签,因此无法直接实现。本指南提供了所需的极简自定义代码——一个数据集类和一个训练器类。定义后,训练仅需要一个标准的model.train()调用。本指南涵盖对象检测。若要添加实例分割支持,请在每个标签字典的
segments字段中包含来自 COCO 标注的segmentation多边形数据。对于姿态估计,请包含keypoints。(GroundingDataset) source code 提供了处理分割的参考实现。类别按
id排序并映射到从 0 开始的连续索引。这可以处理基于 1 的 ID(标准 COCO)、基于 0 的 ID 以及非连续 ID。dataset.yaml中的names字典应遵循与 COCOcategories数组相同的排序顺序。COCO JSON 在第一次训练运行期间会被解析一次。解析后的标签会保存在
.cache文件中,因此后续运行可以瞬间加载而无需重新解析。由于标注保留在内存中,训练速度与标准 YOLO 训练完全相同。如果 JSON 文件发生更改,缓存会自动重建。