yolov5face.cc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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/yolov5face.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. void LetterBox(Mat *mat, std::vector<int> size, std::vector<float> color,
  21. bool _auto, bool scale_fill = false, bool scale_up = true,
  22. int stride = 32) {
  23. float scale =
  24. std::min(size[1] * 1.0 / mat->Height(), size[0] * 1.0 / mat->Width());
  25. if (!scale_up) {
  26. scale = std::min(scale, 1.0f);
  27. }
  28. int resize_h = int(round(mat->Height() * scale));
  29. int resize_w = int(round(mat->Width() * scale));
  30. int pad_w = size[0] - resize_w;
  31. int pad_h = size[1] - resize_h;
  32. if (_auto) {
  33. pad_h = pad_h % stride;
  34. pad_w = pad_w % stride;
  35. } else if (scale_fill) {
  36. pad_h = 0;
  37. pad_w = 0;
  38. resize_h = size[1];
  39. resize_w = size[0];
  40. }
  41. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  42. Resize::Run(mat, resize_w, resize_h);
  43. }
  44. if (pad_h > 0 || pad_w > 0) {
  45. float half_h = pad_h * 1.0 / 2;
  46. int top = int(round(half_h - 0.1));
  47. int bottom = int(round(half_h + 0.1));
  48. float half_w = pad_w * 1.0 / 2;
  49. int left = int(round(half_w - 0.1));
  50. int right = int(round(half_w + 0.1));
  51. Pad::Run(mat, top, bottom, left, right, color);
  52. }
  53. }
  54. YOLOv5Face::YOLOv5Face(const std::string &model_file,
  55. const std::string &params_file,
  56. const RuntimeOption &custom_option,
  57. const ModelFormat &model_format) {
  58. if (model_format == ModelFormat::ONNX) {
  59. valid_cpu_backends = {Backend::ORT};
  60. valid_gpu_backends = {Backend::ORT, Backend::TRT};
  61. } else {
  62. valid_cpu_backends = {Backend::PDINFER, Backend::ORT, Backend::LITE};
  63. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  64. }
  65. runtime_option = custom_option;
  66. runtime_option.model_format = model_format;
  67. runtime_option.model_file = model_file;
  68. runtime_option.params_file = params_file;
  69. initialized = Initialize();
  70. }
  71. bool YOLOv5Face::Initialize() {
  72. // parameters for preprocess
  73. size = {640, 640};
  74. padding_value = {114.0, 114.0, 114.0};
  75. is_mini_pad = false;
  76. is_no_pad = false;
  77. is_scale_up = false;
  78. stride = 32;
  79. landmarks_per_face = 5;
  80. if (!InitRuntime()) {
  81. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  82. return false;
  83. }
  84. // Check if the input shape is dynamic after Runtime already initialized,
  85. // Note that, We need to force is_mini_pad 'false' to keep static
  86. // shape after padding (LetterBox) when the is_dynamic_input_ is 'false'.
  87. is_dynamic_input_ = false;
  88. auto shape = InputInfoOfRuntime(0).shape;
  89. for (int i = 0; i < shape.size(); ++i) {
  90. // if height or width is dynamic
  91. if (i >= 2 && shape[i] <= 0) {
  92. is_dynamic_input_ = true;
  93. break;
  94. }
  95. }
  96. if (!is_dynamic_input_) {
  97. is_mini_pad = false;
  98. }
  99. return true;
  100. }
  101. bool YOLOv5Face::Preprocess(
  102. Mat *mat, FDTensor *output,
  103. std::map<std::string, std::array<float, 2>> *im_info) {
  104. // process after image load
  105. float ratio = std::min(size[1] * 1.0f / static_cast<float>(mat->Height()),
  106. size[0] * 1.0f / static_cast<float>(mat->Width()));
  107. if (std::fabs(ratio - 1.0f) > 1e-06) {
  108. int interp = cv::INTER_LINEAR;
  109. if (ratio > 1.0) {
  110. interp = cv::INTER_LINEAR;
  111. }
  112. int resize_h = int(round(static_cast<float>(mat->Height()) * ratio));
  113. int resize_w = int(round(static_cast<float>(mat->Width()) * ratio));
  114. Resize::Run(mat, resize_w, resize_h, -1, -1, interp);
  115. }
  116. // yolov5face's preprocess steps
  117. // 1. letterbox
  118. // 2. BGR->RGB
  119. // 3. HWC->CHW
  120. LetterBox(mat, size, padding_value, is_mini_pad, is_no_pad, is_scale_up,
  121. stride);
  122. BGR2RGB::Run(mat);
  123. // Normalize::Run(mat, std::vector<float>(mat->Channels(), 0.0),
  124. // std::vector<float>(mat->Channels(), 1.0));
  125. // Compute `result = mat * alpha + beta` directly by channel
  126. std::vector<float> alpha = {1.0f / 255.0f, 1.0f / 255.0f, 1.0f / 255.0f};
  127. std::vector<float> beta = {0.0f, 0.0f, 0.0f};
  128. Convert::Run(mat, alpha, beta);
  129. // Record output shape of preprocessed image
  130. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  131. static_cast<float>(mat->Width())};
  132. HWC2CHW::Run(mat);
  133. Cast::Run(mat, "float");
  134. mat->ShareWithTensor(output);
  135. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  136. return true;
  137. }
  138. bool YOLOv5Face::Postprocess(
  139. FDTensor &infer_result, FaceDetectionResult *result,
  140. const std::map<std::string, std::array<float, 2>> &im_info,
  141. float conf_threshold, float nms_iou_threshold) {
  142. // infer_result: (1,n,16) 16=4+1+10+1
  143. FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now.");
  144. if (infer_result.dtype != FDDataType::FP32) {
  145. FDERROR << "Only support post process with float32 data." << std::endl;
  146. return false;
  147. }
  148. result->Clear();
  149. // must be setup landmarks_per_face before reserve
  150. result->landmarks_per_face = landmarks_per_face;
  151. result->Reserve(infer_result.shape[1]);
  152. float *data = static_cast<float *>(infer_result.Data());
  153. for (size_t i = 0; i < infer_result.shape[1]; ++i) {
  154. float *reg_cls_ptr = data + (i * infer_result.shape[2]);
  155. float obj_conf = reg_cls_ptr[4];
  156. float cls_conf = reg_cls_ptr[15];
  157. float confidence = obj_conf * cls_conf;
  158. // filter boxes by conf_threshold
  159. if (confidence <= conf_threshold) {
  160. continue;
  161. }
  162. float x = reg_cls_ptr[0];
  163. float y = reg_cls_ptr[1];
  164. float w = reg_cls_ptr[2];
  165. float h = reg_cls_ptr[3];
  166. // convert from [x, y, w, h] to [x1, y1, x2, y2]
  167. result->boxes.emplace_back(std::array<float, 4>{
  168. (x - w / 2.f), (y - h / 2.f), (x + w / 2.f), (y + h / 2.f)});
  169. result->scores.push_back(confidence);
  170. // decode landmarks (default 5 landmarks)
  171. if (landmarks_per_face > 0) {
  172. float *landmarks_ptr = reg_cls_ptr + 5;
  173. for (size_t j = 0; j < landmarks_per_face * 2; j += 2) {
  174. result->landmarks.emplace_back(
  175. std::array<float, 2>{landmarks_ptr[j], landmarks_ptr[j + 1]});
  176. }
  177. }
  178. }
  179. if (result->boxes.size() == 0) {
  180. return true;
  181. }
  182. utils::NMS(result, nms_iou_threshold);
  183. // scale the boxes to the origin image shape
  184. auto iter_out = im_info.find("output_shape");
  185. auto iter_ipt = im_info.find("input_shape");
  186. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  187. "Cannot find input_shape or output_shape from im_info.");
  188. float out_h = iter_out->second[0];
  189. float out_w = iter_out->second[1];
  190. float ipt_h = iter_ipt->second[0];
  191. float ipt_w = iter_ipt->second[1];
  192. float scale = std::min(out_h / ipt_h, out_w / ipt_w);
  193. if (!is_scale_up) {
  194. scale = std::min(scale, 1.0f);
  195. }
  196. float pad_h = (out_h - ipt_h * scale) / 2.f;
  197. float pad_w = (out_w - ipt_w * scale) / 2.f;
  198. if (is_mini_pad) {
  199. pad_h = static_cast<float>(static_cast<int>(pad_h) % stride);
  200. pad_w = static_cast<float>(static_cast<int>(pad_w) % stride);
  201. }
  202. // scale and clip box
  203. for (size_t i = 0; i < result->boxes.size(); ++i) {
  204. result->boxes[i][0] = std::max((result->boxes[i][0] - pad_w) / scale, 0.0f);
  205. result->boxes[i][1] = std::max((result->boxes[i][1] - pad_h) / scale, 0.0f);
  206. result->boxes[i][2] = std::max((result->boxes[i][2] - pad_w) / scale, 0.0f);
  207. result->boxes[i][3] = std::max((result->boxes[i][3] - pad_h) / scale, 0.0f);
  208. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  209. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  210. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  211. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  212. }
  213. // scale and clip landmarks
  214. for (size_t i = 0; i < result->landmarks.size(); ++i) {
  215. result->landmarks[i][0] =
  216. std::max((result->landmarks[i][0] - pad_w) / scale, 0.0f);
  217. result->landmarks[i][1] =
  218. std::max((result->landmarks[i][1] - pad_h) / scale, 0.0f);
  219. result->landmarks[i][0] = std::min(result->landmarks[i][0], ipt_w - 1.0f);
  220. result->landmarks[i][1] = std::min(result->landmarks[i][1], ipt_h - 1.0f);
  221. }
  222. return true;
  223. }
  224. bool YOLOv5Face::Predict(cv::Mat *im, FaceDetectionResult *result,
  225. float conf_threshold, float nms_iou_threshold) {
  226. Mat mat(*im);
  227. std::vector<FDTensor> input_tensors(1);
  228. std::map<std::string, std::array<float, 2>> im_info;
  229. // Record the shape of image and the shape of preprocessed image
  230. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  231. static_cast<float>(mat.Width())};
  232. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  233. static_cast<float>(mat.Width())};
  234. if (!Preprocess(&mat, &input_tensors[0], &im_info)) {
  235. FDERROR << "Failed to preprocess input image." << std::endl;
  236. return false;
  237. }
  238. input_tensors[0].name = InputInfoOfRuntime(0).name;
  239. std::vector<FDTensor> output_tensors;
  240. if (!Infer(input_tensors, &output_tensors)) {
  241. FDERROR << "Failed to inference." << std::endl;
  242. return false;
  243. }
  244. if (!Postprocess(output_tensors[0], result, im_info, conf_threshold,
  245. nms_iou_threshold)) {
  246. FDERROR << "Failed to post process." << std::endl;
  247. return false;
  248. }
  249. return true;
  250. }
  251. } // namespace facedet
  252. } // namespace vision
  253. } // namespace ultra_infer