forked from hunglc007/tensorflow-yolov4-tflite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coco_convert.py
112 lines (85 loc) · 3.31 KB
/
coco_convert.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from absl import app, flags, logging
from absl.flags import FLAGS
import cv2
import numpy as np
import os
import json
import sys
import pickle
flags.DEFINE_string('input', '/Volumes/Elements/data/coco_dataset/coco/annotations/instances_val2017.json', 'path to classes file')
flags.DEFINE_string('output', 'val2017.pkl', 'path to classes file')
class COCO:
"""
Handler Class for COCO Format
"""
@staticmethod
def parse(json_path):
try:
json_data = json.load(open(json_path))
images_info = json_data["images"]
cls_info = json_data["categories"]
data = {}
progress_length = len(json_data["annotations"])
progress_cnt = 0
for anno in json_data["annotations"]:
image_id = anno["image_id"]
cls_id = anno["category_id"]
filename = None
img_width = None
img_height = None
cls = None
for info in images_info:
if info["id"] == image_id:
filename, img_width, img_height = \
info["file_name"].split(".")[0], info["width"], info["height"]
for category in cls_info:
if category["id"] == cls_id:
cls = category["name"]
size = {
"width": img_width,
"height": img_height,
"depth": "3"
}
bndbox = {
"xmin": anno["bbox"][0],
"ymin": anno["bbox"][1],
"xmax": anno["bbox"][2] + anno["bbox"][0],
"ymax": anno["bbox"][3] + anno["bbox"][1]
}
obj_info = {
"name": cls,
"bndbox": bndbox
}
if filename in data:
obj_idx = str(int(data[filename]["objects"]["num_obj"]))
data[filename]["objects"][str(obj_idx)] = obj_info
data[filename]["objects"]["num_obj"] = int(obj_idx) + 1
elif filename not in data:
obj = {
"num_obj": "1",
"0": obj_info
}
data[filename] = {
"size": size,
"objects": obj
}
percent = (float(progress_cnt) / float(progress_length)) * 100
print(str(progress_cnt) + "/" + str(progress_length) + " total: " + str(round(percent, 2)))
progress_cnt += 1
#print(json.dumps(data, indent=4, sort_keys = True))
return True, data
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
msg = "ERROR : {}, moreInfo : {}\t{}\t{}".format(e, exc_type, fname, exc_tb.tb_lineno)
return False, msg
def main(_argv):
coco = COCO()
data = coco.parse(FLAGS.input)
with open(FLAGS.output, 'wb') as handle:
pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL)
if __name__ == '__main__':
try:
app.run(main)
except SystemExit:
pass