voc.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. from pycocotools.coco import COCO
  53. super(VOCDetection, self).__init__(
  54. transforms=transforms,
  55. num_workers=num_workers,
  56. buffer_size=buffer_size,
  57. parallel_method=parallel_method,
  58. shuffle=shuffle)
  59. self.file_list = list()
  60. self.labels = list()
  61. self._epoch = 0
  62. annotations = {}
  63. annotations['images'] = []
  64. annotations['categories'] = []
  65. annotations['annotations'] = []
  66. cname2cid = OrderedDict()
  67. label_id = 1
  68. with open(label_list, 'r', encoding=get_encoding(label_list)) as fr:
  69. for line in fr.readlines():
  70. cname2cid[line.strip()] = label_id
  71. label_id += 1
  72. self.labels.append(line.strip())
  73. logging.info("Starting to read file list from dataset...")
  74. for k, v in cname2cid.items():
  75. annotations['categories'].append({
  76. 'supercategory': 'component',
  77. 'id': v,
  78. 'name': k
  79. })
  80. ct = 0
  81. ann_ct = 0
  82. with open(file_list, 'r', encoding=get_encoding(file_list)) as fr:
  83. while True:
  84. line = fr.readline()
  85. if not line:
  86. break
  87. if len(line.strip().split()) > 2:
  88. raise Exception(
  89. "A space is defined as the separator, but it exists in image or label name {}."
  90. .format(line))
  91. img_file, xml_file = [osp.join(data_dir, x) \
  92. for x in line.strip().split()[:2]]
  93. img_file = path_normalization(img_file)
  94. xml_file = path_normalization(xml_file)
  95. if not is_pic(img_file):
  96. continue
  97. if not osp.isfile(xml_file):
  98. continue
  99. if not osp.exists(img_file):
  100. raise IOError('The image file {} is not exist!'.format(
  101. img_file))
  102. tree = ET.parse(xml_file)
  103. if tree.find('id') is None:
  104. im_id = np.array([ct])
  105. else:
  106. ct = int(tree.find('id').text)
  107. im_id = np.array([int(tree.find('id').text)])
  108. pattern = re.compile('<object>', re.IGNORECASE)
  109. obj_match = pattern.findall(
  110. str(ET.tostringlist(tree.getroot())))
  111. if len(obj_match) == 0:
  112. continue
  113. obj_tag = obj_match[0][1:-1]
  114. objs = tree.findall(obj_tag)
  115. pattern = re.compile('<size>', re.IGNORECASE)
  116. size_tag = pattern.findall(
  117. str(ET.tostringlist(tree.getroot())))[0][1:-1]
  118. size_element = tree.find(size_tag)
  119. pattern = re.compile('<width>', re.IGNORECASE)
  120. width_tag = pattern.findall(
  121. str(ET.tostringlist(size_element)))[0][1:-1]
  122. im_w = float(size_element.find(width_tag).text)
  123. pattern = re.compile('<height>', re.IGNORECASE)
  124. height_tag = pattern.findall(
  125. str(ET.tostringlist(size_element)))[0][1:-1]
  126. im_h = float(size_element.find(height_tag).text)
  127. gt_bbox = np.zeros((len(objs), 4), dtype=np.float32)
  128. gt_class = np.zeros((len(objs), 1), dtype=np.int32)
  129. gt_score = np.ones((len(objs), 1), dtype=np.float32)
  130. is_crowd = np.zeros((len(objs), 1), dtype=np.int32)
  131. difficult = np.zeros((len(objs), 1), dtype=np.int32)
  132. for i, obj in enumerate(objs):
  133. pattern = re.compile('<name>', re.IGNORECASE)
  134. name_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
  135. 1:-1]
  136. cname = obj.find(name_tag).text.strip()
  137. gt_class[i][0] = cname2cid[cname]
  138. pattern = re.compile('<difficult>', re.IGNORECASE)
  139. diff_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
  140. 1:-1]
  141. try:
  142. _difficult = int(obj.find(diff_tag).text)
  143. except Exception:
  144. _difficult = 0
  145. pattern = re.compile('<bndbox>', re.IGNORECASE)
  146. box_tag = pattern.findall(str(ET.tostringlist(obj)))[0][1:
  147. -1]
  148. box_element = obj.find(box_tag)
  149. pattern = re.compile('<xmin>', re.IGNORECASE)
  150. xmin_tag = pattern.findall(
  151. str(ET.tostringlist(box_element)))[0][1:-1]
  152. x1 = float(box_element.find(xmin_tag).text)
  153. pattern = re.compile('<ymin>', re.IGNORECASE)
  154. ymin_tag = pattern.findall(
  155. str(ET.tostringlist(box_element)))[0][1:-1]
  156. y1 = float(box_element.find(ymin_tag).text)
  157. pattern = re.compile('<xmax>', re.IGNORECASE)
  158. xmax_tag = pattern.findall(
  159. str(ET.tostringlist(box_element)))[0][1:-1]
  160. x2 = float(box_element.find(xmax_tag).text)
  161. pattern = re.compile('<ymax>', re.IGNORECASE)
  162. ymax_tag = pattern.findall(
  163. str(ET.tostringlist(box_element)))[0][1:-1]
  164. y2 = float(box_element.find(ymax_tag).text)
  165. x1 = max(0, x1)
  166. y1 = max(0, y1)
  167. if im_w > 0.5 and im_h > 0.5:
  168. x2 = min(im_w - 1, x2)
  169. y2 = min(im_h - 1, y2)
  170. gt_bbox[i] = [x1, y1, x2, y2]
  171. is_crowd[i][0] = 0
  172. difficult[i][0] = _difficult
  173. annotations['annotations'].append({
  174. 'iscrowd': 0,
  175. 'image_id': int(im_id[0]),
  176. 'bbox': [x1, y1, x2 - x1 + 1, y2 - y1 + 1],
  177. 'area': float((x2 - x1 + 1) * (y2 - y1 + 1)),
  178. 'category_id': cname2cid[cname],
  179. 'id': ann_ct,
  180. 'difficult': _difficult
  181. })
  182. ann_ct += 1
  183. im_info = {
  184. 'im_id': im_id,
  185. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  186. }
  187. label_info = {
  188. 'is_crowd': is_crowd,
  189. 'gt_class': gt_class,
  190. 'gt_bbox': gt_bbox,
  191. 'gt_score': gt_score,
  192. 'gt_poly': [],
  193. 'difficult': difficult
  194. }
  195. voc_rec = (im_info, label_info)
  196. if len(objs) != 0:
  197. self.file_list.append([img_file, voc_rec])
  198. ct += 1
  199. annotations['images'].append({
  200. 'height': im_h,
  201. 'width': im_w,
  202. 'id': int(im_id[0]),
  203. 'file_name': osp.split(img_file)[1]
  204. })
  205. if not len(self.file_list) > 0:
  206. raise Exception('not found any voc record in %s' % (file_list))
  207. logging.info("{} samples in file {}".format(
  208. len(self.file_list), file_list))
  209. self.num_samples = len(self.file_list)
  210. self.coco_gt = COCO()
  211. self.coco_gt.dataset = annotations
  212. self.coco_gt.createIndex()
  213. def add_negative_samples(self, image_dir):
  214. import cv2
  215. if not osp.exists(image_dir):
  216. raise Exception("{} background images directory does not exist.".
  217. format(image_dir))
  218. image_list = os.listdir(image_dir)
  219. max_img_id = max(self.coco_gt.getImgIds())
  220. for image in image_list:
  221. if not is_pic(image):
  222. continue
  223. # False ground truth
  224. gt_bbox = np.array([[0, 0, 1e-05, 1e-05]], dtype=np.float32)
  225. gt_class = np.array([[0]], dtype=np.int32)
  226. gt_score = np.ones((1, 1), dtype=np.float32)
  227. is_crowd = np.array([[0]], dtype=np.int32)
  228. difficult = np.zeros((1, 1), dtype=np.int32)
  229. gt_poly = [[[0, 0, 0, 1e-05, 1e-05, 1e-05, 1e-05, 0]]]
  230. max_img_id += 1
  231. im_fname = osp.join(image_dir, image)
  232. img_data = cv2.imread(im_fname)
  233. im_h, im_w, im_c = img_data.shape
  234. im_info = {
  235. 'im_id': np.array([max_img_id]).astype('int32'),
  236. 'image_shape': np.array([im_h, im_w]).astype('int32'),
  237. }
  238. label_info = {
  239. 'is_crowd': is_crowd,
  240. 'gt_class': gt_class,
  241. 'gt_bbox': gt_bbox,
  242. 'gt_score': gt_score,
  243. 'difficult': difficult,
  244. 'gt_poly': gt_poly
  245. }
  246. coco_rec = (im_info, label_info)
  247. self.file_list.append([im_fname, coco_rec])
  248. self.num_samples = len(self.file_list)
  249. def iterator(self):
  250. self._epoch += 1
  251. self._pos = 0
  252. files = copy.deepcopy(self.file_list)
  253. if self.shuffle:
  254. random.shuffle(files)
  255. files = files[:self.num_samples]
  256. self.num_samples = len(files)
  257. for f in files:
  258. records = f[1]
  259. im_info = copy.deepcopy(records[0])
  260. label_info = copy.deepcopy(records[1])
  261. im_info['epoch'] = self._epoch
  262. if self.num_samples > 1:
  263. mix_idx = random.randint(1, self.num_samples - 1)
  264. mix_pos = (mix_idx + self._pos) % self.num_samples
  265. else:
  266. mix_pos = 0
  267. im_info['mixup'] = [
  268. files[mix_pos][0], copy.deepcopy(files[mix_pos][1][0]),
  269. copy.deepcopy(files[mix_pos][1][1])
  270. ]
  271. self._pos += 1
  272. sample = [f[0], im_info, label_info]
  273. yield sample