coco_utils.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import sys
  19. import numpy as np
  20. import itertools
  21. from ppdet.metrics.json_results import get_det_res, get_det_poly_res, get_seg_res, get_solov2_segm_res, get_keypoint_res
  22. from ppdet.metrics.map_utils import draw_pr_curve
  23. from ppdet.utils.logger import setup_logger
  24. logger = setup_logger(__name__)
  25. def get_infer_results(outs, catid, bias=0):
  26. """
  27. Get result at the stage of inference.
  28. The output format is dictionary containing bbox or mask result.
  29. For example, bbox result is a list and each element contains
  30. image_id, category_id, bbox and score.
  31. """
  32. if outs is None or len(outs) == 0:
  33. raise ValueError(
  34. 'The number of valid detection result if zero. Please use reasonable model and check input data.'
  35. )
  36. im_id = outs['im_id']
  37. infer_res = {}
  38. if 'bbox' in outs:
  39. if len(outs['bbox']) > 0 and len(outs['bbox'][0]) > 6:
  40. infer_res['bbox'] = get_det_poly_res(
  41. outs['bbox'], outs['bbox_num'], im_id, catid, bias=bias)
  42. else:
  43. infer_res['bbox'] = get_det_res(
  44. outs['bbox'], outs['bbox_num'], im_id, catid, bias=bias)
  45. if 'mask' in outs:
  46. # mask post process
  47. infer_res['mask'] = get_seg_res(outs['mask'], outs['bbox'],
  48. outs['bbox_num'], im_id, catid)
  49. if 'segm' in outs:
  50. infer_res['segm'] = get_solov2_segm_res(outs, im_id, catid)
  51. if 'keypoint' in outs:
  52. infer_res['keypoint'] = get_keypoint_res(outs, im_id)
  53. outs['bbox_num'] = [len(infer_res['keypoint'])]
  54. return infer_res
  55. def cocoapi_eval(jsonfile,
  56. style,
  57. coco_gt=None,
  58. anno_file=None,
  59. max_dets=(100, 300, 1000),
  60. classwise=False,
  61. sigmas=None,
  62. use_area=True):
  63. """
  64. Args:
  65. jsonfile (str): Evaluation json file, eg: bbox.json, mask.json.
  66. style (str): COCOeval style, can be `bbox` , `segm` , `proposal`, `keypoints` and `keypoints_crowd`.
  67. coco_gt (str): Whether to load COCOAPI through anno_file,
  68. eg: coco_gt = COCO(anno_file)
  69. anno_file (str): COCO annotations file.
  70. max_dets (tuple): COCO evaluation maxDets.
  71. classwise (bool): Whether per-category AP and draw P-R Curve or not.
  72. sigmas (nparray): keypoint labelling sigmas.
  73. use_area (bool): If gt annotations (eg. CrowdPose, AIC)
  74. do not have 'area', please set use_area=False.
  75. """
  76. assert coco_gt != None or anno_file != None
  77. if style == 'keypoints_crowd':
  78. #please install xtcocotools==1.6
  79. from xtcocotools.coco import COCO
  80. from xtcocotools.cocoeval import COCOeval
  81. else:
  82. from pycocotools.coco import COCO
  83. from pycocotools.cocoeval import COCOeval
  84. if coco_gt == None:
  85. coco_gt = COCO(anno_file)
  86. logger.info("Start evaluate...")
  87. coco_dt = coco_gt.loadRes(jsonfile)
  88. if style == 'proposal':
  89. coco_eval = COCOeval(coco_gt, coco_dt, 'bbox')
  90. coco_eval.params.useCats = 0
  91. coco_eval.params.maxDets = list(max_dets)
  92. elif style == 'keypoints_crowd':
  93. coco_eval = COCOeval(coco_gt, coco_dt, style, sigmas, use_area)
  94. else:
  95. coco_eval = COCOeval(coco_gt, coco_dt, style)
  96. coco_eval.evaluate()
  97. coco_eval.accumulate()
  98. coco_eval.summarize()
  99. if classwise:
  100. # Compute per-category AP and PR curve
  101. try:
  102. from terminaltables import AsciiTable
  103. except Exception as e:
  104. logger.error(
  105. 'terminaltables not found, plaese install terminaltables. '
  106. 'for example: `pip install terminaltables`.')
  107. raise e
  108. precisions = coco_eval.eval['precision']
  109. cat_ids = coco_gt.getCatIds()
  110. # precision: (iou, recall, cls, area range, max dets)
  111. assert len(cat_ids) == precisions.shape[2]
  112. results_per_category = []
  113. for idx, catId in enumerate(cat_ids):
  114. # area range index 0: all area ranges
  115. # max dets index -1: typically 100 per image
  116. nm = coco_gt.loadCats(catId)[0]
  117. precision = precisions[:, :, idx, 0, -1]
  118. precision = precision[precision > -1]
  119. if precision.size:
  120. ap = np.mean(precision)
  121. else:
  122. ap = float('nan')
  123. results_per_category.append(
  124. (str(nm["name"]), '{:0.3f}'.format(float(ap))))
  125. pr_array = precisions[0, :, idx, 0, 2]
  126. recall_array = np.arange(0.0, 1.01, 0.01)
  127. draw_pr_curve(
  128. pr_array,
  129. recall_array,
  130. out_dir=style + '_pr_curve',
  131. file_name='{}_precision_recall_curve.jpg'.format(nm["name"]))
  132. num_columns = min(6, len(results_per_category) * 2)
  133. results_flatten = list(itertools.chain(*results_per_category))
  134. headers = ['category', 'AP'] * (num_columns // 2)
  135. results_2d = itertools.zip_longest(
  136. *[results_flatten[i::num_columns] for i in range(num_columns)])
  137. table_data = [headers]
  138. table_data += [result for result in results_2d]
  139. table = AsciiTable(table_data)
  140. logger.info('Per-category of {} AP: \n{}'.format(style, table.table))
  141. logger.info("per-category PR curve has output to {} folder.".format(
  142. style + '_pr_curve'))
  143. # flush coco evaluation result
  144. sys.stdout.flush()
  145. return coco_eval.stats
  146. def json_eval_results(metric, json_directory, dataset):
  147. """
  148. cocoapi eval with already exists proposal.json, bbox.json or mask.json
  149. """
  150. assert metric == 'COCO'
  151. anno_file = dataset.get_anno()
  152. json_file_list = ['proposal.json', 'bbox.json', 'mask.json']
  153. if json_directory:
  154. assert os.path.exists(
  155. json_directory), "The json directory:{} does not exist".format(
  156. json_directory)
  157. for k, v in enumerate(json_file_list):
  158. json_file_list[k] = os.path.join(str(json_directory), v)
  159. coco_eval_style = ['proposal', 'bbox', 'segm']
  160. for i, v_json in enumerate(json_file_list):
  161. if os.path.exists(v_json):
  162. cocoapi_eval(v_json, coco_eval_style[i], anno_file=anno_file)
  163. else:
  164. logger.info("{} not exists!".format(v_json))