读取VOC数据集的xml文件并转移

首先从VOC数据集地址获取文件列表

import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element
import os     #用于获取文件夹名称
import shutil # 用于移动文件
xml_path = './xml_dir'  # 处理文件夹
move_path = './move_dir'       # 移动至此文件夹
list1 = os.listdir(xml_path)

接下来判断是否有未标注的照片

for name in list1:
    if name.endswith(".xml"):
        path = xml_path+name
        tree = ET.parse(path)
        root = tree.getroot()
        try:
            if root[6][4][3].tag!="ymax":
                print(path)
        except:
            print("wrong xml file:",path)

将有效的xml文件与img文件转移到目标文件夹下

for name in list1:
    if name.endswith(".xml"):
        path = xml_path+name
        tree = ET.parse(path)
        root = tree.getroot()
        try:
            if root[6].tag == "object":
                if root[6][0].text == "grape":#目标检测类别一
                    beta = name.split('.')[0]
                    grape_path = move_path + "grape/" + beta
                    shutil.copyfile((xml_path+beta+'.jpg'),(grape_path +'.jpg')) # 移动到指定位置
                    shutil.copyfile((xml_path+beta+'.xml'),(grape_path +'.xml'))
                elif root[6][0].text == "walnut":#目标检测类别二
                    beta = name.split('.')[0]
                    walnut_path = move_path + "walnut/" + beta
                    shutil.copyfile((xml_path+beta+'.jpg'),(walnut_path +'.jpg')) # 移动到指定位置
                    shutil.copyfile((xml_path+beta+'.xml'),(walnut_path +'.xml')) 
                else:
                    continue
        except:
            print(path)
list2 = len(os.listdir(move_path + "grape/"))/2
list3 = len(os.listdir(move_path + "walnut/"))/2
print("已转移的有效grape类图像数:",list2)
print("已转移的有效walnut类图像数:",list3)

你可能感兴趣的:(目标检测,xml,计算机视觉)