You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python将自定义JSON标注转换为YOLO系列所需的txt标注文件

JSON标注转YOLO格式Python实现

前置说明

本实现仅依赖Python标准库,无需额外安装第三方包,可直接处理10万级样本的标注转换,124MB的JSON文件可一次性加载无压力。

转换代码

import json
import os

# 配置项,可根据实际情况修改
CONFIG = {
    # 类别映射表
    "class_map": {
        "car": 0,
        "truck": 1,
        "bus": 2,
        "etc vehicle": 3,
        "bike": 4,
        "person": 5
    },
    # 图像固定尺寸
    "img_width": 1920,
    "img_height": 1080,
    # 输入JSON标注文件路径
    "input_json_path": "./annotations.json",
    # 输出YOLO标注txt的存储目录
    "output_txt_dir": "./yolo_labels"
}

def main():
    # 创建输出目录,不存在则自动生成
    os.makedirs(CONFIG["output_txt_dir"], exist_ok=True)
    
    # 加载JSON标注文件
    with open(CONFIG["input_json_path"], "r", encoding="utf-8") as f:
        ann_data = json.load(f)
    annotations = ann_data["annotations"]
    
    # 遍历每张图像的标注
    for ann in annotations:
        # 生成对应txt文件名:替换.jpg后缀为.txt
        img_filename = ann["file_name"]
        txt_filename = os.path.splitext(img_filename)[0] + ".txt"
        txt_save_path = os.path.join(CONFIG["output_txt_dir"], txt_filename)
        
        # 生成单张图的所有标注行
        label_lines = []
        for obj in ann["objects"]:
            cls_name = obj["class"]
            # 跳过不在类别映射里的目标,可根据需求调整逻辑
            if cls_name not in CONFIG["class_map"]:
                continue
            cls_id = CONFIG["class_map"][cls_name]
            xmin, ymin, xmax, ymax = obj["position"]
            
            # 按规则计算归一化参数
            cx = (xmin + xmax) / 2 / CONFIG["img_width"]
            cy = (ymin + ymax) / 2 / CONFIG["img_height"]
            w = (xmax - xmin) / CONFIG["img_width"]
            h = (ymax - ymin) / CONFIG["img_height"]
            
            # 拼接标注行,保留9位小数和示例格式对齐
            line = f"{cls_id} {cx:.9f} {cy:.9f} {w:.9f} {h:.9f}"
            label_lines.append(line)
        
        # 写入txt文件,无目标的图像会生成空txt,符合YOLO训练要求
        with open(txt_save_path, "w", encoding="utf-8") as f:
            f.write("\n".join(label_lines))

if __name__ == "__main__":
    main()

可选优化(按需使用)

如果需要查看转换进度,可以安装tqdm库后修改遍历部分的代码:

  • 先安装依赖:pip install tqdm
  • 导入库:在代码开头添加from tqdm import tqdm
  • 将遍历代码for ann in annotations:修改为for ann in tqdm(annotations, desc="转换进度"):

验证说明

转换完成后可随机抽取几个txt文件和示例对比,确认数值计算、类别映射、命名规则符合要求后再用于训练。

内容的提问来源于stack exchange,提问作者한주형

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 12:24:05