a b/Object-Detection/xml_to_csv.py
1
import os
2
import glob
3
import pandas as pd
4
import xml.etree.ElementTree as ET
5
6
7
def xml_to_csv(path):
8
    xml_list = []
9
    for xml_file in glob.glob(path + '/*.xml'):
10
        tree = ET.parse(xml_file)
11
        root = tree.getroot()
12
        for member in root.findall('object'):
13
            value = (root.find('filename').text,
14
                     int(root.find('size')[0].text),
15
                     int(root.find('size')[1].text),
16
                     member[0].text,
17
                     int(member[4][0].text),
18
                     int(member[4][1].text),
19
                     int(member[4][2].text),
20
                     int(member[4][3].text)
21
                     )
22
            xml_list.append(value)
23
    column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
24
    xml_df = pd.DataFrame(xml_list, columns=column_name)
25
    return xml_df
26
27
28
def main():
29
    for directory in ["train", "test"]:
30
        image_path = os.path.join(os.getcwd(), 'images/{}'.format(directory))
31
        xml_df = xml_to_csv(image_path)
32
        xml_df.to_csv('data/Sag_1-491_Jun22_{}_labels.csv'.format(directory), index=None)
33
        print('Successfully converted xml to csv.')
34
35
36
main()