widerface.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # Copyright (c) 2019 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. import os
  15. import numpy as np
  16. from ppdet.core.workspace import register, serializable
  17. from .dataset import DetDataset
  18. from ppdet.utils.logger import setup_logger
  19. logger = setup_logger(__name__)
  20. @register
  21. @serializable
  22. class WIDERFaceDataSet(DetDataset):
  23. """
  24. Load WiderFace records with 'anno_path'
  25. Args:
  26. dataset_dir (str): root directory for dataset.
  27. image_dir (str): directory for images.
  28. anno_path (str): WiderFace annotation data.
  29. data_fields (list): key name of data dictionary, at least have 'image'.
  30. sample_num (int): number of samples to load, -1 means all.
  31. with_lmk (bool): whether to load face landmark keypoint labels.
  32. """
  33. def __init__(self,
  34. dataset_dir=None,
  35. image_dir=None,
  36. anno_path=None,
  37. data_fields=['image'],
  38. sample_num=-1,
  39. with_lmk=False):
  40. super(WIDERFaceDataSet, self).__init__(
  41. dataset_dir=dataset_dir,
  42. image_dir=image_dir,
  43. anno_path=anno_path,
  44. data_fields=data_fields,
  45. sample_num=sample_num,
  46. with_lmk=with_lmk)
  47. self.anno_path = anno_path
  48. self.sample_num = sample_num
  49. self.roidbs = None
  50. self.cname2cid = None
  51. self.with_lmk = with_lmk
  52. def parse_dataset(self):
  53. anno_path = os.path.join(self.dataset_dir, self.anno_path)
  54. image_dir = os.path.join(self.dataset_dir, self.image_dir)
  55. txt_file = anno_path
  56. records = []
  57. ct = 0
  58. file_lists = self._load_file_list(txt_file)
  59. cname2cid = widerface_label()
  60. for item in file_lists:
  61. im_fname = item[0]
  62. im_id = np.array([ct])
  63. gt_bbox = np.zeros((len(item) - 1, 4), dtype=np.float32)
  64. gt_class = np.zeros((len(item) - 1, 1), dtype=np.int32)
  65. gt_lmk_labels = np.zeros((len(item) - 1, 10), dtype=np.float32)
  66. lmk_ignore_flag = np.zeros((len(item) - 1, 1), dtype=np.int32)
  67. for index_box in range(len(item)):
  68. if index_box < 1:
  69. continue
  70. gt_bbox[index_box - 1] = item[index_box][0]
  71. if self.with_lmk:
  72. gt_lmk_labels[index_box - 1] = item[index_box][1]
  73. lmk_ignore_flag[index_box - 1] = item[index_box][2]
  74. im_fname = os.path.join(image_dir,
  75. im_fname) if image_dir else im_fname
  76. widerface_rec = {
  77. 'im_file': im_fname,
  78. 'im_id': im_id,
  79. } if 'image' in self.data_fields else {}
  80. gt_rec = {
  81. 'gt_bbox': gt_bbox,
  82. 'gt_class': gt_class,
  83. }
  84. for k, v in gt_rec.items():
  85. if k in self.data_fields:
  86. widerface_rec[k] = v
  87. if self.with_lmk:
  88. widerface_rec['gt_keypoint'] = gt_lmk_labels
  89. widerface_rec['keypoint_ignore'] = lmk_ignore_flag
  90. if len(item) != 0:
  91. records.append(widerface_rec)
  92. ct += 1
  93. if self.sample_num > 0 and ct >= self.sample_num:
  94. break
  95. assert len(records) > 0, 'not found any widerface in %s' % (anno_path)
  96. logger.debug('{} samples in file {}'.format(ct, anno_path))
  97. self.roidbs, self.cname2cid = records, cname2cid
  98. def _load_file_list(self, input_txt):
  99. with open(input_txt, 'r') as f_dir:
  100. lines_input_txt = f_dir.readlines()
  101. file_dict = {}
  102. num_class = 0
  103. exts = ['jpg', 'jpeg', 'png', 'bmp']
  104. exts += [ext.upper() for ext in exts]
  105. for i in range(len(lines_input_txt)):
  106. line_txt = lines_input_txt[i].strip('\n\t\r')
  107. split_str = line_txt.split(' ')
  108. if len(split_str) == 1:
  109. img_file_name = os.path.split(split_str[0])[1]
  110. split_txt = img_file_name.split('.')
  111. if len(split_txt) < 2:
  112. continue
  113. elif split_txt[-1] in exts:
  114. if i != 0:
  115. num_class += 1
  116. file_dict[num_class] = [line_txt]
  117. else:
  118. if len(line_txt) <= 6:
  119. continue
  120. result_boxs = []
  121. xmin = float(split_str[0])
  122. ymin = float(split_str[1])
  123. w = float(split_str[2])
  124. h = float(split_str[3])
  125. # Filter out wrong labels
  126. if w < 0 or h < 0:
  127. logger.warning('Illegal box with w: {}, h: {} in '
  128. 'img: {}, and it will be ignored'.format(
  129. w, h, file_dict[num_class][0]))
  130. continue
  131. xmin = max(0, xmin)
  132. ymin = max(0, ymin)
  133. xmax = xmin + w
  134. ymax = ymin + h
  135. gt_bbox = [xmin, ymin, xmax, ymax]
  136. result_boxs.append(gt_bbox)
  137. if self.with_lmk:
  138. assert len(split_str) > 18, 'When `with_lmk=True`, the number' \
  139. 'of characters per line in the annotation file should' \
  140. 'exceed 18.'
  141. lmk0_x = float(split_str[5])
  142. lmk0_y = float(split_str[6])
  143. lmk1_x = float(split_str[8])
  144. lmk1_y = float(split_str[9])
  145. lmk2_x = float(split_str[11])
  146. lmk2_y = float(split_str[12])
  147. lmk3_x = float(split_str[14])
  148. lmk3_y = float(split_str[15])
  149. lmk4_x = float(split_str[17])
  150. lmk4_y = float(split_str[18])
  151. lmk_ignore_flag = 0 if lmk0_x == -1 else 1
  152. gt_lmk_label = [
  153. lmk0_x, lmk0_y, lmk1_x, lmk1_y, lmk2_x, lmk2_y, lmk3_x,
  154. lmk3_y, lmk4_x, lmk4_y
  155. ]
  156. result_boxs.append(gt_lmk_label)
  157. result_boxs.append(lmk_ignore_flag)
  158. file_dict[num_class].append(result_boxs)
  159. return list(file_dict.values())
  160. def widerface_label():
  161. labels_map = {'face': 0}
  162. return labels_map