coco_90class.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import copy
  3. import os.path as osp
  4. from typing import List, Union
  5. from mmengine.fileio import get_local_path
  6. from mmdet.datasets.base_det_dataset import BaseDetDataset
  7. from mmdet.registry import DATASETS
  8. from .api_wrappers import COCO
  9. @DATASETS.register_module()
  10. class Coco90Dataset(BaseDetDataset):
  11. """Dataset for COCO."""
  12. METAINFO = {
  13. 'classes':
  14. ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',
  15. 'truck', 'boat', 'traffic light', 'fire hydrant', None, 'stop sign',
  16. 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',
  17. 'cow', 'elephant', 'bear', 'zebra', 'giraffe', None, 'backpack',
  18. 'umbrella', None, None, 'handbag', 'tie', 'suitcase', 'frisbee',
  19. 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat',
  20. 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
  21. 'bottle', None, 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
  22. 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',
  23. 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant',
  24. 'bed', None, 'dining table', None, None, 'toilet', None, 'tv',
  25. 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
  26. 'oven', 'toaster', 'sink', 'refrigerator', None, 'book', 'clock',
  27. 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'),
  28. # palette is a list of color tuples, which is used for visualization.
  29. 'palette':
  30. [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228),
  31. (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30),
  32. (100, 170, 30), None, (220, 220, 0), (175, 116, 175), (250, 0, 30),
  33. (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255),
  34. (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255),
  35. (199, 100, 0), (72, 0, 118), None,
  36. (255, 179, 240), (0, 125, 92), None, None, (209, 0, 151),
  37. (188, 208, 182), (0, 220, 176), (255, 99, 164), (92, 0, 73),
  38. (133, 129, 255), (78, 180, 255), (0, 228, 0), (174, 255, 243),
  39. (45, 89, 255), (134, 134, 103), (145, 148, 174), (255, 208, 186),
  40. (197, 226, 255), None, (171, 134, 1), (109, 63, 54), (207, 138, 255),
  41. (151, 0, 95), (9, 80, 61), (84, 105, 51), (74, 65, 105),
  42. (166, 196, 102), (208, 195, 210), (255, 109, 65), (0, 143, 149),
  43. (179, 0, 194), (209, 99, 106), (5, 121, 0), (227, 255, 205),
  44. (147, 186, 208), (153, 69, 1), (3, 95, 161), (163, 255, 0),
  45. (119, 0, 170), None, (0, 182, 199), None, None, (0, 165, 120), None,
  46. (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133),
  47. (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62),
  48. (65, 70, 15), (127, 167, 115), (59, 105, 106), None, (142, 108, 45),
  49. (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1),
  50. (246, 0, 122), (191, 162, 208)]
  51. }
  52. COCOAPI = COCO
  53. # ann_id is unique in coco dataset.
  54. ANN_ID_UNIQUE = True
  55. def load_data_list(self) -> List[dict]:
  56. """Load annotations from an annotation file named as ``self.ann_file``
  57. Returns:
  58. List[dict]: A list of annotation.
  59. """ # noqa: E501
  60. with get_local_path(
  61. self.ann_file, backend_args=self.backend_args) as local_path:
  62. self.coco = self.COCOAPI(local_path)
  63. # The order of returned `cat_ids` will not
  64. # change with the order of the `classes`
  65. self.cat_ids = self.coco.get_cat_ids(
  66. cat_names=self.metainfo['classes'])
  67. self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)}
  68. self.cat_img_map = copy.deepcopy(self.coco.cat_img_map)
  69. img_ids = self.coco.get_img_ids()
  70. data_list = []
  71. total_ann_ids = []
  72. for img_id in img_ids:
  73. raw_img_info = self.coco.load_imgs([img_id])[0]
  74. raw_img_info['img_id'] = img_id
  75. ann_ids = self.coco.get_ann_ids(img_ids=[img_id])
  76. raw_ann_info = self.coco.load_anns(ann_ids)
  77. total_ann_ids.extend(ann_ids)
  78. parsed_data_info = self.parse_data_info({
  79. 'raw_ann_info':
  80. raw_ann_info,
  81. 'raw_img_info':
  82. raw_img_info
  83. })
  84. data_list.append(parsed_data_info)
  85. if self.ANN_ID_UNIQUE:
  86. assert len(set(total_ann_ids)) == len(
  87. total_ann_ids
  88. ), f"Annotation ids in '{self.ann_file}' are not unique!"
  89. del self.coco
  90. return data_list
  91. def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]:
  92. """Parse raw annotation to target format.
  93. Args:
  94. raw_data_info (dict): Raw data information load from ``ann_file``
  95. Returns:
  96. Union[dict, List[dict]]: Parsed annotation.
  97. """
  98. img_info = raw_data_info['raw_img_info']
  99. ann_info = raw_data_info['raw_ann_info']
  100. data_info = {}
  101. # TODO: need to change data_prefix['img'] to data_prefix['img_path']
  102. img_path = osp.join(self.data_prefix['img'], img_info['file_name'])
  103. if self.data_prefix.get('seg', None):
  104. seg_map_path = osp.join(
  105. self.data_prefix['seg'],
  106. img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix)
  107. else:
  108. seg_map_path = None
  109. data_info['img_path'] = img_path
  110. data_info['img_id'] = img_info['img_id']
  111. data_info['seg_map_path'] = seg_map_path
  112. data_info['height'] = img_info['height']
  113. data_info['width'] = img_info['width']
  114. instances = []
  115. for i, ann in enumerate(ann_info):
  116. instance = {}
  117. if ann.get('ignore', False):
  118. continue
  119. x1, y1, w, h = ann['bbox']
  120. inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0))
  121. inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0))
  122. if inter_w * inter_h == 0:
  123. continue
  124. if ann['area'] <= 0 or w < 1 or h < 1:
  125. continue
  126. if ann['category_id'] not in self.cat_ids:
  127. continue
  128. bbox = [x1, y1, x1 + w, y1 + h]
  129. if ann.get('iscrowd', False):
  130. instance['ignore_flag'] = 1
  131. else:
  132. instance['ignore_flag'] = 0
  133. instance['bbox'] = bbox
  134. instance['bbox_label'] = self.cat2label[ann['category_id']]
  135. if ann.get('segmentation', None):
  136. instance['mask'] = ann['segmentation']
  137. instances.append(instance)
  138. data_info['instances'] = instances
  139. return data_info
  140. def filter_data(self) -> List[dict]:
  141. """Filter annotations according to filter_cfg.
  142. Returns:
  143. List[dict]: Filtered results.
  144. """
  145. if self.test_mode:
  146. return self.data_list
  147. if self.filter_cfg is None:
  148. return self.data_list
  149. filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False)
  150. min_size = self.filter_cfg.get('min_size', 0)
  151. # obtain images that contain annotation
  152. ids_with_ann = set(data_info['img_id'] for data_info in self.data_list)
  153. # obtain images that contain annotations of the required categories
  154. ids_in_cat = set()
  155. for i, class_id in enumerate(self.cat_ids):
  156. ids_in_cat |= set(self.cat_img_map[class_id])
  157. # merge the image id sets of the two conditions and use the merged set
  158. # to filter out images if self.filter_empty_gt=True
  159. ids_in_cat &= ids_with_ann
  160. valid_data_infos = []
  161. for i, data_info in enumerate(self.data_list):
  162. img_id = data_info['img_id']
  163. width = data_info['width']
  164. height = data_info['height']
  165. if filter_empty_gt and img_id not in ids_in_cat:
  166. continue
  167. if min(width, height) >= min_size:
  168. valid_data_infos.append(data_info)
  169. return valid_data_infos