retinaface.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // Copyright (c) 2022 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. #include "ultra_infer/vision/facedet/contrib/retinaface.h"
  15. #include "ultra_infer/utils/perf.h"
  16. #include "ultra_infer/vision/utils/utils.h"
  17. namespace ultra_infer {
  18. namespace vision {
  19. namespace facedet {
  20. struct RetinaAnchor {
  21. float cx;
  22. float cy;
  23. float s_kx;
  24. float s_ky;
  25. };
  26. void GenerateRetinaAnchors(const std::vector<int> &size,
  27. const std::vector<int> &downsample_strides,
  28. const std::vector<std::vector<int>> &min_sizes,
  29. std::vector<RetinaAnchor> *anchors) {
  30. // size: tuple of input (width, height)
  31. // downsample_strides: downsample strides (steps), e.g (8,16,32)
  32. // min_sizes: width and height for each anchor,
  33. // e.g {{16, 32}, {64, 128}, {256, 512}}
  34. int h = size[1];
  35. int w = size[0];
  36. std::vector<std::vector<int>> feature_maps;
  37. for (auto s : downsample_strides) {
  38. feature_maps.push_back(
  39. {static_cast<int>(
  40. std::ceil(static_cast<float>(h) / static_cast<float>(s))),
  41. static_cast<int>(
  42. std::ceil(static_cast<float>(w) / static_cast<float>(s)))});
  43. }
  44. (*anchors).clear();
  45. const size_t num_feature_map = feature_maps.size();
  46. // reference: layers/functions/prior_box.py#L21
  47. for (size_t k = 0; k < num_feature_map; ++k) {
  48. auto f_map = feature_maps.at(k); // e.g [640//8,640//8]
  49. auto tmp_min_sizes = min_sizes.at(k); // e.g [8,16]
  50. int f_h = f_map.at(0);
  51. int f_w = f_map.at(1);
  52. for (size_t i = 0; i < f_h; ++i) {
  53. for (size_t j = 0; j < f_w; ++j) {
  54. for (auto min_size : tmp_min_sizes) {
  55. float s_kx =
  56. static_cast<float>(min_size) / static_cast<float>(w); // e.g 16/w
  57. float s_ky =
  58. static_cast<float>(min_size) / static_cast<float>(h); // e.g 16/h
  59. // (x + 0.5) * step / w normalized loc mapping to input width
  60. // (y + 0.5) * step / h normalized loc mapping to input height
  61. float s = static_cast<float>(downsample_strides.at(k));
  62. float cx = (static_cast<float>(j) + 0.5f) * s / static_cast<float>(w);
  63. float cy = (static_cast<float>(i) + 0.5f) * s / static_cast<float>(h);
  64. (*anchors).emplace_back(
  65. RetinaAnchor{cx, cy, s_kx, s_ky}); // without clip
  66. }
  67. }
  68. }
  69. }
  70. }
  71. RetinaFace::RetinaFace(const std::string &model_file,
  72. const std::string &params_file,
  73. const RuntimeOption &custom_option,
  74. const ModelFormat &model_format) {
  75. if (model_format == ModelFormat::ONNX) {
  76. valid_cpu_backends = {Backend::ORT};
  77. valid_gpu_backends = {Backend::ORT, Backend::TRT};
  78. } else {
  79. valid_cpu_backends = {Backend::PDINFER, Backend::ORT};
  80. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  81. }
  82. runtime_option = custom_option;
  83. runtime_option.model_format = model_format;
  84. runtime_option.model_file = model_file;
  85. runtime_option.params_file = params_file;
  86. initialized = Initialize();
  87. }
  88. bool RetinaFace::Initialize() {
  89. // parameters for preprocess
  90. size = {640, 640};
  91. variance = {0.1f, 0.2f};
  92. downsample_strides = {8, 16, 32};
  93. min_sizes = {{16, 32}, {64, 128}, {256, 512}};
  94. landmarks_per_face = 5;
  95. if (!InitRuntime()) {
  96. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  97. return false;
  98. }
  99. // Check if the input shape is dynamic after Runtime already initialized,
  100. is_dynamic_input_ = false;
  101. auto shape = InputInfoOfRuntime(0).shape;
  102. for (int i = 0; i < shape.size(); ++i) {
  103. // if height or width is dynamic
  104. if (i >= 2 && shape[i] <= 0) {
  105. is_dynamic_input_ = true;
  106. break;
  107. }
  108. }
  109. return true;
  110. }
  111. bool RetinaFace::Preprocess(
  112. Mat *mat, FDTensor *output,
  113. std::map<std::string, std::array<float, 2>> *im_info) {
  114. // retinaface's preprocess steps
  115. // 1. Resize
  116. // 2. Convert(opencv style) or Normalize
  117. // 3. HWC->CHW
  118. int resize_w = size[0];
  119. int resize_h = size[1];
  120. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  121. Resize::Run(mat, resize_w, resize_h);
  122. }
  123. // Compute `result = mat * alpha + beta` directly by channel
  124. // Reference: detect.py#L94
  125. std::vector<float> alpha = {1.f, 1.f, 1.f};
  126. std::vector<float> beta = {-104.f, -117.f, -123.f}; // BGR;
  127. Convert::Run(mat, alpha, beta);
  128. // Record output shape of preprocessed image
  129. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  130. static_cast<float>(mat->Width())};
  131. HWC2CHW::Run(mat);
  132. Cast::Run(mat, "float");
  133. mat->ShareWithTensor(output);
  134. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  135. return true;
  136. }
  137. bool RetinaFace::Postprocess(
  138. std::vector<FDTensor> &infer_result, FaceDetectionResult *result,
  139. const std::map<std::string, std::array<float, 2>> &im_info,
  140. float conf_threshold, float nms_iou_threshold) {
  141. // retinaface has 3 output tensors, boxes & conf & landmarks
  142. FDASSERT(
  143. (infer_result.size() == 3),
  144. "The default number of output tensor must be 3 according to retinaface.");
  145. FDTensor &boxes_tensor = infer_result.at(0); // (1,n,4)
  146. FDTensor &conf_tensor = infer_result.at(1); // (1,n,2)
  147. FDTensor &landmarks_tensor = infer_result.at(2); // (1,n,10)
  148. FDASSERT((boxes_tensor.shape[0] == 1), "Only support batch =1 now.");
  149. if (boxes_tensor.dtype != FDDataType::FP32) {
  150. FDERROR << "Only support post process with float32 data." << std::endl;
  151. return false;
  152. }
  153. result->Clear();
  154. // must be setup landmarks_per_face before reserve
  155. result->landmarks_per_face = landmarks_per_face;
  156. result->Reserve(boxes_tensor.shape[1]);
  157. float *boxes_ptr = static_cast<float *>(boxes_tensor.Data());
  158. float *conf_ptr = static_cast<float *>(conf_tensor.Data());
  159. float *landmarks_ptr = static_cast<float *>(landmarks_tensor.Data());
  160. const size_t num_bboxes = boxes_tensor.shape[1]; // n
  161. // fetch original image shape
  162. auto iter_ipt = im_info.find("input_shape");
  163. FDASSERT((iter_ipt != im_info.end()),
  164. "Cannot find input_shape from im_info.");
  165. float ipt_h = iter_ipt->second[0];
  166. float ipt_w = iter_ipt->second[1];
  167. // generate anchors with dowmsample strides
  168. std::vector<RetinaAnchor> anchors;
  169. GenerateRetinaAnchors(size, downsample_strides, min_sizes, &anchors);
  170. // decode bounding boxes
  171. for (size_t i = 0; i < num_bboxes; ++i) {
  172. float confidence = conf_ptr[2 * i + 1];
  173. // filter boxes by conf_threshold
  174. if (confidence <= conf_threshold) {
  175. continue;
  176. }
  177. float prior_cx = anchors.at(i).cx;
  178. float prior_cy = anchors.at(i).cy;
  179. float prior_s_kx = anchors.at(i).s_kx;
  180. float prior_s_ky = anchors.at(i).s_ky;
  181. // fetch offsets (dx,dy,dw,dh)
  182. float dx = boxes_ptr[4 * i + 0];
  183. float dy = boxes_ptr[4 * i + 1];
  184. float dw = boxes_ptr[4 * i + 2];
  185. float dh = boxes_ptr[4 * i + 3];
  186. // reference: Pytorch_Retinaface/utils/box_utils.py
  187. float x = prior_cx + dx * variance[0] * prior_s_kx;
  188. float y = prior_cy + dy * variance[0] * prior_s_ky;
  189. float w = prior_s_kx * std::exp(dw * variance[1]);
  190. float h = prior_s_ky * std::exp(dh * variance[1]); // (0.~1.)
  191. // from (x,y,w,h) to (x1,y1,x2,y2)
  192. float x1 = (x - w / 2.f) * ipt_w;
  193. float y1 = (y - h / 2.f) * ipt_h;
  194. float x2 = (x + w / 2.f) * ipt_w;
  195. float y2 = (y + h / 2.f) * ipt_h;
  196. result->boxes.emplace_back(std::array<float, 4>{x1, y1, x2, y2});
  197. result->scores.push_back(confidence);
  198. // decode landmarks (default 5 landmarks)
  199. if (landmarks_per_face > 0) {
  200. // reference: utils/box_utils.py#L241
  201. for (size_t j = 0; j < landmarks_per_face * 2; j += 2) {
  202. float ldx = landmarks_ptr[i * (landmarks_per_face * 2) + (j + 0)];
  203. float ldy = landmarks_ptr[i * (landmarks_per_face * 2) + (j + 1)];
  204. float lx = (prior_cx + ldx * variance[0] * prior_s_kx) * ipt_w;
  205. float ly = (prior_cy + ldy * variance[0] * prior_s_ky) * ipt_h;
  206. result->landmarks.emplace_back(std::array<float, 2>{lx, ly});
  207. }
  208. }
  209. }
  210. if (result->boxes.size() == 0) {
  211. return true;
  212. }
  213. utils::NMS(result, nms_iou_threshold);
  214. // scale and clip box
  215. for (size_t i = 0; i < result->boxes.size(); ++i) {
  216. result->boxes[i][0] = std::max(result->boxes[i][0], 0.0f);
  217. result->boxes[i][1] = std::max(result->boxes[i][1], 0.0f);
  218. result->boxes[i][2] = std::max(result->boxes[i][2], 0.0f);
  219. result->boxes[i][3] = std::max(result->boxes[i][3], 0.0f);
  220. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  221. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  222. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  223. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  224. }
  225. // scale and clip landmarks
  226. for (size_t i = 0; i < result->landmarks.size(); ++i) {
  227. result->landmarks[i][0] = std::max(result->landmarks[i][0], 0.0f);
  228. result->landmarks[i][1] = std::max(result->landmarks[i][1], 0.0f);
  229. result->landmarks[i][0] = std::min(result->landmarks[i][0], ipt_w - 1.0f);
  230. result->landmarks[i][1] = std::min(result->landmarks[i][1], ipt_h - 1.0f);
  231. }
  232. return true;
  233. }
  234. bool RetinaFace::Predict(cv::Mat *im, FaceDetectionResult *result,
  235. float conf_threshold, float nms_iou_threshold) {
  236. Mat mat(*im);
  237. std::vector<FDTensor> input_tensors(1);
  238. std::map<std::string, std::array<float, 2>> im_info;
  239. // Record the shape of image and the shape of preprocessed image
  240. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  241. static_cast<float>(mat.Width())};
  242. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  243. static_cast<float>(mat.Width())};
  244. if (!Preprocess(&mat, &input_tensors[0], &im_info)) {
  245. FDERROR << "Failed to preprocess input image." << std::endl;
  246. return false;
  247. }
  248. input_tensors[0].name = InputInfoOfRuntime(0).name;
  249. std::vector<FDTensor> output_tensors;
  250. if (!Infer(input_tensors, &output_tensors)) {
  251. FDERROR << "Failed to inference." << std::endl;
  252. return false;
  253. }
  254. if (!Postprocess(output_tensors, result, im_info, conf_threshold,
  255. nms_iou_threshold)) {
  256. FDERROR << "Failed to post process." << std::endl;
  257. return false;
  258. }
  259. return true;
  260. }
  261. } // namespace facedet
  262. } // namespace vision
  263. } // namespace ultra_infer