json代码转成txt(yolo专用txt)

本文介绍了一个Python程序,它读取指定目录下的JSON文件,解析其中的数据,特别是Yolo所需的中心点坐标,然后将这些信息写入对应的txt文件。程序通过遍历文件夹来处理多个文件。
该文章已生成可运行项目,

第一章 导包

import os
import json

第二章 两条路径

json_dir = ''  # json文件路径
out_dir = ''  # 输出的 txt 文件路径

 第三章 读取json文件

def get_json(json_file, filename):
    # 读取 json 文件数据
    with open(json_file, 'r') as load_f:
        content = json.load(load_f)

第四章 创建txt文件并写入

tmp = filename
    filename_txt = out_dir + tmp + '.txt'
    # 创建txt文件
    fp = open(filename_txt, mode="w", encoding="utf-8")
    # 将数据写入文件
    # 计算 yolo 数据格式所需要的中心点的 相对 x, y 坐标, w,h 的值
    x = (content["shapes"][0])["points"][0][0]
    y = (content["shapes"][0])["points"][0][1]
    w = (content["shapes"][0])["points"][1][0] - (content["shapes"][0])["points"][0][0]
    h = (content["shapes"][0])["points"][1][1] - (content["shapes"][0])["points"][0][1]
    fp = open(filename_txt, mode="r+", encoding="utf-8")
    file_str = str(filename) + ' ' + str(round(x, 6)) + ' ' + str(round(y, 6)) + ' ' + str(round(w, 6)) + \
               ' ' + str(round(h, 6))
    line_data = fp.readlines()
 
    if len(line_data) != 0:
        fp.write('\n' + file_str)
    else:
        fp.write(file_str)
    fp.close()

第六章 遍历文件夹

def main():
    files = os.listdir(json_dir)  # 得到文件夹下的所有文件名称
    s = []
    for file in files:  # 遍历文件夹
        filename = file.split('.')[0]
        # print(tmp)
        get_json(json_dir + file, filename)
 

第七章 创建主函数并调用

if __name__ == '__main__':
    main()

全部代码如下:

import os
import json
 
json_dir = ''  # json文件路径
out_dir = ''  # 输出的 txt 文件路径
 
 
def get_json(json_file, filename):
    # 读取 json 文件数据
    with open(json_file, 'r') as load_f:
        content = json.load(load_f)
 
    # # 循环处理
    tmp = filename
    filename_txt = out_dir + tmp + '.txt'
    # 创建txt文件
    fp = open(filename_txt, mode="w", encoding="utf-8")
    # 将数据写入文件
    # 计算 yolo 数据格式所需要的中心点的 相对 x, y 坐标, w,h 的值
    x = (content["shapes"][0])["points"][0][0]
    y = (content["shapes"][0])["points"][0][1]
    w = (content["shapes"][0])["points"][1][0] - (content["shapes"][0])["points"][0][0]
    h = (content["shapes"][0])["points"][1][1] - (content["shapes"][0])["points"][0][1]
    fp = open(filename_txt, mode="r+", encoding="utf-8")
    file_str = str(filename) + ' ' + str(round(x, 6)) + ' ' + str(round(y, 6)) + ' ' + str(round(w, 6)) + \
               ' ' + str(round(h, 6))
    line_data = fp.readlines()
 
    if len(line_data) != 0:
        fp.write('\n' + file_str)
    else:
        fp.write(file_str)
    fp.close()
 
 
def main():
    files = os.listdir(json_dir)  # 得到文件夹下的所有文件名称
    s = []
    for file in files:  # 遍历文件夹
        filename = file.split('.')[0]
        # print(tmp)
        get_json(json_dir + file, filename)
 
 
if __name__ == '__main__':
    main()

最近写的一个新版本

import json
import os
from tqdm import tqdm  # 可选进度条库


def labelme_json_to_yolo(txt_save_path, json_path, class_map):
    """
    将LabelMe格式JSON转换为YOLO TXT标注文件
    :param txt_save_path: TXT保存路径
    :param json_path: LabelMe JSON文件路径
    :param class_map: 类别名映射字典(如{"person": 0})
    """
    with open(json_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    img_height = data["imageHeight"]
    img_width = data["imageWidth"]
    img_name = os.path.basename(data["imagePath"])  # 提取图片文件名
    txt_name = os.path.splitext(img_name)[0] + ".txt"
    txt_path = os.path.join(txt_save_path, txt_name)

    lines = []
    for shape in data["shapes"]:
        label = shape["label"]
        if label not in class_map:
            continue  # 跳过未定义类别
        cls_id = class_map[label]

        # 解析多边形/矩形标注为边界框(xmin, ymin, xmax, ymax)
        points = shape["points"]
        x_coords = [p[0] for p in points]
        y_coords = [p[1] for p in points]
        xmin = min(x_coords)
        ymin = min(y_coords)
        xmax = max(x_coords)
        ymax = max(y_coords)

        # 计算YOLO格式坐标(归一化中心坐标+宽高)
        x_center = (xmin + xmax) / (2 * img_width)
        y_center = (ymin + ymax) / (2 * img_height)
        w = (xmax - xmin) / img_width
        h = (ymax - ymin) / img_height

        # 过滤无效坐标(避免越界)
        if 0 <= x_center <= 1 and 0 <= y_center <= 1 and w > 0 and h > 0:
            lines.append(f"{cls_id} {x_center:.6f} {y_center:.6f} {w:.6f} {h:.6f}")

    # 保存TXT文件
    with open(txt_path, 'w') as f:
        f.write('\n'.join(lines))


def batch_convert_labelme_to_yolo(json_folder, txt_folder, class_map):
    """
    批量转换LabelMe格式JSON文件夹到YOLO TXT
    :param json_folder: JSON文件夹路径
    :param txt_folder: TXT保存路径
    :param class_map: 类别名映射字典(如{"person": 0})
    """
    os.makedirs(txt_folder, exist_ok=True)
    json_files = [f for f in os.listdir(json_folder) if f.lower().endswith('.json')]

    for json_file in tqdm(json_files, desc="转换中"):
        json_path = os.path.join(json_folder, json_file)
        labelme_json_to_yolo(txt_folder, json_path, class_map)

    print(f"批量转换完成!共处理{len(json_files)}个JSON文件,保存到:{txt_folder}")


# 示例调用(需根据实际修改)
if __name__ == "__main__":
    JSON_FOLDER = "F:/pytharm/gan/data_dm/lables_json"  # LabelMe JSON文件夹路径
    TXT_FOLDER = "F:/pytharm/gan/data_dm/lables"  # YOLO TXT保存路径
    CLASS_MAP = {"person": 0}  # 类别名映射(需与实际标注一致)

    batch_convert_labelme_to_yolo(JSON_FOLDER, TXT_FOLDER, CLASS_MAP)

json的格式有很多种,要根据自己的json内容格式去写专门的属于自己的转换代码,这两个仅供参考,后续有新格式后也会更新,如有疑问可以留言交流。

本文章已经生成可运行项目
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

李烁.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值