• coco数据集json文件转换成YOLO版的txt文件代码


    coco数据集json文件转换成YOLO版的txt文件

    import os
    import json
    from tqdm import tqdm
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--json_path', default='D:/yolov5_50/data/coco2017/instances_train2017.json', type=str, help="input: coco format(json)")
    parser.add_argument('--save_path', default='D:/yolov5_50/data/coco2017/labeltrain', 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]
    
        x = x * dw
        w = w * dw
        y = y * dh
        h = h * dh
        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不连续!重新映射一下再输出!
        for i, category in enumerate(data['categories']):
            id_map[category['id']] = i
    
        # 通过事先建表来降低时间复杂度
        max_id = 0
        for img in data['images']:
            max_id = max(max_id, img['id'])
        # 注意这里不能写作 [[]]*(max_id+1),否则列表内的空列表共享地址
        img_ann_dict = [[] for i in range(max_id + 1)]
        for i, ann in enumerate(data['annotations']):
            img_ann_dict[ann['image_id']].append(i)
    
        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]))'''
            # 这里可以直接查表而无需重复遍历
            for ann_id in img_ann_dict[img_id]:
                ann = data['annotations'][ann_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()
    
    • 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
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
  • 相关阅读:
    SPARKSQL3.0-Optimizer阶段源码剖析
    Codeforces Round 903 (Div. 3)ABCDE
    今天写了一个可以测试并发数和运行次数的压力测试代码。(Java)
    深入解析React DnD拖拽原理,轻松掌握拖放技巧!
    Business Objects单一报表升级为全套商业智能BI产品,探索更多平台与行业
    京鸿鑫源元宇宙革新探索:开启未来零售新纪元
    An2021软件安装及基本操作(新建文件/导出)
    SpringCloud 微服务应用篇 | (4)Feign远程调用
    React的Context
    Angular依赖注入模式的应用和玩法案例
  • 原文地址:https://blog.csdn.net/qq_46107892/article/details/126117848