nanodet_plus.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // Licensed under the Apache License, Version 2.0 (the "License");
  2. // you may not use this file except in compliance with the License.
  3. // You may obtain a copy of the License at
  4. //
  5. // http://www.apache.org/licenses/LICENSE-2.0
  6. //
  7. // Unless required by applicable law or agreed to in writing, software
  8. // distributed under the License is distributed on an "AS IS" BASIS,
  9. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. // See the License for the specific language governing permissions and
  11. // limitations under the License.
  12. #include "ultra_infer/vision/detection/contrib/nanodet_plus.h"
  13. #include "ultra_infer/utils/perf.h"
  14. #include "ultra_infer/vision/utils/utils.h"
  15. namespace ultra_infer {
  16. namespace vision {
  17. namespace detection {
  18. struct NanoDetPlusCenterPoint {
  19. int grid0;
  20. int grid1;
  21. int stride;
  22. };
  23. void GenerateNanoDetPlusCenterPoints(
  24. const std::vector<int> &size, const std::vector<int> &downsample_strides,
  25. std::vector<NanoDetPlusCenterPoint> *center_points) {
  26. // size: tuple of input (width, height), e.g (320, 320)
  27. // downsample_strides: downsample strides in NanoDet and
  28. // NanoDet-Plus, e.g (8, 16, 32, 64)
  29. const int width = size[0];
  30. const int height = size[1];
  31. for (const auto &ds : downsample_strides) {
  32. int num_grid_w = width / ds;
  33. int num_grid_h = height / ds;
  34. for (int g1 = 0; g1 < num_grid_h; ++g1) {
  35. for (int g0 = 0; g0 < num_grid_w; ++g0) {
  36. (*center_points).emplace_back(NanoDetPlusCenterPoint{g0, g1, ds});
  37. }
  38. }
  39. }
  40. }
  41. void WrapAndResize(Mat *mat, std::vector<int> size, std::vector<float> color,
  42. bool keep_ratio = false) {
  43. // Reference: nanodet/data/transform/warp.py#L139
  44. // size: tuple of input (width, height)
  45. // The default value of `keep_ratio` is `false` in
  46. // `config/nanodet-plus-m-1.5x_320.yml` for both
  47. // train and val processes. So, we just let this
  48. // option default `false` according to the official
  49. // implementation in NanoDet and NanoDet-Plus.
  50. // Note, this function will apply a normal resize
  51. // operation to input Mat if the keep_ratio option
  52. // is false and the behavior will be the same as
  53. // yolov5's letterbox if keep_ratio is true.
  54. // with keep_ratio = false (default)
  55. if (!keep_ratio) {
  56. int resize_h = size[1];
  57. int resize_w = size[0];
  58. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  59. Resize::Run(mat, resize_w, resize_h);
  60. }
  61. return;
  62. }
  63. // with keep_ratio = true, same as yolov5's letterbox
  64. float r = std::min(size[1] * 1.0f / static_cast<float>(mat->Height()),
  65. size[0] * 1.0f / static_cast<float>(mat->Width()));
  66. int resize_h = int(round(static_cast<float>(mat->Height()) * r));
  67. int resize_w = int(round(static_cast<float>(mat->Width()) * r));
  68. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  69. Resize::Run(mat, resize_w, resize_h);
  70. }
  71. int pad_w = size[0] - resize_w;
  72. int pad_h = size[1] - resize_h;
  73. if (pad_h > 0 || pad_w > 0) {
  74. float half_h = pad_h * 1.0 / 2;
  75. int top = int(round(half_h - 0.1));
  76. int bottom = int(round(half_h + 0.1));
  77. float half_w = pad_w * 1.0 / 2;
  78. int left = int(round(half_w - 0.1));
  79. int right = int(round(half_w + 0.1));
  80. Pad::Run(mat, top, bottom, left, right, color);
  81. }
  82. }
  83. void GFLRegression(const float *logits, size_t reg_num, float *offset) {
  84. // Hint: reg_num = reg_max + 1
  85. FDASSERT(((nullptr != logits) && (reg_num != 0)),
  86. "NanoDetPlus: logits is nullptr or reg_num is 0 in GFLRegression.");
  87. // softmax
  88. float total_exp = 0.f;
  89. std::vector<float> softmax_probs(reg_num);
  90. for (size_t i = 0; i < reg_num; ++i) {
  91. softmax_probs[i] = std::exp(logits[i]);
  92. total_exp += softmax_probs[i];
  93. }
  94. for (size_t i = 0; i < reg_num; ++i) {
  95. softmax_probs[i] = softmax_probs[i] / total_exp;
  96. }
  97. // gfl regression -> offset
  98. for (size_t i = 0; i < reg_num; ++i) {
  99. (*offset) += static_cast<float>(i) * softmax_probs[i];
  100. }
  101. }
  102. NanoDetPlus::NanoDetPlus(const std::string &model_file,
  103. const std::string &params_file,
  104. const RuntimeOption &custom_option,
  105. const ModelFormat &model_format) {
  106. if (model_format == ModelFormat::ONNX) {
  107. valid_cpu_backends = {Backend::ORT};
  108. valid_gpu_backends = {Backend::ORT, Backend::TRT};
  109. } else {
  110. valid_cpu_backends = {Backend::PDINFER, Backend::ORT};
  111. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  112. }
  113. runtime_option = custom_option;
  114. runtime_option.model_format = model_format;
  115. runtime_option.model_file = model_file;
  116. runtime_option.params_file = params_file;
  117. initialized = Initialize();
  118. }
  119. bool NanoDetPlus::Initialize() {
  120. // parameters for preprocess
  121. size = {320, 320};
  122. padding_value = {0.0f, 0.0f, 0.0f};
  123. keep_ratio = false;
  124. downsample_strides = {8, 16, 32, 64};
  125. max_wh = 4096.0f;
  126. reg_max = 7;
  127. if (!InitRuntime()) {
  128. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  129. return false;
  130. }
  131. // Check if the input shape is dynamic after Runtime already initialized.
  132. is_dynamic_input_ = false;
  133. auto shape = InputInfoOfRuntime(0).shape;
  134. for (int i = 0; i < shape.size(); ++i) {
  135. // if height or width is dynamic
  136. if (i >= 2 && shape[i] <= 0) {
  137. is_dynamic_input_ = true;
  138. break;
  139. }
  140. }
  141. return true;
  142. }
  143. bool NanoDetPlus::Preprocess(
  144. Mat *mat, FDTensor *output,
  145. std::map<std::string, std::array<float, 2>> *im_info) {
  146. // NanoDet-Plus preprocess steps
  147. // 1. WrapAndResize
  148. // 2. HWC->CHW
  149. // 3. Normalize or Convert (keep BGR order)
  150. WrapAndResize(mat, size, padding_value, keep_ratio);
  151. // Record output shape of preprocessed image
  152. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  153. static_cast<float>(mat->Width())};
  154. // Compute `result = mat * alpha + beta` directly by channel
  155. // Reference: /config/nanodet-plus-m-1.5x_320.yml#L89
  156. // from mean: [103.53, 116.28, 123.675], std: [57.375, 57.12, 58.395]
  157. // x' = (x - mean) / std to x'= x * alpha + beta.
  158. // e.g alpha[0] = 0.017429f = 1.0f / 57.375f
  159. // e.g beta[0] = -103.53f * 0.0174291f
  160. std::vector<float> alpha = {0.017429f, 0.017507f, 0.017125f};
  161. std::vector<float> beta = {-103.53f * 0.0174291f, -116.28f * 0.0175070f,
  162. -123.675f * 0.0171247f}; // BGR order
  163. Convert::Run(mat, alpha, beta);
  164. HWC2CHW::Run(mat);
  165. Cast::Run(mat, "float");
  166. mat->ShareWithTensor(output);
  167. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  168. return true;
  169. }
  170. bool NanoDetPlus::Postprocess(
  171. FDTensor &infer_result, DetectionResult *result,
  172. const std::map<std::string, std::array<float, 2>> &im_info,
  173. float conf_threshold, float nms_iou_threshold) {
  174. FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now.");
  175. result->Clear();
  176. result->Reserve(infer_result.shape[1]);
  177. if (infer_result.dtype != FDDataType::FP32) {
  178. FDERROR << "Only support post process with float32 data." << std::endl;
  179. return false;
  180. }
  181. // generate center points with dowmsample strides
  182. std::vector<NanoDetPlusCenterPoint> center_points;
  183. GenerateNanoDetPlusCenterPoints(size, downsample_strides, &center_points);
  184. // infer_result shape might look like (1,2125,112)
  185. const int num_cls_reg = infer_result.shape[2]; // e.g 112
  186. const int num_classes = num_cls_reg - (reg_max + 1) * 4; // e.g 80
  187. float *data = static_cast<float *>(infer_result.Data());
  188. for (size_t i = 0; i < infer_result.shape[1]; ++i) {
  189. float *scores = data + i * num_cls_reg;
  190. float *max_class_score = std::max_element(scores, scores + num_classes);
  191. float confidence = (*max_class_score);
  192. // filter boxes by conf_threshold
  193. if (confidence <= conf_threshold) {
  194. continue;
  195. }
  196. int32_t label_id = std::distance(scores, max_class_score);
  197. // fetch i-th center point
  198. float grid0 = static_cast<float>(center_points.at(i).grid0);
  199. float grid1 = static_cast<float>(center_points.at(i).grid1);
  200. float downsample_stride = static_cast<float>(center_points.at(i).stride);
  201. // apply gfl regression to get offsets (l,t,r,b)
  202. float *logits = data + i * num_cls_reg + num_classes; // 32|44...
  203. std::vector<float> offsets(4);
  204. for (size_t j = 0; j < 4; ++j) {
  205. GFLRegression(logits + j * (reg_max + 1), reg_max + 1, &offsets[j]);
  206. }
  207. // convert from offsets to [x1, y1, x2, y2]
  208. float l = offsets[0]; // left
  209. float t = offsets[1]; // top
  210. float r = offsets[2]; // right
  211. float b = offsets[3]; // bottom
  212. float x1 = (grid0 - l) * downsample_stride; // cx - l x1
  213. float y1 = (grid1 - t) * downsample_stride; // cy - t y1
  214. float x2 = (grid0 + r) * downsample_stride; // cx + r x2
  215. float y2 = (grid1 + b) * downsample_stride; // cy + b y2
  216. result->boxes.emplace_back(
  217. std::array<float, 4>{x1 + label_id * max_wh, y1 + label_id * max_wh,
  218. x2 + label_id * max_wh, y2 + label_id * max_wh});
  219. // label_id * max_wh for multi classes NMS
  220. result->label_ids.push_back(label_id);
  221. result->scores.push_back(confidence);
  222. }
  223. utils::NMS(result, nms_iou_threshold);
  224. // scale the boxes to the origin image shape
  225. auto iter_out = im_info.find("output_shape");
  226. auto iter_ipt = im_info.find("input_shape");
  227. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  228. "Cannot find input_shape or output_shape from im_info.");
  229. float out_h = iter_out->second[0];
  230. float out_w = iter_out->second[1];
  231. float ipt_h = iter_ipt->second[0];
  232. float ipt_w = iter_ipt->second[1];
  233. // without keep_ratio
  234. if (!keep_ratio) {
  235. // x' = (x / out_w) * ipt_w = x / (out_w / ipt_w)
  236. // y' = (y / out_h) * ipt_h = y / (out_h / ipt_h)
  237. float r_w = out_w / ipt_w;
  238. float r_h = out_h / ipt_h;
  239. for (size_t i = 0; i < result->boxes.size(); ++i) {
  240. int32_t label_id = (result->label_ids)[i];
  241. // clip box
  242. result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id;
  243. result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id;
  244. result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id;
  245. result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id;
  246. result->boxes[i][0] = std::max(result->boxes[i][0] / r_w, 0.0f);
  247. result->boxes[i][1] = std::max(result->boxes[i][1] / r_h, 0.0f);
  248. result->boxes[i][2] = std::max(result->boxes[i][2] / r_w, 0.0f);
  249. result->boxes[i][3] = std::max(result->boxes[i][3] / r_h, 0.0f);
  250. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  251. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  252. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  253. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  254. }
  255. return true;
  256. }
  257. // with keep_ratio
  258. float r = std::min(out_h / ipt_h, out_w / ipt_w);
  259. float pad_h = (out_h - ipt_h * r) / 2;
  260. float pad_w = (out_w - ipt_w * r) / 2;
  261. for (size_t i = 0; i < result->boxes.size(); ++i) {
  262. int32_t label_id = (result->label_ids)[i];
  263. // clip box
  264. result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id;
  265. result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id;
  266. result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id;
  267. result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id;
  268. result->boxes[i][0] = std::max((result->boxes[i][0] - pad_w) / r, 0.0f);
  269. result->boxes[i][1] = std::max((result->boxes[i][1] - pad_h) / r, 0.0f);
  270. result->boxes[i][2] = std::max((result->boxes[i][2] - pad_w) / r, 0.0f);
  271. result->boxes[i][3] = std::max((result->boxes[i][3] - pad_h) / r, 0.0f);
  272. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  273. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  274. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  275. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  276. }
  277. return true;
  278. }
  279. bool NanoDetPlus::Predict(cv::Mat *im, DetectionResult *result,
  280. float conf_threshold, float nms_iou_threshold) {
  281. Mat mat(*im);
  282. std::vector<FDTensor> input_tensors(1);
  283. std::map<std::string, std::array<float, 2>> im_info;
  284. // Record the shape of image and the shape of preprocessed image
  285. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  286. static_cast<float>(mat.Width())};
  287. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  288. static_cast<float>(mat.Width())};
  289. if (!Preprocess(&mat, &input_tensors[0], &im_info)) {
  290. FDERROR << "Failed to preprocess input image." << std::endl;
  291. return false;
  292. }
  293. input_tensors[0].name = InputInfoOfRuntime(0).name;
  294. std::vector<FDTensor> output_tensors;
  295. if (!Infer(input_tensors, &output_tensors)) {
  296. FDERROR << "Failed to inference." << std::endl;
  297. return false;
  298. }
  299. if (!Postprocess(output_tensors[0], result, im_info, conf_threshold,
  300. nms_iou_threshold)) {
  301. FDERROR << "Failed to post process." << std::endl;
  302. return false;
  303. }
  304. return true;
  305. }
  306. } // namespace detection
  307. } // namespace vision
  308. } // namespace ultra_infer