This repository has been archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlabelme2YOLOv5.py
97 lines (80 loc) · 2.44 KB
/
labelme2YOLOv5.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import os
import shutil
import csv
import json
from tqdm import tqdm
import cv2
def initializeData(DataStoreName):
tmp = os.getcwd()
if DataStoreName in os.listdir():
shutil.rmtree(DataStoreName)
os.mkdir(DataStoreName)
os.chdir(DataStoreName)
os.mkdir('images')
os.chdir('images')
os.mkdir('train')
os.mkdir('val')
os.chdir('..')
os.mkdir('labels')
os.chdir('labels')
os.mkdir('train')
os.mkdir('val')
os.chdir(tmp)
def labelme2YOLOv5(target, relJson):
targetDirImg = DataStoreDir + '/images/' + target
targetDirLab = DataStoreDir + '/labels/' + target
relImage = relJson.replace('.json', '.jpg')
# Make Target Data: IMG
shutil.copy(relImage, targetDirImg + '/' + relImage)
# Make Target Data: Poly (GT)
h, w, _ = cv2.imread(relImage).shape
with open(relJson) as f:
data = json.load(f)
for i in range(len(data['shapes'])):
tmp = data['shapes'][i]['points']
tar = []
for j in tmp:
tar.append(j[0]/w)
tar.append(j[1]/h)
with open(targetDirLab + '/' + relJson.replace('.json', '.txt'), 'a', encoding='utf-8') as f:
wr = csv.writer(f, delimiter=' ')
wr.writerow([0, *tar])
if __name__ == "__main__":
DataStoreName = "labelme"
os.chdir('..')
initializeData(DataStoreName)
datasets = os.getcwd()
DataStoreDir = datasets + '/' + DataStoreName
os.chdir('tmp')
candidate = []
for i in os.listdir():
if '.json' in i:
candidate.append(i)
cnt = 0
for c in tqdm(candidate):
if cnt % 3 == 0:
labelme2YOLOv5('val', c)
labelme2YOLOv5('train', c)
else:
labelme2YOLOv5('train', c)
cnt += 1
print('=' * 30)
print('No. Total Data: ', cnt)
print('=' * 30)
os.chdir(DataStoreDir + '/images/train')
tin = len(os.listdir())
print('Training Data: No. Images', tin)
os.chdir(DataStoreDir + '/labels/train')
ttn = len(os.listdir())
print('Training Data: No. GT', ttn)
os.chdir(DataStoreDir + '/images/val')
vin = len(os.listdir())
print('Validation Data: No. Images', vin)
os.chdir(DataStoreDir + '/labels/val')
vtn = len(os.listdir())
print('Validation Data: No. GT', vtn)
print('=' * 30)
print('No. Total Image Data: ', tin + vin)
print('No. Total GT Data: ', ttn + vtn)
print('=' * 30)
os.chdir(datasets + '/MakeData')