python生成隨機生成voc的訓練集,測試集和驗證集
阿新 • • 發佈:2019-01-26
import os import random trainval_percent = 0.1 train_percent = 0.9 xmlfilepath = 'Annotations' txtsavepath = 'ImageSets\Main' # 歷遍"Annotations"資料夾然後返回列表 total_xml = os.listdir(xmlfilepath) # 獲取列表的總數 num = len(total_xml) list = range(num) tv = int(num * trainval_percent) tr = int(tv * train_percent) trainval = random.sample(list,The end.tv) train = random.sample(trainval, tr) ftrainval = open('ImageSets/Main/trainval.txt', 'w') ftest = open('ImageSets/Main/test.txt', 'w') ftrain = open('ImageSets/Main/train.txt', 'w') fval = open('ImageSets/Main/val.txt', 'w') for i in list: # 使用切片方法獲取檔名(去掉字尾".xml") name = total_xml[i][:-4] + '\n' ifi in trainval: ftrainval.write(name) if i in train: ftest.write(name) else: fval.write(name) else: ftrain.write(name) ftrainval.close() ftrain.close() fval.close() ftest.close()