1. 程式人生 > >Python 解析labelme標註的xml檔案(bbounding box)

Python 解析labelme標註的xml檔案(bbounding box)

搭配我之前寫的生成tfrecord的文章,可以直接將labelme標註出來的xml檔案解析出來,用於生成bboundingbox的tfrecod檔案
import xmltodict
import json
import xml.dom.minidom as xmldom
from functools import reduce
import operator
import os
def LabelmeXmlGetCoordinate(LabelmeXmlPath):
    AllcoordinateList = []
    for file in [os.path.join(LabelmeXmlPath,item) for item in os.listdir(LabelmeXmlPath)]:
        fileName = os.path.basename(file).split('.')[0]+'.jpg'
        DOMTree = xmldom.parse(file)
        collection = DOMTree.documentElement
        # 獲取尺寸資訊
        imgSize = collection.getElementsByTagName('size')
        width = imgSize[0].getElementsByTagName('width')[0].childNodes[0].data
        height = imgSize[0].getElementsByTagName('height')[0].childNodes[0].data
        depth = imgSize[0].getElementsByTagName('depth')[0].childNodes[0].data
        # 為了後面將box資訊的列表新增進來後方便降成一維,建立二維陣列
        coordinateList = [[fileName,width,height,depth]]
        imgObjects = collection.getElementsByTagName('object')
        # 獲取bboundingbox資訊
        for imgObject in imgObjects:
            label = imgObject.getElementsByTagName('name')[0].childNodes[0].data
            imgBox = imgObject.getElementsByTagName('bndbox')[0]
            xmin = imgBox.getElementsByTagName('xmin')[0].childNodes[0].data
            ymin = imgBox.getElementsByTagName('ymin')[0].childNodes[0].data
            xmax = imgBox.getElementsByTagName('xmax')[0].childNodes[0].data
            ymax = imgBox.getElementsByTagName('ymax')[0].childNodes[0].data
            bboxList = [xmin,ymin,xmax,ymax,label]
            coordinateList.append(bboxList)
        # 將二維資料變成一維陣列 eg:['0acf8.xml', '331', '257', '3', '65', '78', '234', '196', 'a', '258', '122', '300', '171', 'a']
        coordinateList = reduce(operator.add, coordinateList)
        AllcoordinateList.append(coordinateList)
        print(coordinateList)