detection_eval.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. import numpy as np
  16. import json
  17. import os
  18. import sys
  19. import cv2
  20. import copy
  21. import paddlex.utils.logging as logging
  22. # fix linspace problem for pycocotools while numpy > 1.17.2
  23. backup_linspace = np.linspace
  24. def fixed_linspace(start,
  25. stop,
  26. num=50,
  27. endpoint=True,
  28. retstep=False,
  29. dtype=None,
  30. axis=0):
  31. num = int(num)
  32. return backup_linspace(start, stop, num, endpoint, retstep, dtype, axis)
  33. def eval_results(results,
  34. metric,
  35. coco_gt,
  36. with_background=True,
  37. resolution=None,
  38. is_bbox_normalized=False,
  39. map_type='11point'):
  40. """Evaluation for evaluation program results"""
  41. box_ap_stats = []
  42. coco_gt_data = copy.deepcopy(coco_gt)
  43. eval_details = {'gt': copy.deepcopy(coco_gt.dataset)}
  44. if metric == 'COCO':
  45. np.linspace = fixed_linspace
  46. if 'proposal' in results[0]:
  47. proposal_eval(results, coco_gt_data)
  48. if 'bbox' in results[0]:
  49. box_ap_stats, xywh_results = coco_bbox_eval(
  50. results,
  51. coco_gt_data,
  52. with_background,
  53. is_bbox_normalized=is_bbox_normalized)
  54. if 'mask' in results[0]:
  55. mask_ap_stats, segm_results = mask_eval(results, coco_gt_data,
  56. resolution)
  57. ap_stats = [box_ap_stats, mask_ap_stats]
  58. eval_details['bbox'] = xywh_results
  59. eval_details['mask'] = segm_results
  60. return ap_stats, eval_details
  61. np.linspace = backup_linspace
  62. else:
  63. if 'accum_map' in results[-1]:
  64. res = np.mean(results[-1]['accum_map'][0])
  65. logging.debug('mAP: {:.2f}'.format(res * 100.))
  66. box_ap_stats.append(res * 100.)
  67. elif 'bbox' in results[0]:
  68. box_ap, xywh_results = voc_bbox_eval(
  69. results,
  70. coco_gt_data,
  71. with_background,
  72. is_bbox_normalized=is_bbox_normalized,
  73. map_type=map_type)
  74. box_ap_stats.append(box_ap)
  75. eval_details['bbox'] = xywh_results
  76. return box_ap_stats, eval_details
  77. def proposal_eval(results, coco_gt, outputfile, max_dets=(100, 300, 1000)):
  78. assert 'proposal' in results[0]
  79. assert outfile.endswith('.json')
  80. xywh_results = proposal2out(results)
  81. assert len(
  82. xywh_results) > 0, "The number of valid proposal detected is zero.\n \
  83. Please use reasonable model and check input data."
  84. with open(outfile, 'w') as f:
  85. json.dump(xywh_results, f)
  86. cocoapi_eval(xywh_results, 'proposal', coco_gt=coco_gt, max_dets=max_dets)
  87. # flush coco evaluation result
  88. sys.stdout.flush()
  89. def coco_bbox_eval(results,
  90. coco_gt,
  91. with_background=True,
  92. is_bbox_normalized=False):
  93. assert 'bbox' in results[0]
  94. from pycocotools.coco import COCO
  95. cat_ids = coco_gt.getCatIds()
  96. # when with_background = True, mapping category to classid, like:
  97. # background:0, first_class:1, second_class:2, ...
  98. clsid2catid = dict(
  99. {i + int(with_background): catid
  100. for i, catid in enumerate(cat_ids)})
  101. xywh_results = bbox2out(
  102. results, clsid2catid, is_bbox_normalized=is_bbox_normalized)
  103. results = copy.deepcopy(xywh_results)
  104. if len(xywh_results) == 0:
  105. logging.warning(
  106. "The number of valid bbox detected is zero.\n Please use reasonable model and check input data.\n stop eval!"
  107. )
  108. return [0.0], results
  109. map_stats = cocoapi_eval(xywh_results, 'bbox', coco_gt=coco_gt)
  110. # flush coco evaluation result
  111. sys.stdout.flush()
  112. return map_stats, results
  113. def loadRes(coco_obj, anns):
  114. """
  115. Load result file and return a result api object.
  116. :param resFile (str) : file name of result file
  117. :return: res (obj) : result api object
  118. """
  119. from pycocotools.coco import COCO
  120. import pycocotools.mask as maskUtils
  121. import time
  122. res = COCO()
  123. res.dataset['images'] = [img for img in coco_obj.dataset['images']]
  124. tic = time.time()
  125. assert type(anns) == list, 'results in not an array of objects'
  126. annsImgIds = [ann['image_id'] for ann in anns]
  127. assert set(annsImgIds) == (set(annsImgIds) & set(coco_obj.getImgIds())), \
  128. 'Results do not correspond to current coco set'
  129. if 'caption' in anns[0]:
  130. imgIds = set([img['id'] for img in res.dataset['images']]) & set(
  131. [ann['image_id'] for ann in anns])
  132. res.dataset['images'] = [
  133. img for img in res.dataset['images'] if img['id'] in imgIds
  134. ]
  135. for id, ann in enumerate(anns):
  136. ann['id'] = id + 1
  137. elif 'bbox' in anns[0] and not anns[0]['bbox'] == []:
  138. res.dataset['categories'] = copy.deepcopy(
  139. coco_obj.dataset['categories'])
  140. for id, ann in enumerate(anns):
  141. bb = ann['bbox']
  142. x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]]
  143. if not 'segmentation' in ann:
  144. ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
  145. ann['area'] = bb[2] * bb[3]
  146. ann['id'] = id + 1
  147. ann['iscrowd'] = 0
  148. elif 'segmentation' in anns[0]:
  149. res.dataset['categories'] = copy.deepcopy(
  150. coco_obj.dataset['categories'])
  151. for id, ann in enumerate(anns):
  152. # now only support compressed RLE format as segmentation results
  153. ann['area'] = maskUtils.area(ann['segmentation'])
  154. if not 'bbox' in ann:
  155. ann['bbox'] = maskUtils.toBbox(ann['segmentation'])
  156. ann['id'] = id + 1
  157. ann['iscrowd'] = 0
  158. elif 'keypoints' in anns[0]:
  159. res.dataset['categories'] = copy.deepcopy(
  160. coco_obj.dataset['categories'])
  161. for id, ann in enumerate(anns):
  162. s = ann['keypoints']
  163. x = s[0::3]
  164. y = s[1::3]
  165. x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y)
  166. ann['area'] = (x1 - x0) * (y1 - y0)
  167. ann['id'] = id + 1
  168. ann['bbox'] = [x0, y0, x1 - x0, y1 - y0]
  169. res.dataset['annotations'] = anns
  170. res.createIndex()
  171. return res
  172. def mask_eval(results, coco_gt, resolution, thresh_binarize=0.5):
  173. assert 'mask' in results[0]
  174. from pycocotools.coco import COCO
  175. clsid2catid = {i + 1: v for i, v in enumerate(coco_gt.getCatIds())}
  176. segm_results = mask2out(results, clsid2catid, resolution, thresh_binarize)
  177. results = copy.deepcopy(segm_results)
  178. if len(segm_results) == 0:
  179. logging.warning(
  180. "The number of valid mask detected is zero.\n Please use reasonable model and check input data."
  181. )
  182. return None, results
  183. map_stats = cocoapi_eval(segm_results, 'segm', coco_gt=coco_gt)
  184. return map_stats, results
  185. def cocoapi_eval(anns,
  186. style,
  187. coco_gt=None,
  188. anno_file=None,
  189. max_dets=(100, 300, 1000)):
  190. """
  191. Args:
  192. anns: Evaluation result.
  193. style: COCOeval style, can be `bbox` , `segm` and `proposal`.
  194. coco_gt: Whether to load COCOAPI through anno_file,
  195. eg: coco_gt = COCO(anno_file)
  196. anno_file: COCO annotations file.
  197. max_dets: COCO evaluation maxDets.
  198. """
  199. assert coco_gt != None or anno_file != None
  200. from pycocotools.coco import COCO
  201. from pycocotools.cocoeval import COCOeval
  202. if coco_gt == None:
  203. coco_gt = COCO(anno_file)
  204. logging.debug("Start evaluate...")
  205. coco_dt = loadRes(coco_gt, anns)
  206. if style == 'proposal':
  207. coco_eval = COCOeval(coco_gt, coco_dt, 'bbox')
  208. coco_eval.params.useCats = 0
  209. coco_eval.params.maxDets = list(max_dets)
  210. else:
  211. coco_eval = COCOeval(coco_gt, coco_dt, style)
  212. coco_eval.evaluate()
  213. coco_eval.accumulate()
  214. coco_eval.summarize()
  215. return coco_eval.stats
  216. def proposal2out(results, is_bbox_normalized=False):
  217. xywh_res = []
  218. for t in results:
  219. bboxes = t['proposal'][0]
  220. lengths = t['proposal'][1][0]
  221. im_ids = np.array(t['im_id'][0]).flatten()
  222. assert len(lengths) == im_ids.size
  223. if bboxes.shape == (1, 1) or bboxes is None:
  224. continue
  225. k = 0
  226. for i in range(len(lengths)):
  227. num = lengths[i]
  228. im_id = int(im_ids[i])
  229. for j in range(num):
  230. dt = bboxes[k]
  231. xmin, ymin, xmax, ymax = dt.tolist()
  232. if is_bbox_normalized:
  233. xmin, ymin, xmax, ymax = \
  234. clip_bbox([xmin, ymin, xmax, ymax])
  235. w = xmax - xmin
  236. h = ymax - ymin
  237. else:
  238. w = xmax - xmin + 1
  239. h = ymax - ymin + 1
  240. bbox = [xmin, ymin, w, h]
  241. coco_res = {
  242. 'image_id': im_id,
  243. 'category_id': 1,
  244. 'bbox': bbox,
  245. 'score': 1.0
  246. }
  247. xywh_res.append(coco_res)
  248. k += 1
  249. return xywh_res
  250. def bbox2out(results, clsid2catid, is_bbox_normalized=False):
  251. """
  252. Args:
  253. results: request a dict, should include: `bbox`, `im_id`,
  254. if is_bbox_normalized=True, also need `im_shape`.
  255. clsid2catid: class id to category id map of COCO2017 dataset.
  256. is_bbox_normalized: whether or not bbox is normalized.
  257. """
  258. xywh_res = []
  259. for t in results:
  260. bboxes = t['bbox'][0]
  261. lengths = t['bbox'][1][0]
  262. im_ids = np.array(t['im_id'][0]).flatten()
  263. if bboxes.shape == (1, 1) or bboxes is None:
  264. continue
  265. k = 0
  266. for i in range(len(lengths)):
  267. num = lengths[i]
  268. im_id = int(im_ids[i])
  269. for j in range(num):
  270. dt = bboxes[k]
  271. clsid, score, xmin, ymin, xmax, ymax = dt.tolist()
  272. catid = (clsid2catid[int(clsid)])
  273. if is_bbox_normalized:
  274. xmin, ymin, xmax, ymax = \
  275. clip_bbox([xmin, ymin, xmax, ymax])
  276. w = xmax - xmin
  277. h = ymax - ymin
  278. im_shape = t['im_shape'][0][i].tolist()
  279. im_height, im_width = int(im_shape[0]), int(im_shape[1])
  280. xmin *= im_width
  281. ymin *= im_height
  282. w *= im_width
  283. h *= im_height
  284. else:
  285. w = xmax - xmin + 1
  286. h = ymax - ymin + 1
  287. bbox = [xmin, ymin, w, h]
  288. coco_res = {
  289. 'image_id': im_id,
  290. 'category_id': catid,
  291. 'bbox': bbox,
  292. 'score': score
  293. }
  294. xywh_res.append(coco_res)
  295. k += 1
  296. return xywh_res
  297. def mask2out(results, clsid2catid, resolution, thresh_binarize=0.5):
  298. import pycocotools.mask as mask_util
  299. scale = (resolution + 2.0) / resolution
  300. segm_res = []
  301. # for each batch
  302. for t in results:
  303. bboxes = t['bbox'][0]
  304. lengths = t['bbox'][1][0]
  305. im_ids = np.array(t['im_id'][0])
  306. if bboxes.shape == (1, 1) or bboxes is None:
  307. continue
  308. if len(bboxes.tolist()) == 0:
  309. continue
  310. masks = t['mask'][0]
  311. s = 0
  312. # for each sample
  313. for i in range(len(lengths)):
  314. num = lengths[i]
  315. im_id = int(im_ids[i][0])
  316. im_shape = t['im_shape'][0][i]
  317. bbox = bboxes[s:s + num][:, 2:]
  318. clsid_scores = bboxes[s:s + num][:, 0:2]
  319. mask = masks[s:s + num]
  320. s += num
  321. im_h = int(im_shape[0])
  322. im_w = int(im_shape[1])
  323. expand_bbox = expand_boxes(bbox, scale)
  324. expand_bbox = expand_bbox.astype(np.int32)
  325. padded_mask = np.zeros((resolution + 2, resolution + 2),
  326. dtype=np.float32)
  327. for j in range(num):
  328. xmin, ymin, xmax, ymax = expand_bbox[j].tolist()
  329. clsid, score = clsid_scores[j].tolist()
  330. clsid = int(clsid)
  331. padded_mask[1:-1, 1:-1] = mask[j, clsid, :, :]
  332. catid = clsid2catid[clsid]
  333. w = xmax - xmin + 1
  334. h = ymax - ymin + 1
  335. w = np.maximum(w, 1)
  336. h = np.maximum(h, 1)
  337. resized_mask = cv2.resize(padded_mask, (w, h))
  338. resized_mask = np.array(
  339. resized_mask > thresh_binarize, dtype=np.uint8)
  340. im_mask = np.zeros((im_h, im_w), dtype=np.uint8)
  341. x0 = min(max(xmin, 0), im_w)
  342. x1 = min(max(xmax + 1, 0), im_w)
  343. y0 = min(max(ymin, 0), im_h)
  344. y1 = min(max(ymax + 1, 0), im_h)
  345. im_mask[y0:y1, x0:x1] = resized_mask[(y0 - ymin):(y1 - ymin), (
  346. x0 - xmin):(x1 - xmin)]
  347. segm = mask_util.encode(
  348. np.array(im_mask[:, :, np.newaxis], order='F'))[0]
  349. catid = clsid2catid[clsid]
  350. segm['counts'] = segm['counts'].decode('utf8')
  351. coco_res = {
  352. 'image_id': im_id,
  353. 'category_id': catid,
  354. 'segmentation': segm,
  355. 'score': score
  356. }
  357. segm_res.append(coco_res)
  358. return segm_res
  359. def expand_boxes(boxes, scale):
  360. """
  361. Expand an array of boxes by a given scale.
  362. """
  363. w_half = (boxes[:, 2] - boxes[:, 0]) * .5
  364. h_half = (boxes[:, 3] - boxes[:, 1]) * .5
  365. x_c = (boxes[:, 2] + boxes[:, 0]) * .5
  366. y_c = (boxes[:, 3] + boxes[:, 1]) * .5
  367. w_half *= scale
  368. h_half *= scale
  369. boxes_exp = np.zeros(boxes.shape)
  370. boxes_exp[:, 0] = x_c - w_half
  371. boxes_exp[:, 2] = x_c + w_half
  372. boxes_exp[:, 1] = y_c - h_half
  373. boxes_exp[:, 3] = y_c + h_half
  374. return boxes_exp
  375. def voc_bbox_eval(results,
  376. coco_gt,
  377. with_background=False,
  378. overlap_thresh=0.5,
  379. map_type='11point',
  380. is_bbox_normalized=False,
  381. evaluate_difficult=False):
  382. """
  383. Bounding box evaluation for VOC dataset
  384. Args:
  385. results (list): prediction bounding box results.
  386. class_num (int): evaluation class number.
  387. overlap_thresh (float): the postive threshold of
  388. bbox overlap
  389. map_type (string): method for mAP calcualtion,
  390. can only be '11point' or 'integral'
  391. is_bbox_normalized (bool): whether bbox is normalized
  392. to range [0, 1].
  393. evaluate_difficult (bool): whether to evaluate
  394. difficult gt bbox.
  395. """
  396. assert 'bbox' in results[0]
  397. logging.debug("Start evaluate...")
  398. from pycocotools.coco import COCO
  399. cat_ids = coco_gt.getCatIds()
  400. # when with_background = True, mapping category to classid, like:
  401. # background:0, first_class:1, second_class:2, ...
  402. clsid2catid = dict(
  403. {i + int(with_background): catid
  404. for i, catid in enumerate(cat_ids)})
  405. class_num = len(clsid2catid) + int(with_background)
  406. detection_map = DetectionMAP(
  407. class_num=class_num,
  408. overlap_thresh=overlap_thresh,
  409. map_type=map_type,
  410. is_bbox_normalized=is_bbox_normalized,
  411. evaluate_difficult=evaluate_difficult)
  412. xywh_res = []
  413. det_nums = 0
  414. gt_nums = 0
  415. for t in results:
  416. bboxes = t['bbox'][0]
  417. bbox_lengths = t['bbox'][1][0]
  418. im_ids = np.array(t['im_id'][0]).flatten()
  419. if bboxes.shape == (1, 1) or bboxes is None:
  420. continue
  421. gt_boxes = t['gt_box'][0]
  422. gt_labels = t['gt_label'][0]
  423. difficults = t['is_difficult'][0] if not evaluate_difficult \
  424. else None
  425. if len(t['gt_box'][1]) == 0:
  426. # gt_box, gt_label, difficult read as zero padded Tensor
  427. bbox_idx = 0
  428. for i in range(len(gt_boxes)):
  429. gt_box = gt_boxes[i]
  430. gt_label = gt_labels[i]
  431. difficult = None if difficults is None \
  432. else difficults[i]
  433. bbox_num = bbox_lengths[i]
  434. bbox = bboxes[bbox_idx:bbox_idx + bbox_num]
  435. gt_box, gt_label, difficult = prune_zero_padding(
  436. gt_box, gt_label, difficult)
  437. detection_map.update(bbox, gt_box, gt_label, difficult)
  438. bbox_idx += bbox_num
  439. det_nums += bbox_num
  440. gt_nums += gt_box.shape[0]
  441. im_id = int(im_ids[i])
  442. for b in bbox:
  443. clsid, score, xmin, ymin, xmax, ymax = b.tolist()
  444. w = xmax - xmin + 1
  445. h = ymax - ymin + 1
  446. bbox = [xmin, ymin, w, h]
  447. coco_res = {
  448. 'image_id': im_id,
  449. 'category_id': clsid2catid[clsid],
  450. 'bbox': bbox,
  451. 'score': score
  452. }
  453. xywh_res.append(coco_res)
  454. else:
  455. # gt_box, gt_label, difficult read as LoDTensor
  456. gt_box_lengths = t['gt_box'][1][0]
  457. bbox_idx = 0
  458. gt_box_idx = 0
  459. for i in range(len(bbox_lengths)):
  460. bbox_num = bbox_lengths[i]
  461. gt_box_num = gt_box_lengths[i]
  462. bbox = bboxes[bbox_idx:bbox_idx + bbox_num]
  463. gt_box = gt_boxes[gt_box_idx:gt_box_idx + gt_box_num]
  464. gt_label = gt_labels[gt_box_idx:gt_box_idx + gt_box_num]
  465. difficult = None if difficults is None else \
  466. difficults[gt_box_idx: gt_box_idx + gt_box_num]
  467. detection_map.update(bbox, gt_box, gt_label, difficult)
  468. bbox_idx += bbox_num
  469. gt_box_idx += gt_box_num
  470. im_id = int(im_ids[i])
  471. for b in bbox:
  472. clsid, score, xmin, ymin, xmax, ymax = b.tolist()
  473. w = xmax - xmin + 1
  474. h = ymax - ymin + 1
  475. bbox = [xmin, ymin, w, h]
  476. coco_res = {
  477. 'image_id': im_id,
  478. 'category_id': clsid2catid[clsid],
  479. 'bbox': bbox,
  480. 'score': score
  481. }
  482. xywh_res.append(coco_res)
  483. logging.debug("Accumulating evaluatation results...")
  484. detection_map.accumulate()
  485. map_stat = 100. * detection_map.get_map()
  486. logging.debug("mAP({:.2f}, {}) = {:.2f}".format(overlap_thresh, map_type,
  487. map_stat))
  488. return map_stat, xywh_res
  489. def prune_zero_padding(gt_box, gt_label, difficult=None):
  490. valid_cnt = 0
  491. for i in range(len(gt_box)):
  492. if gt_box[i, 0] == 0 and gt_box[i, 1] == 0 and \
  493. gt_box[i, 2] == 0 and gt_box[i, 3] == 0:
  494. break
  495. valid_cnt += 1
  496. return (gt_box[:valid_cnt], gt_label[:valid_cnt],
  497. difficult[:valid_cnt] if difficult is not None else None)
  498. def bbox_area(bbox, is_bbox_normalized):
  499. """
  500. Calculate area of a bounding box
  501. """
  502. norm = 1. - float(is_bbox_normalized)
  503. width = bbox[2] - bbox[0] + norm
  504. height = bbox[3] - bbox[1] + norm
  505. return width * height
  506. def jaccard_overlap(pred, gt, is_bbox_normalized=False):
  507. """
  508. Calculate jaccard overlap ratio between two bounding box
  509. """
  510. if pred[0] >= gt[2] or pred[2] <= gt[0] or \
  511. pred[1] >= gt[3] or pred[3] <= gt[1]:
  512. return 0.
  513. inter_xmin = max(pred[0], gt[0])
  514. inter_ymin = max(pred[1], gt[1])
  515. inter_xmax = min(pred[2], gt[2])
  516. inter_ymax = min(pred[3], gt[3])
  517. inter_size = bbox_area([inter_xmin, inter_ymin, inter_xmax, inter_ymax],
  518. is_bbox_normalized)
  519. pred_size = bbox_area(pred, is_bbox_normalized)
  520. gt_size = bbox_area(gt, is_bbox_normalized)
  521. overlap = float(inter_size) / (pred_size + gt_size - inter_size)
  522. return overlap
  523. class DetectionMAP(object):
  524. """
  525. Calculate detection mean average precision.
  526. Currently support two types: 11point and integral
  527. Args:
  528. class_num (int): the class number.
  529. overlap_thresh (float): The threshold of overlap
  530. ratio between prediction bounding box and
  531. ground truth bounding box for deciding
  532. true/false positive. Default 0.5.
  533. map_type (str): calculation method of mean average
  534. precision, currently support '11point' and
  535. 'integral'. Default '11point'.
  536. is_bbox_normalized (bool): whther bounding boxes
  537. is normalized to range[0, 1]. Default False.
  538. evaluate_difficult (bool): whether to evaluate
  539. difficult bounding boxes. Default False.
  540. """
  541. def __init__(self,
  542. class_num,
  543. overlap_thresh=0.5,
  544. map_type='11point',
  545. is_bbox_normalized=False,
  546. evaluate_difficult=False):
  547. self.class_num = class_num
  548. self.overlap_thresh = overlap_thresh
  549. assert map_type in ['11point', 'integral'], \
  550. "map_type currently only support '11point' "\
  551. "and 'integral'"
  552. self.map_type = map_type
  553. self.is_bbox_normalized = is_bbox_normalized
  554. self.evaluate_difficult = evaluate_difficult
  555. self.reset()
  556. def update(self, bbox, gt_box, gt_label, difficult=None):
  557. """
  558. Update metric statics from given prediction and ground
  559. truth infomations.
  560. """
  561. if difficult is None:
  562. difficult = np.zeros_like(gt_label)
  563. # record class gt count
  564. for gtl, diff in zip(gt_label, difficult):
  565. if self.evaluate_difficult or int(diff) == 0:
  566. self.class_gt_counts[int(np.array(gtl))] += 1
  567. # record class score positive
  568. visited = [False] * len(gt_label)
  569. for b in bbox:
  570. label, score, xmin, ymin, xmax, ymax = b.tolist()
  571. pred = [xmin, ymin, xmax, ymax]
  572. max_idx = -1
  573. max_overlap = -1.0
  574. for i, gl in enumerate(gt_label):
  575. if int(gl) == int(label):
  576. overlap = jaccard_overlap(pred, gt_box[i],
  577. self.is_bbox_normalized)
  578. if overlap > max_overlap:
  579. max_overlap = overlap
  580. max_idx = i
  581. if max_overlap > self.overlap_thresh:
  582. if self.evaluate_difficult or \
  583. int(np.array(difficult[max_idx])) == 0:
  584. if not visited[max_idx]:
  585. self.class_score_poss[int(label)].append([score, 1.0])
  586. visited[max_idx] = True
  587. else:
  588. self.class_score_poss[int(label)].append([score, 0.0])
  589. else:
  590. self.class_score_poss[int(label)].append([score, 0.0])
  591. def reset(self):
  592. """
  593. Reset metric statics
  594. """
  595. self.class_score_poss = [[] for _ in range(self.class_num)]
  596. self.class_gt_counts = [0] * self.class_num
  597. self.mAP = None
  598. self.APs = [None] * self.class_num
  599. def accumulate(self):
  600. """
  601. Accumulate metric results and calculate mAP
  602. """
  603. mAP = 0.
  604. valid_cnt = 0
  605. for id, (score_pos, count) in enumerate(
  606. zip(self.class_score_poss, self.class_gt_counts)):
  607. if count == 0: continue
  608. if len(score_pos) == 0:
  609. valid_cnt += 1
  610. continue
  611. accum_tp_list, accum_fp_list = \
  612. self._get_tp_fp_accum(score_pos)
  613. precision = []
  614. recall = []
  615. for ac_tp, ac_fp in zip(accum_tp_list, accum_fp_list):
  616. precision.append(float(ac_tp) / (ac_tp + ac_fp))
  617. recall.append(float(ac_tp) / count)
  618. if self.map_type == '11point':
  619. max_precisions = [0.] * 11
  620. start_idx = len(precision) - 1
  621. for j in range(10, -1, -1):
  622. for i in range(start_idx, -1, -1):
  623. if recall[i] < float(j) / 10.:
  624. start_idx = i
  625. if j > 0:
  626. max_precisions[j - 1] = max_precisions[j]
  627. break
  628. else:
  629. if max_precisions[j] < precision[i]:
  630. max_precisions[j] = precision[i]
  631. mAP += sum(max_precisions) / 11.
  632. self.APs[id] = sum(max_precisions) / 11.
  633. valid_cnt += 1
  634. elif self.map_type == 'integral':
  635. import math
  636. ap = 0.
  637. prev_recall = 0.
  638. for i in range(len(precision)):
  639. recall_gap = math.fabs(recall[i] - prev_recall)
  640. if recall_gap > 1e-6:
  641. ap += precision[i] * recall_gap
  642. prev_recall = recall[i]
  643. mAP += ap
  644. self.APs[id] = sum(max_precisions) / 11.
  645. valid_cnt += 1
  646. else:
  647. raise Exception("Unspported mAP type {}".format(self.map_type))
  648. self.mAP = mAP / float(valid_cnt) if valid_cnt > 0 else mAP
  649. def get_map(self):
  650. """
  651. Get mAP result
  652. """
  653. if self.mAP is None:
  654. raise Exception("mAP is not calculated.")
  655. return self.mAP
  656. def _get_tp_fp_accum(self, score_pos_list):
  657. """
  658. Calculate accumulating true/false positive results from
  659. [score, pos] records
  660. """
  661. sorted_list = sorted(score_pos_list, key=lambda s: s[0], reverse=True)
  662. accum_tp = 0
  663. accum_fp = 0
  664. accum_tp_list = []
  665. accum_fp_list = []
  666. for (score, pos) in sorted_list:
  667. accum_tp += int(pos)
  668. accum_tp_list.append(accum_tp)
  669. accum_fp += 1 - int(pos)
  670. accum_fp_list.append(accum_fp)
  671. return accum_tp_list, accum_fp_list