greenhouse/libs/pascal_voc_io.py

167 lines
5.3 KiB
Python
Raw Normal View History

#!/usr/bin/env python
# -*- coding: utf8 -*-
import _init_path
2015-09-17 15:00:52 +08:00
import sys
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement
from lxml import etree
import codecs
XML_EXT = '.xml'
2015-09-17 15:00:52 +08:00
class PascalVocWriter:
2015-09-17 15:00:52 +08:00
def __init__(self, foldername, filename, imgSize, databaseSrc='Unknown', localImgPath=None):
self.foldername = foldername
self.filename = filename
self.databaseSrc = databaseSrc
self.imgSize = imgSize
self.boxlist = []
self.localImgPath = localImgPath
self.verified = False
2015-09-17 15:00:52 +08:00
def prettify(self, elem):
"""
Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf8')
root = etree.fromstring(rough_string)
return etree.tostring(root, pretty_print=True)
2015-09-17 15:00:52 +08:00
def genXML(self):
"""
Return XML root
"""
# Check conditions
if self.filename is None or \
self.foldername is None or \
self.imgSize is None:
return None
2015-09-17 15:00:52 +08:00
top = Element('annotation')
top.set('verified', 'yes' if self.verified else 'no')
folder = SubElement(top, 'folder')
2015-09-17 15:00:52 +08:00
folder.text = self.foldername
filename = SubElement(top, 'filename')
2015-09-17 15:00:52 +08:00
filename.text = self.filename
localImgPath = SubElement(top, 'path')
2015-09-17 15:00:52 +08:00
localImgPath.text = self.localImgPath
source = SubElement(top, 'source')
database = SubElement(source, 'database')
2015-09-17 15:00:52 +08:00
database.text = self.databaseSrc
size_part = SubElement(top, 'size')
width = SubElement(size_part, 'width')
height = SubElement(size_part, 'height')
depth = SubElement(size_part, 'depth')
2015-09-17 15:00:52 +08:00
width.text = str(self.imgSize[1])
height.text = str(self.imgSize[0])
if len(self.imgSize) == 3:
2015-09-17 15:00:52 +08:00
depth.text = str(self.imgSize[2])
else:
depth.text = '1'
segmented = SubElement(top, 'segmented')
segmented.text = '0'
2015-09-17 15:00:52 +08:00
return top
def addBndBox(self, xmin, ymin, xmax, ymax, name):
bndbox = {'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax}
2015-09-17 15:00:52 +08:00
bndbox['name'] = name
self.boxlist.append(bndbox)
2015-09-17 15:00:52 +08:00
def appendObjects(self, top):
for each_object in self.boxlist:
object_item = SubElement(top, 'object')
2015-09-17 15:00:52 +08:00
name = SubElement(object_item, 'name')
try:
name.text = unicode(each_object['name'])
except NameError:
# Py3: NameError: name 'unicode' is not defined
name.text = each_object['name']
2015-09-17 15:00:52 +08:00
pose = SubElement(object_item, 'pose')
pose.text = "Unspecified"
truncated = SubElement(object_item, 'truncated')
truncated.text = "0"
difficult = SubElement(object_item, 'difficult')
difficult.text = "0"
bndbox = SubElement(object_item, 'bndbox')
xmin = SubElement(bndbox, 'xmin')
xmin.text = str(each_object['xmin'])
ymin = SubElement(bndbox, 'ymin')
ymin.text = str(each_object['ymin'])
xmax = SubElement(bndbox, 'xmax')
xmax.text = str(each_object['xmax'])
ymax = SubElement(bndbox, 'ymax')
ymax.text = str(each_object['ymax'])
def save(self, targetFile=None):
2015-09-17 15:00:52 +08:00
root = self.genXML()
self.appendObjects(root)
out_file = None
if targetFile is None:
out_file = codecs.open(
self.filename + XML_EXT, 'w', encoding='utf-8')
2015-09-17 15:00:52 +08:00
else:
out_file = codecs.open(targetFile, 'w', encoding='utf-8')
2015-09-17 15:00:52 +08:00
prettifyResult = self.prettify(root)
out_file.write(prettifyResult.decode('utf8'))
2015-09-17 15:00:52 +08:00
out_file.close()
2015-12-09 21:29:26 +08:00
class PascalVocReader:
def __init__(self, filepath):
# shapes type:
# [labbel, [(x1,y1), (x2,y2), (x3,y3), (x4,y4)], color, color]
self.shapes = []
2015-12-09 21:29:26 +08:00
self.filepath = filepath
self.verified = False
2015-12-09 21:29:26 +08:00
self.parseXML()
def getShapes(self):
return self.shapes
2016-12-20 08:30:11 -06:00
def addShape(self, label, bndbox):
xmin = int(bndbox.find('xmin').text)
ymin = int(bndbox.find('ymin').text)
xmax = int(bndbox.find('xmax').text)
ymax = int(bndbox.find('ymax').text)
points = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
2015-12-09 21:29:26 +08:00
self.shapes.append((label, points, None, None))
def parseXML(self):
assert self.filepath.endswith('.xml'), "Unsupport file format"
parser = etree.XMLParser(encoding='utf-8')
xmltree = ElementTree.parse(self.filepath, parser=parser).getroot()
2015-12-09 21:29:26 +08:00
filename = xmltree.find('filename').text
try:
verified = xmltree.attrib['verified']
if verified == 'yes':
self.verified = True
except KeyError:
self.verified = False
2015-12-09 21:29:26 +08:00
for object_iter in xmltree.findall('object'):
bndbox = object_iter.find("bndbox")
label = object_iter.find('name').text
2016-12-20 08:30:11 -06:00
self.addShape(label, bndbox)
2015-12-09 21:29:26 +08:00
return True
# tempParseReader = PascalVocReader('test.xml')
# print tempParseReader.getShapes()
2015-09-17 15:00:52 +08:00
"""
# Test
tmp = PascalVocWriter('temp','test', (10,20,3))
tmp.addBndBox(10,10,20,30,'chair')
tmp.addBndBox(1,1,600,600,'car')
tmp.save()
"""