Labelme标注的json文件转yolo训练的txt文件

在目标检测任务中,数据标注是模型训练的关键环节。常用的标注工具有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=blog

import json
import os

def 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.")
            continue
        category = category_list.index(label)
        points = shape['points']
        if shape['shape_type'] == 'rectangle':
            (x1, y1), (x2, y2) = points
        elif 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列表中的类别和输入输出文件夹的路径即可,有疑问可以评论区交流~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑脸惹桃花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值