-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathYOLO2VoTTjson.py
More file actions
80 lines (73 loc) · 2.47 KB
/
YOLO2VoTTjson.py
File metadata and controls
80 lines (73 loc) · 2.47 KB
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
import os
import sys
import cv2
import json
argument = sys.argv[1:]
if not argument[0].endswith('/'):
argument[0] += '/'
if not argument[1].endswith('/'):
argument[1] += '/'
if len(argument) < 2 or len(argument) > 3:
print("Example: python test.py ./pic ./txt ./pic.json")
sys.exit(1)
elif len(argument) == 2:
pic_dir = argument[0]
txt_dir = argument[1]
json_des = argument[0].split('/')[1] + ".json"
elif len(argument) == 3:
pic_dir = argument[0]
txt_dir = argument[1]
json_des = argument[2]
print(pic_dir,txt_dir,json_des)
# get all pic filename
pic_filelists = os.listdir(pic_dir)
if pic_filelists == []:
print("No Picture input!")
exit()
# get all txt filename
txt_filelists = os.listdir(txt_dir)
if txt_filelists == []:
print("No txt input!")
exit()
# 8 object types
index = {0:"CarType0",1:"CarType1",2:"CarType2",3:"CarType3",4:"CarType4",5:"CarType5",6:"CarType6",7:"CarType7"}
raw_dict = {"frames": {}, "framerate": "1", "inputTags": "CarType0,CarType1,CarType2,CarType3,CarType4,CarType5,CarType6,CarType7",
"tag_colors": ["#0ce28f","#950bb1","#0017ff","#39a400","#c53f00","#c2f20c","#2c009b","#008acb"]}
# for all filename
for file in txt_filelists:
try:
print('Reading ' + file.split('.txt')[0])
f = open(txt_dir + file, 'r')
s = f.read().split()
image = cv2.imread(pic_dir + file.split('.txt')[0] + '.jpg')
size = image.shape
w = size[1]
h = size[0]
except Exception as e:
print("Make sure txt and pic is corresponding!")
sys.exit()
# if txt is empty, skip
if not s:
continue
pic_info = []
xy_info = {}
bbox_info = {"width": int(w), "height": int(h)}
# for all bounding boxes
for i2 in range(int(len(s)/5)):
t1 = float(s[i2 * 5 + 1])
t2 = float(s[i2 * 5 + 2])
t3 = float(s[i2 * 5 + 3])
t4 = float(s[i2 * 5 + 4])
xy_info["x1"] = int((t1*int(w)*2-t3*int(w))/2)
xy_info["y1"] = int((t2*int(h)*2-t4*int(h))/2)
xy_info["x2"] = int((t1*int(w)*2+t3*int(w))/2)
xy_info["y2"] = int((t2*int(h)*2+t4*int(h))/2)
bbox_info["box"] = xy_info.copy()
bbox_info["type"] = "rect"
bbox_info["tags"] = [index[int(s[i2 * 5])]]
pic_info.append(bbox_info.copy())
raw_dict["frames"][file.split('.txt')[0] + '.jpg'] = pic_info
# white JSON
with open(json_des, "w") as f:
json.dump(raw_dict, f)
print("Result saved as " + json_des)