功能性模块:(2)解析xml
一、 模块介绍
为啥要写这个模块呢,通常公司给的标注文件都是以xml的格式,所以新手第一课就是解析xml,之前lz用的方法比较繁琐,现在有个还不错的方法,就记录一下吧。
二、代码实现
"""
<object>
<name>1</name>
<angle_flag>face</angle_flag>
<face_flag>0</face_flag>
<flag>rectangle</flag>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>1201</xmin>
<ymin>1161</ymin>
<xmax>1566</xmax>
<ymax>1576</ymax>
</bndbox>
<pose>1<coordinate><x>1276</x><y>1334</y></coordinate></pose>
<pose>2<coordinate><x>1301</x><y>1338</y></coordinate></pose>
</object>
"""
# 解析对应的xml,并保存至对应位置
def parseXml(xml_path):
tree = ET.parse(xml_path)
root = tree.getroot()
objects = root.findall('object')
for obj in objects:
print('obj: ', obj)
cls = obj.find('angle_flag').text
print("the cls is: ", cls)
if cls == 'face':
kps_total = []
kps_dict = {}
kps_eye = []
bndbox = obj.find('bndbox')
xmin = float(bndbox.find('xmin').text)
ymin = float(bndbox.find('ymin').text)
xmax = float(bndbox.find('xmax').text)
ymax = float(bndbox.find('ymax').text)
# 按照数据集的方式,进行归一化
width = xmax - xmin + 1
height = ymax - ymin + 1
bbox = [xmin, ymin, width, height]
for pose in obj.findall('pose'):
# print(pose)
pose_id = pose.text
if pose.find('coordinate') is not None:
pose_x = pose.find('coordinate').find('x').text
pose_y = pose.find('coordinate').find('y').text
这里主要就是截取了一下段解析xml的代码,其中
<pose>1<coordinate><x>1276</x><y>1334</y></coordinate></pose>
这个中的1怎么取LZ还想了好久。。。结果其实只要一行代码即可解决
cls = obj.find('angle_flag').text
每天进步一点点吧,奥利给!