forked from Megvii-BaseDetection/YOLOX
-
Notifications
You must be signed in to change notification settings - Fork 26
/
voc_txt.py
69 lines (55 loc) · 1.72 KB
/
voc_txt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import os
import random
import sys
from pathlib import Path
if len(sys.argv) < 2:
print("no directory specified, please input target directory")
exit()
root_path = sys.argv[1]
xmlfilepath = root_path + 'VOC2007/Annotations/'
os.mkdir(xmlfilepath)
imagefilepath = root_path + 'VOC2007/JPEGImages/'
os.mkdir(imagefilepath)
# Move annotations to annotations folder
for filename in os.listdir(root_path):
if filename.endswith('.xml'):
with open(os.path.join(root_path, filename)) as f:
Path(root_path + filename).rename(xmlfilepath + filename)
if filename.endswith('.jpg'):
with open(os.path.join(root_path, filename)) as f:
Path(root_path + filename).rename(imagefilepath + filename)
txtsavepath = root_path + '/VOC2007/ImageSets/Main'
if not os.path.exists(root_path):
print("cannot find such directory: " + root_path)
exit()
if not os.path.exists(txtsavepath):
os.makedirs(txtsavepath)
trainval_percent = 0.9
train_percent = 0.8
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, tv)
train = random.sample(trainval, tr)
print("train and val size:", tv)
print("train size:", tr)
ftrainval = open(txtsavepath + '/trainval.txt', 'w')
ftest = open(txtsavepath + '/test.txt', 'w')
ftrain = open(txtsavepath + '/train.txt', 'w')
fval = open(txtsavepath + '/val.txt', 'w')
for i in list:
name = total_xml[i][:-4] + '\n'
if i in trainval:
ftrainval.write(name)
if i in train:
ftrain.write(name)
else:
fval.write(name)
else:
ftest.write(name)
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()