Coffee_convert_to_csv.py 1.3 KB

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