xml转换csv

首先看下  .xml文件

<annotation verified="no">
  <folder>Pictures</folder>
  <filename>201092903912879</filename>
  <path>D:/Documents/Pictures/201092903912879.jpg</path>
  <source>
    <database>Unknown</database>
  </source>
  <size>
    <width>1366</width>
    <height>768</height>
    <depth>3</depth>
  </size>
  <segmented>0</segmented>
  <object>
    <name>dog</name>
    <pose>Unspecified</pose>
    <truncated>0</truncated>
    <Difficult>0</Difficult>
    <bndbox>
      <xmin>402</xmin>
      <ymin>103</ymin>
      <xmax>1024</xmax>
      <ymax>525</ymax>
    </bndbox>
  </object>
</annotation>

所有 xml 生成   .csv文件

filename,width,height,class,xmin,ymin,xmax,ymax
img1,300,300,hat,71,27,262,134
img2,500,333,hat,244,24,346,59
img3,500,750,hat,126,112,352,234

python脚本

'''
只需修改三处,第一第二处改成对应的文件夹目录,
第三处改成对应的文件名,这里是train.csv
os.chdir('D:\\python3\\models-master\\research\\object_detection\\images\\train')
path = 'D:\\python3\\models-master\\research\\object_detection\\images\\train'
xml_df.to_csv('train.csv', index=None)
'''
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET

os.chdir('C:\\Users\\87703\\Desktop\\picture\\test')
path = 'C:\\Users\\87703\\Desktop\\picture\\test'

def xml_to_csv(path):
    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():
    image_path = path
    xml_df = xml_to_csv(image_path)
    xml_df.to_csv('train.csv', index=None)
    print('Successfully converted xml to csv.')


main()





猜你喜欢

转载自blog.csdn.net/as472780551/article/details/80645861