confusion_matrix.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import argparse
  2. import os
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. from matplotlib.ticker import MultipleLocator
  6. from mmcv.ops import nms
  7. from mmengine import Config, DictAction
  8. from mmengine.fileio import load
  9. from mmengine.registry import init_default_scope
  10. from mmengine.utils import ProgressBar
  11. from mmdet.evaluation import bbox_overlaps
  12. from mmdet.registry import DATASETS
  13. from mmdet.utils import replace_cfg_vals, update_data_root
  14. def parse_args():
  15. parser = argparse.ArgumentParser(
  16. description='Generate confusion matrix from detection results')
  17. parser.add_argument('config', help='test config file path')
  18. parser.add_argument(
  19. 'prediction_path', help='prediction path where test .pkl result')
  20. parser.add_argument(
  21. 'save_dir', help='directory where confusion matrix will be saved')
  22. parser.add_argument(
  23. '--show', action='store_true', help='show confusion matrix')
  24. parser.add_argument(
  25. '--color-theme',
  26. default='plasma',
  27. help='theme of the matrix color map')
  28. parser.add_argument(
  29. '--score-thr',
  30. type=float,
  31. default=0.3,
  32. help='score threshold to filter detection bboxes')
  33. parser.add_argument(
  34. '--tp-iou-thr',
  35. type=float,
  36. default=0.5,
  37. help='IoU threshold to be considered as matched')
  38. parser.add_argument(
  39. '--nms-iou-thr',
  40. type=float,
  41. default=None,
  42. help='nms IoU threshold, only applied when users want to change the'
  43. 'nms IoU threshold.')
  44. parser.add_argument(
  45. '--cfg-options',
  46. nargs='+',
  47. action=DictAction,
  48. help='override some settings in the used config, the key-value pair '
  49. 'in xxx=yyy format will be merged into config file. If the value to '
  50. 'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
  51. 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
  52. 'Note that the quotation marks are necessary and that no white space '
  53. 'is allowed.')
  54. args = parser.parse_args()
  55. return args
  56. def calculate_confusion_matrix(dataset,
  57. results,
  58. score_thr=0,
  59. nms_iou_thr=None,
  60. tp_iou_thr=0.5):
  61. """Calculate the confusion matrix.
  62. Args:
  63. dataset (Dataset): Test or val dataset.
  64. results (list[ndarray]): A list of detection results in each image.
  65. score_thr (float|optional): Score threshold to filter bboxes.
  66. Default: 0.
  67. nms_iou_thr (float|optional): nms IoU threshold, the detection results
  68. have done nms in the detector, only applied when users want to
  69. change the nms IoU threshold. Default: None.
  70. tp_iou_thr (float|optional): IoU threshold to be considered as matched.
  71. Default: 0.5.
  72. """
  73. num_classes = len(dataset.metainfo['classes'])
  74. confusion_matrix = np.zeros(shape=[num_classes + 1, num_classes + 1])
  75. assert len(dataset) == len(results)
  76. prog_bar = ProgressBar(len(results))
  77. for idx, per_img_res in enumerate(results):
  78. res_bboxes = per_img_res['pred_instances']
  79. gts = dataset.get_data_info(idx)['instances']
  80. analyze_per_img_dets(confusion_matrix, gts, res_bboxes, score_thr,
  81. tp_iou_thr, nms_iou_thr)
  82. prog_bar.update()
  83. return confusion_matrix
  84. def analyze_per_img_dets(confusion_matrix,
  85. gts,
  86. result,
  87. score_thr=0,
  88. tp_iou_thr=0.5,
  89. nms_iou_thr=None):
  90. """Analyze detection results on each image.
  91. Args:
  92. confusion_matrix (ndarray): The confusion matrix,
  93. has shape (num_classes + 1, num_classes + 1).
  94. gt_bboxes (ndarray): Ground truth bboxes, has shape (num_gt, 4).
  95. gt_labels (ndarray): Ground truth labels, has shape (num_gt).
  96. result (ndarray): Detection results, has shape
  97. (num_classes, num_bboxes, 5).
  98. score_thr (float): Score threshold to filter bboxes.
  99. Default: 0.
  100. tp_iou_thr (float): IoU threshold to be considered as matched.
  101. Default: 0.5.
  102. nms_iou_thr (float|optional): nms IoU threshold, the detection results
  103. have done nms in the detector, only applied when users want to
  104. change the nms IoU threshold. Default: None.
  105. """
  106. true_positives = np.zeros(len(gts))
  107. gt_bboxes = []
  108. gt_labels = []
  109. for gt in gts:
  110. gt_bboxes.append(gt['bbox'])
  111. gt_labels.append(gt['bbox_label'])
  112. gt_bboxes = np.array(gt_bboxes)
  113. gt_labels = np.array(gt_labels)
  114. unique_label = np.unique(result['labels'].numpy())
  115. for det_label in unique_label:
  116. mask = (result['labels'] == det_label)
  117. det_bboxes = result['bboxes'][mask].numpy()
  118. det_scores = result['scores'][mask].numpy()
  119. if nms_iou_thr:
  120. det_bboxes, _ = nms(
  121. det_bboxes, det_scores, nms_iou_thr, score_threshold=score_thr)
  122. ious = bbox_overlaps(det_bboxes[:, :4], gt_bboxes)
  123. for i, score in enumerate(det_scores):
  124. det_match = 0
  125. if score >= score_thr:
  126. for j, gt_label in enumerate(gt_labels):
  127. if ious[i, j] >= tp_iou_thr:
  128. det_match += 1
  129. if gt_label == det_label:
  130. true_positives[j] += 1 # TP
  131. confusion_matrix[gt_label, det_label] += 1
  132. if det_match == 0: # BG FP
  133. confusion_matrix[-1, det_label] += 1
  134. for num_tp, gt_label in zip(true_positives, gt_labels):
  135. if num_tp == 0: # FN
  136. confusion_matrix[gt_label, -1] += 1
  137. def plot_confusion_matrix(confusion_matrix,
  138. labels,
  139. save_dir=None,
  140. show=True,
  141. title='Normalized Confusion Matrix',
  142. color_theme='plasma'):
  143. """Draw confusion matrix with matplotlib.
  144. Args:
  145. confusion_matrix (ndarray): The confusion matrix.
  146. labels (list[str]): List of class names.
  147. save_dir (str|optional): If set, save the confusion matrix plot to the
  148. given path. Default: None.
  149. show (bool): Whether to show the plot. Default: True.
  150. title (str): Title of the plot. Default: `Normalized Confusion Matrix`.
  151. color_theme (str): Theme of the matrix color map. Default: `plasma`.
  152. """
  153. # normalize the confusion matrix
  154. per_label_sums = confusion_matrix.sum(axis=1)[:, np.newaxis]
  155. confusion_matrix = \
  156. confusion_matrix.astype(np.float32) / per_label_sums * 100
  157. num_classes = len(labels)
  158. fig, ax = plt.subplots(
  159. figsize=(0.5 * num_classes, 0.5 * num_classes * 0.8), dpi=180)
  160. cmap = plt.get_cmap(color_theme)
  161. im = ax.imshow(confusion_matrix, cmap=cmap)
  162. plt.colorbar(mappable=im, ax=ax)
  163. title_font = {'weight': 'bold', 'size': 12}
  164. ax.set_title(title, fontdict=title_font)
  165. label_font = {'size': 10}
  166. plt.ylabel('Ground Truth Label', fontdict=label_font)
  167. plt.xlabel('Prediction Label', fontdict=label_font)
  168. # draw locator
  169. xmajor_locator = MultipleLocator(1)
  170. xminor_locator = MultipleLocator(0.5)
  171. ax.xaxis.set_major_locator(xmajor_locator)
  172. ax.xaxis.set_minor_locator(xminor_locator)
  173. ymajor_locator = MultipleLocator(1)
  174. yminor_locator = MultipleLocator(0.5)
  175. ax.yaxis.set_major_locator(ymajor_locator)
  176. ax.yaxis.set_minor_locator(yminor_locator)
  177. # draw grid
  178. ax.grid(True, which='minor', linestyle='-')
  179. # draw label
  180. ax.set_xticks(np.arange(num_classes))
  181. ax.set_yticks(np.arange(num_classes))
  182. ax.set_xticklabels(labels)
  183. ax.set_yticklabels(labels)
  184. ax.tick_params(
  185. axis='x', bottom=False, top=True, labelbottom=False, labeltop=True)
  186. plt.setp(
  187. ax.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor')
  188. # draw confution matrix value
  189. for i in range(num_classes):
  190. for j in range(num_classes):
  191. ax.text(
  192. j,
  193. i,
  194. '{}%'.format(
  195. int(confusion_matrix[
  196. i,
  197. j]) if not np.isnan(confusion_matrix[i, j]) else -1),
  198. ha='center',
  199. va='center',
  200. color='w',
  201. size=7)
  202. ax.set_ylim(len(confusion_matrix) - 0.5, -0.5) # matplotlib>3.1.1
  203. fig.tight_layout()
  204. if save_dir is not None:
  205. plt.savefig(
  206. os.path.join(save_dir, 'confusion_matrix.png'), format='png')
  207. if show:
  208. plt.show()
  209. def main():
  210. args = parse_args()
  211. cfg = Config.fromfile(args.config)
  212. # replace the ${key} with the value of cfg.key
  213. cfg = replace_cfg_vals(cfg)
  214. # update data root according to MMDET_DATASETS
  215. update_data_root(cfg)
  216. if args.cfg_options is not None:
  217. cfg.merge_from_dict(args.cfg_options)
  218. init_default_scope(cfg.get('default_scope', 'mmdet'))
  219. results = load(args.prediction_path)
  220. if not os.path.exists(args.save_dir):
  221. os.makedirs(args.save_dir)
  222. dataset = DATASETS.build(cfg.test_dataloader.dataset)
  223. confusion_matrix = calculate_confusion_matrix(dataset, results,
  224. args.score_thr,
  225. args.nms_iou_thr,
  226. args.tp_iou_thr)
  227. plot_confusion_matrix(
  228. confusion_matrix,
  229. dataset.metainfo['classes'] + ('background', ),
  230. save_dir=args.save_dir,
  231. show=args.show,
  232. color_theme=args.color_theme)
  233. if __name__ == '__main__':
  234. main()