detection_eval.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. # coding: utf8
  2. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import absolute_import
  16. import numpy as np
  17. import json
  18. import os
  19. import sys
  20. import cv2
  21. import copy
  22. import paddlex.utils.logging as logging
  23. # fix linspace problem for pycocotools while numpy > 1.17.2
  24. backup_linspace = np.linspace
  25. def fixed_linspace(start,
  26. stop,
  27. num=50,
  28. endpoint=True,
  29. retstep=False,
  30. dtype=None,
  31. axis=0):
  32. num = int(num)
  33. return backup_linspace(start, stop, num, endpoint, retstep, dtype, axis)
  34. def eval_results(results,
  35. metric,
  36. coco_gt,
  37. with_background=True,
  38. resolution=None,
  39. is_bbox_normalized=False,
  40. map_type='11point'):
  41. """Evaluation for evaluation program results"""
  42. box_ap_stats = []
  43. coco_gt_data = copy.deepcopy(coco_gt)
  44. eval_details = {'gt': copy.deepcopy(coco_gt.dataset)}
  45. if metric == 'COCO':
  46. np.linspace = fixed_linspace
  47. if 'proposal' in results[0]:
  48. proposal_eval(results, coco_gt_data)
  49. if 'bbox' in results[0]:
  50. box_ap_stats, xywh_results = coco_bbox_eval(
  51. results,
  52. coco_gt_data,
  53. with_background,
  54. is_bbox_normalized=is_bbox_normalized)
  55. if 'mask' in results[0]:
  56. mask_ap_stats, segm_results = mask_eval(results, coco_gt_data,
  57. resolution)
  58. ap_stats = [box_ap_stats, mask_ap_stats]
  59. eval_details['bbox'] = xywh_results
  60. eval_details['mask'] = segm_results
  61. return ap_stats, eval_details
  62. np.linspace = backup_linspace
  63. else:
  64. if 'accum_map' in results[-1]:
  65. res = np.mean(results[-1]['accum_map'][0])
  66. logging.debug('mAP: {:.2f}'.format(res * 100.))
  67. box_ap_stats.append(res * 100.)
  68. elif 'bbox' in results[0]:
  69. box_ap, xywh_results = voc_bbox_eval(
  70. results,
  71. coco_gt_data,
  72. with_background,
  73. is_bbox_normalized=is_bbox_normalized,
  74. map_type=map_type)
  75. box_ap_stats.append(box_ap)
  76. eval_details['bbox'] = xywh_results
  77. return box_ap_stats, eval_details
  78. def proposal_eval(results, coco_gt, outputfile, max_dets=(100, 300, 1000)):
  79. assert 'proposal' in results[0]
  80. assert outfile.endswith('.json')
  81. xywh_results = proposal2out(results)
  82. assert len(
  83. xywh_results) > 0, "The number of valid proposal detected is zero.\n \
  84. Please use reasonable model and check input data."
  85. with open(outfile, 'w') as f:
  86. json.dump(xywh_results, f)
  87. cocoapi_eval(xywh_results, 'proposal', coco_gt=coco_gt, max_dets=max_dets)
  88. # flush coco evaluation result
  89. sys.stdout.flush()
  90. def coco_bbox_eval(results,
  91. coco_gt,
  92. with_background=True,
  93. is_bbox_normalized=False):
  94. assert 'bbox' in results[0]
  95. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  96. # or matplotlib.backends is imported for the first time
  97. # pycocotools import matplotlib
  98. import matplotlib
  99. matplotlib.use('Agg')
  100. from pycocotools.coco import COCO
  101. cat_ids = coco_gt.getCatIds()
  102. # when with_background = True, mapping category to classid, like:
  103. # background:0, first_class:1, second_class:2, ...
  104. clsid2catid = dict(
  105. {i + int(with_background): catid
  106. for i, catid in enumerate(cat_ids)})
  107. xywh_results = bbox2out(
  108. results, clsid2catid, is_bbox_normalized=is_bbox_normalized)
  109. results = copy.deepcopy(xywh_results)
  110. if len(xywh_results) == 0:
  111. logging.warning(
  112. "The number of valid bbox detected is zero.\n Please use reasonable model and check input data.\n stop eval!"
  113. )
  114. return [0.0], results
  115. map_stats = cocoapi_eval(xywh_results, 'bbox', coco_gt=coco_gt)
  116. # flush coco evaluation result
  117. sys.stdout.flush()
  118. return map_stats, results
  119. def loadRes(coco_obj, anns):
  120. """
  121. Load result file and return a result api object.
  122. :param resFile (str) : file name of result file
  123. :return: res (obj) : result api object
  124. """
  125. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  126. # or matplotlib.backends is imported for the first time
  127. # pycocotools import matplotlib
  128. import matplotlib
  129. matplotlib.use('Agg')
  130. from pycocotools.coco import COCO
  131. import pycocotools.mask as maskUtils
  132. import time
  133. res = COCO()
  134. res.dataset['images'] = [img for img in coco_obj.dataset['images']]
  135. tic = time.time()
  136. assert type(anns) == list, 'results in not an array of objects'
  137. annsImgIds = [ann['image_id'] for ann in anns]
  138. assert set(annsImgIds) == (set(annsImgIds) & set(coco_obj.getImgIds())), \
  139. 'Results do not correspond to current coco set'
  140. if 'caption' in anns[0]:
  141. imgIds = set([img['id'] for img in res.dataset['images']]) & set(
  142. [ann['image_id'] for ann in anns])
  143. res.dataset['images'] = [
  144. img for img in res.dataset['images'] if img['id'] in imgIds
  145. ]
  146. for id, ann in enumerate(anns):
  147. ann['id'] = id + 1
  148. elif 'bbox' in anns[0] and not anns[0]['bbox'] == []:
  149. res.dataset['categories'] = copy.deepcopy(coco_obj.dataset[
  150. 'categories'])
  151. for id, ann in enumerate(anns):
  152. bb = ann['bbox']
  153. x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]]
  154. if not 'segmentation' in ann:
  155. ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
  156. ann['area'] = bb[2] * bb[3]
  157. ann['id'] = id + 1
  158. ann['iscrowd'] = 0
  159. elif 'segmentation' in anns[0]:
  160. res.dataset['categories'] = copy.deepcopy(coco_obj.dataset[
  161. 'categories'])
  162. for id, ann in enumerate(anns):
  163. # now only support compressed RLE format as segmentation results
  164. ann['area'] = maskUtils.area(ann['segmentation'])
  165. if not 'bbox' in ann:
  166. ann['bbox'] = maskUtils.toBbox(ann['segmentation'])
  167. ann['id'] = id + 1
  168. ann['iscrowd'] = 0
  169. elif 'keypoints' in anns[0]:
  170. res.dataset['categories'] = copy.deepcopy(coco_obj.dataset[
  171. 'categories'])
  172. for id, ann in enumerate(anns):
  173. s = ann['keypoints']
  174. x = s[0::3]
  175. y = s[1::3]
  176. x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y)
  177. ann['area'] = (x1 - x0) * (y1 - y0)
  178. ann['id'] = id + 1
  179. ann['bbox'] = [x0, y0, x1 - x0, y1 - y0]
  180. res.dataset['annotations'] = anns
  181. res.createIndex()
  182. return res
  183. def mask_eval(results, coco_gt, resolution, thresh_binarize=0.5):
  184. assert 'mask' in results[0]
  185. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  186. # or matplotlib.backends is imported for the first time
  187. # pycocotools import matplotlib
  188. import matplotlib
  189. matplotlib.use('Agg')
  190. from pycocotools.coco import COCO
  191. clsid2catid = {i + 1: v for i, v in enumerate(coco_gt.getCatIds())}
  192. segm_results = mask2out(results, clsid2catid, resolution, thresh_binarize)
  193. results = copy.deepcopy(segm_results)
  194. if len(segm_results) == 0:
  195. logging.warning(
  196. "The number of valid mask detected is zero.\n Please use reasonable model and check input data."
  197. )
  198. return None, results
  199. map_stats = cocoapi_eval(segm_results, 'segm', coco_gt=coco_gt)
  200. return map_stats, results
  201. def cocoapi_eval(anns,
  202. style,
  203. coco_gt=None,
  204. anno_file=None,
  205. max_dets=(100, 300, 1000)):
  206. """
  207. Args:
  208. anns: Evaluation result.
  209. style: COCOeval style, can be `bbox` , `segm` and `proposal`.
  210. coco_gt: Whether to load COCOAPI through anno_file,
  211. eg: coco_gt = COCO(anno_file)
  212. anno_file: COCO annotations file.
  213. max_dets: COCO evaluation maxDets.
  214. """
  215. assert coco_gt != None or anno_file != None
  216. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  217. # or matplotlib.backends is imported for the first time
  218. # pycocotools import matplotlib
  219. import matplotlib
  220. matplotlib.use('Agg')
  221. from pycocotools.coco import COCO
  222. from pycocotools.cocoeval import COCOeval
  223. if coco_gt == None:
  224. coco_gt = COCO(anno_file)
  225. logging.debug("Start evaluate...")
  226. coco_dt = loadRes(coco_gt, anns)
  227. if style == 'proposal':
  228. coco_eval = COCOeval(coco_gt, coco_dt, 'bbox')
  229. coco_eval.params.useCats = 0
  230. coco_eval.params.maxDets = list(max_dets)
  231. else:
  232. coco_eval = COCOeval(coco_gt, coco_dt, style)
  233. coco_eval.evaluate()
  234. coco_eval.accumulate()
  235. coco_eval.summarize()
  236. return coco_eval.stats
  237. def proposal2out(results, is_bbox_normalized=False):
  238. xywh_res = []
  239. for t in results:
  240. bboxes = t['proposal'][0]
  241. lengths = t['proposal'][1][0]
  242. im_ids = np.array(t['im_id'][0]).flatten()
  243. assert len(lengths) == im_ids.size
  244. if bboxes.shape == (1, 1) or bboxes is None:
  245. continue
  246. k = 0
  247. for i in range(len(lengths)):
  248. num = lengths[i]
  249. im_id = int(im_ids[i])
  250. for j in range(num):
  251. dt = bboxes[k]
  252. xmin, ymin, xmax, ymax = dt.tolist()
  253. if is_bbox_normalized:
  254. xmin, ymin, xmax, ymax = \
  255. clip_bbox([xmin, ymin, xmax, ymax])
  256. w = xmax - xmin
  257. h = ymax - ymin
  258. else:
  259. w = xmax - xmin + 1
  260. h = ymax - ymin + 1
  261. bbox = [xmin, ymin, w, h]
  262. coco_res = {
  263. 'image_id': im_id,
  264. 'category_id': 1,
  265. 'bbox': bbox,
  266. 'score': 1.0
  267. }
  268. xywh_res.append(coco_res)
  269. k += 1
  270. return xywh_res
  271. def bbox2out(results, clsid2catid, is_bbox_normalized=False):
  272. """
  273. Args:
  274. results: request a dict, should include: `bbox`, `im_id`,
  275. if is_bbox_normalized=True, also need `im_shape`.
  276. clsid2catid: class id to category id map of COCO2017 dataset.
  277. is_bbox_normalized: whether or not bbox is normalized.
  278. """
  279. xywh_res = []
  280. for t in results:
  281. bboxes = t['bbox'][0]
  282. lengths = t['bbox'][1][0]
  283. im_ids = np.array(t['im_id'][0]).flatten()
  284. if bboxes.shape == (1, 1) or bboxes is None:
  285. continue
  286. k = 0
  287. for i in range(len(lengths)):
  288. num = lengths[i]
  289. im_id = int(im_ids[i])
  290. for j in range(num):
  291. dt = bboxes[k]
  292. clsid, score, xmin, ymin, xmax, ymax = dt.tolist()
  293. catid = (clsid2catid[int(clsid)])
  294. if is_bbox_normalized:
  295. xmin, ymin, xmax, ymax = \
  296. clip_bbox([xmin, ymin, xmax, ymax])
  297. w = xmax - xmin
  298. h = ymax - ymin
  299. im_shape = t['im_shape'][0][i].tolist()
  300. im_height, im_width = int(im_shape[0]), int(im_shape[1])
  301. xmin *= im_width
  302. ymin *= im_height
  303. w *= im_width
  304. h *= im_height
  305. else:
  306. w = xmax - xmin + 1
  307. h = ymax - ymin + 1
  308. bbox = [xmin, ymin, w, h]
  309. coco_res = {
  310. 'image_id': im_id,
  311. 'category_id': catid,
  312. 'bbox': bbox,
  313. 'score': score
  314. }
  315. xywh_res.append(coco_res)
  316. k += 1
  317. return xywh_res
  318. def mask2out(results, clsid2catid, resolution, thresh_binarize=0.5):
  319. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  320. # or matplotlib.backends is imported for the first time
  321. # pycocotools import matplotlib
  322. import matplotlib
  323. matplotlib.use('Agg')
  324. import pycocotools.mask as mask_util
  325. scale = (resolution + 2.0) / resolution
  326. segm_res = []
  327. # for each batch
  328. for t in results:
  329. bboxes = t['bbox'][0]
  330. lengths = t['bbox'][1][0]
  331. im_ids = np.array(t['im_id'][0])
  332. if bboxes.shape == (1, 1) or bboxes is None:
  333. continue
  334. if len(bboxes.tolist()) == 0:
  335. continue
  336. masks = t['mask'][0]
  337. s = 0
  338. # for each sample
  339. for i in range(len(lengths)):
  340. num = lengths[i]
  341. im_id = int(im_ids[i][0])
  342. im_shape = t['im_shape'][0][i]
  343. bbox = bboxes[s:s + num][:, 2:]
  344. clsid_scores = bboxes[s:s + num][:, 0:2]
  345. mask = masks[s:s + num]
  346. s += num
  347. im_h = int(im_shape[0])
  348. im_w = int(im_shape[1])
  349. expand_bbox = expand_boxes(bbox, scale)
  350. expand_bbox = expand_bbox.astype(np.int32)
  351. padded_mask = np.zeros(
  352. (resolution + 2, resolution + 2), dtype=np.float32)
  353. for j in range(num):
  354. xmin, ymin, xmax, ymax = expand_bbox[j].tolist()
  355. clsid, score = clsid_scores[j].tolist()
  356. clsid = int(clsid)
  357. padded_mask[1:-1, 1:-1] = mask[j, clsid, :, :]
  358. catid = clsid2catid[clsid]
  359. w = xmax - xmin + 1
  360. h = ymax - ymin + 1
  361. w = np.maximum(w, 1)
  362. h = np.maximum(h, 1)
  363. resized_mask = cv2.resize(padded_mask, (w, h))
  364. resized_mask = np.array(
  365. resized_mask > thresh_binarize, dtype=np.uint8)
  366. im_mask = np.zeros((im_h, im_w), dtype=np.uint8)
  367. x0 = min(max(xmin, 0), im_w)
  368. x1 = min(max(xmax + 1, 0), im_w)
  369. y0 = min(max(ymin, 0), im_h)
  370. y1 = min(max(ymax + 1, 0), im_h)
  371. im_mask[y0:y1, x0:x1] = resized_mask[(y0 - ymin):(y1 - ymin), (
  372. x0 - xmin):(x1 - xmin)]
  373. segm = mask_util.encode(
  374. np.array(
  375. im_mask[:, :, np.newaxis], order='F'))[0]
  376. catid = clsid2catid[clsid]
  377. segm['counts'] = segm['counts'].decode('utf8')
  378. coco_res = {
  379. 'image_id': im_id,
  380. 'category_id': catid,
  381. 'segmentation': segm,
  382. 'score': score
  383. }
  384. segm_res.append(coco_res)
  385. return segm_res
  386. def expand_boxes(boxes, scale):
  387. """
  388. Expand an array of boxes by a given scale.
  389. """
  390. w_half = (boxes[:, 2] - boxes[:, 0]) * .5
  391. h_half = (boxes[:, 3] - boxes[:, 1]) * .5
  392. x_c = (boxes[:, 2] + boxes[:, 0]) * .5
  393. y_c = (boxes[:, 3] + boxes[:, 1]) * .5
  394. w_half *= scale
  395. h_half *= scale
  396. boxes_exp = np.zeros(boxes.shape)
  397. boxes_exp[:, 0] = x_c - w_half
  398. boxes_exp[:, 2] = x_c + w_half
  399. boxes_exp[:, 1] = y_c - h_half
  400. boxes_exp[:, 3] = y_c + h_half
  401. return boxes_exp
  402. def voc_bbox_eval(results,
  403. coco_gt,
  404. with_background=False,
  405. overlap_thresh=0.5,
  406. map_type='11point',
  407. is_bbox_normalized=False,
  408. evaluate_difficult=False):
  409. """
  410. Bounding box evaluation for VOC dataset
  411. Args:
  412. results (list): prediction bounding box results.
  413. class_num (int): evaluation class number.
  414. overlap_thresh (float): the postive threshold of
  415. bbox overlap
  416. map_type (string): method for mAP calcualtion,
  417. can only be '11point' or 'integral'
  418. is_bbox_normalized (bool): whether bbox is normalized
  419. to range [0, 1].
  420. evaluate_difficult (bool): whether to evaluate
  421. difficult gt bbox.
  422. """
  423. assert 'bbox' in results[0]
  424. logging.debug("Start evaluate...")
  425. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  426. # or matplotlib.backends is imported for the first time
  427. # pycocotools import matplotlib
  428. import matplotlib
  429. matplotlib.use('Agg')
  430. from pycocotools.coco import COCO
  431. cat_ids = coco_gt.getCatIds()
  432. # when with_background = True, mapping category to classid, like:
  433. # background:0, first_class:1, second_class:2, ...
  434. clsid2catid = dict(
  435. {i + int(with_background): catid
  436. for i, catid in enumerate(cat_ids)})
  437. class_num = len(clsid2catid) + int(with_background)
  438. detection_map = DetectionMAP(
  439. class_num=class_num,
  440. overlap_thresh=overlap_thresh,
  441. map_type=map_type,
  442. is_bbox_normalized=is_bbox_normalized,
  443. evaluate_difficult=evaluate_difficult)
  444. xywh_res = []
  445. det_nums = 0
  446. gt_nums = 0
  447. for t in results:
  448. bboxes = t['bbox'][0]
  449. bbox_lengths = t['bbox'][1][0]
  450. im_ids = np.array(t['im_id'][0]).flatten()
  451. if bboxes.shape == (1, 1) or bboxes is None:
  452. continue
  453. gt_boxes = t['gt_box'][0]
  454. gt_labels = t['gt_label'][0]
  455. difficults = t['is_difficult'][0] if not evaluate_difficult \
  456. else None
  457. if len(t['gt_box'][1]) == 0:
  458. # gt_box, gt_label, difficult read as zero padded Tensor
  459. bbox_idx = 0
  460. for i in range(len(gt_boxes)):
  461. gt_box = gt_boxes[i]
  462. gt_label = gt_labels[i]
  463. difficult = None if difficults is None \
  464. else difficults[i]
  465. bbox_num = bbox_lengths[i]
  466. bbox = bboxes[bbox_idx:bbox_idx + bbox_num]
  467. gt_box, gt_label, difficult = prune_zero_padding(
  468. gt_box, gt_label, difficult)
  469. detection_map.update(bbox, gt_box, gt_label, difficult)
  470. bbox_idx += bbox_num
  471. det_nums += bbox_num
  472. gt_nums += gt_box.shape[0]
  473. im_id = int(im_ids[i])
  474. for b in bbox:
  475. clsid, score, xmin, ymin, xmax, ymax = b.tolist()
  476. w = xmax - xmin + 1
  477. h = ymax - ymin + 1
  478. bbox = [xmin, ymin, w, h]
  479. coco_res = {
  480. 'image_id': im_id,
  481. 'category_id': clsid2catid[clsid],
  482. 'bbox': bbox,
  483. 'score': score
  484. }
  485. xywh_res.append(coco_res)
  486. else:
  487. # gt_box, gt_label, difficult read as LoDTensor
  488. gt_box_lengths = t['gt_box'][1][0]
  489. bbox_idx = 0
  490. gt_box_idx = 0
  491. for i in range(len(bbox_lengths)):
  492. bbox_num = bbox_lengths[i]
  493. gt_box_num = gt_box_lengths[i]
  494. bbox = bboxes[bbox_idx:bbox_idx + bbox_num]
  495. gt_box = gt_boxes[gt_box_idx:gt_box_idx + gt_box_num]
  496. gt_label = gt_labels[gt_box_idx:gt_box_idx + gt_box_num]
  497. difficult = None if difficults is None else \
  498. difficults[gt_box_idx: gt_box_idx + gt_box_num]
  499. detection_map.update(bbox, gt_box, gt_label, difficult)
  500. bbox_idx += bbox_num
  501. gt_box_idx += gt_box_num
  502. im_id = int(im_ids[i])
  503. for b in bbox:
  504. clsid, score, xmin, ymin, xmax, ymax = b.tolist()
  505. w = xmax - xmin + 1
  506. h = ymax - ymin + 1
  507. bbox = [xmin, ymin, w, h]
  508. coco_res = {
  509. 'image_id': im_id,
  510. 'category_id': clsid2catid[clsid],
  511. 'bbox': bbox,
  512. 'score': score
  513. }
  514. xywh_res.append(coco_res)
  515. logging.debug("Accumulating evaluatation results...")
  516. detection_map.accumulate()
  517. map_stat = 100. * detection_map.get_map()
  518. logging.debug("mAP({:.2f}, {}) = {:.2f}".format(overlap_thresh, map_type,
  519. map_stat))
  520. return map_stat, xywh_res
  521. def prune_zero_padding(gt_box, gt_label, difficult=None):
  522. valid_cnt = 0
  523. for i in range(len(gt_box)):
  524. if gt_box[i, 0] == 0 and gt_box[i, 1] == 0 and \
  525. gt_box[i, 2] == 0 and gt_box[i, 3] == 0:
  526. break
  527. valid_cnt += 1
  528. return (gt_box[:valid_cnt], gt_label[:valid_cnt], difficult[:valid_cnt]
  529. if difficult is not None else None)
  530. def bbox_area(bbox, is_bbox_normalized):
  531. """
  532. Calculate area of a bounding box
  533. """
  534. norm = 1. - float(is_bbox_normalized)
  535. width = bbox[2] - bbox[0] + norm
  536. height = bbox[3] - bbox[1] + norm
  537. return width * height
  538. def jaccard_overlap(pred, gt, is_bbox_normalized=False):
  539. """
  540. Calculate jaccard overlap ratio between two bounding box
  541. """
  542. if pred[0] >= gt[2] or pred[2] <= gt[0] or \
  543. pred[1] >= gt[3] or pred[3] <= gt[1]:
  544. return 0.
  545. inter_xmin = max(pred[0], gt[0])
  546. inter_ymin = max(pred[1], gt[1])
  547. inter_xmax = min(pred[2], gt[2])
  548. inter_ymax = min(pred[3], gt[3])
  549. inter_size = bbox_area([inter_xmin, inter_ymin, inter_xmax, inter_ymax],
  550. is_bbox_normalized)
  551. pred_size = bbox_area(pred, is_bbox_normalized)
  552. gt_size = bbox_area(gt, is_bbox_normalized)
  553. overlap = float(inter_size) / (pred_size + gt_size - inter_size)
  554. return overlap
  555. class DetectionMAP(object):
  556. """
  557. Calculate detection mean average precision.
  558. Currently support two types: 11point and integral
  559. Args:
  560. class_num (int): the class number.
  561. overlap_thresh (float): The threshold of overlap
  562. ratio between prediction bounding box and
  563. ground truth bounding box for deciding
  564. true/false positive. Default 0.5.
  565. map_type (str): calculation method of mean average
  566. precision, currently support '11point' and
  567. 'integral'. Default '11point'.
  568. is_bbox_normalized (bool): whther bounding boxes
  569. is normalized to range[0, 1]. Default False.
  570. evaluate_difficult (bool): whether to evaluate
  571. difficult bounding boxes. Default False.
  572. """
  573. def __init__(self,
  574. class_num,
  575. overlap_thresh=0.5,
  576. map_type='11point',
  577. is_bbox_normalized=False,
  578. evaluate_difficult=False):
  579. self.class_num = class_num
  580. self.overlap_thresh = overlap_thresh
  581. assert map_type in ['11point', 'integral'], \
  582. "map_type currently only support '11point' "\
  583. "and 'integral'"
  584. self.map_type = map_type
  585. self.is_bbox_normalized = is_bbox_normalized
  586. self.evaluate_difficult = evaluate_difficult
  587. self.reset()
  588. def update(self, bbox, gt_box, gt_label, difficult=None):
  589. """
  590. Update metric statics from given prediction and ground
  591. truth infomations.
  592. """
  593. if difficult is None:
  594. difficult = np.zeros_like(gt_label)
  595. # record class gt count
  596. for gtl, diff in zip(gt_label, difficult):
  597. if self.evaluate_difficult or int(diff) == 0:
  598. self.class_gt_counts[int(np.array(gtl))] += 1
  599. # record class score positive
  600. visited = [False] * len(gt_label)
  601. for b in bbox:
  602. label, score, xmin, ymin, xmax, ymax = b.tolist()
  603. pred = [xmin, ymin, xmax, ymax]
  604. max_idx = -1
  605. max_overlap = -1.0
  606. for i, gl in enumerate(gt_label):
  607. if int(gl) == int(label):
  608. overlap = jaccard_overlap(pred, gt_box[i],
  609. self.is_bbox_normalized)
  610. if overlap > max_overlap:
  611. max_overlap = overlap
  612. max_idx = i
  613. if max_overlap > self.overlap_thresh:
  614. if self.evaluate_difficult or \
  615. int(np.array(difficult[max_idx])) == 0:
  616. if not visited[max_idx]:
  617. self.class_score_poss[int(label)].append([score, 1.0])
  618. visited[max_idx] = True
  619. else:
  620. self.class_score_poss[int(label)].append([score, 0.0])
  621. else:
  622. self.class_score_poss[int(label)].append([score, 0.0])
  623. def reset(self):
  624. """
  625. Reset metric statics
  626. """
  627. self.class_score_poss = [[] for _ in range(self.class_num)]
  628. self.class_gt_counts = [0] * self.class_num
  629. self.mAP = None
  630. self.APs = [None] * self.class_num
  631. def accumulate(self):
  632. """
  633. Accumulate metric results and calculate mAP
  634. """
  635. mAP = 0.
  636. valid_cnt = 0
  637. for id, (
  638. score_pos, count
  639. ) in enumerate(zip(self.class_score_poss, self.class_gt_counts)):
  640. if count == 0: continue
  641. if len(score_pos) == 0:
  642. valid_cnt += 1
  643. continue
  644. accum_tp_list, accum_fp_list = \
  645. self._get_tp_fp_accum(score_pos)
  646. precision = []
  647. recall = []
  648. for ac_tp, ac_fp in zip(accum_tp_list, accum_fp_list):
  649. precision.append(float(ac_tp) / (ac_tp + ac_fp))
  650. recall.append(float(ac_tp) / count)
  651. if self.map_type == '11point':
  652. max_precisions = [0.] * 11
  653. start_idx = len(precision) - 1
  654. for j in range(10, -1, -1):
  655. for i in range(start_idx, -1, -1):
  656. if recall[i] < float(j) / 10.:
  657. start_idx = i
  658. if j > 0:
  659. max_precisions[j - 1] = max_precisions[j]
  660. break
  661. else:
  662. if max_precisions[j] < precision[i]:
  663. max_precisions[j] = precision[i]
  664. mAP += sum(max_precisions) / 11.
  665. self.APs[id] = sum(max_precisions) / 11.
  666. valid_cnt += 1
  667. elif self.map_type == 'integral':
  668. import math
  669. ap = 0.
  670. prev_recall = 0.
  671. for i in range(len(precision)):
  672. recall_gap = math.fabs(recall[i] - prev_recall)
  673. if recall_gap > 1e-6:
  674. ap += precision[i] * recall_gap
  675. prev_recall = recall[i]
  676. mAP += ap
  677. self.APs[id] = sum(max_precisions) / 11.
  678. valid_cnt += 1
  679. else:
  680. raise Exception("Unspported mAP type {}".format(self.map_type))
  681. self.mAP = mAP / float(valid_cnt) if valid_cnt > 0 else mAP
  682. def get_map(self):
  683. """
  684. Get mAP result
  685. """
  686. if self.mAP is None:
  687. raise Exception("mAP is not calculated.")
  688. return self.mAP
  689. def _get_tp_fp_accum(self, score_pos_list):
  690. """
  691. Calculate accumulating true/false positive results from
  692. [score, pos] records
  693. """
  694. sorted_list = sorted(score_pos_list, key=lambda s: s[0], reverse=True)
  695. accum_tp = 0
  696. accum_fp = 0
  697. accum_tp_list = []
  698. accum_fp_list = []
  699. for (score, pos) in sorted_list:
  700. accum_tp += int(pos)
  701. accum_tp_list.append(accum_tp)
  702. accum_fp += 1 - int(pos)
  703. accum_fp_list.append(accum_fp)
  704. return accum_tp_list, accum_fp_list
  705. def makeplot(rs, ps, outDir, class_name, iou_type):
  706. """针对某个特定类别,绘制不同评估要求下的准确率和召回率。
  707. 绘制结果说明参考COCODataset官网给出分析工具说明https://cocodataset.org/#detection-eval。
  708. Refer to https://github.com/open-mmlab/mmdetection/blob/master/tools/coco_error_analysis.py
  709. Args:
  710. rs (np.array): 在不同置信度阈值下计算得到的召回率。
  711. ps (np.array): 在不同置信度阈值下计算得到的准确率。ps与rs相同位置下的数值为同一个置信度阈值
  712. 计算得到的准确率与召回率。
  713. outDir (str): 图表保存的路径。
  714. class_name (str): 类别名。
  715. iou_type (str): iou计算方式,若为检测框,则设置为'bbox',若为像素级分割结果,则设置为'segm'。
  716. """
  717. import matplotlib.pyplot as plt
  718. cs = np.vstack([
  719. np.ones((2, 3)), np.array([.31, .51, .74]), np.array([.75, .31, .30]),
  720. np.array([.36, .90, .38]), np.array([.50, .39, .64]),
  721. np.array([1, .6, 0])
  722. ])
  723. areaNames = ['allarea', 'small', 'medium', 'large']
  724. types = ['C75', 'C50', 'Loc', 'Sim', 'Oth', 'BG', 'FN']
  725. for i in range(len(areaNames)):
  726. area_ps = ps[..., i, 0]
  727. figure_tile = iou_type + '-' + class_name + '-' + areaNames[i]
  728. aps = [ps_.mean() for ps_ in area_ps]
  729. ps_curve = [
  730. ps_.mean(axis=1) if ps_.ndim > 1 else ps_ for ps_ in area_ps
  731. ]
  732. ps_curve.insert(0, np.zeros(ps_curve[0].shape))
  733. fig = plt.figure()
  734. ax = plt.subplot(111)
  735. for k in range(len(types)):
  736. ax.plot(rs, ps_curve[k + 1], color=[0, 0, 0], linewidth=0.5)
  737. ax.fill_between(
  738. rs,
  739. ps_curve[k],
  740. ps_curve[k + 1],
  741. color=cs[k],
  742. label=str('[{:.3f}'.format(aps[k]) + ']' + types[k]))
  743. plt.xlabel('recall')
  744. plt.ylabel('precision')
  745. plt.xlim(0, 1.)
  746. plt.ylim(0, 1.)
  747. plt.title(figure_tile)
  748. plt.legend()
  749. fig.savefig(outDir + '/{}.png'.format(figure_tile))
  750. plt.close(fig)
  751. def analyze_individual_category(k, cocoDt, cocoGt, catId, iou_type):
  752. """针对某个特定类别,分析忽略亚类混淆和类别混淆时的准确率。
  753. Refer to https://github.com/open-mmlab/mmdetection/blob/master/tools/coco_error_analysis.py
  754. Args:
  755. k (int): 待分析类别的序号。
  756. cocoDt (pycocotols.coco.COCO): 按COCO类存放的预测结果。
  757. cocoGt (pycocotols.coco.COCO): 按COCO类存放的真值。
  758. catId (int): 待分析类别在数据集中的类别id。
  759. iou_type (str): iou计算方式,若为检测框,则设置为'bbox',若为像素级分割结果,则设置为'segm'。
  760. Returns:
  761. int:
  762. dict: 有关键字'ps_supercategory'和'ps_allcategory'。关键字'ps_supercategory'的键值是忽略亚类间
  763. 混淆时的准确率,关键字'ps_allcategory'的键值是忽略类别间混淆时的准确率。
  764. """
  765. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  766. # or matplotlib.backends is imported for the first time
  767. # pycocotools import matplotlib
  768. import matplotlib
  769. matplotlib.use('Agg')
  770. from pycocotools.coco import COCO
  771. from pycocotools.cocoeval import COCOeval
  772. nm = cocoGt.loadCats(catId)[0]
  773. logging.info('--------------analyzing {}-{}---------------'.format(
  774. k + 1, nm['name']))
  775. ps_ = {}
  776. dt = copy.deepcopy(cocoDt)
  777. nm = cocoGt.loadCats(catId)[0]
  778. imgIds = cocoGt.getImgIds()
  779. dt_anns = dt.dataset['annotations']
  780. select_dt_anns = []
  781. for ann in dt_anns:
  782. if ann['category_id'] == catId:
  783. select_dt_anns.append(ann)
  784. dt.dataset['annotations'] = select_dt_anns
  785. dt.createIndex()
  786. # compute precision but ignore superclass confusion
  787. gt = copy.deepcopy(cocoGt)
  788. child_catIds = gt.getCatIds(supNms=[nm['supercategory']])
  789. for idx, ann in enumerate(gt.dataset['annotations']):
  790. if (ann['category_id'] in child_catIds and
  791. ann['category_id'] != catId):
  792. gt.dataset['annotations'][idx]['ignore'] = 1
  793. gt.dataset['annotations'][idx]['iscrowd'] = 1
  794. gt.dataset['annotations'][idx]['category_id'] = catId
  795. cocoEval = COCOeval(gt, copy.deepcopy(dt), iou_type)
  796. cocoEval.params.imgIds = imgIds
  797. cocoEval.params.maxDets = [100]
  798. cocoEval.params.iouThrs = [.1]
  799. cocoEval.params.useCats = 1
  800. cocoEval.evaluate()
  801. cocoEval.accumulate()
  802. ps_supercategory = cocoEval.eval['precision'][0, :, k, :, :]
  803. ps_['ps_supercategory'] = ps_supercategory
  804. # compute precision but ignore any class confusion
  805. gt = copy.deepcopy(cocoGt)
  806. for idx, ann in enumerate(gt.dataset['annotations']):
  807. if ann['category_id'] != catId:
  808. gt.dataset['annotations'][idx]['ignore'] = 1
  809. gt.dataset['annotations'][idx]['iscrowd'] = 1
  810. gt.dataset['annotations'][idx]['category_id'] = catId
  811. cocoEval = COCOeval(gt, copy.deepcopy(dt), iou_type)
  812. cocoEval.params.imgIds = imgIds
  813. cocoEval.params.maxDets = [100]
  814. cocoEval.params.iouThrs = [.1]
  815. cocoEval.params.useCats = 1
  816. cocoEval.evaluate()
  817. cocoEval.accumulate()
  818. ps_allcategory = cocoEval.eval['precision'][0, :, k, :, :]
  819. ps_['ps_allcategory'] = ps_allcategory
  820. return k, ps_
  821. def coco_error_analysis(eval_details_file=None,
  822. gt=None,
  823. pred_bbox=None,
  824. pred_mask=None,
  825. save_dir='./output'):
  826. """逐个分析模型预测错误的原因,并将分析结果以图表的形式展示。
  827. 分析结果说明参考COCODataset官网给出分析工具说明https://cocodataset.org/#detection-eval。
  828. Refer to https://github.com/open-mmlab/mmdetection/blob/master/tools/coco_error_analysis.py
  829. Args:
  830. eval_details_file (str): 模型评估结果的保存路径,包含真值信息和预测结果。
  831. gt (list): 数据集的真值信息。默认值为None。
  832. pred_bbox (list): 模型在数据集上的预测框。默认值为None。
  833. pred_mask (list): 模型在数据集上的预测mask。默认值为None。
  834. save_dir (str): 可视化结果保存路径。默认值为'./output'。
  835. Note:
  836. eval_details_file的优先级更高,只要eval_details_file不为None,
  837. 就会从eval_details_file提取真值信息和预测结果做分析。
  838. 当eval_details_file为None时,则用gt、pred_mask、pred_mask做分析。
  839. """
  840. import multiprocessing as mp
  841. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  842. # or matplotlib.backends is imported for the first time
  843. # pycocotools import matplotlib
  844. import matplotlib
  845. matplotlib.use('Agg')
  846. from pycocotools.coco import COCO
  847. from pycocotools.cocoeval import COCOeval
  848. if eval_details_file is not None:
  849. import json
  850. with open(eval_details_file, 'r') as f:
  851. eval_details = json.load(f)
  852. pred_bbox = eval_details['bbox']
  853. if 'mask' in eval_details:
  854. pred_mask = eval_details['mask']
  855. gt = eval_details['gt']
  856. if gt is None or pred_bbox is None:
  857. raise Exception(
  858. "gt/pred_bbox/pred_mask is None now, please set right eval_details_file or gt/pred_bbox/pred_mask."
  859. )
  860. if pred_bbox is not None and len(pred_bbox) == 0:
  861. raise Exception("There is no predicted bbox.")
  862. if pred_mask is not None and len(pred_mask) == 0:
  863. raise Exception("There is no predicted mask.")
  864. def _analyze_results(cocoGt, cocoDt, res_type, out_dir):
  865. directory = os.path.dirname(out_dir + '/')
  866. if not os.path.exists(directory):
  867. logging.info('-------------create {}-----------------'.format(
  868. out_dir))
  869. os.makedirs(directory)
  870. imgIds = cocoGt.getImgIds()
  871. res_out_dir = out_dir + '/' + res_type + '/'
  872. res_directory = os.path.dirname(res_out_dir)
  873. if not os.path.exists(res_directory):
  874. logging.info('-------------create {}-----------------'.format(
  875. res_out_dir))
  876. os.makedirs(res_directory)
  877. iou_type = res_type
  878. cocoEval = COCOeval(
  879. copy.deepcopy(cocoGt), copy.deepcopy(cocoDt), iou_type)
  880. cocoEval.params.imgIds = imgIds
  881. cocoEval.params.iouThrs = [.75, .5, .1]
  882. cocoEval.params.maxDets = [100]
  883. cocoEval.evaluate()
  884. cocoEval.accumulate()
  885. ps = cocoEval.eval['precision']
  886. ps = np.vstack([ps, np.zeros((4, *ps.shape[1:]))])
  887. catIds = cocoGt.getCatIds()
  888. recThrs = cocoEval.params.recThrs
  889. thread_num = mp.cpu_count() if mp.cpu_count() < 8 else 8
  890. thread_pool = mp.pool.ThreadPool(thread_num)
  891. args = [(k, cocoDt, cocoGt, catId, iou_type)
  892. for k, catId in enumerate(catIds)]
  893. analyze_results = thread_pool.starmap(analyze_individual_category,
  894. args)
  895. for k, catId in enumerate(catIds):
  896. nm = cocoGt.loadCats(catId)[0]
  897. logging.info('--------------saving {}-{}---------------'.format(
  898. k + 1, nm['name']))
  899. analyze_result = analyze_results[k]
  900. assert k == analyze_result[0], ""
  901. ps_supercategory = analyze_result[1]['ps_supercategory']
  902. ps_allcategory = analyze_result[1]['ps_allcategory']
  903. # compute precision but ignore superclass confusion
  904. ps[3, :, k, :, :] = ps_supercategory
  905. # compute precision but ignore any class confusion
  906. ps[4, :, k, :, :] = ps_allcategory
  907. # fill in background and false negative errors and plot
  908. T, _, _, A, _ = ps.shape
  909. for t in range(T):
  910. for a in range(A):
  911. if np.sum(ps[t, :, k, a, :] ==
  912. -1) != len(ps[t, :, k, :, :]):
  913. ps[t, :, k, a, :][ps[t, :, k, a, :] == -1] = 0
  914. ps[5, :, k, :, :] = (ps[4, :, k, :, :] > 0)
  915. ps[6, :, k, :, :] = 1.0
  916. makeplot(recThrs, ps[:, :, k], res_out_dir, nm['name'], iou_type)
  917. makeplot(recThrs, ps, res_out_dir, 'allclass', iou_type)
  918. np.linspace = fixed_linspace
  919. coco_gt = COCO()
  920. coco_gt.dataset = gt
  921. coco_gt.createIndex()
  922. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  923. # or matplotlib.backends is imported for the first time
  924. # pycocotools import matplotlib
  925. import matplotlib
  926. matplotlib.use('Agg')
  927. from pycocotools.cocoeval import COCOeval
  928. if pred_bbox is not None:
  929. coco_dt = loadRes(coco_gt, pred_bbox)
  930. _analyze_results(coco_gt, coco_dt, res_type='bbox', out_dir=save_dir)
  931. if pred_mask is not None:
  932. coco_dt = loadRes(coco_gt, pred_mask)
  933. _analyze_results(coco_gt, coco_dt, res_type='segm', out_dir=save_dir)
  934. np.linspace = backup_linspace
  935. logging.info("The analysis figures are saved in {}".format(save_dir))