voc.py 18 KB

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