Python xml write and read turorial

Python xml write and read

“`
import xml.etree.cElementTree as ET
import numpy as np
root = ET.Element(“annotation”)
ET.SubElement(root,’filename’).text = “2011_004109.jpg”
ET.SubElement(root,’subfolder’).text = ‘VOC2011’
ET.SubElement(root,’action’).text = ‘riding horse’
object = ET.SubElement(root,’object’)
ET.SubElement(object,’name’).text = ‘person’
bndbox = ET.SubElement(object,’bndbox’)
ET.SubElement(bndbox, ‘xmin’).text = ‘281’
ET.SubElement(bndbox, ‘xmax’).text = ‘283’
ET.SubElement(bndbox, ‘ymin’).text = ‘381’
ET.SubElement(bndbox, ‘ymax’).text = ‘481’
object = ET.SubElement(root,’object’)
ET.SubElement(object,’name’).text = ‘horse’
bndbox = ET.SubElement(object,’bndbox’)
ET.SubElement(bndbox, ‘xmin’).text = ‘281’
ET.SubElement(bndbox, ‘xmax’).text = ‘283’
ET.SubElement(bndbox, ‘ymin’).text = ‘381’
ET.SubElement(bndbox, ‘ymax’).text = ‘481’

size = ET.SubElement(root,’size’)
ET.SubElement(size,’depth’).text = ‘3’
ET.SubElement(size,’height’).text = ‘500’
ET.SubElement(size,’width’).text = ‘300’
source = ET.SubElement(root,’source’)
ET.SubElement(source,’anonotation’).text = ‘PASCAL VOC2011’
ET.SubElement(source,’database’).text = ‘The VOC2011 Database’
ET.SubElement(source,’image’).text = ‘flickr’

tree = ET.ElementTree(root)
file_name = ‘action_0.xml’
tree.write(file_name)

“to read the xml data from the file_name”

tree = ET.parse(file_name)
objs = tree.findall(‘object’)
num_objs = len(objs)
objs_name = []
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
action = tree.find(‘action’).text

Load object bounding boxes into a data frame.

for ix, obj in enumerate(objs):
bbox = obj.find(‘bndbox’)
# Make pixel indexes 0-based
x1 = float(bbox.find(‘xmin’).text) - 1
y1 = float(bbox.find(‘ymin’).text) - 1
x2 = float(bbox.find(‘xmax’).text) - 1
y2 = float(bbox.find(‘ymax’).text) - 1
name = obj.find(‘name’).text
objs_name.append(name)
boxes[ix, :] = [x1, y1, x2, y2]

print(action,boxes,objs_name)

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页