说明:

深度模型训练的时候,我们需要先标注数据集,往往我们用lableme或者labelImg标注的格式是xml的,而好多算法是基于coco或者voc数据集的,一般是json格式,所以,需要将xml文档转换为json格式文档,本文分享一种将voc中xml格式文档转化为json格式文档的算法。

代码:

# -*- coding='utf-8' -*-
##功能:将xml文件夹下的xml文件转换为json格式文件import xml.etree.ElementTree as ET
import os
import jsoncoco = dict()
coco['images'] = []
coco['type'] = 'instances'
coco['annotations'] = []
coco['categories'] = []category_set = dict()
image_set = set()category_item_id = -1
image_id = 0
annotation_id = 0def addCatItem(name):global category_item_idcategory_item = dict()category_item['supercategory'] = 'none'category_item_id += 1category_item['id'] = category_item_idcategory_item['name'] = namecoco['categories'].append(category_item)category_set[name] = category_item_idreturn category_item_iddef addImgItem(file_name, size):global image_idif file_name is None:raise Exception('Could not find filename tag in xml file.')if size['width'] is None:raise Exception('Could not find width tag in xml file.')if size['height'] is None:raise Exception('Could not find height tag in xml file.')image_id += 1image_item = dict()image_item['id'] = image_idprint(file_name)image_item['file_name'] = file_name+".jpg"image_item['width'] = size['width']image_item['height'] = size['height']coco['images'].append(image_item)image_set.add(file_name)return image_iddef addAnnoItem(object_name, image_id, category_id, bbox):global annotation_idannotation_item = dict()annotation_item['segmentation'] = []seg = []# bbox[] is x,y,w,h# left_topseg.append(bbox[0])seg.append(bbox[1])# left_bottomseg.append(bbox[0])seg.append(bbox[1] + bbox[3])# right_bottomseg.append(bbox[0] + bbox[2])seg.append(bbox[1] + bbox[3])# right_topseg.append(bbox[0] + bbox[2])seg.append(bbox[1])annotation_item['segmentation'].append(seg)annotation_item['area'] = bbox[2] * bbox[3]annotation_item['iscrowd'] = 0annotation_item['ignore'] = 0annotation_item['image_id'] = image_idannotation_item['bbox'] = bboxannotation_item['category_id'] = category_idannotation_id += 1annotation_item['id'] = annotation_idcoco['annotations'].append(annotation_item)def parseXmlFiles(xml_path):for f in os.listdir(xml_path):if not f.endswith('.xml'):continuexmlname = f.split('.xml')[0]bndbox = dict()size = dict()current_image_id = Nonecurrent_category_id = Nonefile_name = Nonesize['width'] = Nonesize['height'] = Nonesize['depth'] = Nonexml_file = os.path.join(xml_path, f)print(xml_file)tree = ET.parse(xml_file)root = tree.getroot()if root.tag != 'annotation':raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))# elem is <folder>, <filename>, <size>, <object>for elem in root:current_parent = elem.tagcurrent_sub = Noneobject_name = Noneif elem.tag == 'folder':continueif elem.tag == 'filename':file_name = xmlnameif file_name in category_set:raise Exception('file_name duplicated')# add img item only after parse <size> tagelif current_image_id is None and file_name is not None and size['width'] is not None:if file_name not in image_set:current_image_id = addImgItem(file_name, size)print('add image with {} and {}'.format(file_name, size))else:raise Exception('duplicated image: {}'.format(file_name))# subelem is <width>, <height>, <depth>, <name>, <bndbox>for subelem in elem:bndbox['xmin'] = Nonebndbox['xmax'] = Nonebndbox['ymin'] = Nonebndbox['ymax'] = Nonecurrent_sub = subelem.tagif current_parent == 'object' and subelem.tag == 'name':object_name = subelem.textif object_name not in category_set:current_category_id = addCatItem(object_name)else:current_category_id = category_set[object_name]elif current_parent == 'size':if size[subelem.tag] is not None:raise Exception('xml structure broken at size tag.')size[subelem.tag] = int(subelem.text)# option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>for option in subelem:if current_sub == 'bndbox':if bndbox[option.tag] is not None:raise Exception('xml structure corrupted at bndbox tag.')bndbox[option.tag] = int(float(option.text))# only after parse the <object> tagif bndbox['xmin'] is not None:if object_name is None:raise Exception('xml structure broken at bndbox tag')if current_image_id is None:raise Exception('xml structure broken at bndbox tag')if current_category_id is None:raise Exception('xml structure broken at bndbox tag')bbox = []# xbbox.append(bndbox['xmin'])# ybbox.append(bndbox['ymin'])# wbbox.append(bndbox['xmax'] - bndbox['xmin'])# hbbox.append(bndbox['ymax'] - bndbox['ymin'])print('add annotation with {},{},{},{}'.format(object_name, current_image_id, current_category_id,bbox))addAnnoItem(object_name, current_image_id, current_category_id, bbox)if __name__ == '__main__':xml_path = './xml'json_file = './instances_test2017.json'parseXmlFiles(xml_path)json.dump(coco, open(json_file, 'w'))

