voc.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. # copyright (c) 2020 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. import paddlex.utils.logging as logging
  24. from paddlex.utils import path_normalization
  25. from .dataset import Dataset
  26. from .dataset import is_pic
  27. from .dataset import get_encoding
  28. class VOCDetection(Dataset):
  29. """读取PascalVOC格式的检测数据集,并对样本进行相应的处理。
  30. Args:
  31. data_dir (str): 数据集所在的目录路径。
  32. file_list (str): 描述数据集图片文件和对应标注文件的文件路径(文本内每行路径为相对data_dir的相对路)。
  33. label_list (str): 描述数据集包含的类别信息文件路径。
  34. transforms (paddlex.det.transforms): 数据集中每个样本的预处理/增强算子。
  35. num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
  36. 系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核数的
  37. 一半。
  38. buffer_size (int): 数据集中样本在预处理过程中队列的缓存长度,以样本数为单位。默认为100。
  39. parallel_method (str): 数据集中样本在预处理过程中并行处理的方式,支持'thread'
  40. 线程和'process'进程两种方式。默认为'process'(Windows和Mac下会强制使用thread,该参数无效)。
  41. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  42. """
  43. def __init__(self,
  44. data_dir,
  45. file_list,
  46. label_list,
  47. transforms=None,
  48. num_workers='auto',
  49. buffer_size=100,
  50. parallel_method='process',
  51. shuffle=False):
  52. # matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  53. # or matplotlib.backends is imported for the first time
  54. # pycocotools import matplotlib
  55. import matplotlib
  56. matplotlib.use('Agg')
  57. from pycocotools.coco import COCO
  58. super(VOCDetection, self).__init__(
  59. transforms=transforms,
  60. num_workers=num_workers,
  61. buffer_size=buffer_size,
  62. parallel_method=parallel_method,
  63. shuffle=shuffle)
  64. self.file_list = list()
  65. self.labels = list()
  66. self._epoch = 0
  67. annotations = {}
  68. annotations['images'] = []
  69. annotations['categories'] = []
  70. annotations['annotations'] = []
  71. cname2cid = OrderedDict()
  72. label_id = 1
  73. with open(label_list, 'r', encoding=get_encoding(label_list)) as fr:
  74. for line in fr.readlines():
  75. cname2cid[line.strip()] = label_id
  76. label_id += 1
  77. self.labels.append(line.strip())
  78. logging.info("Starting to read file list from dataset...")
  79. for k, v in cname2cid.items():
  80. annotations['categories'].append({
  81. 'supercategory': 'component',
  82. 'id': v,
  83. 'name': k
  84. })
  85. ct = 0
  86. ann_ct = 0
  87. with open(file_list, 'r', encoding=get_encoding(file_list)) as fr:
  88. while True:
  89. line = fr.readline()
  90. if not line:
  91. break
  92. if len(line.strip().split()) > 2:
  93. raise Exception(
  94. "A space is defined as the separator, but it exists in image or label name {}."
  95. .format(line))
  96. img_file, xml_file = [osp.join(data_dir, x) \
  97. for x in line.strip().split()[:2]]
  98. img_file = path_normalization(img_file)
  99. xml_file = path_normalization(xml_file)
  100. if not is_pic(img_file):
  101. continue
  102. if not osp.isfile(xml_file):
  103. continue
  104. if not osp.exists(img_file):
  105. logging.warning('The image file {} is not exist!'.format(
  106. img_file))
  107. continue
  108. if not osp.exists(xml_file):
  109. logging.warning('The annotation file {} is not exist!'.
  110. format(xml_file))
  111. continue
  112. tree = ET.parse(xml_file)
  113. if tree.find('id') is None:
  114. im_id = np.array([ct])
  115. else:
  116. ct = int(tree.find('id').text)
  117. im_id = np.array([int(tree.find('id').text)])
  118. pattern = re.compile('<object>', re.IGNORECASE)
  119. obj_match = pattern.findall(
  120. str(ET.tostringlist(tree.getroot())))
  121. if len(obj_match) == 0:
  122. continue
  123. obj_tag = obj_match[0][1:-1]
  124. objs = tree.findall(obj_tag)
  125. pattern = re.compile('<size>', re.IGNORECASE)
  126. size_tag = pattern.findall(
  127. 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. gt_bbox = np.zeros((len(objs), 4), dtype=np.float32)
  143. gt_class = np.zeros((len(objs), 1), dtype=np.int32)
  144. gt_score = np.ones((len(objs), 1), dtype=np.float32)
  145. is_crowd = np.zeros((len(objs), 1), dtype=np.int32)
  146. difficult = np.zeros((len(objs), 1), dtype=np.int32)
  147. for i, obj in enumerate(objs):
  148. pattern = re.compile('<name>', re.IGNORECASE)
  149. name_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
  150. 1:-1]
  151. cname = obj.find(name_tag).text.strip()
  152. gt_class[i][0] = cname2cid[cname]
  153. pattern = re.compile('<difficult>', re.IGNORECASE)
  154. diff_tag = pattern.findall(str(ET.tostringlist(obj)))
  155. if len(diff_tag) == 0:
  156. _difficult = 0
  157. else:
  158. diff_tag = diff_tag[0][1:-1]
  159. try:
  160. _difficult = int(obj.find(diff_tag).text)
  161. except Exception:
  162. _difficult = 0
  163. pattern = re.compile('<bndbox>', re.IGNORECASE)
  164. box_tag = pattern.findall(str(ET.tostringlist(obj)))
  165. if len(box_tag) == 0:
  166. logging.warning(
  167. "There's no field '<bndbox>' in one of object, so this object will be ignored. xml file: {}".
  168. format(xml_file))
  169. continue
  170. box_tag = box_tag[0][1:-1]
  171. box_element = obj.find(box_tag)
  172. pattern = re.compile('<xmin>', re.IGNORECASE)
  173. xmin_tag = pattern.findall(
  174. str(ET.tostringlist(box_element)))[0][1:-1]
  175. x1 = float(box_element.find(xmin_tag).text)
  176. pattern = re.compile('<ymin>', re.IGNORECASE)
  177. ymin_tag = pattern.findall(
  178. str(ET.tostringlist(box_element)))[0][1:-1]
  179. y1 = float(box_element.find(ymin_tag).text)
  180. pattern = re.compile('<xmax>', re.IGNORECASE)
  181. xmax_tag = pattern.findall(
  182. str(ET.tostringlist(box_element)))[0][1:-1]
  183. x2 = float(box_element.find(xmax_tag).text)
  184. pattern = re.compile('<ymax>', re.IGNORECASE)
  185. ymax_tag = pattern.findall(
  186. str(ET.tostringlist(box_element)))[0][1:-1]
  187. y2 = float(box_element.find(ymax_tag).text)
  188. x1 = max(0, x1)
  189. y1 = max(0, y1)
  190. if im_w > 0.5 and im_h > 0.5:
  191. x2 = min(im_w - 1, x2)
  192. y2 = min(im_h - 1, y2)
  193. gt_bbox[i] = [x1, y1, x2, y2]
  194. is_crowd[i][0] = 0
  195. difficult[i][0] = _difficult
  196. annotations['annotations'].append({
  197. 'iscrowd': 0,
  198. 'image_id': int(im_id[0]),
  199. 'bbox': [x1, y1, x2 - x1 + 1, y2 - y1 + 1],
  200. 'area': float((x2 - x1 + 1) * (y2 - y1 + 1)),
  201. 'category_id': cname2cid[cname],
  202. 'id': ann_ct,
  203. 'difficult': _difficult
  204. })
  205. ann_ct += 1
  206. im_info = {
  207. 'im_id': im_id,
  208. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  209. }
  210. label_info = {
  211. 'is_crowd': is_crowd,
  212. 'gt_class': gt_class,
  213. 'gt_bbox': gt_bbox,
  214. 'gt_score': gt_score,
  215. 'gt_poly': [],
  216. 'difficult': difficult
  217. }
  218. voc_rec = (im_info, label_info)
  219. if len(objs) != 0:
  220. self.file_list.append([img_file, voc_rec])
  221. ct += 1
  222. annotations['images'].append({
  223. 'height': im_h,
  224. 'width': im_w,
  225. 'id': int(im_id[0]),
  226. 'file_name': osp.split(img_file)[1]
  227. })
  228. if not len(self.file_list) > 0:
  229. raise Exception('not found any voc record in %s' % (file_list))
  230. logging.info("{} samples in file {}".format(
  231. len(self.file_list), file_list))
  232. self.num_samples = len(self.file_list)
  233. self.coco_gt = COCO()
  234. self.coco_gt.dataset = annotations
  235. self.coco_gt.createIndex()
  236. def add_negative_samples(self, image_dir):
  237. """将背景图片加入训练
  238. Args:
  239. image_dir (str):背景图片所在的文件夹目录。
  240. """
  241. import cv2
  242. if not osp.exists(image_dir):
  243. raise Exception("{} background images directory does not exist.".
  244. format(image_dir))
  245. image_list = os.listdir(image_dir)
  246. max_img_id = max(self.coco_gt.getImgIds())
  247. for image in image_list:
  248. if not is_pic(image):
  249. continue
  250. # False ground truth
  251. gt_bbox = np.array([[0, 0, 1e-05, 1e-05]], dtype=np.float32)
  252. gt_class = np.array([[0]], dtype=np.int32)
  253. gt_score = np.ones((1, 1), dtype=np.float32)
  254. is_crowd = np.array([[0]], dtype=np.int32)
  255. difficult = np.zeros((1, 1), dtype=np.int32)
  256. gt_poly = [[[0, 0, 0, 1e-05, 1e-05, 1e-05, 1e-05, 0]]]
  257. max_img_id += 1
  258. im_fname = osp.join(image_dir, image)
  259. img_data = cv2.imread(im_fname, cv2.IMREAD_UNCHANGED)
  260. im_h, im_w, im_c = img_data.shape
  261. im_info = {
  262. 'im_id': np.array([max_img_id]).astype('int32'),
  263. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  264. }
  265. label_info = {
  266. 'is_crowd': is_crowd,
  267. 'gt_class': gt_class,
  268. 'gt_bbox': gt_bbox,
  269. 'gt_score': gt_score,
  270. 'difficult': difficult,
  271. 'gt_poly': gt_poly
  272. }
  273. coco_rec = (im_info, label_info)
  274. self.file_list.append([im_fname, coco_rec])
  275. self.num_samples = len(self.file_list)
  276. def iterator(self):
  277. self._epoch += 1
  278. self._pos = 0
  279. files = copy.deepcopy(self.file_list)
  280. if self.shuffle:
  281. random.shuffle(files)
  282. files = files[:self.num_samples]
  283. self.num_samples = len(files)
  284. for f in files:
  285. records = f[1]
  286. im_info = copy.deepcopy(records[0])
  287. label_info = copy.deepcopy(records[1])
  288. im_info['epoch'] = self._epoch
  289. if self.num_samples > 1:
  290. mix_idx = random.randint(1, self.num_samples - 1)
  291. mix_pos = (mix_idx + self._pos) % self.num_samples
  292. else:
  293. mix_pos = 0
  294. im_info['mixup'] = [
  295. files[mix_pos][0], copy.deepcopy(files[mix_pos][1][0]),
  296. copy.deepcopy(files[mix_pos][1][1])
  297. ]
  298. self._pos += 1
  299. sample = [f[0], im_info, label_info]
  300. yield sample