scaledyolov4.cc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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/detection/contrib/scaledyolov4.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 detection {
  20. void ScaledYOLOv4::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. ScaledYOLOv4::ScaledYOLOv4(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};
  63. valid_gpu_backends = {Backend::PDINFER};
  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 ScaledYOLOv4::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. max_wh = 7680.0;
  80. reused_input_tensors_.resize(1);
  81. if (!InitRuntime()) {
  82. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  83. return false;
  84. }
  85. // Check if the input shape is dynamic after Runtime already initialized,
  86. // Note that, We need to force is_mini_pad 'false' to keep static
  87. // shape after padding (LetterBox) when the is_dynamic_shape is 'false'.
  88. is_dynamic_input_ = false;
  89. auto shape = InputInfoOfRuntime(0).shape;
  90. for (int i = 0; i < shape.size(); ++i) {
  91. // if height or width is dynamic
  92. if (i >= 2 && shape[i] <= 0) {
  93. is_dynamic_input_ = true;
  94. break;
  95. }
  96. }
  97. if (!is_dynamic_input_) {
  98. is_mini_pad = false;
  99. }
  100. return true;
  101. }
  102. bool ScaledYOLOv4::Preprocess(
  103. Mat *mat, FDTensor *output,
  104. std::map<std::string, std::array<float, 2>> *im_info) {
  105. // process after image load
  106. float ratio = std::min(size[1] * 1.0f / static_cast<float>(mat->Height()),
  107. size[0] * 1.0f / static_cast<float>(mat->Width()));
  108. if (std::fabs(ratio - 1.0f) > 1e-06) {
  109. int interp = cv::INTER_AREA;
  110. if (ratio > 1.0) {
  111. interp = cv::INTER_LINEAR;
  112. }
  113. int resize_h = int(mat->Height() * ratio);
  114. int resize_w = int(mat->Width() * ratio);
  115. Resize::Run(mat, resize_w, resize_h, -1, -1, interp);
  116. }
  117. // ScaledYOLOv4's preprocess steps
  118. // 1. letterbox
  119. // 2. BGR->RGB
  120. // 3. HWC->CHW
  121. ScaledYOLOv4::LetterBox(mat, size, padding_value, is_mini_pad, is_no_pad,
  122. is_scale_up, stride);
  123. BGR2RGB::Run(mat);
  124. // Normalize::Run(mat, std::vector<float>(mat->Channels(), 0.0),
  125. // std::vector<float>(mat->Channels(), 1.0));
  126. // Compute `result = mat * alpha + beta` directly by channel
  127. std::vector<float> alpha = {1.0f / 255.0f, 1.0f / 255.0f, 1.0f / 255.0f};
  128. std::vector<float> beta = {0.0f, 0.0f, 0.0f};
  129. Convert::Run(mat, alpha, beta);
  130. // Record output shape of preprocessed image
  131. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  132. static_cast<float>(mat->Width())};
  133. HWC2CHW::Run(mat);
  134. Cast::Run(mat, "float");
  135. mat->ShareWithTensor(output);
  136. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  137. return true;
  138. }
  139. bool ScaledYOLOv4::Postprocess(
  140. FDTensor &infer_result, DetectionResult *result,
  141. const std::map<std::string, std::array<float, 2>> &im_info,
  142. float conf_threshold, float nms_iou_threshold) {
  143. FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now.");
  144. result->Clear();
  145. result->Reserve(infer_result.shape[1]);
  146. if (infer_result.dtype != FDDataType::FP32) {
  147. FDERROR << "Only support post process with float32 data." << std::endl;
  148. return false;
  149. }
  150. float *data = static_cast<float *>(infer_result.Data());
  151. for (size_t i = 0; i < infer_result.shape[1]; ++i) {
  152. int s = i * infer_result.shape[2];
  153. float confidence = data[s + 4];
  154. float *max_class_score =
  155. std::max_element(data + s + 5, data + s + infer_result.shape[2]);
  156. confidence *= (*max_class_score);
  157. // filter boxes by conf_threshold
  158. if (confidence <= conf_threshold) {
  159. continue;
  160. }
  161. int32_t label_id = std::distance(data + s + 5, max_class_score);
  162. // convert from [x, y, w, h] to [x1, y1, x2, y2]
  163. result->boxes.emplace_back(std::array<float, 4>{
  164. data[s] - data[s + 2] / 2.0f + label_id * max_wh,
  165. data[s + 1] - data[s + 3] / 2.0f + label_id * max_wh,
  166. data[s + 0] + data[s + 2] / 2.0f + label_id * max_wh,
  167. data[s + 1] + data[s + 3] / 2.0f + label_id * max_wh});
  168. result->label_ids.push_back(label_id);
  169. result->scores.push_back(confidence);
  170. }
  171. utils::NMS(result, nms_iou_threshold);
  172. // scale the boxes to the origin image shape
  173. auto iter_out = im_info.find("output_shape");
  174. auto iter_ipt = im_info.find("input_shape");
  175. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  176. "Cannot find input_shape or output_shape from im_info.");
  177. float out_h = iter_out->second[0];
  178. float out_w = iter_out->second[1];
  179. float ipt_h = iter_ipt->second[0];
  180. float ipt_w = iter_ipt->second[1];
  181. float scale = std::min(out_h / ipt_h, out_w / ipt_w);
  182. float pad_h = (out_h - ipt_h * scale) / 2.0f;
  183. float pad_w = (out_w - ipt_w * scale) / 2.0f;
  184. if (is_mini_pad) {
  185. // 和 LetterBox中_auto=true的处理逻辑对应
  186. pad_h = static_cast<float>(static_cast<int>(pad_h) % stride);
  187. pad_w = static_cast<float>(static_cast<int>(pad_w) % stride);
  188. }
  189. for (size_t i = 0; i < result->boxes.size(); ++i) {
  190. int32_t label_id = (result->label_ids)[i];
  191. // clip box
  192. result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id;
  193. result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id;
  194. result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id;
  195. result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id;
  196. result->boxes[i][0] = std::max((result->boxes[i][0] - pad_w) / scale, 0.0f);
  197. result->boxes[i][1] = std::max((result->boxes[i][1] - pad_h) / scale, 0.0f);
  198. result->boxes[i][2] = std::max((result->boxes[i][2] - pad_w) / scale, 0.0f);
  199. result->boxes[i][3] = std::max((result->boxes[i][3] - pad_h) / scale, 0.0f);
  200. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  201. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  202. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  203. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  204. }
  205. return true;
  206. }
  207. bool ScaledYOLOv4::Predict(cv::Mat *im, DetectionResult *result,
  208. float conf_threshold, float nms_iou_threshold) {
  209. Mat mat(*im);
  210. std::map<std::string, std::array<float, 2>> im_info;
  211. // Record the shape of image and the shape of preprocessed image
  212. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  213. static_cast<float>(mat.Width())};
  214. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  215. static_cast<float>(mat.Width())};
  216. if (!Preprocess(&mat, &reused_input_tensors_[0], &im_info)) {
  217. FDERROR << "Failed to preprocess input image." << std::endl;
  218. return false;
  219. }
  220. reused_input_tensors_[0].name = InputInfoOfRuntime(0).name;
  221. if (!Infer()) {
  222. FDERROR << "Failed to inference." << std::endl;
  223. return false;
  224. }
  225. if (!Postprocess(reused_output_tensors_[0], result, im_info, conf_threshold,
  226. nms_iou_threshold)) {
  227. FDERROR << "Failed to post process." << std::endl;
  228. return false;
  229. }
  230. return true;
  231. }
  232. } // namespace detection
  233. } // namespace vision
  234. } // namespace ultra_infer