把voc格式的标注文件.xml转为coco格式的.json文件

在训练目标检测模型的时候一般使用labelimg标注的图像生产.xml格式的标注文件。有时候需要用到coco格式的json标注文件,在github找到了一个xml转json的脚本。(https://github.com/CivilNet/Gemfield/blob/master/src/python/pascal_voc_xml2json/pascal_voc_xml2json.py)

执行该脚本会读取Annotations下的.xml文件并解析其中的类别及boundbox的坐标,最后生成instances.json的文件。

这里使用了4张图像的xml进行测试。图像名字为2007_000027.jpg 2007_000032.jpg 2007_000033.jpg 2007_000039.jpg。

如下图所示为instances.json文件内容。从下图可以看到,coco的json标注格式实际上是一个大字典{},里面包括了“images”,"annotations","type","categories"等信息(为了便于观察,图中画出的双箭头表示该属性从开始到结束的范围)。"images"存放每个图像的名字宽高及图像id,"annotations"存放对应相同图像id的图像box的四个坐标位置及该框的类别id,"categories"则表示每个类别id到该类真实名字的对应关系。

 

 

原git的脚本不支持划分训练集测试集,也不能提前设定标签的索引。所以进行了改动,如下:

#coding:utf-8

# pip install lxml

import os
import glob
import json
import shutil
import numpy as np
import xml.etree.ElementTree as ET



path2 = "."


START_BOUNDING_BOX_ID = 1


def get(root, name):
    return root.findall(name)


def get_and_check(root, name, length):
    vars = root.findall(name)
    if len(vars) == 0:
        raise NotImplementedError('Can not find %s in %s.'%(name, root.tag))
    if length > 0 and len(vars) != length:
        raise NotImplementedError('The size of %s is supposed to be %d, but is %d.'%(name, length, len(vars)))
    if length == 1:
        vars = vars[0]
    return vars


def convert(xml_list, json_file):
    json_dict = {"images": [], "type": "instances", "annotations": [], "categories": []}
    categories = pre_define_categories.copy()
    bnd_id = START_BOUNDING_BOX_ID
    all_categories = {}
    for index, line in enumerate(xml_list):
        # print("Processing %s"%(line))
        xml_f = line
        tree = ET.parse(xml_f)
        root = tree.getroot()
        
        filename = os.path.basename(xml_f)[:-4] + ".jpg"
        image_id = 20190000001 + index
        size = get_and_check(root, 'size', 1)
        width = int(get_and_check(size, 'width', 1).text)
        height = int(get_and_check(size, 'height', 1).text)
        image = {'file_name': filename, 'height': height, 'width': width, 'id':image_id}
        json_dict['images'].append(image)
        ## Cruuently we do not support segmentation
        #  segmented = get_and_check(root, 'segmented', 1).text
        #  assert segmented == '0'
        for obj in get(root, 'object'):
            category = get_and_check(obj, 'name', 1).text
            if category in all_categories:
                all_categories[category] += 1
            else:
                all_categories[category] = 1
            if category not in categories:
                if only_care_pre_define_categories:
                    continue
                new_id = len(categories) + 1
                print("[warning] category '{}' not in 'pre_define_categories'({}), create new id: {} automatically".format(category, pre_define_categories, new_id))
                categories[category] = new_id
            category_id = categories[category]
            bndbox = get_and_check(obj, 'bndbox', 1)
            xmin = int(float(get_and_check(bndbox, 'xmin', 1).text))
            ymin = int(float(get_and_check(bndbox, 'ymin', 1).text))
            xmax = int(float(get_and_check(bndbox, 'xmax', 1).text))
            ymax = int(float(get_and_check(bndbox, 'ymax', 1).text))
            assert(xmax > xmin), "xmax <= xmin, {}".format(line)
            assert(ymax > ymin), "ymax <= ymin, {}".format(line)
            o_width = abs(xmax - xmin)
            o_height = abs(ymax - ymin)
            ann = {'area': o_width*o_height, 'iscrowd': 0, 'image_id':
                   image_id, 'bbox':[xmin, ymin, o_width, o_height],
                   'category_id': category_id, 'id': bnd_id, 'ignore': 0,
                   'segmentation': []}
            json_dict['annotations'].append(ann)
            bnd_id = bnd_id + 1

    for cate, cid in categories.items():
        cat = {'supercategory': 'none', 'id': cid, 'name': cate}
        json_dict['categories'].append(cat)
    json_fp = open(json_file, 'w')
    json_str = json.dumps(json_dict)
    json_fp.write(json_str)
    json_fp.close()
    print("------------create {} done--------------".format(json_file))
    print("find {} categories: {} -->>> your pre_define_categories {}: {}".format(len(all_categories), all_categories.keys(), len(pre_define_categories), pre_define_categories.keys()))
    print("category: id --> {}".format(categories))
    print(categories.keys())
    print(categories.values())


if __name__ == '__main__':
    classes = ['bicycle', 'pottedplant', 'tvmonitor']
    pre_define_categories = {}
    for i, cls in enumerate(classes):
        pre_define_categories[cls] = i + 1
    # pre_define_categories = {'a1': 1, 'a3': 2, 'a6': 3, 'a9': 4, "a10": 5}
    only_care_pre_define_categories = True
    # only_care_pre_define_categories = False

    train_ratio = 0.9
    save_json_train = 'instances_train2014.json'
    save_json_val = 'instances_val2014.json'
    xml_dir = "./tmp_xml"

    xml_list = glob.glob(xml_dir + "/*.xml")
    xml_list = np.sort(xml_list)
    np.random.seed(100)
    np.random.shuffle(xml_list)

    train_num = int(len(xml_list)*train_ratio)
    xml_list_train = xml_list[:train_num]
    xml_list_val = xml_list[train_num:]

    convert(xml_list_train, save_json_train)
    convert(xml_list_val, save_json_val)

    if os.path.exists(path2 + "/annotations"):
        shutil.rmtree(path2 + "/annotations")
    os.makedirs(path2 + "/annotations")
    if os.path.exists(path2 + "/images/train2014"):
        shutil.rmtree(path2 + "/images/train2014")
    os.makedirs(path2 + "/images/train2014")
    if os.path.exists(path2 + "/images/val2014"):
        shutil.rmtree(path2 +"/images/val2014")
    os.makedirs(path2 + "/images/val2014")

    f1 = open("train.txt", "w")
    for xml in xml_list_train:
        img = xml[:-4] + ".jpg"
        f1.write(os.path.basename(xml)[:-4] + "\n")
        shutil.copyfile(img, path2 + "/images/train2014/" + os.path.basename(img))

    f2 = open("test.txt", "w")
    for xml in xml_list_val:
        img = xml[:-4] + ".jpg"
        f2.write(os.path.basename(xml)[:-4] + "\n") 
        shutil.copyfile(img, path2 + "/images/val2014/" + os.path.basename(img))
    f1.close()
    f2.close()
    print("-------------------------------")
    print("train number:", len(xml_list_train))
    print("val number:", len(xml_list_val))

 

  • 18
    点赞
  • 106
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
### 回答1: COCO格式JSON转换为VOC格式XML需要经过以下几个步骤: 第一步,读取COCO格式JSON文件,解析其中的对象标注数据。一般来说,COCO格式JSON中每个对象标注都包含类别、边界框位置、标注区域等信息。 第二步,根据解析得到的标注信息,生成VOC格式XML文件。在生成XML文件时,需要按照VOC格式的要求,设置好文件头和对象标注信息。每个对象标注都需要有其类别、边界框位置、标注区域等信息。 第三步,将生成的VOC格式XML文件保存到指定路径下。 其中,关于转换的实现细节需要注意以下几点: 首先,在解析COCO格式JSON文件时,需要根据JSON结构中不同的字段和嵌套关系,逐层解析并提取出标注信息。其中,需要注意一些数据格式的转换,如COCO格式中的标注区域信息通常是多边形或RLE格式,需要根据VOC格式要求转化为矩形。 其次,在生成VOC格式XML文件时,需要注意文件头的设置,并遵守XML文档的一些规范。例如,每个XML文件都需要有一个根节点,对象标注的信息需要封装在“object”标签中,且标签中的文本内容需要进行编码和转义。 最后,在保存XML文件时,需要确保文件目录存在及权限设置正确。此外,还可以为XML文件设置其它元信息,如创建时间、文件格式等。 综上所述,将COCO格式JSON文件转换为VOC格式XML需要按照一定的规则解析和生成文件,实现上需要注意一些细节。 ### 回答2: 要将COCO格式JSON文件转换为VOC格式XML文件,需要进行以下步骤: 1.准备好COCO格式JSON文件VOC格式的模板XML文件。 2.读取COCO格式JSON文件,可以使用Python中的json模块来实现。 3.遍历JSON文件中的所有目标,提取出相应的信息,例如目标的类别、位置等。 4.将提取出的信息填写到VOC格式XML模板中,并保存成XML文件。 5.可以使用Python中的xml.etree.ElementTree模块来实现XML文件的创建和编辑。 6.将转换后的XML文件导入到目标检测框架中进行训练和测试。 需要注意的是,COCO格式VOC格式有很大的差异,因此在转换过程中需要特别小心。同时,也需要根据具体的数据集和目标检测框架的要求进行相应的修改和调整。 ### 回答3: COCO (Common Objects in Context)格式是一种常用的目标检测数据集格式,而VOC (Visual Object Classes)格式是另一种经常用于目标检测任务的格式。在实际应用中,有时需要将COCO格式的数据转换为VOC格式,以便在某些特定场景中使用。 要将COCO格式JSON转换为VOC格式XML,需要进行以下几个步骤: 1. 解析COCO格式JSON数据,获得图片路径、图片大小以及目标检测框的坐标、类别等信息。 2. 根据得到的类别信息,确定VOC格式XML中用于表示目标类别的ID号。 3. 将解析得到的图片大小以及目标框坐标转换为VOC格式需要的左上角坐标、右下角坐标等信息。 4. 根据得到的信息,生成VOC格式XML文件。其中,每个目标检测框对应一个对象节点,包含对象的类别、位置等信息。 需要注意的是,COCO格式VOC格式的差异比较大,对于某些特定的键值对,需要进行相应的转换或忽略。此外,在进行数据转换时,应注意保留足够的信息,以便后续任务能够顺利进行。 总的来说,将COCO格式JSON转换为VOC格式XML需要较为复杂的代码实现,对于没有相关经验的人来说难度较大,建议寻求专业人士的帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值