coco.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import numpy as np
  16. from paddlex.ppdet.core.workspace import register, serializable
  17. from .dataset import DetDataset
  18. from paddlex.ppdet.utils.logger import setup_logger
  19. logger = setup_logger(__name__)
  20. @register
  21. @serializable
  22. class COCODataSet(DetDataset):
  23. """
  24. Load dataset with COCO format.
  25. Args:
  26. dataset_dir (str): root directory for dataset.
  27. image_dir (str): directory for images.
  28. anno_path (str): coco annotation file path.
  29. data_fields (list): key name of data dictionary, at least have 'image'.
  30. sample_num (int): number of samples to load, -1 means all.
  31. load_crowd (bool): whether to load crowded ground-truth.
  32. False as default
  33. allow_empty (bool): whether to load empty entry. False as default
  34. empty_ratio (float): the ratio of empty record number to total
  35. record's, if empty_ratio is out of [0. ,1.), do not sample the
  36. records. 1. as default
  37. """
  38. def __init__(self,
  39. dataset_dir=None,
  40. image_dir=None,
  41. anno_path=None,
  42. data_fields=['image'],
  43. sample_num=-1,
  44. load_crowd=False,
  45. allow_empty=False,
  46. empty_ratio=1.):
  47. super(COCODataSet, self).__init__(dataset_dir, image_dir, anno_path,
  48. data_fields, sample_num)
  49. self.load_image_only = False
  50. self.load_semantic = False
  51. self.load_crowd = load_crowd
  52. self.allow_empty = allow_empty
  53. self.empty_ratio = empty_ratio
  54. def _sample_empty(self, records, num):
  55. # if empty_ratio is out of [0. ,1.), do not sample the records
  56. if self.empty_ratio < 0. or self.empty_ratio >= 1.:
  57. return records
  58. import random
  59. sample_num = int(num * self.empty_ratio / (1 - self.empty_ratio))
  60. records = random.sample(records, sample_num)
  61. return records
  62. def parse_dataset(self):
  63. anno_path = os.path.join(self.dataset_dir, self.anno_path)
  64. image_dir = os.path.join(self.dataset_dir, self.image_dir)
  65. assert anno_path.endswith('.json'), \
  66. 'invalid coco annotation file: ' + anno_path
  67. from pycocotools.coco import COCO
  68. coco = COCO(anno_path)
  69. img_ids = coco.getImgIds()
  70. img_ids.sort()
  71. cat_ids = coco.getCatIds()
  72. records = []
  73. empty_records = []
  74. ct = 0
  75. self.catid2clsid = dict({catid: i for i, catid in enumerate(cat_ids)})
  76. self.cname2cid = dict({
  77. coco.loadCats(catid)[0]['name']: clsid
  78. for catid, clsid in self.catid2clsid.items()
  79. })
  80. if 'annotations' not in coco.dataset:
  81. self.load_image_only = True
  82. logger.warning(
  83. 'Annotation file: {} does not contains ground truth '
  84. 'and load image information only.'.format(anno_path))
  85. for img_id in img_ids:
  86. img_anno = coco.loadImgs([img_id])[0]
  87. im_fname = img_anno['file_name']
  88. im_w = float(img_anno['width'])
  89. im_h = float(img_anno['height'])
  90. im_path = os.path.join(image_dir,
  91. im_fname) if image_dir else im_fname
  92. is_empty = False
  93. if not os.path.exists(im_path):
  94. logger.warning('Illegal image file: {}, and it will be '
  95. 'ignored'.format(im_path))
  96. continue
  97. if im_w < 0 or im_h < 0:
  98. logger.warning(
  99. 'Illegal width: {} or height: {} in annotation, '
  100. 'and im_id: {} will be ignored'.format(im_w, im_h, img_id))
  101. continue
  102. coco_rec = {
  103. 'im_file': im_path,
  104. 'im_id': np.array([img_id]),
  105. 'h': im_h,
  106. 'w': im_w,
  107. } if 'image' in self.data_fields else {}
  108. if not self.load_image_only:
  109. ins_anno_ids = coco.getAnnIds(
  110. imgIds=[img_id],
  111. iscrowd=None if self.load_crowd else False)
  112. instances = coco.loadAnns(ins_anno_ids)
  113. bboxes = []
  114. is_rbox_anno = False
  115. for inst in instances:
  116. # check gt bbox
  117. if inst.get('ignore', False):
  118. continue
  119. if 'bbox' not in inst.keys():
  120. continue
  121. else:
  122. if not any(np.array(inst['bbox'])):
  123. continue
  124. # read rbox anno or not
  125. is_rbox_anno = True if len(inst['bbox']) == 5 else False
  126. if is_rbox_anno:
  127. xc, yc, box_w, box_h, angle = inst['bbox']
  128. x1 = xc - box_w / 2.0
  129. y1 = yc - box_h / 2.0
  130. x2 = x1 + box_w
  131. y2 = y1 + box_h
  132. else:
  133. x1, y1, box_w, box_h = inst['bbox']
  134. x2 = x1 + box_w
  135. y2 = y1 + box_h
  136. eps = 1e-5
  137. if inst['area'] > 0 and x2 - x1 > eps and y2 - y1 > eps:
  138. inst['clean_bbox'] = [
  139. round(float(x), 3) for x in [x1, y1, x2, y2]
  140. ]
  141. if is_rbox_anno:
  142. inst['clean_rbox'] = [xc, yc, box_w, box_h, angle]
  143. bboxes.append(inst)
  144. else:
  145. logger.warning(
  146. 'Found an invalid bbox in annotations: im_id: {}, '
  147. 'area: {} x1: {}, y1: {}, x2: {}, y2: {}.'.format(
  148. img_id, float(inst['area']), x1, y1, x2, y2))
  149. num_bbox = len(bboxes)
  150. if num_bbox <= 0 and not self.allow_empty:
  151. continue
  152. elif num_bbox <= 0:
  153. is_empty = True
  154. gt_bbox = np.zeros((num_bbox, 4), dtype=np.float32)
  155. if is_rbox_anno:
  156. gt_rbox = np.zeros((num_bbox, 5), dtype=np.float32)
  157. gt_theta = np.zeros((num_bbox, 1), dtype=np.int32)
  158. gt_class = np.zeros((num_bbox, 1), dtype=np.int32)
  159. is_crowd = np.zeros((num_bbox, 1), dtype=np.int32)
  160. difficult = np.zeros((num_bbox, 1), dtype=np.int32)
  161. gt_poly = [None] * num_bbox
  162. has_segmentation = False
  163. for i, box in enumerate(bboxes):
  164. catid = box['category_id']
  165. gt_class[i][0] = self.catid2clsid[catid]
  166. gt_bbox[i, :] = box['clean_bbox']
  167. # xc, yc, w, h, theta
  168. if is_rbox_anno:
  169. gt_rbox[i, :] = box['clean_rbox']
  170. is_crowd[i][0] = box['iscrowd']
  171. # check RLE format
  172. if 'segmentation' in box and box['iscrowd'] == 1:
  173. gt_poly[i] = [[0.0, 0.0], ]
  174. elif 'segmentation' in box and box['segmentation']:
  175. gt_poly[i] = box['segmentation']
  176. has_segmentation = True
  177. if has_segmentation and not any(
  178. gt_poly) and not self.allow_empty:
  179. continue
  180. if is_rbox_anno:
  181. gt_rec = {
  182. 'is_crowd': is_crowd,
  183. 'gt_class': gt_class,
  184. 'gt_bbox': gt_bbox,
  185. 'gt_rbox': gt_rbox,
  186. 'gt_poly': gt_poly,
  187. }
  188. else:
  189. gt_rec = {
  190. 'is_crowd': is_crowd,
  191. 'gt_class': gt_class,
  192. 'gt_bbox': gt_bbox,
  193. 'gt_poly': gt_poly,
  194. }
  195. for k, v in gt_rec.items():
  196. if k in self.data_fields:
  197. coco_rec[k] = v
  198. # TODO: remove load_semantic
  199. if self.load_semantic and 'semantic' in self.data_fields:
  200. seg_path = os.path.join(self.dataset_dir, 'stuffthingmaps',
  201. 'train2017', im_fname[:-3] + 'png')
  202. coco_rec.update({'semantic': seg_path})
  203. logger.debug('Load file: {}, im_id: {}, h: {}, w: {}.'.format(
  204. im_path, img_id, im_h, im_w))
  205. if is_empty:
  206. empty_records.append(coco_rec)
  207. else:
  208. records.append(coco_rec)
  209. ct += 1
  210. if self.sample_num > 0 and ct >= self.sample_num:
  211. break
  212. assert ct > 0, 'not found any coco record in %s' % (anno_path)
  213. logger.debug('{} samples in file {}'.format(ct, anno_path))
  214. if len(empty_records) > 0:
  215. empty_records = self._sample_empty(empty_records, len(records))
  216. records += empty_records
  217. self.roidbs = records