easydata_det.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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 random
  17. import copy
  18. import json
  19. import cv2
  20. import numpy as np
  21. import paddlex.utils.logging as logging
  22. from .voc import VOCDetection
  23. from .dataset import is_pic
  24. from .dataset import get_encoding
  25. class EasyDataDet(VOCDetection):
  26. """读取EasyDataDet格式的检测数据集,并对样本进行相应的处理。
  27. Args:
  28. data_dir (str): 数据集所在的目录路径。
  29. file_list (str): 描述数据集图片文件和对应标注文件的文件路径(文本内每行路径为相对data_dir的相对路)。
  30. label_list (str): 描述数据集包含的类别信息文件路径。
  31. transforms (paddlex.det.transforms): 数据集中每个样本的预处理/增强算子。
  32. num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
  33. 系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核数的
  34. 一半。
  35. buffer_size (int): 数据集中样本在预处理过程中队列的缓存长度,以样本数为单位。默认为100。
  36. parallel_method (str): 数据集中样本在预处理过程中并行处理的方式,支持'thread'
  37. 线程和'process'进程两种方式。默认为'process'(Windows和Mac下会强制使用thread,该参数无效)。
  38. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  39. """
  40. def __init__(self,
  41. data_dir,
  42. file_list,
  43. label_list,
  44. transforms=None,
  45. num_workers='auto',
  46. buffer_size=100,
  47. parallel_method='process',
  48. shuffle=False):
  49. super(VOCDetection, self).__init__(
  50. transforms=transforms,
  51. num_workers=num_workers,
  52. buffer_size=buffer_size,
  53. parallel_method=parallel_method,
  54. shuffle=shuffle)
  55. self.file_list = list()
  56. self.labels = list()
  57. self._epoch = 0
  58. annotations = {}
  59. annotations['images'] = []
  60. annotations['categories'] = []
  61. annotations['annotations'] = []
  62. cname2cid = {}
  63. label_id = 1
  64. with open(label_list, encoding=get_encoding(label_list)) as fr:
  65. for line in fr.readlines():
  66. cname2cid[line.strip()] = label_id
  67. label_id += 1
  68. self.labels.append(line.strip())
  69. logging.info("Starting to read file list from dataset...")
  70. for k, v in cname2cid.items():
  71. annotations['categories'].append({
  72. 'supercategory': 'component',
  73. 'id': v,
  74. 'name': k
  75. })
  76. from pycocotools.mask import decode
  77. ct = 0
  78. ann_ct = 0
  79. with open(file_list, encoding=get_encoding(file_list)) as f:
  80. for line in f:
  81. img_file, json_file = [osp.join(data_dir, x) \
  82. for x in line.strip().split()[:2]]
  83. if not is_pic(img_file):
  84. continue
  85. if not osp.isfile(json_file):
  86. continue
  87. if not osp.exists(img_file):
  88. raise IOError(
  89. 'The image file {} is not exist!'.format(img_file))
  90. with open(json_file, mode='r', \
  91. encoding=get_encoding(json_file)) as j:
  92. json_info = json.load(j)
  93. im_id = np.array([ct])
  94. im = cv2.imread(img_file)
  95. im_w = im.shape[1]
  96. im_h = im.shape[0]
  97. objs = json_info['labels']
  98. gt_bbox = np.zeros((len(objs), 4), dtype=np.float32)
  99. gt_class = np.zeros((len(objs), 1), dtype=np.int32)
  100. gt_score = np.ones((len(objs), 1), dtype=np.float32)
  101. is_crowd = np.zeros((len(objs), 1), dtype=np.int32)
  102. difficult = np.zeros((len(objs), 1), dtype=np.int32)
  103. gt_poly = [None] * len(objs)
  104. for i, obj in enumerate(objs):
  105. cname = obj['name']
  106. gt_class[i][0] = cname2cid[cname]
  107. x1 = max(0, obj['x1'])
  108. y1 = max(0, obj['y1'])
  109. x2 = min(im_w - 1, obj['x2'])
  110. y2 = min(im_h - 1, obj['y2'])
  111. gt_bbox[i] = [x1, y1, x2, y2]
  112. is_crowd[i][0] = 0
  113. if 'mask' in obj:
  114. mask_dict = {}
  115. mask_dict['size'] = [im_h, im_w]
  116. mask_dict['counts'] = obj['mask'].encode()
  117. mask = decode(mask_dict)
  118. gt_poly[i] = self.mask2polygon(mask)
  119. annotations['annotations'].append({
  120. 'iscrowd':
  121. 0,
  122. 'image_id':
  123. int(im_id[0]),
  124. 'bbox': [x1, y1, x2 - x1 + 1, y2 - y1 + 1],
  125. 'area':
  126. float((x2 - x1 + 1) * (y2 - y1 + 1)),
  127. 'segmentation':
  128. [[x1, y1, x1, y2, x2, y2, x2, y1]] if gt_poly[i] is None else gt_poly[i],
  129. 'category_id':
  130. cname2cid[cname],
  131. 'id':
  132. ann_ct,
  133. 'difficult':
  134. 0
  135. })
  136. ann_ct += 1
  137. im_info = {
  138. 'im_id': im_id,
  139. 'origin_shape': np.array([im_h, im_w]).astype('int32'),
  140. }
  141. label_info = {
  142. 'is_crowd': is_crowd,
  143. 'gt_class': gt_class,
  144. 'gt_bbox': gt_bbox,
  145. 'gt_score': gt_score,
  146. 'difficult': difficult
  147. }
  148. if None not in gt_poly:
  149. label_info['gt_poly'] = gt_poly
  150. voc_rec = (im_info, label_info)
  151. if len(objs) != 0:
  152. self.file_list.append([img_file, voc_rec])
  153. ct += 1
  154. annotations['images'].append({
  155. 'height':
  156. im_h,
  157. 'width':
  158. im_w,
  159. 'id':
  160. int(im_id[0]),
  161. 'file_name':
  162. osp.split(img_file)[1]
  163. })
  164. if not len(self.file_list) > 0:
  165. raise Exception('not found any voc record in %s' % (file_list))
  166. logging.info("{} samples in file {}".format(
  167. len(self.file_list), file_list))
  168. self.num_samples = len(self.file_list)
  169. from pycocotools.coco import COCO
  170. self.coco_gt = COCO()
  171. self.coco_gt.dataset = annotations
  172. self.coco_gt.createIndex()
  173. def mask2polygon(self, mask):
  174. contours, hierarchy = cv2.findContours(
  175. (mask).astype(np.uint8), cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  176. segmentation = []
  177. for contour in contours:
  178. contour_list = contour.flatten().tolist()
  179. if len(contour_list) > 4:
  180. segmentation.append(contour_list)
  181. return segmentation