使用说明:

修改代码中适当的路径既可以,xml文件夹存放你要转换的xml文件,在当前目录下生成转换后的json格式文档。

目录展示:

​​​​​​​

xml文件转json文件相关推荐

  1. Python将txt文件转为json文件

    python将txt文件转为json文件 txt文件中内容: [*]www.xiaoyang.1 [*]www.xiaoyang.12 [*]www.xiaoyang.135 [*]www.xiaoy ...

  2. pb文件转json文件python脚本

    from google.protobuf import json_format import json import xxxx as pb # <--------- 这里是 proto 编译出来 ...

  3. 常用文件类型 -- JSON文件介绍

    文章目录 JSON文件介绍 1.1 什么是JSON 1.2 JSON语法规则 1.3 JSON举例 1.4 JSON和XML比较 1.4.1 XML的优缺点 1.4.1.1 XML的优点 1.4.1. ...

  4. Kettle CSV文件与json文件转换实例

    一.CSV文件转换 CSV是Comma-Separated Values的缩写,即逗号分隔值.CSV文件是用逗号分隔数据字段的文件,因此也被称为逗号分隔值文件,有时会使用字符来替代逗号实现分隔,因此, ...

  5. CSV文件与json文件转换实例

    一.CSV文件转换 CSV作为数据转存的一种常用格式,它有特定的实现规则,具体如下: 文件开头不能留空,以"行"为单位: 文件可含或不含列名,若含有列名,则位于文件第一行: 文件中 ...

  6. Python之文件处理-JSON文件

    Step1:什么是JSON文件 JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式.它基于 ECMAScript (欧洲计算机协会制定的js ...

  7. 【Python】实现csv文件转json文件

    import jsonimport pandas as pd# 读取CSV文件 csvData = pd.read_csv(r'testData.csv', header = 0) # 读取CSV文件 ...

  8. TxT文件转json文件

    实际应用中很多设备导出的数据均为表格形式TXT文件,为了实际使用方便,可将内容转换成json文件,方便使用,java代码如下 import com.alibaba.fastjson.JSONArray ...

  9. jackson Read 读取 json 文件和 Write 写入 json 文件 读写 json 文件

    jackson Read Write 读取 json 文件和写入 json 文件 jackson 可以由这里获得 http://repo1.maven.org/maven2/com/fasterxml ...

  10. xml文件转为json文件

    import xmltodict import json import osdef load_json(xml_path,outurl):#获取xml文件xml_file = open(xml_pat ...

最新文章

  1. 利用Spring AOP与JAVA注解为系统增加日志功能
  2. 计算音频数据音量_【翻译】线性的音量推子……简直像一个个秤砣!
  3. 【洛谷】P1388 算式(dp)
  4. 云痕大数据 家长登录_云痕家长app
  5. java url api_深入阅读java api之URL
  6. RIP协议相关知识总结
  7. 限制网速 制造测试条件
  8. github ssh密钥_如何使用SSH密钥在一台机器上管理多个GitHub帐户
  9. Docker入门与应用系列(二)镜像管理
  10. 我的WCF之旅(10):如何在WCF进行Exception Handling
  11. 如何在思科虚拟PC机信息进行修改
  12. Linux链表list_head/hlist_head/hlist_nulls_head的并发性
  13. 定积分证明题例题_一个广义积分不等式证明(送给数学分析同学)
  14. 【毕业季·进击的技术er】大学生计算机毕业设计应该这样写
  15. Vue动态加载本地磁盘图片
  16. 豆豆趣事[2014年08月]
  17. Kindle 可旋转桌面时钟
  18. html创建电子邮件链接教程
  19. Android中APK打包流程
  20. 单页面系统知识点记录

热门文章

  1. linux查看服务进程发包,11月18日linux服务器后,服务器向外发包,CPU达99%以上
  2. win任务栏计算机变未知,深度技术Win7电脑任务栏图标显示异常的解决方法
  3. 中国首档「程序员真人秀」综艺登上热搜,燃炸了!
  4. PowerDesign画ER图
  5. MyEclipse10安装破解教程
  6. 国内网络游戏企业的困境和出路
  7. python发邮件被认定为垃圾邮件_【python文本分类】20行代码识别垃圾邮件
  8. 从日企和水浒传看企业如何转型
  9. Ubuntu 安装sopcast-player看网络电视
  10. 魔兽争霸如何修改快捷键