1. 程式人生 > 其它 >【VOC格式xml檔案解析】——Python

【VOC格式xml檔案解析】——Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/4/26 12:49
# @Author  : @linlianqin
# @Site    : 
# @File    : test1.py
# @Software: PyCharm
# @description:
import xml.etree.ElementTree as ET

def xmli(xmlpath):
	xmlTree = ET.parse(xmlpath) # 解析xml檔案
	root = xmlTree.getroot() # 獲得xml根節點
	size = root.find('size') # 查詢size結點
	# 主要這裡一定是findall,查詢所有的object結點,也就是標註框的資訊,否則用find返回的是Nonetype
	objects = root.findall('object') # 查詢所有的object結點
	for obj in objects:
		bbox = obj.find('bndbox')
		# 修改相應結點的值
		bbox.find('ymin').text = str(222)
		bbox.find('ymax').text = str(222)
	return xmlTree # 返回更新後的xml檔案控制代碼

xmlTree = xmli(r'test.xml')
xmlTree.write('_flip_updown.xml') # 儲存新的xml檔案

以下轉自:python VOC格式的xml檔案解析

python解析XML常見的有三種方法:

xml.dom.*模組,它是W3C DOM API的實現,若需要處理DOM API則該模組很適合;
xml.sax.*模組,它是SAX API的實現,這個模組犧牲了便捷性來換取速度和記憶體佔用,SAX是一個基於事件的API,這就意味著它可以“在空中”處理龐大數量的的文件,不用完全載入進記憶體;
xml.etree.ElementTree模組(簡稱 ET),它提供了輕量級的Python式的API,相對於DOM來說ET 快了很多,而且有很多令人愉悅的API可以使用,相對於SAX來說ET的ET.iterparse也提供了 “在空中” 的處理方式,沒有必要載入整個文件到記憶體,ET的效能的平均值和SAX差不多,但是API的效率更高一點而且使用起來很方便。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# get annotation object bndbox location
try:
    import xml.etree.cElementTree as ET  #解析xml的c語言版的模組
except ImportError:
    import xml.etree.ElementTree as ET
											         
##get object annotation bndbox loc start 
def GetAnnotBoxLoc(AnotPath):#AnotPath VOC標註檔案路徑
    tree = ET.ElementTree(file=AnotPath)  #開啟檔案,解析成一棵樹型結構
    root = tree.getroot()#獲取樹型結構的根
    ObjectSet=root.findall('object')#找到檔案中所有含有object關鍵字的地方,這些地方含有標註目標
    ObjBndBoxSet={} #以目標類別為關鍵字,目標框為值組成的字典結構
    for Object in ObjectSet:
        ObjName=Object.find('name').text
        BndBox=Object.find('bndbox')
        x1 = int(BndBox.find('xmin').text)#-1 #-1是因為程式是按0作為起始位置的
        y1 = int(BndBox.find('ymin').text)#-1
        x2 = int(BndBox.find('xmax').text)#-1
        y2 = int(BndBox.find('ymax').text)#-1
        BndBoxLoc=[x1,y1,x2,y2]
        if ObjBndBoxSet.__contains__(ObjName):
        	ObjBndBoxSet[ObjName].append(BndBoxLoc)#如果字典結構中含有這個類別了,那麼這個目標框要追加到其值的末尾
        else:
        	ObjBndBoxSet[ObjName]=[BndBoxLoc]#如果字典結構中沒有這個類別,那麼這個目標框就直接賦值給其值吧
    return ObjBndBoxSet
##get object annotation bndbox loc end

其他xml檔案的操作——寫入、更新、讀取請參考:python解析xml檔案(解析、更新、寫入)