coco.py 6.9 KB

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