保姆级教程:用Python脚本一键搞定YOLOv8-Pose的JSON标注转TXT(附两种格式切换)

张开发
2026/6/9 16:38:35 15 分钟阅读
保姆级教程:用Python脚本一键搞定YOLOv8-Pose的JSON标注转TXT(附两种格式切换)
Python实战YOLOv8-Pose标注格式转换全攻略第一次接触YOLOv8姿态估计时最让人头疼的莫过于数据标注格式的转换问题。上周有位刚入行的算法工程师朋友向我诉苦说他花了三天时间手动修改了2000多张图片的标注文件结果训练时还是报错。这让我意识到一个可靠的格式转换工具对开发者来说有多重要。1. YOLOv8-Pose标注格式深度解析YOLOv8官方支持两种关键点标注格式理解它们的差异是进行格式转换的前提。这两种格式都包含目标检测框和关键点信息但在细节处理上有所不同。1.1 基础格式对比格式1简洁版class_id x_center y_center width height kp1_x kp1_y ... kpn_x kpn_y格式2带可见性class_id x_center y_center width height kp1_x kp1_y kp1_v ... kpn_x kpn_y kpn_v关键区别在于格式1只记录关键点的坐标位置格式2额外存储了每个关键点的可见性标志通常用0/1表示1.2 可见性标志的实战意义在实际项目中可见性标志非常重要。考虑以下场景被遮挡的关键点应标记为不可见超出图像边界的关键点低质量标注或模糊不清的部位# 可见性标志示例 visibility_flags { 0: 不可见, 1: 可见但被遮挡, 2: 完全可见且清晰 }2. 开发环境准备与工具选择2.1 推荐工具组合工具用途备注LabelImg初始标注支持导出JSON格式Python 3.8脚本运行建议使用虚拟环境OpenCV图像处理用于可视化验证tqdm进度显示处理大量文件时很实用2.2 一键安装依赖pip install opencv-python tqdm numpy3. JSON转TXT核心代码实现3.1 完整转换脚本import json import os from pathlib import Path from tqdm import tqdm def convert_json_to_txt(json_path, txt_path, include_visibilityFalse): 将单个JSON标注文件转换为YOLOv8格式的TXT文件 参数: json_path: 输入的JSON文件路径 txt_path: 输出的TXT文件路径 include_visibility: 是否包含可见性标志 with open(json_path, r) as f: data json.load(f) img_width data[imageWidth] img_height data[imageHeight] output_lines [] # 处理每个标注形状 for shape in data[shapes]: points shape[points] # 处理边界框 if shape[shape_type] rectangle: x_coords [p[0] for p in points] y_coords [p[1] for p in points] x_min, x_max min(x_coords), max(x_coords) y_min, y_max min(y_coords), max(y_coords) # 计算归一化后的中心点和宽高 x_center ((x_min x_max) / 2) / img_width y_center ((y_min y_max) / 2) / img_height width (x_max - x_min) / img_width height (y_max - y_min) / img_height # 添加到输出行 output_lines.append(f{shape[label]} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}) # 处理关键点 elif shape[shape_type] point: x points[0][0] / img_width y points[0][1] / img_height if include_visibility: visibility shape.get(group_id, 2) # 默认为可见 output_lines.append(f{x:.6f} {y:.6f} {visibility}) else: output_lines.append(f{x:.6f} {y:.6f}) # 写入TXT文件 with open(txt_path, w) as f: f.write( .join(output_lines)) def batch_convert(json_dir, txt_dir, include_visibilityFalse): 批量转换JSON标注文件夹 参数: json_dir: 包含JSON文件的目录 txt_dir: 输出TXT文件的目录 include_visibility: 是否包含可见性标志 os.makedirs(txt_dir, exist_okTrue) json_files list(Path(json_dir).glob(*.json)) for json_file in tqdm(json_files, desc转换进度): txt_file Path(txt_dir) / (json_file.stem .txt) convert_json_to_txt(json_file, txt_file, include_visibility)3.2 关键代码解析归一化处理x_center ((x_min x_max) / 2) / img_width这个步骤将绝对坐标转换为相对坐标是YOLO格式的核心要求。可见性处理逻辑visibility shape.get(group_id, 2)这里使用LabelImg的group_id字段存储可见性信息默认值为2表示完全可见。4. 实战应用与问题排查4.1 典型使用场景基础转换不带可见性batch_convert(input_json, output_txt)带可见性的转换batch_convert(input_json, output_txt, include_visibilityTrue)4.2 常见问题解决方案问题1转换后坐标值异常检查原始JSON中的imageWidth/imageHeight是否正确确认标注点没有超出图像边界问题2关键点顺序混乱在标注时使用一致的标记顺序可以考虑添加关键点ID到标注属性中问题3批量处理速度慢使用多进程加速from multiprocessing import Pool def worker(args): json_file, txt_dir, include_visibility args txt_file Path(txt_dir) / (json_file.stem .txt) convert_json_to_txt(json_file, txt_file, include_visibility) if __name__ __main__: json_files list(Path(input_json).glob(*.json)) args_list [(f, output_txt, True) for f in json_files] with Pool(4) as p: # 使用4个进程 list(tqdm(p.imap(worker, args_list), totallen(args_list)))5. 高级技巧与扩展应用5.1 可视化验证工具转换后建议使用可视化脚本检查结果import cv2 import numpy as np def visualize_annotation(img_path, txt_path): img cv2.imread(img_path) h, w img.shape[:2] with open(txt_path, r) as f: data f.read().split() # 解析边界框 class_id int(data[0]) x_center, y_center float(data[1]), float(data[2]) box_w, box_h float(data[3]), float(data[4]) # 转换为像素坐标 x1 int((x_center - box_w/2) * w) y1 int((y_center - box_h/2) * h) x2 int((x_center box_w/2) * w) y2 int((y_center box_h/2) * h) # 绘制边界框 cv2.rectangle(img, (x1, y1), (x2, y2), (0,255,0), 2) # 绘制关键点 kp_data data[5:] for i in range(0, len(kp_data), 2 if len(kp_data)%20 else 3): kp_x float(kp_data[i]) * w kp_y float(kp_data[i1]) * h cv2.circle(img, (int(kp_x), int(kp_y)), 5, (0,0,255), -1) cv2.imshow(Annotation, img) cv2.waitKey(0)5.2 支持更多标注工具如果需要支持其他标注工具如CVAT、LabelMe只需调整JSON解析逻辑# CVAT格式适配 if annotations in data: # CVAT格式 for annotation in data[annotations]: points annotation[points] # 其他处理逻辑...在实际项目中我发现将转换脚本与训练流程集成可以大幅提升效率。比如在YOLOv8训练命令前自动执行格式转换python convert_annotations.py --json_dir dataset/json --txt_dir dataset/labels --vis python yolov8 train modelyolov8n-pose.pt datadataset.yaml

更多文章