metrics.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # Copyright (c) 2021 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 copy
  18. import sys
  19. from collections import OrderedDict
  20. import paddle
  21. import numpy as np
  22. from ppdet.metrics.map_utils import prune_zero_padding, DetectionMAP
  23. from .coco_utils import get_infer_results, cocoapi_eval
  24. import paddlex.utils.logging as logging
  25. __all__ = ['Metric', 'VOCMetric', 'COCOMetric']
  26. class Metric(paddle.metric.Metric):
  27. def name(self):
  28. return self.__class__.__name__
  29. def reset(self):
  30. pass
  31. def accumulate(self):
  32. pass
  33. # paddle.metric.Metric defined :metch:`update`, :meth:`accumulate`
  34. # :metch:`reset`, in ppdet, we also need following 2 methods:
  35. # abstract method for logging metric results
  36. def log(self):
  37. pass
  38. # abstract method for getting metric results
  39. def get_results(self):
  40. pass
  41. class VOCMetric(Metric):
  42. def __init__(self,
  43. labels,
  44. coco_gt,
  45. overlap_thresh=0.5,
  46. map_type='11point',
  47. is_bbox_normalized=False,
  48. evaluate_difficult=False,
  49. classwise=False):
  50. self.cid2cname = {i: name for i, name in enumerate(labels)}
  51. self.coco_gt = coco_gt
  52. self.clsid2catid = {
  53. i: cat['id']
  54. for i, cat in enumerate(
  55. self.coco_gt.loadCats(self.coco_gt.getCatIds()))
  56. }
  57. self.overlap_thresh = overlap_thresh
  58. self.map_type = map_type
  59. self.evaluate_difficult = evaluate_difficult
  60. self.detection_map = DetectionMAP(
  61. class_num=len(labels),
  62. overlap_thresh=overlap_thresh,
  63. map_type=map_type,
  64. is_bbox_normalized=is_bbox_normalized,
  65. evaluate_difficult=evaluate_difficult,
  66. catid2name=self.cid2cname,
  67. classwise=classwise)
  68. self.reset()
  69. def reset(self):
  70. self.details = {'gt': copy.deepcopy(self.coco_gt.dataset), 'bbox': []}
  71. self.detection_map.reset()
  72. def update(self, inputs, outputs):
  73. bbox_np = outputs['bbox'].numpy()
  74. bboxes = bbox_np[:, 2:]
  75. scores = bbox_np[:, 1]
  76. labels = bbox_np[:, 0]
  77. bbox_lengths = outputs['bbox_num'].numpy()
  78. if bboxes.shape == (1, 1) or bboxes is None:
  79. return
  80. gt_boxes = inputs['gt_bbox']
  81. gt_labels = inputs['gt_class']
  82. difficults = inputs['difficult'] if not self.evaluate_difficult \
  83. else None
  84. scale_factor = inputs['scale_factor'].numpy(
  85. ) if 'scale_factor' in inputs else np.ones(
  86. (gt_boxes.shape[0], 2)).astype('float32')
  87. bbox_idx = 0
  88. for i in range(len(gt_boxes)):
  89. gt_box = gt_boxes[i].numpy()
  90. h, w = scale_factor[i]
  91. gt_box = gt_box / np.array([w, h, w, h])
  92. gt_label = gt_labels[i].numpy()
  93. difficult = None if difficults is None \
  94. else difficults[i].numpy()
  95. bbox_num = bbox_lengths[i]
  96. bbox = bboxes[bbox_idx:bbox_idx + bbox_num]
  97. score = scores[bbox_idx:bbox_idx + bbox_num]
  98. label = labels[bbox_idx:bbox_idx + bbox_num]
  99. gt_box, gt_label, difficult = prune_zero_padding(gt_box, gt_label,
  100. difficult)
  101. self.detection_map.update(bbox, score, label, gt_box, gt_label,
  102. difficult)
  103. bbox_idx += bbox_num
  104. for l, s, b in zip(label, score, bbox):
  105. xmin, ymin, xmax, ymax = b.tolist()
  106. w = xmax - xmin
  107. h = ymax - ymin
  108. bbox = [xmin, ymin, w, h]
  109. coco_res = {
  110. 'image_id': int(inputs['im_id']),
  111. 'category_id': self.clsid2catid[int(l)],
  112. 'bbox': bbox,
  113. 'score': float(s)
  114. }
  115. self.details['bbox'].append(coco_res)
  116. def accumulate(self):
  117. logging.info("Accumulating evaluatation results...")
  118. self.detection_map.accumulate()
  119. def log(self):
  120. map_stat = 100. * self.detection_map.get_map()
  121. logging.info("bbox_map = {:.2f}%".format(map_stat))
  122. def get_results(self):
  123. return {'bbox': [self.detection_map.get_map()]}
  124. def get(self):
  125. map_stat = 100. * self.detection_map.get_map()
  126. stats = {"bbox_map": map_stat}
  127. return stats
  128. class COCOMetric(Metric):
  129. def __init__(self, coco_gt, **kwargs):
  130. self.clsid2catid = {
  131. i: cat['id']
  132. for i, cat in enumerate(coco_gt.loadCats(coco_gt.getCatIds()))
  133. }
  134. self.coco_gt = coco_gt
  135. self.classwise = kwargs.get('classwise', False)
  136. self.bias = 0
  137. self.reset()
  138. def reset(self):
  139. # only bbox and mask evaluation support currently
  140. self.details = {
  141. 'gt': copy.deepcopy(self.coco_gt.dataset),
  142. 'bbox': [],
  143. 'mask': []
  144. }
  145. self.eval_stats = {}
  146. def update(self, inputs, outputs):
  147. outs = {}
  148. # outputs Tensor -> numpy.ndarray
  149. for k, v in outputs.items():
  150. outs[k] = v.numpy() if isinstance(v, paddle.Tensor) else v
  151. im_id = inputs['im_id']
  152. outs['im_id'] = im_id.numpy() if isinstance(im_id,
  153. paddle.Tensor) else im_id
  154. infer_results = get_infer_results(
  155. outs, self.clsid2catid, bias=self.bias)
  156. self.details['bbox'] += infer_results[
  157. 'bbox'] if 'bbox' in infer_results else []
  158. self.details['mask'] += infer_results[
  159. 'mask'] if 'mask' in infer_results else []
  160. def accumulate(self):
  161. if len(self.details['bbox']) > 0:
  162. bbox_stats = cocoapi_eval(
  163. copy.deepcopy(self.details['bbox']),
  164. 'bbox',
  165. coco_gt=self.coco_gt,
  166. classwise=self.classwise)
  167. self.eval_stats['bbox'] = bbox_stats
  168. sys.stdout.flush()
  169. if len(self.details['mask']) > 0:
  170. seg_stats = cocoapi_eval(
  171. copy.deepcopy(self.details['mask']),
  172. 'segm',
  173. coco_gt=self.coco_gt,
  174. classwise=self.classwise)
  175. self.eval_stats['mask'] = seg_stats
  176. sys.stdout.flush()
  177. def log(self):
  178. pass
  179. def get(self):
  180. if 'mask' in self.eval_stats:
  181. return OrderedDict(
  182. zip(['bbox_mmap', 'segm_mmap'],
  183. [self.eval_stats['bbox'][0], self.eval_stats['mask'][0]]))
  184. else:
  185. return {'bbox_mmap': self.eval_stats['bbox'][0]}