当前位置:   article > 正文

跑模型——labelme的json文件转成yolo使用的txt文件(语义分割,目标检测需要自己改改)_语义分割json转txt

语义分割json转txt

前言
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)}")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

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

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

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号