voc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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
  17. import os.path as osp
  18. import random
  19. import re
  20. import numpy as np
  21. from collections import OrderedDict
  22. import xml.etree.ElementTree as ET
  23. from paddle.io import Dataset
  24. from paddlex.utils import logging, get_num_workers, get_encoding, path_normalization, is_pic
  25. from paddlex.cv.transforms import Decode, MixupImage
  26. class VOCDetection(Dataset):
  27. """读取PascalVOC格式的检测数据集,并对样本进行相应的处理。
  28. Args:
  29. data_dir (str): 数据集所在的目录路径。
  30. file_list (str): 描述数据集图片文件和对应标注文件的文件路径(文本内每行路径为相对data_dir的相对路)。
  31. label_list (str): 描述数据集包含的类别信息文件路径。
  32. transforms (paddlex.det.transforms): 数据集中每个样本的预处理/增强算子。
  33. num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
  34. 系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核数的
  35. 一半。
  36. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  37. """
  38. def __init__(self,
  39. data_dir,
  40. file_list,
  41. label_list,
  42. transforms=None,
  43. num_workers='auto',
  44. shuffle=False):
  45. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  46. # or matplotlib.backends is imported for the first time
  47. # pycocotools import matplotlib
  48. import matplotlib
  49. matplotlib.use('Agg')
  50. from pycocotools.coco import COCO
  51. super(VOCDetection, self).__init__()
  52. self.data_fields = None
  53. self.transforms = copy.deepcopy(transforms)
  54. self.num_max_boxes = 50
  55. self.use_mix = False
  56. if self.transforms is not None:
  57. for op in self.transforms.transforms:
  58. if isinstance(op, MixupImage):
  59. self.mixup_op = copy.deepcopy(op)
  60. self.use_mix = True
  61. self.num_max_boxes *= 2
  62. break
  63. self.batch_transforms = None
  64. self.num_workers = get_num_workers(num_workers)
  65. self.shuffle = shuffle
  66. self.file_list = list()
  67. self.labels = list()
  68. annotations = dict()
  69. annotations['images'] = list()
  70. annotations['categories'] = list()
  71. annotations['annotations'] = list()
  72. cname2cid = OrderedDict()
  73. label_id = 0
  74. with open(label_list, 'r', encoding=get_encoding(label_list)) as f:
  75. for line in f.readlines():
  76. cname2cid[line.strip()] = label_id
  77. label_id += 1
  78. self.labels.append(line.strip())
  79. logging.info("Starting to read file list from dataset...")
  80. for k, v in cname2cid.items():
  81. annotations['categories'].append({
  82. 'supercategory': 'component',
  83. 'id': v + 1,
  84. 'name': k
  85. })
  86. ct = 0
  87. ann_ct = 0
  88. with open(file_list, 'r', encoding=get_encoding(file_list)) as f:
  89. while True:
  90. line = f.readline()
  91. if not line:
  92. break
  93. if len(line.strip().split()) > 2:
  94. raise Exception("A space is defined as the separator, "
  95. "but it exists in image or label name {}."
  96. .format(line))
  97. img_file, xml_file = [
  98. osp.join(data_dir, x) for x in line.strip().split()[:2]
  99. ]
  100. img_file = path_normalization(img_file)
  101. xml_file = path_normalization(xml_file)
  102. if not is_pic(img_file):
  103. continue
  104. if not osp.isfile(xml_file):
  105. continue
  106. if not osp.exists(img_file):
  107. logging.warning('The image file {} does not exist!'.format(
  108. img_file))
  109. continue
  110. if not osp.exists(xml_file):
  111. logging.warning('The annotation file {} does not exist!'.
  112. format(xml_file))
  113. continue
  114. tree = ET.parse(xml_file)
  115. if tree.find('id') is None:
  116. im_id = np.array([ct])
  117. else:
  118. ct = int(tree.find('id').text)
  119. im_id = np.array([int(tree.find('id').text)])
  120. pattern = re.compile('<object>', re.IGNORECASE)
  121. obj_match = pattern.findall(
  122. str(ET.tostringlist(tree.getroot())))
  123. if len(obj_match) == 0:
  124. continue
  125. obj_tag = obj_match[0][1:-1]
  126. objs = tree.findall(obj_tag)
  127. pattern = re.compile('<size>', re.IGNORECASE)
  128. size_tag = pattern.findall(
  129. str(ET.tostringlist(tree.getroot())))
  130. if len(size_tag) > 0:
  131. size_tag = size_tag[0][1:-1]
  132. size_element = tree.find(size_tag)
  133. pattern = re.compile('<width>', re.IGNORECASE)
  134. width_tag = pattern.findall(
  135. str(ET.tostringlist(size_element)))[0][1:-1]
  136. im_w = float(size_element.find(width_tag).text)
  137. pattern = re.compile('<height>', re.IGNORECASE)
  138. height_tag = pattern.findall(
  139. str(ET.tostringlist(size_element)))[0][1:-1]
  140. im_h = float(size_element.find(height_tag).text)
  141. else:
  142. im_w = 0
  143. im_h = 0
  144. gt_bbox = np.zeros((len(objs), 4), dtype=np.float32)
  145. gt_class = np.zeros((len(objs), 1), dtype=np.int32)
  146. gt_score = np.ones((len(objs), 1), dtype=np.float32)
  147. is_crowd = np.zeros((len(objs), 1), dtype=np.int32)
  148. difficult = np.zeros((len(objs), 1), dtype=np.int32)
  149. skipped_indices = list()
  150. for i, obj in enumerate(objs):
  151. pattern = re.compile('<name>', re.IGNORECASE)
  152. name_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
  153. 1:-1]
  154. cname = obj.find(name_tag).text.strip()
  155. gt_class[i][0] = cname2cid[cname]
  156. pattern = re.compile('<difficult>', re.IGNORECASE)
  157. diff_tag = pattern.findall(str(ET.tostringlist(obj)))
  158. if len(diff_tag) == 0:
  159. _difficult = 0
  160. else:
  161. diff_tag = diff_tag[0][1:-1]
  162. try:
  163. _difficult = int(obj.find(diff_tag).text)
  164. except Exception:
  165. _difficult = 0
  166. pattern = re.compile('<bndbox>', re.IGNORECASE)
  167. box_tag = pattern.findall(str(ET.tostringlist(obj)))
  168. if len(box_tag) == 0:
  169. logging.warning(
  170. "There's no field '<bndbox>' in one of object, "
  171. "so this object will be ignored. xml file: {}".
  172. format(xml_file))
  173. continue
  174. box_tag = box_tag[0][1:-1]
  175. box_element = obj.find(box_tag)
  176. pattern = re.compile('<xmin>', re.IGNORECASE)
  177. xmin_tag = pattern.findall(
  178. str(ET.tostringlist(box_element)))[0][1:-1]
  179. x1 = float(box_element.find(xmin_tag).text)
  180. pattern = re.compile('<ymin>', re.IGNORECASE)
  181. ymin_tag = pattern.findall(
  182. str(ET.tostringlist(box_element)))[0][1:-1]
  183. y1 = float(box_element.find(ymin_tag).text)
  184. pattern = re.compile('<xmax>', re.IGNORECASE)
  185. xmax_tag = pattern.findall(
  186. str(ET.tostringlist(box_element)))[0][1:-1]
  187. x2 = float(box_element.find(xmax_tag).text)
  188. pattern = re.compile('<ymax>', re.IGNORECASE)
  189. ymax_tag = pattern.findall(
  190. str(ET.tostringlist(box_element)))[0][1:-1]
  191. y2 = float(box_element.find(ymax_tag).text)
  192. x1 = max(0, x1)
  193. y1 = max(0, y1)
  194. if im_w > 0.5 and im_h > 0.5:
  195. x2 = min(im_w - 1, x2)
  196. y2 = min(im_h - 1, y2)
  197. if not (x2 >= x1 and y2 >= y1):
  198. skipped_indices.append(i)
  199. logging.warning(
  200. "Bounding box for object {} does not satisfy x1 <= x2 and y1 <= y2, "
  201. "so this object is skipped".format(i))
  202. continue
  203. gt_bbox[i] = [x1, y1, x2, y2]
  204. is_crowd[i][0] = 0
  205. difficult[i][0] = _difficult
  206. annotations['annotations'].append({
  207. 'iscrowd': 0,
  208. 'image_id': int(im_id[0]),
  209. 'bbox': [x1, y1, x2 - x1 + 1, y2 - y1 + 1],
  210. 'area': float((x2 - x1 + 1) * (y2 - y1 + 1)),
  211. 'category_id': cname2cid[cname] + 1,
  212. 'id': ann_ct,
  213. 'difficult': _difficult
  214. })
  215. ann_ct += 1
  216. if skipped_indices:
  217. gt_bbox = np.delete(gt_bbox, skipped_indices, axis=0)
  218. gt_class = np.delete(gt_class, skipped_indices, axis=0)
  219. gt_score = np.delete(gt_score, skipped_indices, axis=0)
  220. is_crowd = np.delete(is_crowd, skipped_indices, axis=0)
  221. difficult = np.delete(difficult, skipped_indices, axis=0)
  222. im_info = {
  223. 'im_id': im_id,
  224. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  225. }
  226. label_info = {
  227. 'is_crowd': is_crowd,
  228. 'gt_class': gt_class,
  229. 'gt_bbox': gt_bbox,
  230. 'gt_score': gt_score,
  231. 'difficult': difficult
  232. }
  233. if gt_bbox.size != 0:
  234. self.file_list.append({
  235. 'image': img_file,
  236. **
  237. im_info,
  238. **
  239. label_info
  240. })
  241. ct += 1
  242. annotations['images'].append({
  243. 'height': im_h,
  244. 'width': im_w,
  245. 'id': int(im_id[0]),
  246. 'file_name': osp.split(img_file)[1]
  247. })
  248. if self.use_mix:
  249. self.num_max_boxes = max(self.num_max_boxes, 2 * len(objs))
  250. else:
  251. self.num_max_boxes = max(self.num_max_boxes, len(objs))
  252. if not len(self.file_list) > 0:
  253. raise Exception('not found any voc record in %s' % (file_list))
  254. logging.info("{} samples in file {}".format(
  255. len(self.file_list), file_list))
  256. self.num_samples = len(self.file_list)
  257. self.coco_gt = COCO()
  258. self.coco_gt.dataset = annotations
  259. self.coco_gt.createIndex()
  260. self._epoch = 0
  261. def __getitem__(self, idx):
  262. sample = copy.deepcopy(self.file_list[idx])
  263. if self.data_fields is not None:
  264. sample = {k: sample[k] for k in self.data_fields}
  265. if self.use_mix and (self.mixup_op.mixup_epoch == -1 or
  266. self._epoch < self.mixup_op.mixup_epoch):
  267. if self.num_samples > 1:
  268. mix_idx = random.randint(1, self.num_samples - 1)
  269. mix_pos = (mix_idx + idx) % self.num_samples
  270. else:
  271. mix_pos = 0
  272. sample_mix = copy.deepcopy(self.file_list[mix_pos])
  273. if self.data_fields is not None:
  274. sample_mix = {k: sample_mix[k] for k in self.data_fields}
  275. sample = self.mixup_op(sample=[
  276. Decode(to_rgb=False)(sample), Decode(to_rgb=False)(sample_mix)
  277. ])
  278. sample = self.transforms(sample)
  279. return sample
  280. def __len__(self):
  281. return self.num_samples
  282. def set_epoch(self, epoch_id):
  283. self._epoch = epoch_id