如何将JSON格式标注转换为YOLOv7 PyTorch兼容格式?
JSON标注转YOLOv7格式的可行方法
Roboflow报错大概率是因为它无法识别你这种自定义JSON结构,或是标注文件和图像文件名不匹配。最可靠的解决方式是手动编写Python脚本完成转换,以下是具体步骤:
一、先明确YOLOv7的标注规则
- 每个图像对应一个同名的
.txt标注文件(比如img_001.jpg对应img_001.txt) - 每行代表一个目标,格式为:
class_id x_center y_center width heightclass_id:整数,需自行建立类别与索引的映射表x_center/y_center:目标框中心坐标,相对于图像宽高归一化到0-1区间width/height:目标框的宽和高,同样相对于图像宽高归一化到0-1区间
二、编写Python转换脚本
针对你提供的JSON结构,脚本可完成以下操作:遍历JSON文件、读取标注数据、转换坐标格式、生成YOLO兼容的txt文件。
示例脚本
import json import os # 1. 自定义类别映射表,需补充你的数据集所有标签 label_map = { "regulatory--stop--g1": 0, "warning--wild-animals--g4": 1, "other-sign": 2, "regulatory--reversible-lanes--g2": 3, "warning--junction-with-a-side-road-perpendicular-left--g3": 4 } # 2. 设置路径:替换为你的JSON文件夹和输出标注文件夹路径 json_dir = "your/json/folder/path" output_dir = "your/output/label/folder/path" os.makedirs(output_dir, exist_ok=True) # 3. 批量处理所有JSON文件 for json_file in os.listdir(json_dir): if not json_file.endswith(".json"): continue # 生成对应图像的txt文件名(假设JSON和图像同名,仅后缀不同) image_base_name = os.path.splitext(json_file)[0] txt_save_path = os.path.join(output_dir, f"{image_base_name}.txt") with open(os.path.join(json_dir, json_file), "r", encoding="utf-8") as f: annot_data = json.load(f) img_width = annot_data["width"] img_height = annot_data["height"] objects = annot_data["objects"] with open(txt_save_path, "w", encoding="utf-8") as txt_f: for obj in objects: # 可根据需求过滤无效目标,比如跳过模糊标注 if obj["properties"]["ambiguous"]: continue label = obj["label"] if label not in label_map: print(f"发现未映射标签:{label},已跳过") continue class_id = label_map[label] # 读取原始bbox坐标 xmin = obj["bbox"]["xmin"] ymin = obj["bbox"]["ymin"] xmax = obj["bbox"]["xmax"] ymax = obj["bbox"]["ymax"] # 转换为YOLO归一化格式 x_center = (xmin + xmax) / 2 / img_width y_center = (ymin + ymax) / 2 / img_height box_width = (xmax - xmin) / img_width box_height = (ymax - ymin) / img_height # 写入txt文件,保留6位小数精度 txt_f.write(f"{class_id} {x_center:.6f} {y_center:.6f} {box_width:.6f} {box_height:.6f}\n") print("标注转换完成!")
三、关键注意事项
- 类别映射表:先遍历所有JSON文件收集全部标签,再统一分配索引,避免遗漏
- 文件名匹配:确保JSON文件和对应图像文件名完全一致,否则YOLO无法关联图像与标注
- 坐标归一化:必须使用JSON中记录的图像实际宽高计算,不能用固定值,否则标注会错位
- 无效目标过滤:可根据
properties字段跳过模糊、出框的目标,减少训练噪声
四、若仍想用Roboflow解决
需检查以下几点:
- 图像与JSON文件放在同一文件夹,且文件名完全匹配
- 上传时选择「Custom Format」,手动指定JSON结构(比如标签路径
objects.label、bbox路径objects.bbox.xmin等) - 确认JSON中
width和height字段完整,Roboflow依赖这两个值计算归一化坐标
内容的提问来源于stack exchange,提问作者Tahmid
相关产品推荐
相关产品推荐

