Created
June 21, 2020 09:41
-
-
Save bionade24/67b98fac657ecadd4dbc5a9b875da498 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python3 | |
""" | |
Usage: | |
# Create train data: | |
python xml_to_csv.py -i [PATH_TO_IMAGES_FOLDER]/train -o [PATH_TO_ANNOTATIONS_FOLDER]/train_labels.csv | |
# Create test data: | |
python xml_to_csv.py -i [PATH_TO_IMAGES_FOLDER]/test -o [PATH_TO_ANNOTATIONS_FOLDER]/test_labels.csv | |
""" | |
import os | |
import glob | |
import pandas as pd | |
import argparse | |
import xml.etree.ElementTree as ET | |
def xml_to_csv(path): | |
"""Iterates through all .xml files (generated by labelImg) in a given directory and combines them in a single Pandas datagrame. | |
Parameters: | |
---------- | |
path : {str} | |
The path containing the .xml files | |
Returns | |
------- | |
Pandas DataFrame | |
The produced dataframe | |
""" | |
xml_list = [] | |
for xml_file in glob.glob(path + '/*.xml'): | |
tree = ET.parse(xml_file) | |
root = tree.getroot() | |
for member in root.findall('object'): | |
value = (root.find('filename').text, | |
int(root.find('size')[0].text), | |
int(root.find('size')[1].text), | |
member[0].text, | |
int(member[4][0].text), | |
int(member[4][1].text), | |
int(member[4][2].text), | |
int(member[4][3].text) | |
) | |
xml_list.append(value) | |
column_name = ['filename', 'width', 'height', | |
'class', 'xmin', 'ymin', 'xmax', 'ymax'] | |
xml_df = pd.DataFrame(xml_list, columns=column_name) | |
return xml_df | |
def main(): | |
# Initiate argument parser | |
parser = argparse.ArgumentParser( | |
description="Sample TensorFlow XML-to-CSV converter") | |
parser.add_argument("-i", | |
"--inputDir", | |
help="Path to the folder where the input .xml files are stored", | |
type=str) | |
parser.add_argument("-o", | |
"--outputFile", | |
help="Name of output .csv file (including path)", type=str) | |
args = parser.parse_args() | |
if(args.inputDir is None): | |
args.inputDir = os.getcwd() | |
if(args.outputFile is None): | |
args.outputFile = args.inputDir + "/labels.csv" | |
assert(os.path.isdir(args.inputDir)) | |
xml_df = xml_to_csv(args.inputDir) | |
xml_df.to_csv( | |
args.outputFile, index=None) | |
print('Successfully converted xml to csv.') | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment