coco.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. # Copyright (c) 2021 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. from __future__ import absolute_import
  15. import copy
  16. import os.path as osp
  17. import six
  18. import sys
  19. import numpy as np
  20. from paddlex.utils import logging, is_pic, get_num_workers
  21. from .voc import VOCDetection
  22. from paddlex.cv.transforms import MixupImage
  23. class CocoDetection(VOCDetection):
  24. """读取MSCOCO格式的检测数据集,并对样本进行相应的处理,该格式的数据集同样可以应用到实例分割模型的训练中。
  25. Args:
  26. data_dir (str): 数据集所在的目录路径。
  27. ann_file (str): 数据集的标注文件,为一个独立的json格式文件。
  28. transforms (paddlex.det.transforms): 数据集中每个样本的预处理/增强算子。
  29. num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
  30. 系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核数的一半。
  31. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  32. allow_empty (bool): 是否加载负样本。默认为False。
  33. empty_ratio (float): 用于指定负样本占总样本数的比例。如果小于0或大于等于1,则保留全部的负样本。默认为1。
  34. """
  35. def __init__(self,
  36. data_dir,
  37. ann_file,
  38. transforms=None,
  39. num_workers='auto',
  40. shuffle=False,
  41. allow_empty=False,
  42. empty_ratio=1.):
  43. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  44. # or matplotlib.backends is imported for the first time
  45. # pycocotools import matplotlib
  46. import matplotlib
  47. matplotlib.use('Agg')
  48. from pycocotools.coco import COCO
  49. try:
  50. import shapely.ops
  51. from shapely.geometry import Polygon, MultiPolygon, GeometryCollection
  52. except:
  53. six.reraise(*sys.exc_info())
  54. super(VOCDetection, self).__init__()
  55. self.data_fields = None
  56. self.transforms = copy.deepcopy(transforms)
  57. self.num_max_boxes = 50
  58. self.use_mix = False
  59. if self.transforms is not None:
  60. for op in self.transforms.transforms:
  61. if isinstance(op, MixupImage):
  62. self.mixup_op = copy.deepcopy(op)
  63. self.use_mix = True
  64. self.num_max_boxes *= 2
  65. break
  66. self.batch_transforms = None
  67. self.num_workers = get_num_workers(num_workers)
  68. self.shuffle = shuffle
  69. self.allow_empty = allow_empty
  70. self.empty_ratio = empty_ratio
  71. self.file_list = list()
  72. neg_file_list = list()
  73. self.labels = list()
  74. coco = COCO(ann_file)
  75. self.coco_gt = coco
  76. img_ids = sorted(coco.getImgIds())
  77. cat_ids = coco.getCatIds()
  78. catid2clsid = dict({catid: i for i, catid in enumerate(cat_ids)})
  79. cname2clsid = dict({
  80. coco.loadCats(catid)[0]['name']: clsid
  81. for catid, clsid in catid2clsid.items()
  82. })
  83. for label, cid in sorted(cname2clsid.items(), key=lambda d: d[1]):
  84. self.labels.append(label)
  85. logging.info("Starting to read file list from dataset...")
  86. ct = 0
  87. for img_id in img_ids:
  88. is_empty = False
  89. img_anno = coco.loadImgs(img_id)[0]
  90. im_fname = osp.join(data_dir, img_anno['file_name'])
  91. if not is_pic(im_fname):
  92. continue
  93. im_w = float(img_anno['width'])
  94. im_h = float(img_anno['height'])
  95. ins_anno_ids = coco.getAnnIds(imgIds=img_id, iscrowd=False)
  96. instances = coco.loadAnns(ins_anno_ids)
  97. bboxes = []
  98. for inst in instances:
  99. x, y, box_w, box_h = inst['bbox']
  100. x1 = max(0, x)
  101. y1 = max(0, y)
  102. x2 = min(im_w - 1, x1 + max(0, box_w))
  103. y2 = min(im_h - 1, y1 + max(0, box_h))
  104. if inst['area'] > 0 and x2 >= x1 and y2 >= y1:
  105. inst['clean_bbox'] = [x1, y1, x2, y2]
  106. bboxes.append(inst)
  107. else:
  108. logging.warning(
  109. "Found an invalid bbox in annotations: "
  110. "im_id: {}, area: {} x1: {}, y1: {}, x2: {}, y2: {}."
  111. .format(img_id, float(inst['area']), x1, y1, x2, y2))
  112. num_bbox = len(bboxes)
  113. if num_bbox == 0 and not self.allow_empty:
  114. continue
  115. elif num_bbox == 0:
  116. is_empty = True
  117. gt_bbox = np.zeros((num_bbox, 4), dtype=np.float32)
  118. gt_class = np.zeros((num_bbox, 1), dtype=np.int32)
  119. gt_score = np.ones((num_bbox, 1), dtype=np.float32)
  120. is_crowd = np.zeros((num_bbox, 1), dtype=np.int32)
  121. difficult = np.zeros((num_bbox, 1), dtype=np.int32)
  122. gt_poly = [None] * num_bbox
  123. has_segmentation = False
  124. for i, box in reversed(list(enumerate(bboxes))):
  125. catid = box['category_id']
  126. gt_class[i][0] = catid2clsid[catid]
  127. gt_bbox[i, :] = box['clean_bbox']
  128. is_crowd[i][0] = box['iscrowd']
  129. if 'segmentation' in box and box['iscrowd'] == 1:
  130. gt_poly[i] = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
  131. elif 'segmentation' in box and box['segmentation']:
  132. if not np.array(box[
  133. 'segmentation']).size > 0 and not self.allow_empty:
  134. gt_poly.pop(i)
  135. is_crowd = np.delete(is_crowd, i)
  136. gt_class = np.delete(gt_class, i)
  137. gt_bbox = np.delete(gt_bbox, i)
  138. else:
  139. gt_poly[i] = box['segmentation']
  140. has_segmentation = True
  141. if has_segmentation and not any(gt_poly) and not self.allow_empty:
  142. continue
  143. im_info = {
  144. 'im_id': np.array([img_id]).astype('int32'),
  145. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  146. }
  147. label_info = {
  148. 'is_crowd': is_crowd,
  149. 'gt_class': gt_class,
  150. 'gt_bbox': gt_bbox,
  151. 'gt_score': gt_score,
  152. 'gt_poly': gt_poly,
  153. 'difficult': difficult
  154. }
  155. if is_empty:
  156. neg_file_list.append({
  157. 'image': im_fname,
  158. **
  159. im_info,
  160. **
  161. label_info
  162. })
  163. else:
  164. self.file_list.append({
  165. 'image': im_fname,
  166. **
  167. im_info,
  168. **
  169. label_info
  170. })
  171. ct += 1
  172. if self.use_mix:
  173. self.num_max_boxes = max(self.num_max_boxes,
  174. 2 * len(instances))
  175. else:
  176. self.num_max_boxes = max(self.num_max_boxes, len(instances))
  177. if not ct:
  178. logging.error(
  179. "No coco record found in %s' % (ann_file)", exit=True)
  180. self.pos_num = len(self.file_list)
  181. if self.allow_empty:
  182. self.file_list += self._sample_empty(neg_file_list)
  183. logging.info(
  184. "{} samples in file {}, including {} positive samples and {} negative samples.".
  185. format(
  186. len(self.file_list), ann_file, self.pos_num,
  187. len(self.file_list) - self.pos_num))
  188. self.num_samples = len(self.file_list)
  189. self._epoch = 0