coco_90metric.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import datetime
  3. import itertools
  4. import os.path as osp
  5. import tempfile
  6. from collections import OrderedDict
  7. from typing import Dict, List, Optional, Sequence, Union
  8. import numpy as np
  9. from mmengine.evaluator import BaseMetric
  10. from mmengine.fileio import dump, get_local_path, load
  11. from mmengine.logging import MMLogger
  12. from terminaltables import AsciiTable
  13. from mmdet.evaluation.functional import eval_recalls
  14. from mmdet.registry import METRICS
  15. from mmdet.structures.mask import encode_mask_results
  16. from .api_wrappers import COCO, COCOeval
  17. @METRICS.register_module()
  18. class Coco90Metric(BaseMetric):
  19. """COCO evaluation metric.
  20. Evaluate AR, AP, and mAP for detection tasks including proposal/box
  21. detection and instance segmentation. Please refer to
  22. https://cocodataset.org/#detection-eval for more details.
  23. Args:
  24. ann_file (str, optional): Path to the coco format annotation file.
  25. If not specified, ground truth annotations from the dataset will
  26. be converted to coco format. Defaults to None.
  27. metric (str | List[str]): Metrics to be evaluated. Valid metrics
  28. include 'bbox', 'segm', 'proposal', and 'proposal_fast'.
  29. Defaults to 'bbox'.
  30. classwise (bool): Whether to evaluate the metric class-wise.
  31. Defaults to False.
  32. proposal_nums (Sequence[int]): Numbers of proposals to be evaluated.
  33. Defaults to (100, 300, 1000).
  34. iou_thrs (float | List[float], optional): IoU threshold to compute AP
  35. and AR. If not specified, IoUs from 0.5 to 0.95 will be used.
  36. Defaults to None.
  37. metric_items (List[str], optional): Metric result names to be
  38. recorded in the evaluation result. Defaults to None.
  39. format_only (bool): Format the output results without perform
  40. evaluation. It is useful when you want to format the result
  41. to a specific format and submit it to the test server.
  42. Defaults to False.
  43. outfile_prefix (str, optional): The prefix of json files. It includes
  44. the file path and the prefix of filename, e.g., "a/b/prefix".
  45. If not specified, a temp file will be created. Defaults to None.
  46. backend_args (dict, optional): Arguments to instantiate the
  47. corresponding backend. Defaults to None.
  48. collect_device (str): Device name used for collecting results from
  49. different ranks during distributed training. Must be 'cpu' or
  50. 'gpu'. Defaults to 'cpu'.
  51. prefix (str, optional): The prefix that will be added in the metric
  52. names to disambiguate homonymous metrics of different evaluators.
  53. If prefix is not provided in the argument, self.default_prefix
  54. will be used instead. Defaults to None.
  55. """
  56. default_prefix: Optional[str] = 'coco'
  57. def __init__(self,
  58. ann_file: Optional[str] = None,
  59. metric: Union[str, List[str]] = 'bbox',
  60. classwise: bool = False,
  61. proposal_nums: Sequence[int] = (100, 300, 1000),
  62. iou_thrs: Optional[Union[float, Sequence[float]]] = None,
  63. metric_items: Optional[Sequence[str]] = None,
  64. format_only: bool = False,
  65. outfile_prefix: Optional[str] = None,
  66. backend_args: dict = None,
  67. collect_device: str = 'cpu',
  68. prefix: Optional[str] = None) -> None:
  69. super().__init__(collect_device=collect_device, prefix=prefix)
  70. # coco evaluation metrics
  71. self.metrics = metric if isinstance(metric, list) else [metric]
  72. allowed_metrics = ['bbox', 'segm', 'proposal', 'proposal_fast']
  73. for metric in self.metrics:
  74. if metric not in allowed_metrics:
  75. raise KeyError(
  76. "metric should be one of 'bbox', 'segm', 'proposal', "
  77. f"'proposal_fast', but got {metric}.")
  78. # do class wise evaluation, default False
  79. self.classwise = classwise
  80. # proposal_nums used to compute recall or precision.
  81. self.proposal_nums = list(proposal_nums)
  82. # iou_thrs used to compute recall or precision.
  83. if iou_thrs is None:
  84. iou_thrs = np.linspace(
  85. .5, 0.95, int(np.round((0.95 - .5) / .05)) + 1, endpoint=True)
  86. self.iou_thrs = iou_thrs
  87. self.metric_items = metric_items
  88. self.format_only = format_only
  89. if self.format_only:
  90. assert outfile_prefix is not None, 'outfile_prefix must be not'
  91. 'None when format_only is True, otherwise the result files will'
  92. 'be saved to a temp directory which will be cleaned up at the end.'
  93. self.outfile_prefix = outfile_prefix
  94. self.backend_args = backend_args
  95. # if ann_file is not specified,
  96. # initialize coco api with the converted dataset
  97. if ann_file is not None:
  98. with get_local_path(
  99. ann_file, backend_args=self.backend_args) as local_path:
  100. self._coco_api = COCO(local_path)
  101. else:
  102. self._coco_api = None
  103. # handle dataset lazy init
  104. self.cat_ids = None
  105. self.img_ids = None
  106. def fast_eval_recall(self,
  107. results: List[dict],
  108. proposal_nums: Sequence[int],
  109. iou_thrs: Sequence[float],
  110. logger: Optional[MMLogger] = None) -> np.ndarray:
  111. """Evaluate proposal recall with COCO's fast_eval_recall.
  112. Args:
  113. results (List[dict]): Results of the dataset.
  114. proposal_nums (Sequence[int]): Proposal numbers used for
  115. evaluation.
  116. iou_thrs (Sequence[float]): IoU thresholds used for evaluation.
  117. logger (MMLogger, optional): Logger used for logging the recall
  118. summary.
  119. Returns:
  120. np.ndarray: Averaged recall results.
  121. """
  122. gt_bboxes = []
  123. pred_bboxes = [result['bboxes'] for result in results]
  124. for i in range(len(self.img_ids)):
  125. ann_ids = self._coco_api.get_ann_ids(img_ids=self.img_ids[i])
  126. ann_info = self._coco_api.load_anns(ann_ids)
  127. if len(ann_info) == 0:
  128. gt_bboxes.append(np.zeros((0, 4)))
  129. continue
  130. bboxes = []
  131. for ann in ann_info:
  132. if ann.get('ignore', False) or ann['iscrowd']:
  133. continue
  134. x1, y1, w, h = ann['bbox']
  135. bboxes.append([x1, y1, x1 + w, y1 + h])
  136. bboxes = np.array(bboxes, dtype=np.float32)
  137. if bboxes.shape[0] == 0:
  138. bboxes = np.zeros((0, 4))
  139. gt_bboxes.append(bboxes)
  140. recalls = eval_recalls(
  141. gt_bboxes, pred_bboxes, proposal_nums, iou_thrs, logger=logger)
  142. ar = recalls.mean(axis=1)
  143. return ar
  144. def xyxy2xywh(self, bbox: np.ndarray) -> list:
  145. """Convert ``xyxy`` style bounding boxes to ``xywh`` style for COCO
  146. evaluation.
  147. Args:
  148. bbox (numpy.ndarray): The bounding boxes, shape (4, ), in
  149. ``xyxy`` order.
  150. Returns:
  151. list[float]: The converted bounding boxes, in ``xywh`` order.
  152. """
  153. _bbox: List = bbox.tolist()
  154. return [
  155. _bbox[0],
  156. _bbox[1],
  157. _bbox[2] - _bbox[0],
  158. _bbox[3] - _bbox[1],
  159. ]
  160. def results2json(self, results: Sequence[dict],
  161. outfile_prefix: str) -> dict:
  162. """Dump the detection results to a COCO style json file.
  163. There are 3 types of results: proposals, bbox predictions, mask
  164. predictions, and they have different data types. This method will
  165. automatically recognize the type, and dump them to json files.
  166. Args:
  167. results (Sequence[dict]): Testing results of the
  168. dataset.
  169. outfile_prefix (str): The filename prefix of the json files. If the
  170. prefix is "somepath/xxx", the json files will be named
  171. "somepath/xxx.bbox.json", "somepath/xxx.segm.json",
  172. "somepath/xxx.proposal.json".
  173. Returns:
  174. dict: Possible keys are "bbox", "segm", "proposal", and
  175. values are corresponding filenames.
  176. """
  177. bbox_json_results = []
  178. segm_json_results = [] if 'masks' in results[0] else None
  179. for idx, result in enumerate(results):
  180. image_id = result.get('img_id', idx)
  181. labels = result['labels']
  182. bboxes = result['bboxes']
  183. scores = result['scores']
  184. # bbox results
  185. for i, label in enumerate(labels):
  186. data = dict()
  187. data['image_id'] = image_id
  188. data['bbox'] = self.xyxy2xywh(bboxes[i])
  189. data['score'] = float(scores[i])
  190. data['category_id'] = self.cat_ids[label]
  191. bbox_json_results.append(data)
  192. if segm_json_results is None:
  193. continue
  194. # segm results
  195. masks = result['masks']
  196. mask_scores = result.get('mask_scores', scores)
  197. for i, label in enumerate(labels):
  198. data = dict()
  199. data['image_id'] = image_id
  200. data['bbox'] = self.xyxy2xywh(bboxes[i])
  201. data['score'] = float(mask_scores[i])
  202. data['category_id'] = self.cat_ids[label]
  203. if isinstance(masks[i]['counts'], bytes):
  204. masks[i]['counts'] = masks[i]['counts'].decode()
  205. data['segmentation'] = masks[i]
  206. segm_json_results.append(data)
  207. result_files = dict()
  208. result_files['bbox'] = f'{outfile_prefix}.bbox.json'
  209. result_files['proposal'] = f'{outfile_prefix}.bbox.json'
  210. dump(bbox_json_results, result_files['bbox'])
  211. if segm_json_results is not None:
  212. result_files['segm'] = f'{outfile_prefix}.segm.json'
  213. dump(segm_json_results, result_files['segm'])
  214. return result_files
  215. def gt_to_coco_json(self, gt_dicts: Sequence[dict],
  216. outfile_prefix: str) -> str:
  217. """Convert ground truth to coco format json file.
  218. Args:
  219. gt_dicts (Sequence[dict]): Ground truth of the dataset.
  220. outfile_prefix (str): The filename prefix of the json files. If the
  221. prefix is "somepath/xxx", the json file will be named
  222. "somepath/xxx.gt.json".
  223. Returns:
  224. str: The filename of the json file.
  225. """
  226. categories = [
  227. dict(id=id, name=name)
  228. for id, name in enumerate(self.dataset_meta['classes'])
  229. ]
  230. image_infos = []
  231. annotations = []
  232. for idx, gt_dict in enumerate(gt_dicts):
  233. img_id = gt_dict.get('img_id', idx)
  234. image_info = dict(
  235. id=img_id,
  236. width=gt_dict['width'],
  237. height=gt_dict['height'],
  238. file_name='')
  239. image_infos.append(image_info)
  240. for ann in gt_dict['anns']:
  241. label = ann['bbox_label']
  242. bbox = ann['bbox']
  243. coco_bbox = [
  244. bbox[0],
  245. bbox[1],
  246. bbox[2] - bbox[0],
  247. bbox[3] - bbox[1],
  248. ]
  249. annotation = dict(
  250. id=len(annotations) +
  251. 1, # coco api requires id starts with 1
  252. image_id=img_id,
  253. bbox=coco_bbox,
  254. iscrowd=ann.get('ignore_flag', 0),
  255. category_id=int(label),
  256. area=coco_bbox[2] * coco_bbox[3])
  257. if ann.get('mask', None):
  258. mask = ann['mask']
  259. # area = mask_util.area(mask)
  260. if isinstance(mask, dict) and isinstance(
  261. mask['counts'], bytes):
  262. mask['counts'] = mask['counts'].decode()
  263. annotation['segmentation'] = mask
  264. # annotation['area'] = float(area)
  265. annotations.append(annotation)
  266. info = dict(
  267. date_created=str(datetime.datetime.now()),
  268. description='Coco json file converted by mmdet CocoMetric.')
  269. coco_json = dict(
  270. info=info,
  271. images=image_infos,
  272. categories=categories,
  273. licenses=None,
  274. )
  275. if len(annotations) > 0:
  276. coco_json['annotations'] = annotations
  277. converted_json_path = f'{outfile_prefix}.gt.json'
  278. dump(coco_json, converted_json_path)
  279. return converted_json_path
  280. # TODO: data_batch is no longer needed, consider adjusting the
  281. # parameter position
  282. def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None:
  283. """Process one batch of data samples and predictions. The processed
  284. results should be stored in ``self.results``, which will be used to
  285. compute the metrics when all batches have been processed.
  286. Args:
  287. data_batch (dict): A batch of data from the dataloader.
  288. data_samples (Sequence[dict]): A batch of data samples that
  289. contain annotations and predictions.
  290. """
  291. for data_sample in data_samples:
  292. result = dict()
  293. pred = data_sample['pred_instances']
  294. result['img_id'] = data_sample['img_id']
  295. result['bboxes'] = pred['bboxes'].cpu().numpy()
  296. result['scores'] = pred['scores'].cpu().numpy()
  297. result['labels'] = pred['labels'].cpu().numpy()
  298. # encode mask to RLE
  299. if 'masks' in pred:
  300. result['masks'] = encode_mask_results(
  301. pred['masks'].detach().cpu().numpy())
  302. # some detectors use different scores for bbox and mask
  303. if 'mask_scores' in pred:
  304. result['mask_scores'] = pred['mask_scores'].cpu().numpy()
  305. # parse gt
  306. gt = dict()
  307. gt['width'] = data_sample['ori_shape'][1]
  308. gt['height'] = data_sample['ori_shape'][0]
  309. gt['img_id'] = data_sample['img_id']
  310. if self._coco_api is None:
  311. # TODO: Need to refactor to support LoadAnnotations
  312. assert 'instances' in data_sample, \
  313. 'ground truth is required for evaluation when ' \
  314. '`ann_file` is not provided'
  315. gt['anns'] = data_sample['instances']
  316. # add converted result to the results list
  317. self.results.append((gt, result))
  318. def compute_metrics(self, results: list) -> Dict[str, float]:
  319. """Compute the metrics from processed results.
  320. Args:
  321. results (list): The processed results of each batch.
  322. Returns:
  323. Dict[str, float]: The computed metrics. The keys are the names of
  324. the metrics, and the values are corresponding results.
  325. """
  326. logger: MMLogger = MMLogger.get_current_instance()
  327. # split gt and prediction list
  328. gts, preds = zip(*results)
  329. tmp_dir = None
  330. if self.outfile_prefix is None:
  331. tmp_dir = tempfile.TemporaryDirectory()
  332. outfile_prefix = osp.join(tmp_dir.name, 'results')
  333. else:
  334. outfile_prefix = self.outfile_prefix
  335. if self._coco_api is None:
  336. # use converted gt json file to initialize coco api
  337. logger.info('Converting ground truth to coco format...')
  338. coco_json_path = self.gt_to_coco_json(
  339. gt_dicts=gts, outfile_prefix=outfile_prefix)
  340. self._coco_api = COCO(coco_json_path)
  341. # handle lazy init
  342. if self.cat_ids is None:
  343. self.cat_ids = self._coco_api.get_cat_ids(
  344. cat_names=self.dataset_meta['classes'])
  345. if self.img_ids is None:
  346. self.img_ids = self._coco_api.get_img_ids()
  347. # convert predictions to coco format and dump to json file
  348. result_files = self.results2json(preds, outfile_prefix)
  349. eval_results = OrderedDict()
  350. if self.format_only:
  351. logger.info('results are saved in '
  352. f'{osp.dirname(outfile_prefix)}')
  353. return eval_results
  354. for metric in self.metrics:
  355. logger.info(f'Evaluating {metric}...')
  356. # TODO: May refactor fast_eval_recall to an independent metric?
  357. # fast eval recall
  358. if metric == 'proposal_fast':
  359. ar = self.fast_eval_recall(
  360. preds, self.proposal_nums, self.iou_thrs, logger=logger)
  361. log_msg = []
  362. for i, num in enumerate(self.proposal_nums):
  363. eval_results[f'AR@{num}'] = ar[i]
  364. log_msg.append(f'\nAR@{num}\t{ar[i]:.4f}')
  365. log_msg = ''.join(log_msg)
  366. logger.info(log_msg)
  367. continue
  368. # evaluate proposal, bbox and segm
  369. iou_type = 'bbox' if metric == 'proposal' else metric
  370. if metric not in result_files:
  371. raise KeyError(f'{metric} is not in results')
  372. try:
  373. predictions = load(result_files[metric])
  374. if iou_type == 'segm':
  375. # Refer to https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/coco.py#L331 # noqa
  376. # When evaluating mask AP, if the results contain bbox,
  377. # cocoapi will use the box area instead of the mask area
  378. # for calculating the instance area. Though the overall AP
  379. # is not affected, this leads to different
  380. # small/medium/large mask AP results.
  381. for x in predictions:
  382. x.pop('bbox')
  383. coco_dt = self._coco_api.loadRes(predictions)
  384. except IndexError:
  385. logger.error(
  386. 'The testing results of the whole dataset is empty.')
  387. break
  388. coco_eval = COCOeval(self._coco_api, coco_dt, iou_type)
  389. coco_eval.params.catIds = self.cat_ids
  390. coco_eval.params.imgIds = self.img_ids
  391. coco_eval.params.maxDets = list(self.proposal_nums)
  392. coco_eval.params.iouThrs = self.iou_thrs
  393. # mapping of cocoEval.stats
  394. coco_metric_names = {
  395. 'mAP': 0,
  396. 'mAP_50': 1,
  397. 'mAP_75': 2,
  398. 'mAP_s': 3,
  399. 'mAP_m': 4,
  400. 'mAP_l': 5,
  401. 'AR@100': 6,
  402. 'AR@300': 7,
  403. 'AR@1000': 8,
  404. 'AR_s@1000': 9,
  405. 'AR_m@1000': 10,
  406. 'AR_l@1000': 11
  407. }
  408. metric_items = self.metric_items
  409. if metric_items is not None:
  410. for metric_item in metric_items:
  411. if metric_item not in coco_metric_names:
  412. raise KeyError(
  413. f'metric item "{metric_item}" is not supported')
  414. if metric == 'proposal':
  415. coco_eval.params.useCats = 0
  416. coco_eval.evaluate()
  417. coco_eval.accumulate()
  418. coco_eval.summarize()
  419. if metric_items is None:
  420. metric_items = [
  421. 'AR@100', 'AR@300', 'AR@1000', 'AR_s@1000',
  422. 'AR_m@1000', 'AR_l@1000'
  423. ]
  424. for item in metric_items:
  425. val = float(
  426. f'{coco_eval.stats[coco_metric_names[item]]:.3f}')
  427. eval_results[item] = val
  428. else:
  429. coco_eval.evaluate()
  430. coco_eval.accumulate()
  431. coco_eval.summarize()
  432. if self.classwise: # Compute per-category AP
  433. # Compute per-category AP
  434. # from https://github.com/facebookresearch/detectron2/
  435. precisions = coco_eval.eval['precision']
  436. # precision: (iou, recall, cls, area range, max dets)
  437. assert len(self.cat_ids) == precisions.shape[2]
  438. results_per_category = []
  439. for idx, cat_id in enumerate(self.cat_ids):
  440. # area range index 0: all area ranges
  441. # max dets index -1: typically 100 per image
  442. nm = self._coco_api.loadCats(cat_id)[0]
  443. precision = precisions[:, :, idx, 0, -1]
  444. precision = precision[precision > -1]
  445. if precision.size:
  446. ap = np.mean(precision)
  447. else:
  448. ap = float('nan')
  449. results_per_category.append(
  450. (f'{nm["name"]}', f'{round(ap, 3)}'))
  451. eval_results[f'{nm["name"]}_precision'] = round(ap, 3)
  452. num_columns = min(6, len(results_per_category) * 2)
  453. results_flatten = list(
  454. itertools.chain(*results_per_category))
  455. headers = ['category', 'AP'] * (num_columns // 2)
  456. results_2d = itertools.zip_longest(*[
  457. results_flatten[i::num_columns]
  458. for i in range(num_columns)
  459. ])
  460. table_data = [headers]
  461. table_data += [result for result in results_2d]
  462. table = AsciiTable(table_data)
  463. logger.info('\n' + table.table)
  464. if metric_items is None:
  465. metric_items = [
  466. 'mAP', 'mAP_50', 'mAP_75', 'mAP_s', 'mAP_m', 'mAP_l'
  467. ]
  468. for metric_item in metric_items:
  469. key = f'{metric}_{metric_item}'
  470. val = coco_eval.stats[coco_metric_names[metric_item]]
  471. eval_results[key] = float(f'{round(val, 3)}')
  472. ap = coco_eval.stats[:6]
  473. logger.info(f'{metric}_mAP_copypaste: {ap[0]:.3f} '
  474. f'{ap[1]:.3f} {ap[2]:.3f} {ap[3]:.3f} '
  475. f'{ap[4]:.3f} {ap[5]:.3f}')
  476. if tmp_dir is not None:
  477. tmp_dir.cleanup()
  478. return eval_results