coco.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # copyright (c) 2020 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 random
  20. import numpy as np
  21. import paddlex.utils.logging as logging
  22. import paddlex as pst
  23. from .voc import VOCDetection
  24. from .dataset import is_pic
  25. class CocoDetection(VOCDetection):
  26. """读取MSCOCO格式的检测数据集,并对样本进行相应的处理,该格式的数据集同样可以应用到实例分割模型的训练中。
  27. Args:
  28. data_dir (str): 数据集所在的目录路径。
  29. ann_file (str): 数据集的标注文件,为一个独立的json格式文件。
  30. transforms (paddlex.det.transforms): 数据集中每个样本的预处理/增强算子。
  31. num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
  32. 系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核数的一半。
  33. buffer_size (int): 数据集中样本在预处理过程中队列的缓存长度,以样本数为单位。默认为100。
  34. parallel_method (str): 数据集中样本在预处理过程中并行处理的方式,支持'thread'
  35. 线程和'process'进程两种方式。默认为'process'(Windows和Mac下会强制使用thread,该参数无效)。
  36. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  37. """
  38. def __init__(self,
  39. data_dir,
  40. ann_file,
  41. transforms=None,
  42. num_workers='auto',
  43. buffer_size=100,
  44. parallel_method='process',
  45. shuffle=False):
  46. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  47. # or matplotlib.backends is imported for the first time
  48. # pycocotools import matplotlib
  49. import matplotlib
  50. matplotlib.use('Agg')
  51. from pycocotools.coco import COCO
  52. try:
  53. import shapely.ops
  54. from shapely.geometry import Polygon, MultiPolygon, GeometryCollection
  55. except:
  56. six.reraise(*sys.exc_info())
  57. super(VOCDetection, self).__init__(
  58. transforms=transforms,
  59. num_workers=num_workers,
  60. buffer_size=buffer_size,
  61. parallel_method=parallel_method,
  62. shuffle=shuffle)
  63. self.file_list = list()
  64. self.labels = list()
  65. self._epoch = 0
  66. coco = COCO(ann_file)
  67. self.coco_gt = coco
  68. img_ids = coco.getImgIds()
  69. cat_ids = coco.getCatIds()
  70. catid2clsid = dict({catid: i + 1 for i, catid in enumerate(cat_ids)})
  71. cname2cid = dict({
  72. coco.loadCats(catid)[0]['name']: clsid
  73. for catid, clsid in catid2clsid.items()
  74. })
  75. for label, cid in sorted(cname2cid.items(), key=lambda d: d[1]):
  76. self.labels.append(label)
  77. logging.info("Starting to read file list from dataset...")
  78. for img_id in img_ids:
  79. img_anno = coco.loadImgs(img_id)[0]
  80. im_fname = osp.join(data_dir, img_anno['file_name'])
  81. if not is_pic(im_fname):
  82. continue
  83. im_w = float(img_anno['width'])
  84. im_h = float(img_anno['height'])
  85. ins_anno_ids = coco.getAnnIds(imgIds=img_id, iscrowd=False)
  86. instances = coco.loadAnns(ins_anno_ids)
  87. bboxes = []
  88. for inst in instances:
  89. x, y, box_w, box_h = inst['bbox']
  90. x1 = max(0, x)
  91. y1 = max(0, y)
  92. x2 = min(im_w - 1, x1 + max(0, box_w - 1))
  93. y2 = min(im_h - 1, y1 + max(0, box_h - 1))
  94. if inst['area'] > 0 and x2 >= x1 and y2 >= y1:
  95. inst['clean_bbox'] = [x1, y1, x2, y2]
  96. bboxes.append(inst)
  97. else:
  98. logging.warning(
  99. "Found an invalid bbox in annotations: im_id: {}, area: {} x1: {}, y1: {}, x2: {}, y2: {}."
  100. .format(img_id, float(inst['area']), x1, y1, x2, y2))
  101. num_bbox = len(bboxes)
  102. gt_bbox = np.zeros((num_bbox, 4), dtype=np.float32)
  103. gt_class = np.zeros((num_bbox, 1), dtype=np.int32)
  104. gt_score = np.ones((num_bbox, 1), dtype=np.float32)
  105. is_crowd = np.zeros((num_bbox, 1), dtype=np.int32)
  106. difficult = np.zeros((num_bbox, 1), dtype=np.int32)
  107. gt_poly = [None] * num_bbox
  108. for i, box in enumerate(bboxes):
  109. catid = box['category_id']
  110. gt_class[i][0] = catid2clsid[catid]
  111. gt_bbox[i, :] = box['clean_bbox']
  112. is_crowd[i][0] = box['iscrowd']
  113. if 'segmentation' in box:
  114. gt_poly[i] = box['segmentation']
  115. im_info = {
  116. 'im_id': np.array([img_id]).astype('int32'),
  117. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  118. }
  119. label_info = {
  120. 'is_crowd': is_crowd,
  121. 'gt_class': gt_class,
  122. 'gt_bbox': gt_bbox,
  123. 'gt_score': gt_score,
  124. 'gt_poly': gt_poly,
  125. 'difficult': difficult
  126. }
  127. if None in gt_poly:
  128. del label_info['gt_poly']
  129. coco_rec = (im_info, label_info)
  130. self.file_list.append([im_fname, coco_rec])
  131. if not len(self.file_list) > 0:
  132. raise Exception('not found any coco record in %s' % (ann_file))
  133. logging.info("{} samples in file {}".format(
  134. len(self.file_list), ann_file))
  135. self.num_samples = len(self.file_list)