import os
import sys
import  .etree.ElementTree as ET
import glob

def  _to_txt(indir,outdir):

    os.chdir(indir)
    annotations = os.listdir(\'.\')
    annotations = glob.glob(str(annotations)+\'*. \')
    print(annotations)
    for i, file in enumerate(annotations):

        file_save = file.split(\'.\')[0]+\'.txt\'
        # file_txt=os.path.join(outdir,file_save)
        file_txt = outdir+\"\\\\\"+file_save
        # print(file_save)
        f_w = open(file_txt, \'w\')

        # actual parsing
        in_file = open(file)
        tree=ET.parse(in_file)
        root = tree.getroot()
        filename = root.find(\'filename\').text  #这里是 的根,获取filename那一栏
        for obj in root.iter(\' \'):
                current = list()
                name = obj.find(\'name\').text   #这里获取多个框的名字,底下是获取每个框的位置

                 box = obj.find(\'bndbox\')
                xn =  box.find(\'xmin\').text   
                xx =  box.find(\'xmax\').text
                yn =  box.find(\'ymin\').text
                yx =  box.find(\'ymax\').text
                #print xn
                f_w.write(filename +\' \'+xn+\' \'+yn+\' \'+xx+\' \'+yx+\' \')
                f_w.write(name+\'\\n\')

indir=\'.\\\\BCCD\\\\Annotations\'   # 目录
outdir=\'./BCCD/Annotations_txt\'  #txt目录

 _to_txt(indir,outdir)

转换之后的txt格式如下:可以根据 自己需要的格式调整,分别为图片名,坐标还有,类别

\"\"

收藏 打印