voc.py 17 KB

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