读取xml文件的类别和图片名到字典

import os
import xml.dom.minidom
gt_dict={}
Image_Path="myData/JPEGImages/test"     #图片路径
XML_Path="myData/Annotations/test_xml/" #.xml文件路径
imagelist=os.listdir(Image_Path)
for image in imagelist:
    image_pre, ext = os.path.splitext(image)
    #imgfile = Image_Path + image
    xmlfile = XML_Path + image_pre + '.xml'
    dom = xml.dom.minidom.parse(xmlfile)#读取xml文档
    root = dom.documentElement#得到文档元素对象
    filenamelist = root.getElementsByTagName("filename")
    filename=filenamelist[0].childNodes[0].data
    objectlist=root.getElementsByTagName("object")
    #读取类别标签
    for objects in objectlist:
        namelist=objects.getElementsByTagName("name")
        objectname=namelist[0].childNodes[0].data
#将读取得信息放入字典中
        gt_dict[filename]=objectname
print(gt_dict)

你可能感兴趣的:(python)