widerface.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. import logging
  17. logger = logging.getLogger(__name__)
  18. from ppdet.core.workspace import register, serializable
  19. from .dataset import DataSet
  20. @register
  21. @serializable
  22. class WIDERFaceDataSet(DataSet):
  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): root directory for voc annotation data
  29. sample_num (int): number of samples to load, -1 means all
  30. with_background (bool): whether load background as a class.
  31. if True, total class number will be 2. default True.
  32. """
  33. def __init__(self,
  34. dataset_dir=None,
  35. image_dir=None,
  36. anno_path=None,
  37. sample_num=-1,
  38. with_background=True,
  39. with_lmk=False):
  40. super(WIDERFaceDataSet, self).__init__(
  41. image_dir=image_dir,
  42. anno_path=anno_path,
  43. sample_num=sample_num,
  44. dataset_dir=dataset_dir,
  45. with_background=with_background)
  46. self.anno_path = anno_path
  47. self.sample_num = sample_num
  48. self.with_background = with_background
  49. self.roidbs = None
  50. self.cname2cid = None
  51. self.with_lmk = with_lmk
  52. def load_roidb_and_cname2cid(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(self.with_background)
  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.ones((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. 'gt_bbox': gt_bbox,
  80. 'gt_class': gt_class,
  81. }
  82. if self.with_lmk:
  83. widerface_rec['gt_keypoint'] = gt_lmk_labels
  84. widerface_rec['keypoint_ignore'] = lmk_ignore_flag
  85. if len(item) != 0:
  86. records.append(widerface_rec)
  87. ct += 1
  88. if self.sample_num > 0 and ct >= self.sample_num:
  89. break
  90. assert len(records) > 0, 'not found any widerface in %s' % (anno_path)
  91. logger.debug('{} samples in file {}'.format(ct, anno_path))
  92. self.roidbs, self.cname2cid = records, cname2cid
  93. def _load_file_list(self, input_txt):
  94. with open(input_txt, 'r') as f_dir:
  95. lines_input_txt = f_dir.readlines()
  96. file_dict = {}
  97. num_class = 0
  98. exts = ['jpg', 'jpeg', 'png', 'bmp']
  99. exts += [ext.upper() for ext in exts]
  100. for i in range(len(lines_input_txt)):
  101. line_txt = lines_input_txt[i].strip('\n\t\r')
  102. split_str = line_txt.split(' ')
  103. if len(split_str) == 1:
  104. img_file_name = os.path.split(split_str[0])[1]
  105. split_txt = img_file_name.split('.')
  106. if len(split_txt) < 2:
  107. continue
  108. elif split_txt[-1] in exts:
  109. if i != 0:
  110. num_class += 1
  111. file_dict[num_class] = [line_txt]
  112. else:
  113. if len(line_txt) <= 6:
  114. continue
  115. result_boxs = []
  116. xmin = float(split_str[0])
  117. ymin = float(split_str[1])
  118. w = float(split_str[2])
  119. h = float(split_str[3])
  120. # Filter out wrong labels
  121. if w < 0 or h < 0:
  122. logger.warning('Illegal box with w: {}, h: {} in '
  123. 'img: {}, and it will be ignored'.format(
  124. w, h, file_dict[num_class][0]))
  125. continue
  126. xmin = max(0, xmin)
  127. ymin = max(0, ymin)
  128. xmax = xmin + w
  129. ymax = ymin + h
  130. gt_bbox = [xmin, ymin, xmax, ymax]
  131. result_boxs.append(gt_bbox)
  132. if self.with_lmk:
  133. assert len(split_str) > 18, 'When `with_lmk=True`, the number' \
  134. 'of characters per line in the annotation file should' \
  135. 'exceed 18.'
  136. lmk0_x = float(split_str[5])
  137. lmk0_y = float(split_str[6])
  138. lmk1_x = float(split_str[8])
  139. lmk1_y = float(split_str[9])
  140. lmk2_x = float(split_str[11])
  141. lmk2_y = float(split_str[12])
  142. lmk3_x = float(split_str[14])
  143. lmk3_y = float(split_str[15])
  144. lmk4_x = float(split_str[17])
  145. lmk4_y = float(split_str[18])
  146. lmk_ignore_flag = 0 if lmk0_x == -1 else 1
  147. gt_lmk_label = [
  148. lmk0_x, lmk0_y, lmk1_x, lmk1_y, lmk2_x, lmk2_y, lmk3_x,
  149. lmk3_y, lmk4_x, lmk4_y
  150. ]
  151. result_boxs.append(gt_lmk_label)
  152. result_boxs.append(lmk_ignore_flag)
  153. file_dict[num_class].append(result_boxs)
  154. return list(file_dict.values())
  155. def widerface_label(with_background=True):
  156. labels_map = {'face': 1}
  157. if not with_background:
  158. labels_map = {k: v - 1 for k, v in labels_map.items()}
  159. return labels_map