coco.py 7.9 KB

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