-
Notifications
You must be signed in to change notification settings - Fork 2
/
hico_eval_de_ko.py
338 lines (289 loc) · 11.7 KB
/
hico_eval_de_ko.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import argparse
import os
import numpy as np
import sys
sys.path.insert(0, "/home/xian/Documents/code/GGNet/src/lib")
from utils.bbox import compute_iou
import json
import utils.io as io
def match_hoi(pred_det, gt_dets):
is_match = False
remaining_gt_dets = [gt_det for gt_det in gt_dets]
for i, gt_det in enumerate(gt_dets):
human_iou = compute_iou(pred_det['human_box'], gt_det['human_box'])
if human_iou > 0.5:
object_iou = compute_iou(pred_det['object_box'], gt_det['object_box'])
if object_iou > 0.5:
is_match = True
del remaining_gt_dets[i]
break
return is_match, remaining_gt_dets
def compute_ap(precision, recall):
if np.any(np.isnan(recall)):
return np.nan
ap = 0
for t in np.arange(0, 1.1, 0.1): # 0, 0.1, 0.2, ..., 1.0
selected_p = precision[recall >= t]
if selected_p.size == 0:
p = 0
else:
p = np.max(selected_p)
ap += p / 11.
return ap
def compute_pr(y_true, y_score, npos):
sorted_y_true = [y for y, _ in
sorted(zip(y_true, y_score), key=lambda x: x[1], reverse=True)]
tp = np.array(sorted_y_true)
if len(tp) == 0:
return 0, 0, False
fp = ~tp
tp = np.cumsum(tp)
fp = np.cumsum(fp)
if npos == 0:
recall = np.nan * tp
else:
recall = tp / npos
precision = tp / (tp + fp)
return precision, recall, True
def load_gt_dets():
# Load anno_list
print('Loading anno_list.json ...')
anno_list_json = '/home/xian/Documents/code/GGNet/Dataset/hico_det/annotations/anno_list.json'
anno_list = json.load(open(anno_list_json, "r"))
gt_dets = {}
for anno in anno_list:
if "test" not in anno['global_id']:
continue
global_id = anno['global_id']
gt_dets[global_id] = {}
for hoi in anno['hois']:
hoi_id = hoi['id']
gt_dets[global_id][hoi_id] = []
for human_box_num, object_box_num in hoi['connections']:
human_box = hoi['human_bboxes'][human_box_num]
object_box = hoi['object_bboxes'][object_box_num]
det = {
'human_box': human_box,
'object_box': object_box,
}
gt_dets[global_id][hoi_id].append(det)
return gt_dets
class hico_eval():
def __init__(self, model_path, model_id):
self.out_dir = os.path.join(model_path, 'predictions_model_' + str(model_id))
if not os.path.exists(self.out_dir):
os.makedirs(self.out_dir)
self.annotations = load_gt_dets()
print(len(self.annotations))
self.hoi_list = json.load(open('//home/xian/Documents/code/GGNet/Dataset/hico_det/annotations/hoi_list_new.json', 'r'))
self.file_name_to_obj_cat = json.load(
open('/home/xian/Documents/code/GGNet/Dataset/hico_det/annotations/file_name_to_obj_cat.json', "r"))
self.global_ids = self.annotations.keys()
print(len(self.global_ids))
self.hoi_id_to_num = json.load(open('/home/xian/Documents/code/GGNet/Dataset/hico_det/annotations/hoi_id_to_num.json', "r"))
self.rare_id_json = [key for key, item in self.hoi_id_to_num.items() if item['rare']]
print(len(self.rare_id_json))
self.pred_anno = {}
def evaluation_default(self, predict_annot):
if self.pred_anno == {}:
pred_anno = {}
for pre_anno in predict_annot:
global_id = pre_anno['file_name'].split('.')[0]
pred_anno[global_id] = {}
bbox = pre_anno['predictions']
hois = pre_anno['hoi_prediction']
for hoi in hois:
obj_id = bbox[hoi['object_id']]['category_id']
obj_bbox = bbox[hoi['object_id']]['bbox']
sub_bbox = bbox[hoi['subject_id']]['bbox']
score = hoi['score']
verb_id = hoi['category_id']
hoi_id = '0'
for item in self.hoi_list:
if item['object_cat'] == obj_id and item['verb_id'] == verb_id:
hoi_id = item['id']
assert int(hoi_id) > 0
data = np.array([sub_bbox[0], sub_bbox[1], sub_bbox[2], sub_bbox[3],
obj_bbox[0], obj_bbox[1], obj_bbox[2], obj_bbox[3],
score]).reshape(1, 9)
if hoi_id not in pred_anno[global_id]:
pred_anno[global_id][hoi_id] = np.empty([0, 9])
pred_anno[global_id][hoi_id] = np.concatenate((pred_anno[global_id][hoi_id], data), axis=0)
self.pred_anno = pred_anno
outputs = []
for hoi in self.hoi_list:
o = self.eval_hoi(hoi['id'], self.global_ids, self.annotations, self.pred_anno, self.out_dir)
outputs.append(o)
mAP = {
'AP': {},
'mAP': 0,
'invalid': 0,
'mAP_rare': 0,
'mAP_non_rare': 0,
}
map_ = 0
map_rare = 0
map_non_rare = 0
count = 0
count_rare = 0
count_non_rare = 0
for ap, hoi_id in outputs:
mAP['AP'][hoi_id] = ap
if not np.isnan(ap):
count += 1
map_ += ap
if hoi_id in self.rare_id_json:
count_rare += 1
map_rare += ap
else:
count_non_rare += 1
map_non_rare += ap
mAP['mAP'] = map_ / count
print(mAP['mAP'])
mAP['invalid'] = len(outputs) - count
mAP['mAP_rare'] = map_rare / count_rare
mAP['mAP_non_rare'] = map_non_rare / count_non_rare
mAP_json = os.path.join(
self.out_dir,
'mAP_default.json')
io.dump_json_object(mAP, mAP_json)
print(f'APs have been saved to {self.out_dir}')
def evaluation_ko(self, predict_annot):
if self.pred_anno == {}:
pred_anno = {}
for pre_anno in predict_annot:
global_id = pre_anno['file_name'].split('.')[0]
pred_anno[global_id] = {}
bbox = pre_anno['predictions']
hois = pre_anno['hoi_prediction']
for hoi in hois:
obj_id = bbox[hoi['object_id']]['category_id']
obj_bbox = bbox[hoi['object_id']]['bbox']
sub_bbox = bbox[hoi['subject_id']]['bbox']
score = hoi['score']
verb_id = hoi['category_id']
hoi_id = '0'
for item in self.hoi_list:
if item['object_cat'] == obj_id and item['verb_id'] == verb_id:
hoi_id = item['id']
assert int(hoi_id) > 0
data = np.array([sub_bbox[0], sub_bbox[1], sub_bbox[2], sub_bbox[3],
obj_bbox[0], obj_bbox[1], obj_bbox[2], obj_bbox[3],
score]).reshape(1, 9)
if hoi_id not in pred_anno[global_id]:
pred_anno[global_id][hoi_id] = np.empty([0, 9])
pred_anno[global_id][hoi_id] = np.concatenate((pred_anno[global_id][hoi_id], data), axis=0)
self.pred_anno = pred_anno
outputs = []
for hoi in self.hoi_list:
o = self.eval_hoi(hoi['id'], self.global_ids, self.annotations,
self.pred_anno, mode="ko",
obj_cate=hoi['object_cat'])
outputs.append(o)
mAP = {
'AP': {},
'mAP': 0,
'invalid': 0,
'mAP_rare': 0,
'mAP_non_rare': 0,
}
map_ = 0
map_rare = 0
map_non_rare = 0
count = 0
count_rare = 0
count_non_rare = 0
for ap, hoi_id in outputs:
mAP['AP'][hoi_id] = ap
if not np.isnan(ap):
count += 1
map_ += ap
if hoi_id in self.rare_id_json:
count_rare += 1
map_rare += ap
else:
count_non_rare += 1
map_non_rare += ap
mAP['mAP'] = map_ / count
mAP['invalid'] = len(outputs) - count
print(count_rare, count_non_rare)
mAP['mAP_rare'] = map_rare / count_rare
mAP['mAP_non_rare'] = map_non_rare / count_non_rare
mAP_json = os.path.join(
self.out_dir,
'mAP_ko.json')
io.dump_json_object(mAP, mAP_json)
print(f'APs have been saved to {self.out_dir}')
def eval_hoi(self, hoi_id, global_ids, gt_dets, pred_anno,
mode='default', obj_cate=None):
print(f'Evaluating hoi_id: {hoi_id} ...')
y_true = []
y_score = []
det_id = []
npos = 0
for global_id in global_ids:
if mode == 'ko':
if global_id + ".jpg" not in self.file_name_to_obj_cat:
continue
obj_cats = self.file_name_to_obj_cat[global_id + ".jpg"]
if int(obj_cate) not in obj_cats:
continue
if hoi_id in gt_dets[global_id]:
candidate_gt_dets = gt_dets[global_id][hoi_id]
else:
candidate_gt_dets = []
npos += len(candidate_gt_dets)
if global_id not in pred_anno or hoi_id not in pred_anno[global_id]:
hoi_dets = np.empty([0, 9])
else:
hoi_dets = pred_anno[global_id][hoi_id]
num_dets = hoi_dets.shape[0]
sorted_idx = [idx for idx, _ in sorted(
zip(range(num_dets), hoi_dets[:, 8].tolist()),
key=lambda x: x[1],
reverse=True)]
for i in sorted_idx:
pred_det = {
'human_box': hoi_dets[i, :4],
'object_box': hoi_dets[i, 4:8],
'score': hoi_dets[i, 8]
}
print(hoi_dets[i, 8])
is_match, candidate_gt_dets = match_hoi(pred_det, candidate_gt_dets)
y_true.append(is_match)
y_score.append(pred_det['score'])
det_id.append((global_id, i))
# Compute PR
precision, recall, mark = compute_pr(y_true, y_score, npos)
if not mark:
ap = 0
else:
ap = compute_ap(precision, recall)
# Compute AP
print(f'AP:{ap}')
return (ap, hoi_id)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--exp',
default="hoidet_hico_ggnet",
type=str)
parser.add_argument(
'--start_epoch',
default=100,
type=int)
parser.add_argument(
'--end_epoch',
default=120,
type=int)
args = parser.parse_args()
dir = args.exp
begin = args.start_epoch
end = args.end_epoch
for i in range(begin, end+1):
model_num = i
model_dir = f"/home/xian/Documents/code/GGNet/exp/hoidet/{dir}/"
hoi_eval = hico_eval(f"{model_dir}/", f"{model_num}")
file = json.load(open(f"{model_dir}/predictions_model_{model_num}.json", "r"))
hoi_eval.evaluation_default(file)
hoi_eval.evaluation_ko(file)