您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页Lab-COCO数据集json格式转txt格式

Lab-COCO数据集json格式转txt格式

来源:五一七教育网
Lab-COCO数据集json格式转txt格式

COCO数据集: JSON转txt

JSON⽂件⽰例

代码

#COCO 格式的数据集转化为 YOLO 格式的数据集#--json_path 输⼊的json⽂件路径

#--save_path 保存的⽂件夹名字,默认为当前⽬录下的labels。import osimport json

from tqdm import tqdmimport argparse

parser = argparse.ArgumentParser()

#这⾥根据⾃⼰的json⽂件位置,换成⾃⼰的就⾏

parser.add_argument('--json_path', default='D:/A4-python/JSON/annotations.json',type=str, help=\"input: coco format(json)\")#这⾥设置.txt⽂件保存位置

parser.add_argument('--save_path', default='D:/A4-python/JSON/OP', type=str, help=\"specify where to save the output dir of labels\")arg = parser.parse_args()

def convert(size, box): dw = 1. / (size[0]) dh = 1. / (size[1])

x = box[0] + box[2] / 2.0 y = box[1] + box[3] / 2.0 w = box[2] h = box[3]

#round函数确定(xmin, ymin, xmax, ymax)的⼩数位数 x = round(x * dw, 6) w = round(w * dw, 6) y = round(y * dh, 6) h = round(h * dh, 6) return (x, y, w, h)

if __name__ == '__main__':

json_file = arg.json_path # COCO Object Instance 类型的标注 ana_txt_save_path = arg.save_path # 保存的路径 data = json.load(open(json_file, 'r'))

if not os.path.exists(ana_txt_save_path): os.makedirs(ana_txt_save_path)

id_map = {} # coco数据集的id不连续!重新映射⼀下再输出! with open(os.path.join(ana_txt_save_path, 'classes.txt'), 'w') as f: # 写⼊classes.txt

for i, category in enumerate(data['categories']): f.write(f\"{category['name']}\\n\") id_map[category['id']] = i # print(id_map)

#这⾥需要根据⾃⼰的需要,更改写⼊图像相对路径的⽂件位置。 list_file = open(os.path.join(ana_txt_save_path, 'train2017.txt'), 'w') for img in tqdm(data['images']): filename = img[\"file_name\"] img_width = img[\"width\"] img_height = img[\"height\"] img_id = img[\"id\"]

head, tail = os.path.splitext(filename)

ana_txt_name = head + \".txt\" # 对应的txt名字,与jpg⼀致

f_txt = open(os.path.join(ana_txt_save_path, ana_txt_name), 'w') for ann in data['annotations']: if ann['image_id'] == img_id:

box = convert((img_width, img_height), ann[\"bbox\"])

f_txt.write(\"%s %s %s %s %s\\n\" % (id_map[ann[\"category_id\"]], box[0], box[1], box[2], box[3])) f_txt.close()

#将图⽚的相对路径写⼊train2017或val2017的路径 list_file.write('./images/train2017/%s.jpg\\n' %(head)) list_file.close()

参考代码链接

结果展⽰

Tips

⽂件夹的名字不能包含 \\ / : * ? \" < > |

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务