ultraface.cc 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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/ultraface.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. UltraFace::UltraFace(const std::string &model_file,
  21. const std::string &params_file,
  22. const RuntimeOption &custom_option,
  23. const ModelFormat &model_format) {
  24. if (model_format == ModelFormat::ONNX) {
  25. valid_cpu_backends = {Backend::ORT};
  26. valid_gpu_backends = {Backend::ORT, Backend::TRT};
  27. } else {
  28. valid_cpu_backends = {Backend::PDINFER, Backend::ORT};
  29. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  30. }
  31. runtime_option = custom_option;
  32. runtime_option.model_format = model_format;
  33. runtime_option.model_file = model_file;
  34. runtime_option.params_file = params_file;
  35. initialized = Initialize();
  36. }
  37. bool UltraFace::Initialize() {
  38. // parameters for preprocess
  39. size = {320, 240};
  40. if (!InitRuntime()) {
  41. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  42. return false;
  43. }
  44. // Check if the input shape is dynamic after Runtime already initialized,
  45. is_dynamic_input_ = false;
  46. auto shape = InputInfoOfRuntime(0).shape;
  47. for (int i = 0; i < shape.size(); ++i) {
  48. // if height or width is dynamic
  49. if (i >= 2 && shape[i] <= 0) {
  50. is_dynamic_input_ = true;
  51. break;
  52. }
  53. }
  54. return true;
  55. }
  56. bool UltraFace::Preprocess(
  57. Mat *mat, FDTensor *output,
  58. std::map<std::string, std::array<float, 2>> *im_info) {
  59. // ultraface's preprocess steps
  60. // 1. resize
  61. // 2. BGR->RGB
  62. // 3. HWC->CHW
  63. int resize_w = size[0];
  64. int resize_h = size[1];
  65. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  66. Resize::Run(mat, resize_w, resize_h);
  67. }
  68. BGR2RGB::Run(mat);
  69. // Compute `result = mat * alpha + beta` directly by channel
  70. // Reference: detect_imgs_onnx.py#L73
  71. std::vector<float> alpha = {1.0f / 128.0f, 1.0f / 128.0f, 1.0f / 128.0f};
  72. std::vector<float> beta = {-127.0f * (1.0f / 128.0f),
  73. -127.0f * (1.0f / 128.0f),
  74. -127.0f * (1.0f / 128.0f)}; // RGB;
  75. Convert::Run(mat, alpha, beta);
  76. // Record output shape of preprocessed image
  77. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  78. static_cast<float>(mat->Width())};
  79. HWC2CHW::Run(mat);
  80. Cast::Run(mat, "float");
  81. mat->ShareWithTensor(output);
  82. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  83. return true;
  84. }
  85. bool UltraFace::Postprocess(
  86. std::vector<FDTensor> &infer_result, FaceDetectionResult *result,
  87. const std::map<std::string, std::array<float, 2>> &im_info,
  88. float conf_threshold, float nms_iou_threshold) {
  89. // ultraface has 2 output tensors, scores & boxes
  90. FDASSERT(
  91. (infer_result.size() == 2),
  92. "The default number of output tensor must be 2 according to ultraface.");
  93. FDTensor &scores_tensor = infer_result.at(0); // (1,4420,2)
  94. FDTensor &boxes_tensor = infer_result.at(1); // (1,4420,4)
  95. FDASSERT((scores_tensor.shape[0] == 1), "Only support batch =1 now.");
  96. FDASSERT((boxes_tensor.shape[0] == 1), "Only support batch =1 now.");
  97. if (scores_tensor.dtype != FDDataType::FP32) {
  98. FDERROR << "Only support post process with float32 data." << std::endl;
  99. return false;
  100. }
  101. if (boxes_tensor.dtype != FDDataType::FP32) {
  102. FDERROR << "Only support post process with float32 data." << std::endl;
  103. return false;
  104. }
  105. result->Clear();
  106. // must be setup landmarks_per_face before reserve.
  107. // ultraface detector does not detect landmarks by default.
  108. result->landmarks_per_face = 0;
  109. result->Reserve(boxes_tensor.shape[1]);
  110. float *scores_ptr = static_cast<float *>(scores_tensor.Data());
  111. float *boxes_ptr = static_cast<float *>(boxes_tensor.Data());
  112. const size_t num_bboxes = boxes_tensor.shape[1]; // e.g 4420
  113. // fetch original image shape
  114. auto iter_ipt = im_info.find("input_shape");
  115. FDASSERT((iter_ipt != im_info.end()),
  116. "Cannot find input_shape from im_info.");
  117. float ipt_h = iter_ipt->second[0];
  118. float ipt_w = iter_ipt->second[1];
  119. // decode bounding boxes
  120. for (size_t i = 0; i < num_bboxes; ++i) {
  121. float confidence = scores_ptr[2 * i + 1];
  122. // filter boxes by conf_threshold
  123. if (confidence <= conf_threshold) {
  124. continue;
  125. }
  126. float x1 = boxes_ptr[4 * i + 0] * ipt_w;
  127. float y1 = boxes_ptr[4 * i + 1] * ipt_h;
  128. float x2 = boxes_ptr[4 * i + 2] * ipt_w;
  129. float y2 = boxes_ptr[4 * i + 3] * ipt_h;
  130. result->boxes.emplace_back(std::array<float, 4>{x1, y1, x2, y2});
  131. result->scores.push_back(confidence);
  132. }
  133. if (result->boxes.size() == 0) {
  134. return true;
  135. }
  136. utils::NMS(result, nms_iou_threshold);
  137. // scale and clip box
  138. for (size_t i = 0; i < result->boxes.size(); ++i) {
  139. result->boxes[i][0] = std::max(result->boxes[i][0], 0.0f);
  140. result->boxes[i][1] = std::max(result->boxes[i][1], 0.0f);
  141. result->boxes[i][2] = std::max(result->boxes[i][2], 0.0f);
  142. result->boxes[i][3] = std::max(result->boxes[i][3], 0.0f);
  143. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  144. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  145. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  146. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  147. }
  148. return true;
  149. }
  150. bool UltraFace::Predict(cv::Mat *im, FaceDetectionResult *result,
  151. float conf_threshold, float nms_iou_threshold) {
  152. Mat mat(*im);
  153. std::vector<FDTensor> input_tensors(1);
  154. std::map<std::string, std::array<float, 2>> im_info;
  155. // Record the shape of image and the shape of preprocessed image
  156. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  157. static_cast<float>(mat.Width())};
  158. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  159. static_cast<float>(mat.Width())};
  160. if (!Preprocess(&mat, &input_tensors[0], &im_info)) {
  161. FDERROR << "Failed to preprocess input image." << std::endl;
  162. return false;
  163. }
  164. input_tensors[0].name = InputInfoOfRuntime(0).name;
  165. std::vector<FDTensor> output_tensors;
  166. if (!Infer(input_tensors, &output_tensors)) {
  167. FDERROR << "Failed to inference." << std::endl;
  168. return false;
  169. }
  170. if (!Postprocess(output_tensors, result, im_info, conf_threshold,
  171. nms_iou_threshold)) {
  172. FDERROR << "Failed to post process." << std::endl;
  173. return false;
  174. }
  175. return true;
  176. }
  177. } // namespace facedet
  178. } // namespace vision
  179. } // namespace ultra_infer