前言
将labelme多边形标注的json文件转换成yolo使用的txt文件

import os
import json
import numpy as np
from tqdm import tqdm

#实现函数
def json2txt(path_json, path_txt):  # 可修改生成格式
    with open(path_json, 'r') as path_json:
        jsonx = json.load(path_json)
        with open(path_txt, 'w+') as ftxt:
            width,height = jsonx['imageWidth'],jsonx['imageHeight']
            for shape in jsonx['shapes']:
                label_name = shape['label']
                label_index = str(classes_name.index(label_name))
                label = label_index + ' '
                #目标检测 改这 获取xywh 对应去除上width与height
                xy = np.array(shape['points'])
                strxy = ''
                for x, y in xy:
                    x = float(x)/width
                    y = float(y)/height
                    strxy += str(x) + ' ' + str(y) + ' '

                label += strxy
                ftxt.writelines(label + "\n")

dir_json = 'D:/data_val/phone_1_dai/new/output/'  # json存储的文件目录 这里需要在最后加'/'
dir_txt = 'D:/data_val/phone_1_dai/new/txt'  # txt存储目录

#如果不存在则创建txt存储目录
os.makedirs(dir_txt,exist_ok=True)
list_json = os.listdir(dir_json)

#标签名
classes_name = ["_background_", 'phone']

pbar = tqdm(total=len(list_json))
error_list=[]
for cnt, json_name in enumerate(list_json):
    try:
        # print('cnt=%d,name=%s' % (cnt, json_name))
        path_json = dir_json + json_name
        path_txt = dir_txt +'/'+ json_name.replace('.json', '.txt')
        json2txt(path_json, path_txt)
    except Exception as e:
        # print('cnt=%d,name=%s' % (cnt, json_name))
        error_list.append({json_name:e})
    pbar.update(1)


for error in error_list:
    print(error)
print(f"error length={len(error_list)}")

如果有什么不懂的,可以在评论区底下评论哦,我会努力解答的

欢迎大家点赞或收藏,点赞或收藏可以鼓励作者更新哟~

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