美文网首页
生成XML文件

生成XML文件

作者: chunleiml | 来源:发表于2020-01-17 10:49 被阅读0次

使用labelImg生成的xml用于yolov3目标检测训练,为了减少标注工作量,可以使用少部分数据训练模型,然后使用模型跑剩下的数据,把预测的结果写到xml文件中,再使用labelImg文件进行修正,可以减少总体的标注工作量。

import xml.dom.minidom
import os

def create_xml(save_path, bboxes, a, name):
    #在内存中创建一个空的文档
    doc = xml.dom.minidom.Document() 
    #创建一个根节点Managers对象
    root = doc.createElement('annotation') 
    #设置根节点的属性
    #将根节点添加到文档对象中
    doc.appendChild(root) 
    nodesize = doc.createElement('size')
    nodewidth = doc.createElement('width')
    nodewidth.appendChild(doc.createTextNode(str(240)))
    nodeheight = doc.createElement('height')
    nodeheight.appendChild(doc.createTextNode(str(80)))
    nodedepth = doc.createElement('depth')
    nodedepth.appendChild(doc.createTextNode(str(1)))
    nodesize.appendChild(nodewidth)
    nodesize.appendChild(nodeheight)
    nodesize.appendChild(nodedepth)
    classes = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N',
                   'P','Q','R','S','T','U','V','W','X','Y','Z']
    managerList = []
    for bbox in bboxes:
        managerList.append({'name':classes[int(bbox[5])],'xmin' : int(bbox[0]),  'ymin' : int(bbox[1]), 'xmax' : int(bbox[2]), 'ymax' :int(bbox[3])})
        
    
    
    for i in managerList :
        nodefilename = doc.createElement('filename')
#        nodefilename = doc.createElement('name')
        nodefilename.appendChild(doc.createTextNode(name))
        root.appendChild(nodefilename)        
        
        nodeobject = doc.createElement('object')
        nodeName = doc.createElement('name')
        nodeName.appendChild(doc.createTextNode(str(i['name'])))
        nodeobject.appendChild(nodeName)
        
        nodebndbox = doc.createElement('bndbox')
#        nodebndbox.appendChild(doc.createTextNode(str(i['name'])))
        nodeobject.appendChild(nodebndbox)        
        
        nodexmin = doc.createElement('xmin')
        #给叶子节点name设置一个文本节点,用于显示文本内容
        nodexmin.appendChild(doc.createTextNode(str(i['xmin'])))
        
        nodeymin = doc.createElement("ymin")
        nodeymin.appendChild(doc.createTextNode(str(i["ymin"])))
        
        nodexmax = doc.createElement("xmax")
        nodexmax.appendChild(doc.createTextNode(str(i["xmax"])))
        
        nodeymax = doc.createElement("ymax")
        nodeymax.appendChild(doc.createTextNode(str(i["ymax"])))
        
        #将各叶子节点添加到父节点Manager中,
        #最后将Manager添加到根节点Managers中
        nodebndbox.appendChild(nodexmin)
        nodebndbox.appendChild(nodeymin)
        nodebndbox.appendChild(nodexmax)
        nodebndbox.appendChild(nodeymax)
        root.appendChild(nodeobject)
    #开始写xml文档
    
    fp = open(os.path.join(save_path,a+'.xml'), 'w')
    doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")

相关文章

网友评论

      本文标题:生成XML文件

      本文链接:https://www.haomeiwen.com/subject/fhdczctx.html