Created
April 10, 2019 05:56
-
-
Save uzl/7d1591251429fec0081e680130175e5c to your computer and use it in GitHub Desktop.
Quadrilateral bounding box to LabelImg xml generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from pathlib import Path | |
import xml.etree.cElementTree as ET | |
from PIL import Image | |
def create_labimg_xml(image_path, annotation_list): | |
image_path = Path(image_path) | |
img = np.array(Image.open(image_path).convert('RGB')) | |
annotation = ET.Element('annotation') | |
ET.SubElement(annotation, 'folder').text = str(image_path.parent.name) | |
ET.SubElement(annotation, 'filename').text = str(image_path.name) | |
ET.SubElement(annotation, 'path').text = str(image_path) | |
source = ET.SubElement(annotation, 'source') | |
ET.SubElement(source, 'database').text = 'Unknown' | |
size = ET.SubElement(annotation, 'size') | |
ET.SubElement(size, 'width').text = str (img.shape[1]) | |
ET.SubElement(size, 'height').text = str(img.shape[0]) | |
ET.SubElement(size, 'depth').text = str(img.shape[2]) | |
ET.SubElement(annotation, 'segmented').text = '0' | |
for annot in annotation_list: | |
tmp_annot = annot.split(',') | |
cords, label = tmp_annot[0:-2], tmp_annot[-1] | |
xmin, ymin, xmax, ymax = cords[0], cords[1], cords[4], cords[5] | |
object = ET.SubElement(annotation, 'object') | |
ET.SubElement(object, 'name').text = label | |
ET.SubElement(object, 'pose').text = 'Unspecified' | |
ET.SubElement(object, 'truncated').text = '0' | |
ET.SubElement(object, 'difficult').text = '0' | |
bndbox = ET.SubElement(object, 'bndbox') | |
ET.SubElement(bndbox, 'xmin').text = str(xmin) | |
ET.SubElement(bndbox, 'ymin').text = str(ymin) | |
ET.SubElement(bndbox, 'xmax').text = str(xmax) | |
ET.SubElement(bndbox, 'ymax').text = str(ymax) | |
tree = ET.ElementTree(annotation) | |
xml_file_name = image_path.parent / (image_path.name.split('.')[0]+'.xml') | |
tree.write(xml_file_name) | |
# ---------------------------------------------------------------------------------- | |
anotation_list = ['291,473,385,481,383,504,289,496,Hello', | |
'270,507,330,507,330,516,270,516,SUPERLATIVE'] | |
create_labimg_xml('data/demo.jpg', anotation_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Suggest to use this code in the end.
it will save the xml in pretty view.
just need to delete next lines:
tree = ET.ElementTree(annotation)
tree.write(xml_file_name)
and after the line:
xml_file_name = image_path.parent / (image_path.name.split('.')[0]+'.xml')
past this lines:
import xml.dom.minidom as minidom
xmlstr = minidom.parseString(ET.tostring(annotation)).toprettyxml(indent=" ")
with open(xml_file_name, "w") as tree:
tree.write(xmlstr)