widerface_eval_utils.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import numpy as np
  19. from ppdet.data.source.widerface import widerface_label
  20. import logging
  21. logger = logging.getLogger(__name__)
  22. __all__ = [
  23. 'get_shrink', 'bbox_vote', 'save_widerface_bboxes', 'save_fddb_bboxes',
  24. 'to_chw_bgr', 'bbox2out', 'get_category_info', 'lmk2out'
  25. ]
  26. def to_chw_bgr(image):
  27. """
  28. Transpose image from HWC to CHW and from RBG to BGR.
  29. Args:
  30. image (np.array): an image with HWC and RBG layout.
  31. """
  32. # HWC to CHW
  33. if len(image.shape) == 3:
  34. image = np.swapaxes(image, 1, 2)
  35. image = np.swapaxes(image, 1, 0)
  36. # RBG to BGR
  37. image = image[[2, 1, 0], :, :]
  38. return image
  39. def bbox_vote(det):
  40. order = det[:, 4].ravel().argsort()[::-1]
  41. det = det[order, :]
  42. if det.shape[0] == 0:
  43. dets = np.array([[10, 10, 20, 20, 0.002]])
  44. det = np.empty(shape=[0, 5])
  45. while det.shape[0] > 0:
  46. # IOU
  47. area = (det[:, 2] - det[:, 0] + 1) * (det[:, 3] - det[:, 1] + 1)
  48. xx1 = np.maximum(det[0, 0], det[:, 0])
  49. yy1 = np.maximum(det[0, 1], det[:, 1])
  50. xx2 = np.minimum(det[0, 2], det[:, 2])
  51. yy2 = np.minimum(det[0, 3], det[:, 3])
  52. w = np.maximum(0.0, xx2 - xx1 + 1)
  53. h = np.maximum(0.0, yy2 - yy1 + 1)
  54. inter = w * h
  55. o = inter / (area[0] + area[:] - inter)
  56. # nms
  57. merge_index = np.where(o >= 0.3)[0]
  58. det_accu = det[merge_index, :]
  59. det = np.delete(det, merge_index, 0)
  60. if merge_index.shape[0] <= 1:
  61. if det.shape[0] == 0:
  62. try:
  63. dets = np.row_stack((dets, det_accu))
  64. except:
  65. dets = det_accu
  66. continue
  67. det_accu[:, 0:4] = det_accu[:, 0:4] * np.tile(det_accu[:, -1:], (1, 4))
  68. max_score = np.max(det_accu[:, 4])
  69. det_accu_sum = np.zeros((1, 5))
  70. det_accu_sum[:, 0:4] = np.sum(det_accu[:, 0:4],
  71. axis=0) / np.sum(det_accu[:, -1:])
  72. det_accu_sum[:, 4] = max_score
  73. try:
  74. dets = np.row_stack((dets, det_accu_sum))
  75. except:
  76. dets = det_accu_sum
  77. dets = dets[0:750, :]
  78. # Only keep 0.3 or more
  79. keep_index = np.where(dets[:, 4] >= 0.01)[0]
  80. dets = dets[keep_index, :]
  81. return dets
  82. def get_shrink(height, width):
  83. """
  84. Args:
  85. height (int): image height.
  86. width (int): image width.
  87. """
  88. # avoid out of memory
  89. max_shrink_v1 = (0x7fffffff / 577.0 / (height * width))**0.5
  90. max_shrink_v2 = ((678 * 1024 * 2.0 * 2.0) / (height * width))**0.5
  91. def get_round(x, loc):
  92. str_x = str(x)
  93. if '.' in str_x:
  94. str_before, str_after = str_x.split('.')
  95. len_after = len(str_after)
  96. if len_after >= 3:
  97. str_final = str_before + '.' + str_after[0:loc]
  98. return float(str_final)
  99. else:
  100. return x
  101. max_shrink = get_round(min(max_shrink_v1, max_shrink_v2), 2) - 0.3
  102. if max_shrink >= 1.5 and max_shrink < 2:
  103. max_shrink = max_shrink - 0.1
  104. elif max_shrink >= 2 and max_shrink < 3:
  105. max_shrink = max_shrink - 0.2
  106. elif max_shrink >= 3 and max_shrink < 4:
  107. max_shrink = max_shrink - 0.3
  108. elif max_shrink >= 4 and max_shrink < 5:
  109. max_shrink = max_shrink - 0.4
  110. elif max_shrink >= 5:
  111. max_shrink = max_shrink - 0.5
  112. elif max_shrink <= 0.1:
  113. max_shrink = 0.1
  114. shrink = max_shrink if max_shrink < 1 else 1
  115. return shrink, max_shrink
  116. def save_widerface_bboxes(image_path, bboxes_scores, output_dir):
  117. image_name = image_path.split('/')[-1]
  118. image_class = image_path.split('/')[-2]
  119. odir = os.path.join(output_dir, image_class)
  120. if not os.path.exists(odir):
  121. os.makedirs(odir)
  122. ofname = os.path.join(odir, '%s.txt' % (image_name[:-4]))
  123. f = open(ofname, 'w')
  124. f.write('{:s}\n'.format(image_class + '/' + image_name))
  125. f.write('{:d}\n'.format(bboxes_scores.shape[0]))
  126. for box_score in bboxes_scores:
  127. xmin, ymin, xmax, ymax, score = box_score
  128. f.write('{:.1f} {:.1f} {:.1f} {:.1f} {:.3f}\n'.format(xmin, ymin, (
  129. xmax - xmin + 1), (ymax - ymin + 1), score))
  130. f.close()
  131. logger.info("The predicted result is saved as {}".format(ofname))
  132. def save_fddb_bboxes(bboxes_scores,
  133. output_dir,
  134. output_fname='pred_fddb_res.txt'):
  135. if not os.path.exists(output_dir):
  136. os.makedirs(output_dir)
  137. predict_file = os.path.join(output_dir, output_fname)
  138. f = open(predict_file, 'w')
  139. for image_path, dets in bboxes_scores.iteritems():
  140. f.write('{:s}\n'.format(image_path))
  141. f.write('{:d}\n'.format(dets.shape[0]))
  142. for box_score in dets:
  143. xmin, ymin, xmax, ymax, score = box_score
  144. width, height = xmax - xmin, ymax - ymin
  145. f.write('{:.1f} {:.1f} {:.1f} {:.1f} {:.3f}\n'
  146. .format(xmin, ymin, width, height, score))
  147. logger.info("The predicted result is saved as {}".format(predict_file))
  148. return predict_file
  149. def get_category_info(anno_file=None,
  150. with_background=True,
  151. use_default_label=False):
  152. if use_default_label or anno_file is None \
  153. or not os.path.exists(anno_file):
  154. logger.info("Not found annotation file {}, load "
  155. "wider-face categories.".format(anno_file))
  156. return widerfaceall_category_info(with_background)
  157. else:
  158. logger.info("Load categories from {}".format(anno_file))
  159. return get_category_info_from_anno(anno_file, with_background)
  160. def get_category_info_from_anno(anno_file, with_background=True):
  161. """
  162. Get class id to category id map and category id
  163. to category name map from annotation file.
  164. Args:
  165. anno_file (str): annotation file path
  166. with_background (bool, default True):
  167. whether load background as class 0.
  168. """
  169. cats = []
  170. with open(anno_file) as f:
  171. for line in f.readlines():
  172. cats.append(line.strip())
  173. if cats[0] != 'background' and with_background:
  174. cats.insert(0, 'background')
  175. if cats[0] == 'background' and not with_background:
  176. cats = cats[1:]
  177. clsid2catid = {i: i for i in range(len(cats))}
  178. catid2name = {i: name for i, name in enumerate(cats)}
  179. return clsid2catid, catid2name
  180. def widerfaceall_category_info(with_background=True):
  181. """
  182. Get class id to category id map and category id
  183. to category name map of mixup wider_face dataset
  184. Args:
  185. with_background (bool, default True):
  186. whether load background as class 0.
  187. """
  188. label_map = widerface_label(with_background)
  189. label_map = sorted(label_map.items(), key=lambda x: x[1])
  190. cats = [l[0] for l in label_map]
  191. if with_background:
  192. cats.insert(0, 'background')
  193. clsid2catid = {i: i for i in range(len(cats))}
  194. catid2name = {i: name for i, name in enumerate(cats)}
  195. return clsid2catid, catid2name
  196. def lmk2out(results, is_bbox_normalized=False):
  197. """
  198. Args:
  199. results: request a dict, should include: `landmark`, `im_id`,
  200. if is_bbox_normalized=True, also need `im_shape`.
  201. is_bbox_normalized: whether or not landmark is normalized.
  202. """
  203. xywh_res = []
  204. for t in results:
  205. bboxes = t['bbox'][0]
  206. lengths = t['bbox'][1][0]
  207. im_ids = np.array(t['im_id'][0]).flatten()
  208. if bboxes.shape == (1, 1) or bboxes is None:
  209. continue
  210. face_index = t['face_index'][0]
  211. prior_box = t['prior_boxes'][0]
  212. predict_lmk = t['landmark'][0]
  213. prior = np.reshape(prior_box, (-1, 4))
  214. predictlmk = np.reshape(predict_lmk, (-1, 10))
  215. k = 0
  216. for a in range(len(lengths)):
  217. num = lengths[a]
  218. im_id = int(im_ids[a])
  219. for i in range(num):
  220. score = bboxes[k][1]
  221. theindex = face_index[i][0]
  222. me_prior = prior[theindex, :]
  223. lmk_pred = predictlmk[theindex, :]
  224. prior_w = me_prior[2] - me_prior[0]
  225. prior_h = me_prior[3] - me_prior[1]
  226. prior_w_center = (me_prior[2] + me_prior[0]) / 2
  227. prior_h_center = (me_prior[3] + me_prior[1]) / 2
  228. lmk_decode = np.zeros((10))
  229. for j in [0, 2, 4, 6, 8]:
  230. lmk_decode[j] = lmk_pred[j] * 0.1 * prior_w + prior_w_center
  231. for j in [1, 3, 5, 7, 9]:
  232. lmk_decode[j] = lmk_pred[j] * 0.1 * prior_h + prior_h_center
  233. im_shape = t['im_shape'][0][a].tolist()
  234. image_h, image_w = int(im_shape[0]), int(im_shape[1])
  235. if is_bbox_normalized:
  236. lmk_decode = lmk_decode * np.array([
  237. image_w, image_h, image_w, image_h, image_w, image_h,
  238. image_w, image_h, image_w, image_h
  239. ])
  240. lmk_res = {
  241. 'image_id': im_id,
  242. 'landmark': lmk_decode,
  243. 'score': score,
  244. }
  245. xywh_res.append(lmk_res)
  246. k += 1
  247. return xywh_res