youtube_vis_metric.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import os.path as osp
  3. import tempfile
  4. import warnings
  5. import zipfile
  6. from collections import OrderedDict, defaultdict
  7. from typing import Dict, List, Optional, Sequence, Tuple, Union
  8. import mmengine
  9. import numpy as np
  10. from mmengine.dist import (all_gather_object, barrier, broadcast_object_list,
  11. is_main_process)
  12. from mmengine.logging import MMLogger
  13. from mmdet.registry import METRICS
  14. from mmdet.structures.mask import encode_mask_results
  15. from ..functional import YTVIS, YTVISeval
  16. from .base_video_metric import BaseVideoMetric, collect_tracking_results
  17. @METRICS.register_module()
  18. class YouTubeVISMetric(BaseVideoMetric):
  19. """mAP evaluation metrics for the VIS task.
  20. Args:
  21. metric (str | list[str]): Metrics to be evaluated.
  22. Default value is `youtube_vis_ap`.
  23. metric_items (List[str], optional): Metric result names to be
  24. recorded in the evaluation result. Defaults to None.
  25. outfile_prefix (str | None): The prefix of json files. It includes
  26. the file path and the prefix of filename, e.g., "a/b/prefix".
  27. If not specified, a temp file will be created. Defaults to None.
  28. collect_device (str): Device name used for collecting results from
  29. different ranks during distributed training. Must be 'cpu' or
  30. 'gpu'. Defaults to 'cpu'.
  31. prefix (str, optional): The prefix that will be added in the metric
  32. names to disambiguate homonyms metrics of different evaluators.
  33. If prefix is not provided in the argument, self.default_prefix
  34. will be used instead. Default: None
  35. format_only (bool): If True, only formatting the results to the
  36. official format and not performing evaluation. Defaults to False.
  37. """
  38. default_prefix: Optional[str] = 'youtube_vis'
  39. def __init__(self,
  40. metric: Union[str, List[str]] = 'youtube_vis_ap',
  41. metric_items: Optional[Sequence[str]] = None,
  42. outfile_prefix: Optional[str] = None,
  43. collect_device: str = 'cpu',
  44. prefix: Optional[str] = None,
  45. format_only: bool = False) -> None:
  46. super().__init__(collect_device=collect_device, prefix=prefix)
  47. # vis evaluation metrics
  48. self.metrics = metric if isinstance(metric, list) else [metric]
  49. self.format_only = format_only
  50. allowed_metrics = ['youtube_vis_ap']
  51. for metric in self.metrics:
  52. if metric not in allowed_metrics:
  53. raise KeyError(
  54. f"metric should be 'youtube_vis_ap', but got {metric}.")
  55. self.metric_items = metric_items
  56. self.outfile_prefix = outfile_prefix
  57. self.per_video_res = []
  58. self.categories = []
  59. self._vis_meta_info = defaultdict(list) # record video and image infos
  60. def process_video(self, data_samples):
  61. video_length = len(data_samples)
  62. for frame_id in range(video_length):
  63. result = dict()
  64. img_data_sample = data_samples[frame_id].to_dict()
  65. pred = img_data_sample['pred_track_instances']
  66. video_id = img_data_sample['video_id']
  67. result['img_id'] = img_data_sample['img_id']
  68. result['bboxes'] = pred['bboxes'].cpu().numpy()
  69. result['scores'] = pred['scores'].cpu().numpy()
  70. result['labels'] = pred['labels'].cpu().numpy()
  71. result['instances_id'] = pred['instances_id'].cpu().numpy()
  72. # encode mask to RLE
  73. assert 'masks' in pred, \
  74. 'masks must exist in YouTube-VIS metric'
  75. result['masks'] = encode_mask_results(
  76. pred['masks'].detach().cpu().numpy())
  77. # parse gt
  78. gt = dict()
  79. gt['width'] = img_data_sample['ori_shape'][1]
  80. gt['height'] = img_data_sample['ori_shape'][0]
  81. gt['img_id'] = img_data_sample['img_id']
  82. gt['frame_id'] = frame_id
  83. gt['video_id'] = video_id
  84. gt['video_length'] = video_length
  85. if 'instances' in img_data_sample:
  86. gt['anns'] = img_data_sample['instances']
  87. else:
  88. gt['anns'] = dict()
  89. self.per_video_res.append((result, gt))
  90. preds, gts = zip(*self.per_video_res)
  91. # format the results
  92. # we must format gts first to update self._vis_meta_info
  93. gt_results = self._format_one_video_gts(gts)
  94. pred_results = self._format_one_video_preds(preds)
  95. self.per_video_res.clear()
  96. # add converted result to the results list
  97. self.results.append((pred_results, gt_results))
  98. def compute_metrics(self, results: List) -> Dict[str, float]:
  99. """Compute the metrics from processed results.
  100. Args:
  101. results (List): The processed results of each batch.
  102. Returns:
  103. Dict[str, float]: The computed metrics. The keys are the names of
  104. the metrics, and the values are corresponding results.
  105. """
  106. # split gt and prediction list
  107. tmp_pred_results, tmp_gt_results = zip(*results)
  108. gt_results = self.format_gts(tmp_gt_results)
  109. pred_results = self.format_preds(tmp_pred_results)
  110. if self.format_only:
  111. self.save_pred_results(pred_results)
  112. return dict()
  113. ytvis = YTVIS(gt_results)
  114. ytvis_dets = ytvis.loadRes(pred_results)
  115. vid_ids = ytvis.getVidIds()
  116. iou_type = metric = 'segm'
  117. eval_results = OrderedDict()
  118. ytvisEval = YTVISeval(ytvis, ytvis_dets, iou_type)
  119. ytvisEval.params.vidIds = vid_ids
  120. ytvisEval.evaluate()
  121. ytvisEval.accumulate()
  122. ytvisEval.summarize()
  123. coco_metric_names = {
  124. 'mAP': 0,
  125. 'mAP_50': 1,
  126. 'mAP_75': 2,
  127. 'mAP_s': 3,
  128. 'mAP_m': 4,
  129. 'mAP_l': 5,
  130. 'AR@1': 6,
  131. 'AR@10': 7,
  132. 'AR@100': 8,
  133. 'AR_s@100': 9,
  134. 'AR_m@100': 10,
  135. 'AR_l@100': 11
  136. }
  137. metric_items = self.metric_items
  138. if metric_items is not None:
  139. for metric_item in metric_items:
  140. if metric_item not in coco_metric_names:
  141. raise KeyError(
  142. f'metric item "{metric_item}" is not supported')
  143. if metric_items is None:
  144. metric_items = [
  145. 'mAP', 'mAP_50', 'mAP_75', 'mAP_s', 'mAP_m', 'mAP_l'
  146. ]
  147. for metric_item in metric_items:
  148. key = f'{metric}_{metric_item}'
  149. val = float(
  150. f'{ytvisEval.stats[coco_metric_names[metric_item]]:.3f}')
  151. eval_results[key] = val
  152. return eval_results
  153. def format_gts(self, gts: Tuple[List]) -> dict:
  154. """Gather all ground-truth from self.results."""
  155. self.categories = [
  156. dict(id=id + 1, name=name)
  157. for id, name in enumerate(self.dataset_meta['classes'])
  158. ]
  159. gt_results = dict(
  160. categories=self.categories,
  161. videos=self._vis_meta_info['videos'],
  162. annotations=[])
  163. for gt_result in gts:
  164. gt_results['annotations'].extend(gt_result)
  165. return gt_results
  166. def format_preds(self, preds: Tuple[List]) -> List:
  167. """Gather all predictions from self.results."""
  168. pred_results = []
  169. for pred_result in preds:
  170. pred_results.extend(pred_result)
  171. return pred_results
  172. def _format_one_video_preds(self, pred_dicts: Tuple[dict]) -> List:
  173. """Convert the annotation to the format of YouTube-VIS.
  174. This operation is to make it easier to use the official eval API.
  175. Args:
  176. pred_dicts (Tuple[dict]): Prediction of the dataset.
  177. Returns:
  178. List: The formatted predictions.
  179. """
  180. # Collate preds scatters (tuple of dict to dict of list)
  181. preds = defaultdict(list)
  182. for pred in pred_dicts:
  183. for key in pred.keys():
  184. preds[key].append(pred[key])
  185. img_infos = self._vis_meta_info['images']
  186. vid_infos = self._vis_meta_info['videos']
  187. inds = [i for i, _ in enumerate(img_infos) if _['frame_id'] == 0]
  188. inds.append(len(img_infos))
  189. json_results = []
  190. video_id = vid_infos[-1]['id']
  191. # collect data for each instances in a video.
  192. collect_data = dict()
  193. for frame_id, (masks, scores, labels, ids) in enumerate(
  194. zip(preds['masks'], preds['scores'], preds['labels'],
  195. preds['instances_id'])):
  196. assert len(masks) == len(labels)
  197. for j, id in enumerate(ids):
  198. if id not in collect_data:
  199. collect_data[id] = dict(
  200. category_ids=[], scores=[], segmentations=dict())
  201. collect_data[id]['category_ids'].append(labels[j])
  202. collect_data[id]['scores'].append(scores[j])
  203. if isinstance(masks[j]['counts'], bytes):
  204. masks[j]['counts'] = masks[j]['counts'].decode()
  205. collect_data[id]['segmentations'][frame_id] = masks[j]
  206. # transform the collected data into official format
  207. for id, id_data in collect_data.items():
  208. output = dict()
  209. output['video_id'] = video_id
  210. output['score'] = np.array(id_data['scores']).mean().item()
  211. # majority voting for sequence category
  212. output['category_id'] = np.bincount(
  213. np.array(id_data['category_ids'])).argmax().item() + 1
  214. output['segmentations'] = []
  215. for frame_id in range(inds[-1] - inds[-2]):
  216. if frame_id in id_data['segmentations']:
  217. output['segmentations'].append(
  218. id_data['segmentations'][frame_id])
  219. else:
  220. output['segmentations'].append(None)
  221. json_results.append(output)
  222. return json_results
  223. def _format_one_video_gts(self, gt_dicts: Tuple[dict]) -> List:
  224. """Convert the annotation to the format of YouTube-VIS.
  225. This operation is to make it easier to use the official eval API.
  226. Args:
  227. gt_dicts (Tuple[dict]): Ground truth of the dataset.
  228. Returns:
  229. list: The formatted gts.
  230. """
  231. video_infos = []
  232. image_infos = []
  233. instance_infos = defaultdict(list)
  234. len_videos = dict() # mapping from instance_id to video_length
  235. vis_anns = []
  236. # get video infos
  237. for gt_dict in gt_dicts:
  238. frame_id = gt_dict['frame_id']
  239. video_id = gt_dict['video_id']
  240. img_id = gt_dict['img_id']
  241. image_info = dict(
  242. id=img_id,
  243. width=gt_dict['width'],
  244. height=gt_dict['height'],
  245. frame_id=frame_id,
  246. file_name='')
  247. image_infos.append(image_info)
  248. if frame_id == 0:
  249. video_info = dict(
  250. id=video_id,
  251. width=gt_dict['width'],
  252. height=gt_dict['height'],
  253. file_name='')
  254. video_infos.append(video_info)
  255. for ann in gt_dict['anns']:
  256. label = ann['bbox_label']
  257. bbox = ann['bbox']
  258. instance_id = ann['instance_id']
  259. # update video length
  260. len_videos[instance_id] = gt_dict['video_length']
  261. coco_bbox = [
  262. bbox[0],
  263. bbox[1],
  264. bbox[2] - bbox[0],
  265. bbox[3] - bbox[1],
  266. ]
  267. annotation = dict(
  268. video_id=video_id,
  269. frame_id=frame_id,
  270. bbox=coco_bbox,
  271. instance_id=instance_id,
  272. iscrowd=ann.get('ignore_flag', 0),
  273. category_id=int(label) + 1,
  274. area=coco_bbox[2] * coco_bbox[3])
  275. if ann.get('mask', None):
  276. mask = ann['mask']
  277. # area = mask_util.area(mask)
  278. if isinstance(mask, dict) and isinstance(
  279. mask['counts'], bytes):
  280. mask['counts'] = mask['counts'].decode()
  281. annotation['segmentation'] = mask
  282. instance_infos[instance_id].append(annotation)
  283. # update vis meta info
  284. self._vis_meta_info['images'].extend(image_infos)
  285. self._vis_meta_info['videos'].extend(video_infos)
  286. for instance_id, ann_infos in instance_infos.items():
  287. cur_video_len = len_videos[instance_id]
  288. segm = [None] * cur_video_len
  289. bbox = [None] * cur_video_len
  290. area = [None] * cur_video_len
  291. # In the official format, no instances are represented by
  292. # 'None', however, only images with instances are recorded
  293. # in the current annotations, so we need to use 'None' to
  294. # initialize these lists.
  295. for ann_info in ann_infos:
  296. frame_id = ann_info['frame_id']
  297. segm[frame_id] = ann_info['segmentation']
  298. bbox[frame_id] = ann_info['bbox']
  299. area[frame_id] = ann_info['area']
  300. instance = dict(
  301. category_id=ann_infos[0]['category_id'],
  302. segmentations=segm,
  303. bboxes=bbox,
  304. video_id=ann_infos[0]['video_id'],
  305. areas=area,
  306. id=instance_id,
  307. iscrowd=ann_infos[0]['iscrowd'])
  308. vis_anns.append(instance)
  309. return vis_anns
  310. def save_pred_results(self, pred_results: List) -> None:
  311. """Save the results to a zip file (standard format for YouTube-VIS
  312. Challenge).
  313. Args:
  314. pred_results (list): Testing results of the
  315. dataset.
  316. """
  317. logger: MMLogger = MMLogger.get_current_instance()
  318. if self.outfile_prefix is None:
  319. tmp_dir = tempfile.TemporaryDirectory()
  320. outfile_prefix = osp.join(tmp_dir.name, 'results')
  321. else:
  322. outfile_prefix = self.outfile_prefix
  323. mmengine.dump(pred_results, f'{outfile_prefix}.json')
  324. # zip the json file in order to submit to the test server.
  325. zip_file_name = f'{outfile_prefix}.submission_file.zip'
  326. zf = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED)
  327. logger.info(f"zip the 'results.json' into '{zip_file_name}', "
  328. 'please submmit the zip file to the test server')
  329. zf.write(f'{outfile_prefix}.json', 'results.json')
  330. zf.close()
  331. def evaluate(self, size: int) -> dict:
  332. """Evaluate the model performance of the whole dataset after processing
  333. all batches.
  334. Args:
  335. size (int): Length of the entire validation dataset.
  336. Returns:
  337. dict: Evaluation metrics dict on the val dataset. The keys are the
  338. names of the metrics, and the values are corresponding results.
  339. """
  340. # wait for all processes to complete prediction.
  341. barrier()
  342. if len(self.results) == 0:
  343. warnings.warn(
  344. f'{self.__class__.__name__} got empty `self.results`. Please '
  345. 'ensure that the processed results are properly added into '
  346. '`self.results` in `process` method.')
  347. results = collect_tracking_results(self.results, self.collect_device)
  348. # gather seq_info
  349. gathered_seq_info = all_gather_object(self._vis_meta_info['videos'])
  350. all_seq_info = []
  351. for _seq_info in gathered_seq_info:
  352. all_seq_info.extend(_seq_info)
  353. # update self._vis_meta_info
  354. self._vis_meta_info = dict(videos=all_seq_info)
  355. if is_main_process():
  356. _metrics = self.compute_metrics(results) # type: ignore
  357. # Add prefix to metric names
  358. if self.prefix:
  359. _metrics = {
  360. '/'.join((self.prefix, k)): v
  361. for k, v in _metrics.items()
  362. }
  363. metrics = [_metrics]
  364. else:
  365. metrics = [None] # type: ignore
  366. broadcast_object_list(metrics)
  367. # reset the results list
  368. self.results.clear()
  369. # reset the vis_meta_info
  370. self._vis_meta_info.clear()
  371. return metrics[0]