voc.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. allow_empty (bool): 是否加载负样本。默认为False。
  38. """
  39. def __init__(self,
  40. data_dir,
  41. file_list,
  42. label_list,
  43. transforms=None,
  44. num_workers='auto',
  45. shuffle=False,
  46. allow_empty=False):
  47. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  48. # or matplotlib.backends is imported for the first time
  49. # pycocotools import matplotlib
  50. import matplotlib
  51. matplotlib.use('Agg')
  52. from pycocotools.coco import COCO
  53. super(VOCDetection, self).__init__()
  54. self.data_fields = None
  55. self.transforms = copy.deepcopy(transforms)
  56. self.num_max_boxes = 50
  57. self.use_mix = False
  58. if self.transforms is not None:
  59. for op in self.transforms.transforms:
  60. if isinstance(op, MixupImage):
  61. self.mixup_op = copy.deepcopy(op)
  62. self.use_mix = True
  63. self.num_max_boxes *= 2
  64. break
  65. self.batch_transforms = None
  66. self.num_workers = get_num_workers(num_workers)
  67. self.shuffle = shuffle
  68. self.allow_empty = allow_empty
  69. self.file_list = list()
  70. self.neg_file_list = list()
  71. self.labels = list()
  72. annotations = dict()
  73. annotations['images'] = list()
  74. annotations['categories'] = list()
  75. annotations['annotations'] = list()
  76. cname2cid = OrderedDict()
  77. label_id = 0
  78. with open(label_list, 'r', encoding=get_encoding(label_list)) as f:
  79. for line in f.readlines():
  80. cname2cid[line.strip()] = label_id
  81. label_id += 1
  82. self.labels.append(line.strip())
  83. logging.info("Starting to read file list from dataset...")
  84. for k, v in cname2cid.items():
  85. annotations['categories'].append({
  86. 'supercategory': 'component',
  87. 'id': v + 1,
  88. 'name': k
  89. })
  90. ct = 0
  91. ann_ct = 0
  92. with open(file_list, 'r', encoding=get_encoding(file_list)) as f:
  93. while True:
  94. line = f.readline()
  95. if not line:
  96. break
  97. if len(line.strip().split()) > 2:
  98. raise Exception("A space is defined as the separator, "
  99. "but it exists in image or label name {}."
  100. .format(line))
  101. img_file, xml_file = [
  102. osp.join(data_dir, x) for x in line.strip().split()[:2]
  103. ]
  104. img_file = path_normalization(img_file)
  105. xml_file = path_normalization(xml_file)
  106. if not is_pic(img_file):
  107. continue
  108. if not osp.isfile(xml_file):
  109. continue
  110. if not osp.exists(img_file):
  111. logging.warning('The image file {} does not exist!'.format(
  112. img_file))
  113. continue
  114. if not osp.exists(xml_file):
  115. logging.warning('The annotation file {} does not exist!'.
  116. format(xml_file))
  117. continue
  118. tree = ET.parse(xml_file)
  119. if tree.find('id') is None:
  120. im_id = np.asarray([ct])
  121. else:
  122. ct = int(tree.find('id').text)
  123. im_id = np.asarray([int(tree.find('id').text)])
  124. pattern = re.compile('<size>', re.IGNORECASE)
  125. size_tag = pattern.findall(
  126. str(ET.tostringlist(tree.getroot())))
  127. if len(size_tag) > 0:
  128. size_tag = size_tag[0][1:-1]
  129. size_element = tree.find(size_tag)
  130. pattern = re.compile('<width>', re.IGNORECASE)
  131. width_tag = pattern.findall(
  132. str(ET.tostringlist(size_element)))[0][1:-1]
  133. im_w = float(size_element.find(width_tag).text)
  134. pattern = re.compile('<height>', re.IGNORECASE)
  135. height_tag = pattern.findall(
  136. str(ET.tostringlist(size_element)))[0][1:-1]
  137. im_h = float(size_element.find(height_tag).text)
  138. else:
  139. im_w = 0
  140. im_h = 0
  141. pattern = re.compile('<object>', re.IGNORECASE)
  142. obj_match = pattern.findall(
  143. str(ET.tostringlist(tree.getroot())))
  144. if len(obj_match) > 0:
  145. obj_tag = obj_match[0][1:-1]
  146. objs = tree.findall(obj_tag)
  147. else:
  148. objs = list()
  149. gt_bbox = list()
  150. gt_class = list()
  151. gt_score = list()
  152. is_crowd = list()
  153. difficult = list()
  154. for i, obj in enumerate(objs):
  155. pattern = re.compile('<name>', re.IGNORECASE)
  156. name_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
  157. 1:-1]
  158. cname = obj.find(name_tag).text.strip()
  159. pattern = re.compile('<difficult>', re.IGNORECASE)
  160. diff_tag = pattern.findall(str(ET.tostringlist(obj)))
  161. if len(diff_tag) == 0:
  162. _difficult = 0
  163. else:
  164. diff_tag = diff_tag[0][1:-1]
  165. try:
  166. _difficult = int(obj.find(diff_tag).text)
  167. except Exception:
  168. _difficult = 0
  169. pattern = re.compile('<bndbox>', re.IGNORECASE)
  170. box_tag = pattern.findall(str(ET.tostringlist(obj)))
  171. if len(box_tag) == 0:
  172. logging.warning(
  173. "There's no field '<bndbox>' in one of object, "
  174. "so this object will be ignored. xml file: {}".
  175. format(xml_file))
  176. continue
  177. box_tag = box_tag[0][1:-1]
  178. box_element = obj.find(box_tag)
  179. pattern = re.compile('<xmin>', re.IGNORECASE)
  180. xmin_tag = pattern.findall(
  181. str(ET.tostringlist(box_element)))[0][1:-1]
  182. x1 = float(box_element.find(xmin_tag).text)
  183. pattern = re.compile('<ymin>', re.IGNORECASE)
  184. ymin_tag = pattern.findall(
  185. str(ET.tostringlist(box_element)))[0][1:-1]
  186. y1 = float(box_element.find(ymin_tag).text)
  187. pattern = re.compile('<xmax>', re.IGNORECASE)
  188. xmax_tag = pattern.findall(
  189. str(ET.tostringlist(box_element)))[0][1:-1]
  190. x2 = float(box_element.find(xmax_tag).text)
  191. pattern = re.compile('<ymax>', re.IGNORECASE)
  192. ymax_tag = pattern.findall(
  193. str(ET.tostringlist(box_element)))[0][1:-1]
  194. y2 = float(box_element.find(ymax_tag).text)
  195. x1 = max(0, x1)
  196. y1 = max(0, y1)
  197. if im_w > 0.5 and im_h > 0.5:
  198. x2 = min(im_w - 1, x2)
  199. y2 = min(im_h - 1, y2)
  200. if not (x2 >= x1 and y2 >= y1):
  201. logging.warning(
  202. "Bounding box for object {} does not satisfy x1 <= x2 and y1 <= y2, "
  203. "so this object is skipped".format(i))
  204. continue
  205. gt_bbox.append([x1, y1, x2, y2])
  206. gt_class.append([cname2cid[cname]])
  207. gt_score.append([1.])
  208. is_crowd.append(0)
  209. difficult.append([_difficult])
  210. annotations['annotations'].append({
  211. 'iscrowd': 0,
  212. 'image_id': int(im_id[0]),
  213. 'bbox': [x1, y1, x2 - x1, y2 - y1],
  214. 'area': float((x2 - x1) * (y2 - y1)),
  215. 'category_id': cname2cid[cname] + 1,
  216. 'id': ann_ct,
  217. 'difficult': _difficult
  218. })
  219. ann_ct += 1
  220. gt_bbox = np.array(gt_bbox, dtype=np.float32)
  221. gt_class = np.array(gt_class, dtype=np.int32)
  222. gt_score = np.array(gt_score, dtype=np.float32)
  223. is_crowd = np.array(is_crowd, dtype=np.int32)
  224. difficult = np.array(difficult, dtype=np.int32)
  225. im_info = {
  226. 'im_id': im_id,
  227. 'image_shape': np.array(
  228. [im_h, im_w], dtype=np.int32)
  229. }
  230. label_info = {
  231. 'is_crowd': is_crowd,
  232. 'gt_class': gt_class,
  233. 'gt_bbox': gt_bbox,
  234. 'gt_score': gt_score,
  235. 'difficult': difficult
  236. }
  237. if gt_bbox.size > 0:
  238. self.file_list.append({
  239. 'image': img_file,
  240. **
  241. im_info,
  242. **
  243. label_info
  244. })
  245. annotations['images'].append({
  246. 'height': im_h,
  247. 'width': im_w,
  248. 'id': int(im_id[0]),
  249. 'file_name': osp.split(img_file)[1]
  250. })
  251. else:
  252. self.neg_file_list.append({
  253. 'image': img_file,
  254. **
  255. im_info,
  256. **
  257. label_info
  258. })
  259. ct += 1
  260. if self.use_mix:
  261. self.num_max_boxes = max(self.num_max_boxes, 2 * len(objs))
  262. else:
  263. self.num_max_boxes = max(self.num_max_boxes, len(objs))
  264. if not ct:
  265. logging.error(
  266. "No voc record found in %s' % (file_list)", exit=True)
  267. logging.info(
  268. "{} samples in file {}, including {} positive samples and {} negative samples.".
  269. format(
  270. len(self.file_list) + len(self.neg_file_list), file_list,
  271. len(self.file_list), len(self.neg_file_list)))
  272. if self.allow_empty:
  273. self.file_list += self.neg_file_list
  274. self.num_samples = len(self.file_list)
  275. self.coco_gt = COCO()
  276. self.coco_gt.dataset = annotations
  277. self.coco_gt.createIndex()
  278. self._epoch = 0
  279. def __getitem__(self, idx):
  280. sample = copy.deepcopy(self.file_list[idx])
  281. if self.data_fields is not None:
  282. sample = {k: sample[k] for k in self.data_fields}
  283. if self.use_mix and (self.mixup_op.mixup_epoch == -1 or
  284. self._epoch < self.mixup_op.mixup_epoch):
  285. if self.num_samples > 1:
  286. mix_idx = random.randint(1, self.num_samples - 1)
  287. mix_pos = (mix_idx + idx) % self.num_samples
  288. else:
  289. mix_pos = 0
  290. sample_mix = copy.deepcopy(self.file_list[mix_pos])
  291. if self.data_fields is not None:
  292. sample_mix = {k: sample_mix[k] for k in self.data_fields}
  293. sample = self.mixup_op(sample=[
  294. Decode(to_rgb=False)(sample), Decode(to_rgb=False)(sample_mix)
  295. ])
  296. sample = self.transforms(sample)
  297. return sample
  298. def __len__(self):
  299. return self.num_samples
  300. def set_epoch(self, epoch_id):
  301. self._epoch = epoch_id
  302. def add_negative_samples(self, image_dir):
  303. """将背景图片加入训练
  304. Args:
  305. image_dir (str):背景图片所在的文件夹目录。
  306. """
  307. import cv2
  308. if not osp.isdir(image_dir):
  309. raise Exception("{} is not a valid image directory.".format(
  310. image_dir))
  311. image_list = os.listdir(image_dir)
  312. max_img_id = len(self.file_list)
  313. ct = 0
  314. for image in image_list:
  315. if not is_pic(image):
  316. continue
  317. gt_bbox = np.array([], dtype=np.float32)
  318. gt_class = np.array([], dtype=np.int32)
  319. gt_score = np.array([], dtype=np.float32)
  320. is_crowd = np.array([], dtype=np.int32)
  321. difficult = np.array([], dtype=np.int32)
  322. max_img_id += 1
  323. im_fname = osp.join(image_dir, image)
  324. img_data = cv2.imread(im_fname, cv2.IMREAD_UNCHANGED)
  325. im_h, im_w, im_c = img_data.shape
  326. im_info = {
  327. 'im_id': np.asarray([max_img_id]),
  328. 'image_shape': np.array(
  329. [im_h, im_w], dtype=np.int32)
  330. }
  331. label_info = {
  332. 'is_crowd': is_crowd,
  333. 'gt_class': gt_class,
  334. 'gt_bbox': gt_bbox,
  335. 'gt_score': gt_score,
  336. 'difficult': difficult
  337. }
  338. if 'gt_poly' in self.file_list[0]:
  339. label_info['gt_poly'] = []
  340. self.neg_file_list.append({
  341. 'image': im_fname,
  342. **
  343. im_info,
  344. **
  345. label_info
  346. })
  347. self.file_list.append({
  348. 'image': im_fname,
  349. **
  350. im_info,
  351. **
  352. label_info
  353. })
  354. ct += 1
  355. self.num_samples = len(self.file_list)
  356. logging.info("{} negative samples added.".format(ct))