test_lvis_metric.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import os.path as osp
  2. import tempfile
  3. import unittest
  4. import numpy as np
  5. import pycocotools.mask as mask_util
  6. import torch
  7. from mmdet.evaluation.metrics import LVISMetric
  8. try:
  9. import lvis
  10. except ImportError:
  11. lvis = None
  12. from mmengine.fileio import dump
  13. class TestLVISMetric(unittest.TestCase):
  14. def _create_dummy_lvis_json(self, json_name):
  15. dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8)
  16. dummy_mask[:5, :5] = 1
  17. rle_mask = mask_util.encode(dummy_mask)
  18. rle_mask['counts'] = rle_mask['counts'].decode('utf-8')
  19. image = {
  20. 'id': 0,
  21. 'width': 640,
  22. 'height': 640,
  23. 'neg_category_ids': [],
  24. 'not_exhaustive_category_ids': [],
  25. 'coco_url': 'http://images.cocodataset.org/val2017/0.jpg',
  26. }
  27. annotation_1 = {
  28. 'id': 1,
  29. 'image_id': 0,
  30. 'category_id': 1,
  31. 'area': 400,
  32. 'bbox': [50, 60, 20, 20],
  33. 'segmentation': rle_mask,
  34. }
  35. annotation_2 = {
  36. 'id': 2,
  37. 'image_id': 0,
  38. 'category_id': 1,
  39. 'area': 900,
  40. 'bbox': [100, 120, 30, 30],
  41. 'segmentation': rle_mask,
  42. }
  43. annotation_3 = {
  44. 'id': 3,
  45. 'image_id': 0,
  46. 'category_id': 2,
  47. 'area': 1600,
  48. 'bbox': [150, 160, 40, 40],
  49. 'segmentation': rle_mask,
  50. }
  51. annotation_4 = {
  52. 'id': 4,
  53. 'image_id': 0,
  54. 'category_id': 1,
  55. 'area': 10000,
  56. 'bbox': [250, 260, 100, 100],
  57. 'segmentation': rle_mask,
  58. }
  59. categories = [
  60. {
  61. 'id': 1,
  62. 'name': 'aerosol_can',
  63. 'frequency': 'c',
  64. 'image_count': 64
  65. },
  66. {
  67. 'id': 2,
  68. 'name': 'air_conditioner',
  69. 'frequency': 'f',
  70. 'image_count': 364
  71. },
  72. ]
  73. fake_json = {
  74. 'images': [image],
  75. 'annotations':
  76. [annotation_1, annotation_2, annotation_3, annotation_4],
  77. 'categories': categories
  78. }
  79. dump(fake_json, json_name)
  80. def _create_dummy_results(self):
  81. bboxes = np.array([[50, 60, 70, 80], [100, 120, 130, 150],
  82. [150, 160, 190, 200], [250, 260, 350, 360]])
  83. scores = np.array([1.0, 0.98, 0.96, 0.95])
  84. labels = np.array([0, 0, 1, 0])
  85. dummy_mask = np.zeros((4, 10, 10), dtype=np.uint8)
  86. dummy_mask[:, :5, :5] = 1
  87. return dict(
  88. bboxes=torch.from_numpy(bboxes),
  89. scores=torch.from_numpy(scores),
  90. labels=torch.from_numpy(labels),
  91. masks=torch.from_numpy(dummy_mask))
  92. def setUp(self):
  93. self.tmp_dir = tempfile.TemporaryDirectory()
  94. def tearDown(self):
  95. self.tmp_dir.cleanup()
  96. @unittest.skipIf(lvis is None, 'lvis is not installed.')
  97. def test_init(self):
  98. fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json')
  99. self._create_dummy_lvis_json(fake_json_file)
  100. with self.assertRaisesRegex(KeyError, 'metric should be one of'):
  101. LVISMetric(ann_file=fake_json_file, metric='unknown')
  102. @unittest.skipIf(lvis is None, 'lvis is not installed.')
  103. def test_evaluate(self):
  104. # create dummy data
  105. fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json')
  106. self._create_dummy_lvis_json(fake_json_file)
  107. dummy_pred = self._create_dummy_results()
  108. # test single lvis dataset evaluation
  109. lvis_metric = LVISMetric(
  110. ann_file=fake_json_file,
  111. classwise=False,
  112. outfile_prefix=f'{self.tmp_dir.name}/test')
  113. lvis_metric.dataset_meta = dict(
  114. classes=['aerosol_can', 'air_conditioner'])
  115. lvis_metric.process(
  116. {},
  117. [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))])
  118. eval_results = lvis_metric.evaluate(size=1)
  119. target = {
  120. 'lvis/bbox_AP': 1.0,
  121. 'lvis/bbox_AP50': 1.0,
  122. 'lvis/bbox_AP75': 1.0,
  123. 'lvis/bbox_APs': 1.0,
  124. 'lvis/bbox_APm': 1.0,
  125. 'lvis/bbox_APl': 1.0,
  126. 'lvis/bbox_APr': -1.0,
  127. 'lvis/bbox_APc': 1.0,
  128. 'lvis/bbox_APf': 1.0
  129. }
  130. self.assertDictEqual(eval_results, target)
  131. self.assertTrue(
  132. osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json')))
  133. # test box and segm lvis dataset evaluation
  134. lvis_metric = LVISMetric(
  135. ann_file=fake_json_file,
  136. metric=['bbox', 'segm'],
  137. classwise=False,
  138. outfile_prefix=f'{self.tmp_dir.name}/test')
  139. lvis_metric.dataset_meta = dict(
  140. classes=['aerosol_can', 'air_conditioner'])
  141. lvis_metric.process(
  142. {},
  143. [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))])
  144. eval_results = lvis_metric.evaluate(size=1)
  145. target = {
  146. 'lvis/bbox_AP': 1.0,
  147. 'lvis/bbox_AP50': 1.0,
  148. 'lvis/bbox_AP75': 1.0,
  149. 'lvis/bbox_APs': 1.0,
  150. 'lvis/bbox_APm': 1.0,
  151. 'lvis/bbox_APl': 1.0,
  152. 'lvis/bbox_APr': -1.0,
  153. 'lvis/bbox_APc': 1.0,
  154. 'lvis/bbox_APf': 1.0,
  155. 'lvis/segm_AP': 1.0,
  156. 'lvis/segm_AP50': 1.0,
  157. 'lvis/segm_AP75': 1.0,
  158. 'lvis/segm_APs': 1.0,
  159. 'lvis/segm_APm': 1.0,
  160. 'lvis/segm_APl': 1.0,
  161. 'lvis/segm_APr': -1.0,
  162. 'lvis/segm_APc': 1.0,
  163. 'lvis/segm_APf': 1.0
  164. }
  165. self.assertDictEqual(eval_results, target)
  166. self.assertTrue(
  167. osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json')))
  168. self.assertTrue(
  169. osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json')))
  170. # test invalid custom metric_items
  171. with self.assertRaisesRegex(
  172. KeyError,
  173. "metric should be one of 'bbox', 'segm', 'proposal', "
  174. "'proposal_fast', but got invalid."):
  175. lvis_metric = LVISMetric(
  176. ann_file=fake_json_file, metric=['invalid'])
  177. lvis_metric.evaluate(size=1)
  178. # test custom metric_items
  179. lvis_metric = LVISMetric(ann_file=fake_json_file, metric_items=['APm'])
  180. lvis_metric.dataset_meta = dict(
  181. classes=['aerosol_can', 'air_conditioner'])
  182. lvis_metric.process(
  183. {},
  184. [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))])
  185. eval_results = lvis_metric.evaluate(size=1)
  186. target = {
  187. 'lvis/bbox_APm': 1.0,
  188. }
  189. self.assertDictEqual(eval_results, target)
  190. @unittest.skipIf(lvis is None, 'lvis is not installed.')
  191. def test_classwise_evaluate(self):
  192. # create dummy data
  193. fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json')
  194. self._create_dummy_lvis_json(fake_json_file)
  195. dummy_pred = self._create_dummy_results()
  196. # test single lvis dataset evaluation
  197. lvis_metric = LVISMetric(
  198. ann_file=fake_json_file, metric='bbox', classwise=True)
  199. lvis_metric.dataset_meta = dict(
  200. classes=['aerosol_can', 'air_conditioner'])
  201. lvis_metric.process(
  202. {},
  203. [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))])
  204. eval_results = lvis_metric.evaluate(size=1)
  205. target = {
  206. 'lvis/bbox_AP': 1.0,
  207. 'lvis/bbox_AP50': 1.0,
  208. 'lvis/bbox_AP75': 1.0,
  209. 'lvis/bbox_APs': 1.0,
  210. 'lvis/bbox_APm': 1.0,
  211. 'lvis/bbox_APl': 1.0,
  212. 'lvis/bbox_APr': -1.0,
  213. 'lvis/bbox_APc': 1.0,
  214. 'lvis/bbox_APf': 1.0,
  215. 'lvis/aerosol_can_precision': 1.0,
  216. 'lvis/air_conditioner_precision': 1.0,
  217. }
  218. self.assertDictEqual(eval_results, target)
  219. @unittest.skipIf(lvis is None, 'lvis is not installed.')
  220. def test_manually_set_iou_thrs(self):
  221. # create dummy data
  222. fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json')
  223. self._create_dummy_lvis_json(fake_json_file)
  224. # test single lvis dataset evaluation
  225. lvis_metric = LVISMetric(
  226. ann_file=fake_json_file, metric='bbox', iou_thrs=[0.3, 0.6])
  227. lvis_metric.dataset_meta = dict(
  228. classes=['aerosol_can', 'air_conditioner'])
  229. self.assertEqual(lvis_metric.iou_thrs, [0.3, 0.6])
  230. @unittest.skipIf(lvis is None, 'lvis is not installed.')
  231. def test_fast_eval_recall(self):
  232. # create dummy data
  233. fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json')
  234. self._create_dummy_lvis_json(fake_json_file)
  235. dummy_pred = self._create_dummy_results()
  236. # test default proposal nums
  237. lvis_metric = LVISMetric(
  238. ann_file=fake_json_file, metric='proposal_fast')
  239. lvis_metric.dataset_meta = dict(
  240. classes=['aerosol_can', 'air_conditioner'])
  241. lvis_metric.process(
  242. {},
  243. [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))])
  244. eval_results = lvis_metric.evaluate(size=1)
  245. target = {'lvis/AR@100': 1.0, 'lvis/AR@300': 1.0, 'lvis/AR@1000': 1.0}
  246. self.assertDictEqual(eval_results, target)
  247. # test manually set proposal nums
  248. lvis_metric = LVISMetric(
  249. ann_file=fake_json_file,
  250. metric='proposal_fast',
  251. proposal_nums=(2, 4))
  252. lvis_metric.dataset_meta = dict(
  253. classes=['aerosol_can', 'air_conditioner'])
  254. lvis_metric.process(
  255. {},
  256. [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))])
  257. eval_results = lvis_metric.evaluate(size=1)
  258. target = {'lvis/AR@2': 0.5, 'lvis/AR@4': 1.0}
  259. self.assertDictEqual(eval_results, target)
  260. @unittest.skipIf(lvis is None, 'lvis is not installed.')
  261. def test_evaluate_proposal(self):
  262. # create dummy data
  263. fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json')
  264. self._create_dummy_lvis_json(fake_json_file)
  265. dummy_pred = self._create_dummy_results()
  266. lvis_metric = LVISMetric(ann_file=fake_json_file, metric='proposal')
  267. lvis_metric.dataset_meta = dict(
  268. classes=['aerosol_can', 'air_conditioner'])
  269. lvis_metric.process(
  270. {},
  271. [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))])
  272. eval_results = lvis_metric.evaluate(size=1)
  273. target = {
  274. 'lvis/AR@300': 1.0,
  275. 'lvis/ARs@300': 1.0,
  276. 'lvis/ARm@300': 1.0,
  277. 'lvis/ARl@300': 1.0
  278. }
  279. self.assertDictEqual(eval_results, target)
  280. @unittest.skipIf(lvis is None, 'lvis is not installed.')
  281. def test_empty_results(self):
  282. # create dummy data
  283. fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json')
  284. self._create_dummy_lvis_json(fake_json_file)
  285. lvis_metric = LVISMetric(ann_file=fake_json_file, metric='bbox')
  286. lvis_metric.dataset_meta = dict(
  287. classes=['aerosol_can', 'air_conditioner'])
  288. bboxes = np.zeros((0, 4))
  289. labels = np.array([])
  290. scores = np.array([])
  291. dummy_mask = np.zeros((0, 10, 10), dtype=np.uint8)
  292. empty_pred = dict(
  293. bboxes=torch.from_numpy(bboxes),
  294. scores=torch.from_numpy(scores),
  295. labels=torch.from_numpy(labels),
  296. masks=torch.from_numpy(dummy_mask))
  297. lvis_metric.process(
  298. {},
  299. [dict(pred_instances=empty_pred, img_id=0, ori_shape=(640, 640))])
  300. # lvis api Index error will be caught
  301. lvis_metric.evaluate(size=1)
  302. @unittest.skipIf(lvis is None, 'lvis is not installed.')
  303. def test_format_only(self):
  304. # create dummy data
  305. fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json')
  306. self._create_dummy_lvis_json(fake_json_file)
  307. dummy_pred = self._create_dummy_results()
  308. with self.assertRaises(AssertionError):
  309. LVISMetric(
  310. ann_file=fake_json_file,
  311. classwise=False,
  312. format_only=True,
  313. outfile_prefix=None)
  314. lvis_metric = LVISMetric(
  315. ann_file=fake_json_file,
  316. metric='bbox',
  317. classwise=False,
  318. format_only=True,
  319. outfile_prefix=f'{self.tmp_dir.name}/test')
  320. lvis_metric.dataset_meta = dict(
  321. classes=['aerosol_can', 'air_conditioner'])
  322. lvis_metric.process(
  323. {},
  324. [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))])
  325. eval_results = lvis_metric.evaluate(size=1)
  326. self.assertDictEqual(eval_results, dict())
  327. self.assertTrue(osp.exists(f'{self.tmp_dir.name}/test.bbox.json'))