X-AnyLabeling中OBB json标签文件转换YOLO txt标签 用X-AnyLabeling标注OBB标签用于YOLO训练但标注完后一直没转好txt标签便写了一个脚本用于转换。JSON_DIRX-AnyLabeling标注完的json标签文件SAVE_DIR转换后保存的路径CLASS_MAPPING类别映射importjsonimportosfrompathlibimportPathdefconvert_json_to_yolov8_obb(json_dir,save_dir,class_mapping): 批量转换JSON标签为YOLOv8 OBB格式 :param json_dir: JSON标签文件所在目录 :param save_dir: 转换后TXT标签保存目录 :param class_mapping: 类别名到数字的映射字典如{person:0, car:1} # 创建保存目录不存在则创建Path(save_dir).mkdir(parentsTrue,exist_okTrue)# 遍历目录下所有JSON文件forjson_fileinPath(json_dir).glob(*.json):try:# 读取JSON文件withopen(json_file,r,encodingutf-8)asf:datajson.load(f)# 获取图片尺寸用于归一化img_widthdata[imageWidth]img_heightdata[imageHeight]# 准备TXT内容txt_content[]forshapeindata[shapes]:ifshape[shape_type]!rotation:continue# 获取类别class_nameshape[label]ifclass_namenotinclass_mapping:print(f警告{json_file}中类别{class_name}未在映射表中已跳过)continueclass_idclass_mapping[class_name]# 获取四个角点坐标原始像素值pointsshape[points]# 检查是否为4个点iflen(points)!4:print(f警告{json_file}中{class_name}标注点数量异常非4个已跳过)continue# 归一化坐标转YOLO格式0~1之间normalized_points[]forx,yinpoints:norm_xx/img_width norm_yy/img_height normalized_points.append(f{norm_x:.6f}{norm_y:.6f})# YOLOv8 OBB格式class_id x1 y1 x2 y2 x3 y3 x4 y4linef{class_id} .join(normalized_points)txt_content.append(line)# 保存TXT文件txt_filePath(save_dir)/json_file.name.replace(.json,.txt)withopen(txt_file,w,encodingutf-8)asf:f.write(\n.join(txt_content))print(f成功转换{json_file}-{txt_file})exceptExceptionase:print(f处理{json_file}时出错{str(e)})if__name____main__:# -------------------------- 配置参数 --------------------------JSON_DIRrC:\\Users\\Administrator.JM-202404091914\\Desktop\\新建文件夹\\txt\\labels# JSON标签目录SAVE_DIRrC:\\Users\\Administrator.JM-202404091914\\Desktop\\新建文件夹\\txt\\txt# TXT标签保存目录# 类别映射根据实际标注类别调整key标注类别名value类别IDCLASS_MAPPING{person:0,car:1}# -------------------------------------------------------------# 执行转换convert_json_to_yolov8_obb(JSON_DIR,SAVE_DIR,CLASS_MAPPING)print(批量转换完成)