读取文件夹内所有文件数,随机分成训练集、测试集,将生成的text文件遍历后,移动xml文件和jpg图片到训练集测试集中
import os
import random
from shutil import copyfile
def create_main_txts(trainval_percent, train_percent):
xmlfilepath = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations'
imgfilepath = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages'
txtsavepath = 'ImageSets\Main'
if not os.path.exists(txtsavepath):
os.makedirs(txtsavepath)
total_xml = os.listdir(xmlfilepath)
#total_img = os.listdir(imgfilepath)
num=len(total_xml)
list=range(num)
tv=int(num*trainval_percent)
tr=int(tv*train_percent)
trainval= random.sample(list,tv)
train=random.sample(trainval,tr)
for i in list:
name_xml=total_xml[i]
oldname_xml = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations/'+name_xml
trainname_xml = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations2/train/'+name_xml
valname_xml = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations2/val/'+name_xml
testname_xml = '/home/per/yolov3/data/VOCdevkit/VOC2007/Annotations2/test/'+name_xml
name_img=total_xml[i][:-4]+'.jpg'
oldname_img = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages/'+name_img
trainname_img = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages2/train/'+name_img
valname_img = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages2/val/'+name_img
testname_img = '/home/per/yolov3/data/VOCdevkit/VOC2007/JPEGImages2/test/'+name_img
if i in trainval:
if i in train:
copyfile(oldname_xml,trainname_xml)
copyfile(oldname_img,trainname_img)
else:
copyfile(oldname_xml,valname_xml)
copyfile(oldname_img,valname_img)
else:
copyfile(oldname_xml,testname_xml)
copyfile(oldname_img,testname_img)
if __name__ == "__main__":
create_main_txts(0.8,1)