Skip to content

Instantly share code, notes, and snippets.

@techzizou
Created January 7, 2021 17:12
Show Gist options
  • Save techzizou/5592c9b66e07f2483593b3edaa701c7e to your computer and use it in GitHub Desktop.
Save techzizou/5592c9b66e07f2483593b3edaa701c7e to your computer and use it in GitHub Desktop.
#adjusted from: https://github.com/datitran/raccoon_dataset
def xml_to_csv(path):
classes_names = []
xml_list = []
for xml_file in glob.glob(path + '/*.xml'):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('object'):
classes_names.append(member[0].text)
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)
classes_names = list(set(classes_names))
classes_names.sort()
return xml_df, classes_names
for label_path in ['train_labels', 'test_labels']:
image_path = os.path.join(os.getcwd(), label_path)
xml_df, classes = xml_to_csv(label_path)
xml_df.to_csv(f'{label_path}.csv', index=None)
print(f'Successfully converted {label_path} xml to csv.')
label_map_path = os.path.join("label_map.pbtxt")
pbtxt_content = ""
for i, class_name in enumerate(classes):
pbtxt_content = (
pbtxt_content
+ "item {{\n id: {0}\n name: '{1}'\n}}\n\n".format(i + 1, class_name)
)
pbtxt_content = pbtxt_content.strip()
with open(label_map_path, "w") as f:
f.write(pbtxt_content)
print('Successfully created label_map.pbtxt ')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment