voc.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. from paddlex.tools import YOLOAnchorCluster
  27. class VOCDetection(Dataset):
  28. """读取PascalVOC格式的检测数据集,并对样本进行相应的处理。
  29. Args:
  30. data_dir (str): 数据集所在的目录路径。
  31. file_list (str): 描述数据集图片文件和对应标注文件的文件路径(文本内每行路径为相对data_dir的相对路)。
  32. label_list (str): 描述数据集包含的类别信息文件路径。
  33. transforms (paddlex.det.transforms): 数据集中每个样本的预处理/增强算子。
  34. num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
  35. 系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核数的
  36. 一半。
  37. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  38. allow_empty (bool): 是否加载负样本。默认为False。
  39. empty_ratio (float): 用于指定负样本占总样本数的比例。如果小于0或大于等于1,则保留全部的负样本。默认为1。
  40. """
  41. def __init__(self,
  42. data_dir,
  43. file_list,
  44. label_list,
  45. transforms=None,
  46. num_workers='auto',
  47. shuffle=False,
  48. allow_empty=False,
  49. empty_ratio=1.):
  50. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  51. # or matplotlib.backends is imported for the first time
  52. # pycocotools import matplotlib
  53. import matplotlib
  54. matplotlib.use('Agg')
  55. from pycocotools.coco import COCO
  56. super(VOCDetection, self).__init__()
  57. self.data_dir = data_dir
  58. self.data_fields = None
  59. self.transforms = copy.deepcopy(transforms)
  60. self.num_max_boxes = 50
  61. self.use_mix = False
  62. if self.transforms is not None:
  63. for op in self.transforms.transforms:
  64. if isinstance(op, MixupImage):
  65. self.mixup_op = copy.deepcopy(op)
  66. self.use_mix = True
  67. self.num_max_boxes *= 2
  68. break
  69. self.batch_transforms = None
  70. self.num_workers = get_num_workers(num_workers)
  71. self.shuffle = shuffle
  72. self.allow_empty = allow_empty
  73. self.empty_ratio = empty_ratio
  74. self.file_list = list()
  75. neg_file_list = list()
  76. self.labels = list()
  77. annotations = dict()
  78. annotations['images'] = list()
  79. annotations['categories'] = list()
  80. annotations['annotations'] = list()
  81. cname2cid = OrderedDict()
  82. label_id = 0
  83. with open(label_list, 'r', encoding=get_encoding(label_list)) as f:
  84. for line in f.readlines():
  85. cname2cid[line.strip()] = label_id
  86. label_id += 1
  87. self.labels.append(line.strip())
  88. logging.info("Starting to read file list from dataset...")
  89. for k, v in cname2cid.items():
  90. annotations['categories'].append({
  91. 'supercategory': 'component',
  92. 'id': v + 1,
  93. 'name': k
  94. })
  95. ct = 0
  96. ann_ct = 0
  97. with open(file_list, 'r', encoding=get_encoding(file_list)) as f:
  98. while True:
  99. line = f.readline()
  100. if not line:
  101. break
  102. if len(line.strip().split()) > 2:
  103. raise Exception("A space is defined as the separator, "
  104. "but it exists in image or label name {}."
  105. .format(line))
  106. img_file, xml_file = [
  107. osp.join(data_dir, x) for x in line.strip().split()[:2]
  108. ]
  109. img_file = path_normalization(img_file)
  110. xml_file = path_normalization(xml_file)
  111. if not is_pic(img_file):
  112. continue
  113. if not osp.isfile(xml_file):
  114. continue
  115. if not osp.exists(img_file):
  116. logging.warning('The image file {} does not exist!'.format(
  117. img_file))
  118. continue
  119. if not osp.exists(xml_file):
  120. logging.warning('The annotation file {} does not exist!'.
  121. format(xml_file))
  122. continue
  123. tree = ET.parse(xml_file)
  124. if tree.find('id') is None:
  125. im_id = np.asarray([ct])
  126. else:
  127. ct = int(tree.find('id').text)
  128. im_id = np.asarray([int(tree.find('id').text)])
  129. pattern = re.compile('<size>', re.IGNORECASE)
  130. size_tag = pattern.findall(
  131. str(ET.tostringlist(tree.getroot())))
  132. if len(size_tag) > 0:
  133. size_tag = size_tag[0][1:-1]
  134. size_element = tree.find(size_tag)
  135. pattern = re.compile('<width>', re.IGNORECASE)
  136. width_tag = pattern.findall(
  137. str(ET.tostringlist(size_element)))[0][1:-1]
  138. im_w = float(size_element.find(width_tag).text)
  139. pattern = re.compile('<height>', re.IGNORECASE)
  140. height_tag = pattern.findall(
  141. str(ET.tostringlist(size_element)))[0][1:-1]
  142. im_h = float(size_element.find(height_tag).text)
  143. else:
  144. im_w = 0
  145. im_h = 0
  146. pattern = re.compile('<object>', re.IGNORECASE)
  147. obj_match = pattern.findall(
  148. str(ET.tostringlist(tree.getroot())))
  149. if len(obj_match) > 0:
  150. obj_tag = obj_match[0][1:-1]
  151. objs = tree.findall(obj_tag)
  152. else:
  153. objs = list()
  154. num_bbox, i = len(objs), 0
  155. gt_bbox = np.zeros((num_bbox, 4), dtype=np.float32)
  156. gt_class = np.zeros((num_bbox, 1), dtype=np.int32)
  157. gt_score = np.zeros((num_bbox, 1), dtype=np.float32)
  158. is_crowd = np.zeros((num_bbox, 1), dtype=np.int32)
  159. difficult = np.zeros((num_bbox, 1), dtype=np.int32)
  160. for obj in objs:
  161. pattern = re.compile('<name>', re.IGNORECASE)
  162. name_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
  163. 1:-1]
  164. cname = obj.find(name_tag).text.strip()
  165. pattern = re.compile('<difficult>', re.IGNORECASE)
  166. diff_tag = pattern.findall(str(ET.tostringlist(obj)))
  167. if len(diff_tag) == 0:
  168. _difficult = 0
  169. else:
  170. diff_tag = diff_tag[0][1:-1]
  171. try:
  172. _difficult = int(obj.find(diff_tag).text)
  173. except Exception:
  174. _difficult = 0
  175. pattern = re.compile('<bndbox>', re.IGNORECASE)
  176. box_tag = pattern.findall(str(ET.tostringlist(obj)))
  177. if len(box_tag) == 0:
  178. logging.warning(
  179. "There's no field '<bndbox>' in one of object, "
  180. "so this object will be ignored. xml file: {}".
  181. format(xml_file))
  182. continue
  183. box_tag = box_tag[0][1:-1]
  184. box_element = obj.find(box_tag)
  185. pattern = re.compile('<xmin>', re.IGNORECASE)
  186. xmin_tag = pattern.findall(
  187. str(ET.tostringlist(box_element)))[0][1:-1]
  188. x1 = float(box_element.find(xmin_tag).text)
  189. pattern = re.compile('<ymin>', re.IGNORECASE)
  190. ymin_tag = pattern.findall(
  191. str(ET.tostringlist(box_element)))[0][1:-1]
  192. y1 = float(box_element.find(ymin_tag).text)
  193. pattern = re.compile('<xmax>', re.IGNORECASE)
  194. xmax_tag = pattern.findall(
  195. str(ET.tostringlist(box_element)))[0][1:-1]
  196. x2 = float(box_element.find(xmax_tag).text)
  197. pattern = re.compile('<ymax>', re.IGNORECASE)
  198. ymax_tag = pattern.findall(
  199. str(ET.tostringlist(box_element)))[0][1:-1]
  200. y2 = float(box_element.find(ymax_tag).text)
  201. x1 = max(0, x1)
  202. y1 = max(0, y1)
  203. if im_w > 0.5 and im_h > 0.5:
  204. x2 = min(im_w - 1, x2)
  205. y2 = min(im_h - 1, y2)
  206. if not (x2 >= x1 and y2 >= y1):
  207. logging.warning(
  208. "Bounding box for object {} does not satisfy x1 <= x2 and y1 <= y2, "
  209. "so this object is skipped".format(i))
  210. continue
  211. gt_bbox[i, :] = [x1, y1, x2, y2]
  212. gt_class[i, 0] = cname2cid[cname]
  213. gt_score[i, 0] = 1.
  214. is_crowd[i, 0] = 0
  215. difficult[i, 0] = _difficult
  216. i += 1
  217. annotations['annotations'].append({
  218. 'iscrowd': 0,
  219. 'image_id': int(im_id[0]),
  220. 'bbox': [x1, y1, x2 - x1, y2 - y1],
  221. 'area': float((x2 - x1) * (y2 - y1)),
  222. 'category_id': cname2cid[cname] + 1,
  223. 'id': ann_ct,
  224. 'difficult': _difficult
  225. })
  226. ann_ct += 1
  227. gt_bbox = gt_bbox[:i, :]
  228. gt_class = gt_class[:i, :]
  229. gt_score = gt_score[:i, :]
  230. is_crowd = is_crowd[:i, :]
  231. difficult = difficult[:i, :]
  232. im_info = {
  233. 'im_id': im_id,
  234. 'image_shape': np.array(
  235. [im_h, im_w], dtype=np.int32)
  236. }
  237. label_info = {
  238. 'is_crowd': is_crowd,
  239. 'gt_class': gt_class,
  240. 'gt_bbox': gt_bbox,
  241. 'gt_score': gt_score,
  242. 'difficult': difficult
  243. }
  244. if gt_bbox.size > 0:
  245. self.file_list.append({
  246. 'image': img_file,
  247. **
  248. im_info,
  249. **
  250. label_info
  251. })
  252. annotations['images'].append({
  253. 'height': im_h,
  254. 'width': im_w,
  255. 'id': int(im_id[0]),
  256. 'file_name': osp.split(img_file)[1]
  257. })
  258. else:
  259. neg_file_list.append({
  260. 'image': img_file,
  261. **
  262. im_info,
  263. **
  264. label_info
  265. })
  266. ct += 1
  267. if self.use_mix:
  268. self.num_max_boxes = max(self.num_max_boxes, 2 * len(objs))
  269. else:
  270. self.num_max_boxes = max(self.num_max_boxes, len(objs))
  271. if not ct:
  272. logging.error(
  273. "No voc record found in %s' % (file_list)", exit=True)
  274. self.pos_num = len(self.file_list)
  275. if self.allow_empty and neg_file_list:
  276. self.file_list += self._sample_empty(neg_file_list)
  277. self.num_workers = 0
  278. logging.info(
  279. "{} samples in file {}, including {} positive samples and {} negative samples.".
  280. format(
  281. len(self.file_list), file_list, self.pos_num,
  282. len(self.file_list) - self.pos_num))
  283. self.num_samples = len(self.file_list)
  284. self.coco_gt = COCO()
  285. self.coco_gt.dataset = annotations
  286. self.coco_gt.createIndex()
  287. self._epoch = 0
  288. def __getitem__(self, idx):
  289. sample = copy.deepcopy(self.file_list[idx])
  290. if self.data_fields is not None:
  291. sample = {k: sample[k] for k in self.data_fields}
  292. if self.use_mix and (self.mixup_op.mixup_epoch == -1 or
  293. self._epoch < self.mixup_op.mixup_epoch):
  294. if self.num_samples > 1:
  295. mix_idx = random.randint(1, self.num_samples - 1)
  296. mix_pos = (mix_idx + idx) % self.num_samples
  297. else:
  298. mix_pos = 0
  299. sample_mix = copy.deepcopy(self.file_list[mix_pos])
  300. if self.data_fields is not None:
  301. sample_mix = {k: sample_mix[k] for k in self.data_fields}
  302. sample = self.mixup_op(sample=[
  303. Decode(to_rgb=False)(sample), Decode(to_rgb=False)(sample_mix)
  304. ])
  305. sample = self.transforms(sample)
  306. return sample
  307. def __len__(self):
  308. return self.num_samples
  309. def set_epoch(self, epoch_id):
  310. self._epoch = epoch_id
  311. def cluster_yolo_anchor(self,
  312. num_anchors,
  313. image_size,
  314. cache=True,
  315. cache_path=None,
  316. iters=300,
  317. gen_iters=1000,
  318. thresh=.25):
  319. """
  320. Cluster YOLO anchors.
  321. Reference:
  322. https://github.com/ultralytics/yolov5/blob/master/utils/autoanchor.py
  323. Args:
  324. num_anchors (int): number of clusters
  325. image_size (list or int): [h, w], being an int means image height and image width are the same.
  326. cache (bool): whether using cache
  327. cache_path (str or None, optional): cache directory path. If None, use `data_dir` of dataset.
  328. iters (int, optional): iters of kmeans algorithm
  329. gen_iters (int, optional): iters of genetic algorithm
  330. threshold (float, optional): anchor scale threshold
  331. verbose (bool, optional): whether print results
  332. """
  333. if cache_path is None:
  334. cache_path = self.data_dir
  335. cluster = YOLOAnchorCluster(
  336. num_anchors=num_anchors,
  337. dataset=self,
  338. image_size=image_size,
  339. cache=cache,
  340. cache_path=cache_path,
  341. iters=iters,
  342. gen_iters=gen_iters,
  343. thresh=thresh)
  344. anchors = cluster()
  345. return anchors
  346. def add_negative_samples(self, image_dir, empty_ratio=1):
  347. """将背景图片加入训练
  348. Args:
  349. image_dir (str):背景图片所在的文件夹目录。
  350. empty_ratio (float or None): 用于指定负样本占总样本数的比例。如果为None,保留数据集初始化是设置的`empty_ratio`值,
  351. 否则更新原有`empty_ratio`值。如果小于0或大于等于1,则保留全部的负样本。默认为1。
  352. """
  353. import cv2
  354. if not osp.isdir(image_dir):
  355. raise Exception("{} is not a valid image directory.".format(
  356. image_dir))
  357. if empty_ratio is not None:
  358. self.empty_ratio = empty_ratio
  359. image_list = os.listdir(image_dir)
  360. max_img_id = max(
  361. len(self.file_list) - 1, max(self.coco_gt.getImgIds()))
  362. neg_file_list = list()
  363. for image in image_list:
  364. if not is_pic(image):
  365. continue
  366. gt_bbox = np.zeros((0, 4), dtype=np.float32)
  367. gt_class = np.zeros((0, 1), dtype=np.int32)
  368. gt_score = np.zeros((0, 1), dtype=np.float32)
  369. is_crowd = np.zeros((0, 1), dtype=np.int32)
  370. difficult = np.zeros((0, 1), dtype=np.int32)
  371. max_img_id += 1
  372. im_fname = osp.join(image_dir, image)
  373. img_data = cv2.imread(im_fname, cv2.IMREAD_UNCHANGED)
  374. im_h, im_w, im_c = img_data.shape
  375. im_info = {
  376. 'im_id': np.asarray([max_img_id]),
  377. 'image_shape': np.array(
  378. [im_h, im_w], dtype=np.int32)
  379. }
  380. label_info = {
  381. 'is_crowd': is_crowd,
  382. 'gt_class': gt_class,
  383. 'gt_bbox': gt_bbox,
  384. 'gt_score': gt_score,
  385. 'difficult': difficult
  386. }
  387. if 'gt_poly' in self.file_list[0]:
  388. label_info['gt_poly'] = []
  389. neg_file_list.append({
  390. 'image': im_fname,
  391. **
  392. im_info,
  393. **
  394. label_info
  395. })
  396. if neg_file_list:
  397. self.allow_empty = True
  398. self.file_list += self._sample_empty(neg_file_list)
  399. self.num_workers = 0
  400. logging.info(
  401. "{} negative samples added. Dataset contains {} positive samples and {} negative samples.".
  402. format(
  403. len(self.file_list) - self.num_samples, self.pos_num,
  404. len(self.file_list) - self.pos_num))
  405. self.num_samples = len(self.file_list)
  406. def _sample_empty(self, neg_file_list):
  407. if 0. <= self.empty_ratio < 1.:
  408. import random
  409. total_num = len(self.file_list)
  410. neg_num = total_num - self.pos_num
  411. sample_num = min((total_num * self.empty_ratio - neg_num) //
  412. (1 - self.empty_ratio), len(neg_file_list))
  413. return random.sample(neg_file_list, sample_num)
  414. else:
  415. return neg_file_list