在目标检测任务中,数据标注是模型训练的关键环节。常用的标注工具有Labelimg和 Labelme,它们均能够以直观的方式对图像中的目标进行标注,并生成包含标注信息的TXT文件或者 JSON 文件。然而,YOLO模型使用的是特定格式的 .txt 文件作为训练数据。因此,在使用 Labelme 进行标注后,如何将 JSON 文件转换为 YOLO 训练所需的 .txt 文件格式,成为了数据准备过程中的重要步骤。
本篇文章将详细介绍如何将 Labelme 生成的 JSON 文件转换为适用于 YOLO 训练的 .txt 文件,并通过 Python 代码示例,帮助你高效完成数据集的格式转换。
思路为,json文件中需要提取的关键信息为类别和坐标,可在shapes标签中通过提取label和points的值并进行分析得到,再将坐标值进行归一化,将全部信息按照每行文本输出到txt文件中,得到的即为yolo格式的txt文件。
需要注意labelme标注的json文件可以有矩形框和多边形框以及其它一些种类的形状,这里我们需要处理矩形“rectangle”和多边形“polygon”两种类型的标签,分别提取后经分析即可。
代码如下,输入输出均为文件夹,都是针对文件夹进行批量格式转换的。
# 作者:CSDN-笑脸惹桃花 https://blog.csdn.net/qq_67105081?type=blogimport json
import osdef json2yolo(json_path, output_dir, category_list):with open(json_path, 'r') as f:labelme_data = json.load(f) # 读取JSON数据image_width = labelme_data.get('imageWidth', 1) # 避免为0的情况image_height = labelme_data.get('imageHeight', 1)l = []# 遍历所有的标注形状for shape in labelme_data['shapes']:label = shape['label']if label not in category_list:print(f"Skipping shape with label '{label}' not in category list.")continuecategory = category_list.index(label)points = shape['points']if shape['shape_type'] == 'rectangle':(x1, y1), (x2, y2) = pointselif shape['shape_type'] == 'polygon':x1, y1 = min(point[0] for point in points), min(point[1] for point in points) x2, y2 = max(point[0] for point in points), max(point[1] for point in points) else:continue# 计算YOLO格式所需的中心点和宽高x_center = max(0, (x1 + x2) / 2.0 / image_width)y_center = max(0, (y1 + y2) / 2.0 / image_height)width = max(0, (x2 - x1) / image_width)height = max(0, (y2 - y1) / image_height)l.append(f"{category} {x_center} {y_center} {width} {height}")# 输出txt文件output_file = os.path.join(output_dir, os.path.splitext(os.path.basename(json_path))[0] + '.txt')with open(output_file, 'w') as f:f.write('\n'.join(l))def process_folder(json_folder, output_folder, category_list):if not os.path.exists(output_folder):os.makedirs(output_folder)for filename in os.listdir(json_folder):if filename.endswith('.json'):json_path = os.path.join(json_folder, filename)json2yolo(json_path, output_folder, category_list)print("Conversion completed!")# 定义类别列表
category_list = ["hat", "nohat"] #修改为自己需要转化的列表# 输入文件夹和输出文件夹
json_folder = r' ' # 修改为输入json文件夹路径
output_txt_folder = r' ' # 修改为输出txt文件夹路径# 处理文件夹中的所有json文件
process_folder(json_folder, output_txt_folder, category_list)
使用时修改category_list列表中的类别和输入输出文件夹的路径即可,有疑问可以评论区交流~