scrfd.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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/scrfd.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 SCRFD::LetterBox(Mat *mat, const std::vector<int> &size,
  21. const std::vector<float> &color, bool _auto,
  22. bool scale_fill, bool scale_up, int stride) {
  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. SCRFD::SCRFD(const std::string &model_file, const std::string &params_file,
  55. const RuntimeOption &custom_option,
  56. const ModelFormat &model_format) {
  57. if (model_format == ModelFormat::ONNX) {
  58. valid_cpu_backends = {Backend::ORT};
  59. valid_gpu_backends = {Backend::ORT, Backend::TRT};
  60. } else {
  61. valid_cpu_backends = {Backend::PDINFER, Backend::ORT, Backend::LITE};
  62. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  63. valid_rknpu_backends = {Backend::RKNPU2};
  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 SCRFD::Initialize() {
  72. // parameters for preprocess
  73. use_kps = true;
  74. size = {640, 640};
  75. padding_value = {0.0, 0.0, 0.0};
  76. is_mini_pad = false;
  77. is_no_pad = false;
  78. is_scale_up = false;
  79. stride = 32;
  80. downsample_strides = {8, 16, 32};
  81. num_anchors = 2;
  82. landmarks_per_face = 5;
  83. center_points_is_update_ = false;
  84. max_nms = 30000;
  85. // num_outputs = use_kps ? 9 : 6;
  86. if (!InitRuntime()) {
  87. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  88. return false;
  89. }
  90. // Check if the input shape is dynamic after Runtime already initialized,
  91. // Note that, We need to force is_mini_pad 'false' to keep static
  92. // shape after padding (LetterBox) when the is_dynamic_shape is 'false'.
  93. is_dynamic_input_ = false;
  94. auto shape = InputInfoOfRuntime(0).shape;
  95. for (int i = 0; i < shape.size(); ++i) {
  96. // if height or width is dynamic
  97. if (i >= 2 && shape[i] <= 0) {
  98. is_dynamic_input_ = true;
  99. break;
  100. }
  101. }
  102. if (!is_dynamic_input_) {
  103. is_mini_pad = false;
  104. }
  105. return true;
  106. }
  107. bool SCRFD::Preprocess(Mat *mat, FDTensor *output,
  108. std::map<std::string, std::array<float, 2>> *im_info) {
  109. float ratio = std::min(size[1] * 1.0f / static_cast<float>(mat->Height()),
  110. size[0] * 1.0f / static_cast<float>(mat->Width()));
  111. if (std::fabs(ratio - 1.0f) > 1e-06) {
  112. int interp = cv::INTER_LINEAR;
  113. if (ratio > 1.0) {
  114. interp = cv::INTER_LINEAR;
  115. }
  116. int resize_h = int(mat->Height() * ratio);
  117. int resize_w = int(mat->Width() * ratio);
  118. Resize::Run(mat, resize_w, resize_h, -1, -1, interp);
  119. }
  120. // scrfd's preprocess steps
  121. // 1. letterbox
  122. // 2. BGR->RGB
  123. // 3. HWC->CHW
  124. SCRFD::LetterBox(mat, size, padding_value, is_mini_pad, is_no_pad,
  125. is_scale_up, stride);
  126. BGR2RGB::Run(mat);
  127. if (!disable_normalize_) {
  128. // Normalize::Run(mat, std::vector<float>(mat->Channels(), 0.0),
  129. // std::vector<float>(mat->Channels(), 1.0));
  130. // Compute `result = mat * alpha + beta` directly by channel
  131. // Original Repo/tools/scrfd.py: cv2.dnn.blobFromImage(img, 1.0/128,
  132. // input_size, (127.5, 127.5, 127.5), swapRB=True)
  133. std::vector<float> alpha = {1.f / 128.f, 1.f / 128.f, 1.f / 128.f};
  134. std::vector<float> beta = {-127.5f / 128.f, -127.5f / 128.f,
  135. -127.5f / 128.f};
  136. Convert::Run(mat, alpha, beta);
  137. }
  138. if (!disable_permute_) {
  139. HWC2CHW::Run(mat);
  140. Cast::Run(mat, "float");
  141. }
  142. // Record output shape of preprocessed image
  143. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  144. static_cast<float>(mat->Width())};
  145. mat->ShareWithTensor(output);
  146. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  147. return true;
  148. }
  149. void SCRFD::GeneratePoints() {
  150. if (center_points_is_update_ && !is_dynamic_input_) {
  151. return;
  152. }
  153. // 8, 16, 32
  154. for (auto local_stride : downsample_strides) {
  155. unsigned int num_grid_w = size[0] / local_stride;
  156. unsigned int num_grid_h = size[1] / local_stride;
  157. // y
  158. for (unsigned int i = 0; i < num_grid_h; ++i) {
  159. // x
  160. for (unsigned int j = 0; j < num_grid_w; ++j) {
  161. // num_anchors, col major
  162. for (unsigned int k = 0; k < num_anchors; ++k) {
  163. SCRFDPoint point;
  164. point.cx = static_cast<float>(j);
  165. point.cy = static_cast<float>(i);
  166. center_points_[local_stride].push_back(point);
  167. }
  168. }
  169. }
  170. }
  171. center_points_is_update_ = true;
  172. }
  173. bool SCRFD::Postprocess(
  174. std::vector<FDTensor> &infer_result, FaceDetectionResult *result,
  175. const std::map<std::string, std::array<float, 2>> &im_info,
  176. float conf_threshold, float nms_iou_threshold) {
  177. // number of downsample_strides
  178. int fmc = downsample_strides.size();
  179. // scrfd has 6,9,10,15 output tensors
  180. FDASSERT((infer_result.size() == 9 || infer_result.size() == 6 ||
  181. infer_result.size() == 10 || infer_result.size() == 15),
  182. "The default number of output tensor must be 6, 9, 10, or 15 "
  183. "according to scrfd.");
  184. FDASSERT((fmc == 3 || fmc == 5), "The fmc must be 3 or 5");
  185. FDASSERT((infer_result.at(0).shape[0] == 1), "Only support batch =1 now.");
  186. for (int i = 0; i < fmc; ++i) {
  187. if (infer_result.at(i).dtype != FDDataType::FP32) {
  188. FDERROR << "Only support post process with float32 data." << std::endl;
  189. return false;
  190. }
  191. }
  192. int total_num_boxes = 0;
  193. // compute the reserve space.
  194. for (int f = 0; f < fmc; ++f) {
  195. total_num_boxes += infer_result.at(f).shape[1];
  196. };
  197. GeneratePoints();
  198. result->Clear();
  199. // scale the boxes to the origin image shape
  200. auto iter_out = im_info.find("output_shape");
  201. auto iter_ipt = im_info.find("input_shape");
  202. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  203. "Cannot find input_shape or output_shape from im_info.");
  204. float out_h = iter_out->second[0];
  205. float out_w = iter_out->second[1];
  206. float ipt_h = iter_ipt->second[0];
  207. float ipt_w = iter_ipt->second[1];
  208. float scale = std::min(out_h / ipt_h, out_w / ipt_w);
  209. if (!is_scale_up) {
  210. scale = std::min(scale, 1.0f);
  211. }
  212. float pad_h = (out_h - ipt_h * scale) / 2.0f;
  213. float pad_w = (out_w - ipt_w * scale) / 2.0f;
  214. if (is_mini_pad) {
  215. pad_h = static_cast<float>(static_cast<int>(pad_h) % stride);
  216. pad_w = static_cast<float>(static_cast<int>(pad_w) % stride);
  217. }
  218. // must be setup landmarks_per_face before reserve
  219. if (use_kps) {
  220. result->landmarks_per_face = landmarks_per_face;
  221. } else {
  222. // force landmarks_per_face = 0, if use_kps has been set as 'false'.
  223. result->landmarks_per_face = 0;
  224. }
  225. result->Reserve(total_num_boxes);
  226. unsigned int count = 0;
  227. // loop each stride
  228. for (int f = 0; f < fmc; ++f) {
  229. float *score_ptr = static_cast<float *>(infer_result.at(f).Data());
  230. float *bbox_ptr = static_cast<float *>(infer_result.at(f + fmc).Data());
  231. const unsigned int num_points = infer_result.at(f).shape[1];
  232. int current_stride = downsample_strides[f];
  233. auto &stride_points = center_points_[current_stride];
  234. // loop each anchor
  235. for (unsigned int i = 0; i < num_points; ++i) {
  236. const float cls_conf = score_ptr[i];
  237. if (cls_conf < conf_threshold)
  238. continue; // filter
  239. auto &point = stride_points.at(i);
  240. const float cx = point.cx; // cx
  241. const float cy = point.cy; // cy
  242. // bbox
  243. const float *offsets = bbox_ptr + i * 4;
  244. float l = offsets[0]; // left
  245. float t = offsets[1]; // top
  246. float r = offsets[2]; // right
  247. float b = offsets[3]; // bottom
  248. float x1 = ((cx - l) * static_cast<float>(current_stride) -
  249. static_cast<float>(pad_w)) /
  250. scale; // cx - l x1
  251. float y1 = ((cy - t) * static_cast<float>(current_stride) -
  252. static_cast<float>(pad_h)) /
  253. scale; // cy - t y1
  254. float x2 = ((cx + r) * static_cast<float>(current_stride) -
  255. static_cast<float>(pad_w)) /
  256. scale; // cx + r x2
  257. float y2 = ((cy + b) * static_cast<float>(current_stride) -
  258. static_cast<float>(pad_h)) /
  259. scale; // cy + b y2
  260. result->boxes.emplace_back(std::array<float, 4>{x1, y1, x2, y2});
  261. result->scores.push_back(cls_conf);
  262. if (use_kps) {
  263. float *landmarks_ptr =
  264. static_cast<float *>(infer_result.at(f + 2 * fmc).Data());
  265. // landmarks
  266. const float *kps_offsets = landmarks_ptr + i * (landmarks_per_face * 2);
  267. for (unsigned int j = 0; j < landmarks_per_face * 2; j += 2) {
  268. float kps_l = kps_offsets[j];
  269. float kps_t = kps_offsets[j + 1];
  270. float kps_x = ((cx + kps_l) * static_cast<float>(current_stride) -
  271. static_cast<float>(pad_w)) /
  272. scale; // cx + l x
  273. float kps_y = ((cy + kps_t) * static_cast<float>(current_stride) -
  274. static_cast<float>(pad_h)) /
  275. scale; // cy + t y
  276. result->landmarks.emplace_back(std::array<float, 2>{kps_x, kps_y});
  277. }
  278. }
  279. count += 1; // limit boxes for nms.
  280. if (count > max_nms) {
  281. break;
  282. }
  283. }
  284. }
  285. // fetch original image shape
  286. FDASSERT((iter_ipt != im_info.end()),
  287. "Cannot find input_shape from im_info.");
  288. if (result->boxes.size() == 0) {
  289. return true;
  290. }
  291. utils::NMS(result, nms_iou_threshold);
  292. // scale and clip box
  293. for (size_t i = 0; i < result->boxes.size(); ++i) {
  294. result->boxes[i][0] = std::max(result->boxes[i][0], 0.0f);
  295. result->boxes[i][1] = std::max(result->boxes[i][1], 0.0f);
  296. result->boxes[i][2] = std::max(result->boxes[i][2], 0.0f);
  297. result->boxes[i][3] = std::max(result->boxes[i][3], 0.0f);
  298. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  299. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  300. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  301. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  302. }
  303. // scale and clip landmarks
  304. if (use_kps) {
  305. for (size_t i = 0; i < result->landmarks.size(); ++i) {
  306. result->landmarks[i][0] = std::max(result->landmarks[i][0], 0.0f);
  307. result->landmarks[i][1] = std::max(result->landmarks[i][1], 0.0f);
  308. result->landmarks[i][0] = std::min(result->landmarks[i][0], ipt_w - 1.0f);
  309. result->landmarks[i][1] = std::min(result->landmarks[i][1], ipt_h - 1.0f);
  310. }
  311. }
  312. return true;
  313. }
  314. bool SCRFD::Predict(cv::Mat *im, FaceDetectionResult *result,
  315. float conf_threshold, float nms_iou_threshold) {
  316. Mat mat(*im);
  317. std::vector<FDTensor> input_tensors(1);
  318. std::map<std::string, std::array<float, 2>> im_info;
  319. // Record the shape of image and the shape of preprocessed image
  320. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  321. static_cast<float>(mat.Width())};
  322. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  323. static_cast<float>(mat.Width())};
  324. if (!Preprocess(&mat, &input_tensors[0], &im_info)) {
  325. FDERROR << "Failed to preprocess input image." << std::endl;
  326. return false;
  327. }
  328. input_tensors[0].name = InputInfoOfRuntime(0).name;
  329. std::vector<FDTensor> output_tensors;
  330. if (!Infer(input_tensors, &output_tensors)) {
  331. FDERROR << "Failed to inference." << std::endl;
  332. return false;
  333. }
  334. if (!Postprocess(output_tensors, result, im_info, conf_threshold,
  335. nms_iou_threshold)) {
  336. FDERROR << "Failed to post process." << std::endl;
  337. return false;
  338. }
  339. return true;
  340. }
  341. void SCRFD::DisableNormalize() { disable_normalize_ = true; }
  342. void SCRFD::DisablePermute() { disable_permute_ = true; }
  343. } // namespace facedet
  344. } // namespace vision
  345. } // namespace ultra_infer