voc.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 random
  18. import re
  19. import numpy as np
  20. from collections import OrderedDict
  21. import xml.etree.ElementTree as ET
  22. from paddle.io import Dataset
  23. from paddlex.utils import logging, get_num_workers, get_encoding, path_normalization, is_pic
  24. from paddlex.cv.transforms import Decode, MixupImage
  25. class VOCDetection(Dataset):
  26. """读取PascalVOC格式的检测数据集,并对样本进行相应的处理。
  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. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  36. allow_empty (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. allow_empty=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. super(VOCDetection, self).__init__()
  53. self.data_fields = None
  54. self.transforms = copy.deepcopy(transforms)
  55. self.num_max_boxes = 50
  56. self.use_mix = False
  57. if self.transforms is not None:
  58. for op in self.transforms.transforms:
  59. if isinstance(op, MixupImage):
  60. self.mixup_op = copy.deepcopy(op)
  61. self.use_mix = True
  62. self.num_max_boxes *= 2
  63. break
  64. self.batch_transforms = None
  65. self.num_workers = get_num_workers(num_workers)
  66. self.shuffle = shuffle
  67. self.allow_empty = allow_empty
  68. self.file_list = list()
  69. self.neg_file_list = list()
  70. self.labels = list()
  71. annotations = dict()
  72. annotations['images'] = list()
  73. annotations['categories'] = list()
  74. annotations['annotations'] = list()
  75. cname2cid = OrderedDict()
  76. label_id = 0
  77. with open(label_list, 'r', encoding=get_encoding(label_list)) as f:
  78. for line in f.readlines():
  79. cname2cid[line.strip()] = label_id
  80. label_id += 1
  81. self.labels.append(line.strip())
  82. logging.info("Starting to read file list from dataset...")
  83. for k, v in cname2cid.items():
  84. annotations['categories'].append({
  85. 'supercategory': 'component',
  86. 'id': v + 1,
  87. 'name': k
  88. })
  89. ct = 0
  90. ann_ct = 0
  91. with open(file_list, 'r', encoding=get_encoding(file_list)) as f:
  92. while True:
  93. line = f.readline()
  94. if not line:
  95. break
  96. if len(line.strip().split()) > 2:
  97. raise Exception("A space is defined as the separator, "
  98. "but it exists in image or label name {}."
  99. .format(line))
  100. img_file, xml_file = [
  101. osp.join(data_dir, x) for x in line.strip().split()[:2]
  102. ]
  103. img_file = path_normalization(img_file)
  104. xml_file = path_normalization(xml_file)
  105. if not is_pic(img_file):
  106. continue
  107. if not osp.isfile(xml_file):
  108. continue
  109. if not osp.exists(img_file):
  110. logging.warning('The image file {} does not exist!'.format(
  111. img_file))
  112. continue
  113. if not osp.exists(xml_file):
  114. logging.warning('The annotation file {} does not exist!'.
  115. format(xml_file))
  116. continue
  117. tree = ET.parse(xml_file)
  118. if tree.find('id') is None:
  119. im_id = np.asarray([ct])
  120. else:
  121. ct = int(tree.find('id').text)
  122. im_id = np.asarray([int(tree.find('id').text)])
  123. pattern = re.compile('<size>', re.IGNORECASE)
  124. size_tag = pattern.findall(
  125. str(ET.tostringlist(tree.getroot())))
  126. if len(size_tag) > 0:
  127. size_tag = size_tag[0][1:-1]
  128. size_element = tree.find(size_tag)
  129. pattern = re.compile('<width>', re.IGNORECASE)
  130. width_tag = pattern.findall(
  131. str(ET.tostringlist(size_element)))[0][1:-1]
  132. im_w = float(size_element.find(width_tag).text)
  133. pattern = re.compile('<height>', re.IGNORECASE)
  134. height_tag = pattern.findall(
  135. str(ET.tostringlist(size_element)))[0][1:-1]
  136. im_h = float(size_element.find(height_tag).text)
  137. else:
  138. im_w = 0
  139. im_h = 0
  140. pattern = re.compile('<object>', re.IGNORECASE)
  141. obj_match = pattern.findall(
  142. str(ET.tostringlist(tree.getroot())))
  143. if len(obj_match) > 0:
  144. obj_tag = obj_match[0][1:-1]
  145. objs = tree.findall(obj_tag)
  146. else:
  147. objs = list()
  148. gt_bbox = list()
  149. gt_class = list()
  150. gt_score = list()
  151. is_crowd = list()
  152. difficult = list()
  153. for i, obj in enumerate(objs):
  154. pattern = re.compile('<name>', re.IGNORECASE)
  155. name_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
  156. 1:-1]
  157. cname = obj.find(name_tag).text.strip()
  158. pattern = re.compile('<difficult>', re.IGNORECASE)
  159. diff_tag = pattern.findall(str(ET.tostringlist(obj)))
  160. if len(diff_tag) == 0:
  161. _difficult = 0
  162. else:
  163. diff_tag = diff_tag[0][1:-1]
  164. try:
  165. _difficult = int(obj.find(diff_tag).text)
  166. except Exception:
  167. _difficult = 0
  168. pattern = re.compile('<bndbox>', re.IGNORECASE)
  169. box_tag = pattern.findall(str(ET.tostringlist(obj)))
  170. if len(box_tag) == 0:
  171. logging.warning(
  172. "There's no field '<bndbox>' in one of object, "
  173. "so this object will be ignored. xml file: {}".
  174. format(xml_file))
  175. continue
  176. box_tag = box_tag[0][1:-1]
  177. box_element = obj.find(box_tag)
  178. pattern = re.compile('<xmin>', re.IGNORECASE)
  179. xmin_tag = pattern.findall(
  180. str(ET.tostringlist(box_element)))[0][1:-1]
  181. x1 = float(box_element.find(xmin_tag).text)
  182. pattern = re.compile('<ymin>', re.IGNORECASE)
  183. ymin_tag = pattern.findall(
  184. str(ET.tostringlist(box_element)))[0][1:-1]
  185. y1 = float(box_element.find(ymin_tag).text)
  186. pattern = re.compile('<xmax>', re.IGNORECASE)
  187. xmax_tag = pattern.findall(
  188. str(ET.tostringlist(box_element)))[0][1:-1]
  189. x2 = float(box_element.find(xmax_tag).text)
  190. pattern = re.compile('<ymax>', re.IGNORECASE)
  191. ymax_tag = pattern.findall(
  192. str(ET.tostringlist(box_element)))[0][1:-1]
  193. y2 = float(box_element.find(ymax_tag).text)
  194. x1 = max(0, x1)
  195. y1 = max(0, y1)
  196. if im_w > 0.5 and im_h > 0.5:
  197. x2 = min(im_w - 1, x2)
  198. y2 = min(im_h - 1, y2)
  199. if not (x2 >= x1 and y2 >= y1):
  200. logging.warning(
  201. "Bounding box for object {} does not satisfy x1 <= x2 and y1 <= y2, "
  202. "so this object is skipped".format(i))
  203. continue
  204. gt_bbox.append([x1, y1, x2, y2])
  205. gt_class.append([cname2cid[cname]])
  206. gt_score.append([1.])
  207. is_crowd.append(0)
  208. difficult.append([_difficult])
  209. annotations['annotations'].append({
  210. 'iscrowd': 0,
  211. 'image_id': int(im_id[0]),
  212. 'bbox': [x1, y1, x2 - x1, y2 - y1],
  213. 'area': float((x2 - x1) * (y2 - y1)),
  214. 'category_id': cname2cid[cname] + 1,
  215. 'id': ann_ct,
  216. 'difficult': _difficult
  217. })
  218. ann_ct += 1
  219. gt_bbox = np.array(gt_bbox, dtype=np.float32)
  220. gt_class = np.array(gt_class, dtype=np.int32)
  221. gt_score = np.array(gt_score, dtype=np.float32)
  222. is_crowd = np.array(is_crowd, dtype=np.int32)
  223. difficult = np.array(difficult, dtype=np.int32)
  224. im_info = {
  225. 'im_id': im_id,
  226. 'image_shape': np.array(
  227. [im_h, im_w], dtype=np.int32),
  228. }
  229. label_info = {
  230. 'is_crowd': is_crowd,
  231. 'gt_class': gt_class,
  232. 'gt_bbox': gt_bbox,
  233. 'gt_score': gt_score,
  234. 'difficult': difficult
  235. }
  236. if gt_bbox.size > 0:
  237. self.file_list.append({
  238. 'image': img_file,
  239. **
  240. im_info,
  241. **
  242. label_info
  243. })
  244. annotations['images'].append({
  245. 'height': im_h,
  246. 'width': im_w,
  247. 'id': int(im_id[0]),
  248. 'file_name': osp.split(img_file)[1]
  249. })
  250. else:
  251. self.neg_file_list.append({
  252. 'image': img_file,
  253. **
  254. im_info,
  255. **
  256. label_info
  257. })
  258. ct += 1
  259. if self.use_mix:
  260. self.num_max_boxes = max(self.num_max_boxes, 2 * len(objs))
  261. else:
  262. self.num_max_boxes = max(self.num_max_boxes, len(objs))
  263. if not ct:
  264. logging.error(
  265. "No voc record found in %s' % (file_list)", exit=True)
  266. logging.info(
  267. "{} samples in file {}, including {} positive samples and {} negative samples.".
  268. format(
  269. len(self.file_list) + len(self.neg_file_list), file_list,
  270. len(self.file_list), len(self.neg_file_list)))
  271. if self.allow_empty:
  272. self.file_list += self.neg_file_list
  273. self.num_samples = len(self.file_list)
  274. self.coco_gt = COCO()
  275. self.coco_gt.dataset = annotations
  276. self.coco_gt.createIndex()
  277. self._epoch = 0
  278. def __getitem__(self, idx):
  279. sample = copy.deepcopy(self.file_list[idx])
  280. if self.data_fields is not None:
  281. sample = {k: sample[k] for k in self.data_fields}
  282. if self.use_mix and (self.mixup_op.mixup_epoch == -1 or
  283. self._epoch < self.mixup_op.mixup_epoch):
  284. if self.num_samples > 1:
  285. mix_idx = random.randint(1, self.num_samples - 1)
  286. mix_pos = (mix_idx + idx) % self.num_samples
  287. else:
  288. mix_pos = 0
  289. sample_mix = copy.deepcopy(self.file_list[mix_pos])
  290. if self.data_fields is not None:
  291. sample_mix = {k: sample_mix[k] for k in self.data_fields}
  292. sample = self.mixup_op(sample=[
  293. Decode(to_rgb=False)(sample), Decode(to_rgb=False)(sample_mix)
  294. ])
  295. sample = self.transforms(sample)
  296. return sample
  297. def __len__(self):
  298. return self.num_samples
  299. def set_epoch(self, epoch_id):
  300. self._epoch = epoch_id