semseg_metric.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import os.path as osp
  3. from collections import OrderedDict
  4. from typing import Dict, Optional, Sequence, Union
  5. import numpy as np
  6. import torch
  7. from mmcv import imwrite
  8. from mmengine.dist import is_main_process
  9. from mmengine.evaluator import BaseMetric
  10. from mmengine.logging import MMLogger, print_log
  11. from mmengine.utils import mkdir_or_exist
  12. from PIL import Image
  13. try:
  14. from prettytable import PrettyTable
  15. except ImportError:
  16. PrettyTable = None
  17. from mmdet.registry import METRICS
  18. @METRICS.register_module()
  19. class SemSegMetric(BaseMetric):
  20. """mIoU evaluation metric.
  21. Args:
  22. iou_metrics (list[str] | str): Metrics to be calculated, the options
  23. includes 'mIoU', 'mDice' and 'mFscore'.
  24. beta (int): Determines the weight of recall in the combined score.
  25. Default: 1.
  26. collect_device (str): Device name used for collecting results from
  27. different ranks during distributed training. Must be 'cpu' or
  28. 'gpu'. Defaults to 'cpu'.
  29. output_dir (str): The directory for output prediction. Defaults to
  30. None.
  31. format_only (bool): Only format result for results commit without
  32. perform evaluation. It is useful when you want to save the result
  33. to a specific format and submit it to the test server.
  34. Defaults to False.
  35. backend_args (dict, optional): Arguments to instantiate the
  36. corresponding backend. Defaults to None.
  37. prefix (str, optional): The prefix that will be added in the metric
  38. names to disambiguate homonymous metrics of different evaluators.
  39. If prefix is not provided in the argument, self.default_prefix
  40. will be used instead. Defaults to None.
  41. """
  42. def __init__(self,
  43. iou_metrics: Sequence[str] = ['mIoU'],
  44. beta: int = 1,
  45. collect_device: str = 'cpu',
  46. output_dir: Optional[str] = None,
  47. format_only: bool = False,
  48. backend_args: dict = None,
  49. prefix: Optional[str] = None) -> None:
  50. super().__init__(collect_device=collect_device, prefix=prefix)
  51. if isinstance(iou_metrics, str):
  52. iou_metrics = [iou_metrics]
  53. if not set(iou_metrics).issubset(set(['mIoU', 'mDice', 'mFscore'])):
  54. raise KeyError(f'metrics {iou_metrics} is not supported. '
  55. f'Only supports mIoU/mDice/mFscore.')
  56. self.metrics = iou_metrics
  57. self.beta = beta
  58. self.output_dir = output_dir
  59. if self.output_dir and is_main_process():
  60. mkdir_or_exist(self.output_dir)
  61. self.format_only = format_only
  62. self.backend_args = backend_args
  63. def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None:
  64. """Process one batch of data and data_samples.
  65. The processed results should be stored in ``self.results``, which will
  66. be used to compute the metrics when all batches have been processed.
  67. Args:
  68. data_batch (dict): A batch of data from the dataloader.
  69. data_samples (Sequence[dict]): A batch of outputs from the model.
  70. """
  71. num_classes = len(self.dataset_meta['classes'])
  72. for data_sample in data_samples:
  73. pred_label = data_sample['pred_sem_seg']['sem_seg'].squeeze()
  74. # format_only always for test dataset without ground truth
  75. if not self.format_only:
  76. label = data_sample['gt_sem_seg']['sem_seg'].squeeze().to(
  77. pred_label)
  78. ignore_index = data_sample['pred_sem_seg'].get(
  79. 'ignore_index', 255)
  80. self.results.append(
  81. self._compute_pred_stats(pred_label, label, num_classes,
  82. ignore_index))
  83. # format_result
  84. if self.output_dir is not None:
  85. basename = osp.splitext(osp.basename(
  86. data_sample['img_path']))[0]
  87. png_filename = osp.abspath(
  88. osp.join(self.output_dir, f'{basename}.png'))
  89. output_mask = pred_label.cpu().numpy()
  90. output = Image.fromarray(output_mask.astype(np.uint8))
  91. imwrite(output, png_filename, backend_args=self.backend_args)
  92. def compute_metrics(self, results: list) -> Dict[str, float]:
  93. """Compute the metrics from processed results.
  94. Args:
  95. results (list): The processed results of each batch.
  96. Returns:
  97. Dict[str, float]: The computed metrics. The keys are the names of
  98. the metrics, and the values are corresponding results. The key
  99. mainly includes aAcc, mIoU, mAcc, mDice, mFscore, mPrecision,
  100. mRecall.
  101. """
  102. logger: MMLogger = MMLogger.get_current_instance()
  103. if self.format_only:
  104. logger.info(f'results are saved to {osp.dirname(self.output_dir)}')
  105. return OrderedDict()
  106. ret_metrics = self.get_return_metrics(results)
  107. # summary table
  108. ret_metrics_summary = OrderedDict({
  109. ret_metric: np.round(np.nanmean(ret_metric_value) * 100, 2)
  110. for ret_metric, ret_metric_value in ret_metrics.items()
  111. })
  112. metrics = dict()
  113. for key, val in ret_metrics_summary.items():
  114. if key == 'aAcc':
  115. metrics[key] = val
  116. else:
  117. metrics['m' + key] = val
  118. print_semantic_table(ret_metrics, self.dataset_meta['classes'], logger)
  119. return metrics
  120. def _compute_pred_stats(self, pred_label: torch.tensor,
  121. label: torch.tensor, num_classes: int,
  122. ignore_index: int):
  123. """Parse semantic segmentation predictions.
  124. Args:
  125. pred_label (torch.tensor): Prediction segmentation map
  126. or predict result filename. The shape is (H, W).
  127. label (torch.tensor): Ground truth segmentation map
  128. or label filename. The shape is (H, W).
  129. num_classes (int): Number of categories.
  130. Returns:
  131. torch.Tensor: The intersection of prediction and ground truth
  132. histogram on all classes.
  133. torch.Tensor: The union of prediction and ground truth histogram on
  134. all classes.
  135. torch.Tensor: The prediction histogram on all classes.
  136. torch.Tensor: The ground truth histogram on all classes.
  137. """
  138. assert pred_label.shape == label.shape
  139. mask = label != ignore_index
  140. label, pred_label = label[mask], pred_label[mask]
  141. intersect = pred_label[pred_label == label]
  142. area_intersect = torch.histc(
  143. intersect.float(), bins=num_classes, min=0, max=num_classes - 1)
  144. area_pred_label = torch.histc(
  145. pred_label.float(), bins=num_classes, min=0, max=num_classes - 1)
  146. area_label = torch.histc(
  147. label.float(), bins=num_classes, min=0, max=num_classes - 1)
  148. area_union = area_pred_label + area_label - area_intersect
  149. result = dict(
  150. area_intersect=area_intersect,
  151. area_union=area_union,
  152. area_pred_label=area_pred_label,
  153. area_label=area_label)
  154. return result
  155. def get_return_metrics(self, results: list) -> dict:
  156. """Calculate evaluation metrics.
  157. Args:
  158. results (list): The processed results of each batch.
  159. Returns:
  160. Dict[str, np.ndarray]: per category evaluation metrics,
  161. shape (num_classes, ).
  162. """
  163. def f_score(precision, recall, beta=1):
  164. """calculate the f-score value.
  165. Args:
  166. precision (float | torch.Tensor): The precision value.
  167. recall (float | torch.Tensor): The recall value.
  168. beta (int): Determines the weight of recall in the combined
  169. score. Default: 1.
  170. Returns:
  171. [torch.tensor]: The f-score value.
  172. """
  173. score = (1 + beta**2) * (precision * recall) / (
  174. (beta**2 * precision) + recall)
  175. return score
  176. total_area_intersect = sum([r['area_intersect'] for r in results])
  177. total_area_union = sum([r['area_union'] for r in results])
  178. total_area_pred_label = sum([r['area_pred_label'] for r in results])
  179. total_area_label = sum([r['area_label'] for r in results])
  180. all_acc = total_area_intersect / total_area_label
  181. ret_metrics = OrderedDict({'aAcc': all_acc})
  182. for metric in self.metrics:
  183. if metric == 'mIoU':
  184. iou = total_area_intersect / total_area_union
  185. acc = total_area_intersect / total_area_label
  186. ret_metrics['IoU'] = iou
  187. ret_metrics['Acc'] = acc
  188. elif metric == 'mDice':
  189. dice = 2 * total_area_intersect / (
  190. total_area_pred_label + total_area_label)
  191. acc = total_area_intersect / total_area_label
  192. ret_metrics['Dice'] = dice
  193. ret_metrics['Acc'] = acc
  194. elif metric == 'mFscore':
  195. precision = total_area_intersect / total_area_pred_label
  196. recall = total_area_intersect / total_area_label
  197. f_value = torch.tensor([
  198. f_score(x[0], x[1], self.beta)
  199. for x in zip(precision, recall)
  200. ])
  201. ret_metrics['Fscore'] = f_value
  202. ret_metrics['Precision'] = precision
  203. ret_metrics['Recall'] = recall
  204. ret_metrics = {
  205. metric: value.cpu().numpy()
  206. for metric, value in ret_metrics.items()
  207. }
  208. return ret_metrics
  209. def print_semantic_table(
  210. results: dict,
  211. class_names: list,
  212. logger: Optional[Union['MMLogger', str]] = None) -> None:
  213. """Print semantic segmentation evaluation results table.
  214. Args:
  215. results (dict): The evaluation results.
  216. class_names (list): Class names.
  217. logger (MMLogger | str, optional): Logger used for printing.
  218. Default: None.
  219. """
  220. # each class table
  221. results.pop('aAcc', None)
  222. ret_metrics_class = OrderedDict({
  223. ret_metric: np.round(ret_metric_value * 100, 2)
  224. for ret_metric, ret_metric_value in results.items()
  225. })
  226. print_log('per class results:', logger)
  227. if PrettyTable:
  228. class_table_data = PrettyTable()
  229. ret_metrics_class.update({'Class': class_names})
  230. ret_metrics_class.move_to_end('Class', last=False)
  231. for key, val in ret_metrics_class.items():
  232. class_table_data.add_column(key, val)
  233. print_log('\n' + class_table_data.get_string(), logger=logger)
  234. else:
  235. logger.warning(
  236. '`prettytable` is not installed, for better table format, '
  237. 'please consider installing it with "pip install prettytable"')
  238. print_result = {}
  239. for class_name, iou, acc in zip(class_names, ret_metrics_class['IoU'],
  240. ret_metrics_class['Acc']):
  241. print_result[class_name] = {'IoU': iou, 'Acc': acc}
  242. print_log(print_result, logger)