代码如下:
import glob
import os
import random
import shutil
# 划分比例
p=3/4#训练集
xmlpath='E:\\shujuji\\MASK\\Annotations\\*'
imgpath='E:\\shujuji\\MASK\\JPEGImages\\*'
xmlpaths=glob.glob(xmlpath)
imgpaths=glob.glob(imgpath)
my_list=[i for i in range(len(xmlpaths))]#打乱列表
random.shuffle(my_list)
train_folder_img = "VOCdevkit\\train\\images"
train_folder_xml = "VOCdevkit\\train\\labels"
val_folder_img = "VOCdevkit\\val\\images"
val_folder_xml = "VOCdevkit\\val\\labels"
try:
os.makedirs(train_folder_img)
os.makedirs(train_folder_xml)
os.makedirs(val_folder_img)
os.makedirs(val_folder_xml)
print(f"成功创建多级目录:train")
except FileExistsError:
print(f"目录 train 已存在。")
except OSError as e:
print(f"创建目录时发生错误:{e}")
for i in range(len(my_list)):
xml = xmlpaths[my_list[i]]
img = imgpaths[my_list[i]]
print(xml)
print(img)
if i<int(len(my_list)*p):
shutil.copy2(xml, train_folder_xml)
shutil.copy2(img, train_folder_img)
else:
shutil.copy2(xml, val_folder_xml)
shutil.copy2(img, val_folder_img)
print('OK!@')