yolov7end2end_ort.cc 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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/yolov7end2end_ort.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 YOLOv7End2EndORT::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. YOLOv7End2EndORT::YOLOv7End2EndORT(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}; // NO 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. if (custom_option.backend == Backend::TRT) {
  69. FDWARNING << "Backend::TRT is not support for YOLOv7End2EndORT, "
  70. << "will fallback to Backend::ORT." << std::endl;
  71. }
  72. initialized = Initialize();
  73. }
  74. bool YOLOv7End2EndORT::Initialize() {
  75. // parameters for preprocess
  76. size = {640, 640};
  77. padding_value = {114.0, 114.0, 114.0};
  78. is_mini_pad = false;
  79. is_no_pad = false;
  80. is_scale_up = false;
  81. stride = 32;
  82. reused_input_tensors_.resize(1);
  83. if (!InitRuntime()) {
  84. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  85. return false;
  86. }
  87. // Check if the input shape is dynamic after Runtime already initialized,
  88. // Note that, We need to force is_mini_pad 'false' to keep static
  89. // shape after padding (LetterBox) when the is_dynamic_shape is 'false'.
  90. is_dynamic_input_ = false;
  91. auto shape = InputInfoOfRuntime(0).shape;
  92. for (int i = 0; i < shape.size(); ++i) {
  93. // if height or width is dynamic
  94. if (i >= 2 && shape[i] <= 0) {
  95. is_dynamic_input_ = true;
  96. break;
  97. }
  98. }
  99. if (!is_dynamic_input_) {
  100. is_mini_pad = false;
  101. }
  102. return true;
  103. }
  104. bool YOLOv7End2EndORT::Preprocess(
  105. Mat *mat, FDTensor *output,
  106. std::map<std::string, std::array<float, 2>> *im_info) {
  107. float ratio = std::min(size[1] * 1.0f / static_cast<float>(mat->Height()),
  108. size[0] * 1.0f / static_cast<float>(mat->Width()));
  109. if (std::fabs(ratio - 1.0f) > 1e-06) {
  110. int interp = cv::INTER_AREA;
  111. if (ratio > 1.0) {
  112. interp = cv::INTER_LINEAR;
  113. }
  114. int resize_h = int(mat->Height() * ratio);
  115. int resize_w = int(mat->Width() * ratio);
  116. Resize::Run(mat, resize_w, resize_h, -1, -1, interp);
  117. }
  118. YOLOv7End2EndORT::LetterBox(mat, size, padding_value, is_mini_pad, is_no_pad,
  119. is_scale_up, stride);
  120. BGR2RGB::Run(mat);
  121. std::vector<float> alpha = {1.0f / 255.0f, 1.0f / 255.0f, 1.0f / 255.0f};
  122. std::vector<float> beta = {0.0f, 0.0f, 0.0f};
  123. Convert::Run(mat, alpha, beta);
  124. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  125. static_cast<float>(mat->Width())};
  126. HWC2CHW::Run(mat);
  127. Cast::Run(mat, "float");
  128. mat->ShareWithTensor(output);
  129. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  130. return true;
  131. }
  132. bool YOLOv7End2EndORT::Postprocess(
  133. FDTensor &infer_result, DetectionResult *result,
  134. const std::map<std::string, std::array<float, 2>> &im_info,
  135. float conf_threshold) {
  136. if (infer_result.dtype != FDDataType::FP32) {
  137. FDERROR << "Only support post process with float32 data." << std::endl;
  138. return false;
  139. }
  140. // detected success without valid objects.
  141. if (infer_result.shape[0] == 0) {
  142. return true;
  143. }
  144. result->Clear();
  145. result->Reserve(infer_result.shape[0]);
  146. // (?,7) (batch_id,x0,y0,x1,y1,cls_id,score) after nms
  147. float *data = static_cast<float *>(infer_result.Data());
  148. for (size_t i = 0; i < infer_result.shape[0]; ++i) {
  149. const float *box_cls_ptr = data + (i * 7);
  150. int64_t batch_id = static_cast<int64_t>(box_cls_ptr[0] + 0.5f); // 0,1, ...
  151. FDASSERT(batch_id == 0,
  152. "Only support batch=1 now, but found batch_id != 0.");
  153. float confidence = box_cls_ptr[6];
  154. if (confidence <= conf_threshold) {
  155. continue;
  156. }
  157. int32_t label_id = static_cast<int32_t>(box_cls_ptr[5] + 0.5f);
  158. float x1 = box_cls_ptr[1];
  159. float y1 = box_cls_ptr[2];
  160. float x2 = box_cls_ptr[3];
  161. float y2 = box_cls_ptr[4];
  162. result->boxes.emplace_back(std::array<float, 4>{x1, y1, x2, y2});
  163. result->label_ids.push_back(label_id);
  164. result->scores.push_back(confidence);
  165. }
  166. if (result->boxes.size() == 0) {
  167. return true;
  168. }
  169. // scale the boxes to the origin image shape
  170. auto iter_out = im_info.find("output_shape");
  171. auto iter_ipt = im_info.find("input_shape");
  172. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  173. "Cannot find input_shape or output_shape from im_info.");
  174. float out_h = iter_out->second[0];
  175. float out_w = iter_out->second[1];
  176. float ipt_h = iter_ipt->second[0];
  177. float ipt_w = iter_ipt->second[1];
  178. float scale = std::min(out_h / ipt_h, out_w / ipt_w);
  179. float pad_h = (out_h - ipt_h * scale) / 2.0f;
  180. float pad_w = (out_w - ipt_w * scale) / 2.0f;
  181. if (is_mini_pad) {
  182. pad_h = static_cast<float>(static_cast<int>(pad_h) % stride);
  183. pad_w = static_cast<float>(static_cast<int>(pad_w) % stride);
  184. }
  185. for (size_t i = 0; i < result->boxes.size(); ++i) {
  186. int32_t label_id = (result->label_ids)[i];
  187. result->boxes[i][0] = std::max((result->boxes[i][0] - pad_w) / scale, 0.0f);
  188. result->boxes[i][1] = std::max((result->boxes[i][1] - pad_h) / scale, 0.0f);
  189. result->boxes[i][2] = std::max((result->boxes[i][2] - pad_w) / scale, 0.0f);
  190. result->boxes[i][3] = std::max((result->boxes[i][3] - pad_h) / scale, 0.0f);
  191. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  192. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  193. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  194. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  195. }
  196. return true;
  197. }
  198. bool YOLOv7End2EndORT::Predict(cv::Mat *im, DetectionResult *result,
  199. float conf_threshold) {
  200. Mat mat(*im);
  201. std::map<std::string, std::array<float, 2>> im_info;
  202. // Record the shape of image and the shape of preprocessed image
  203. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  204. static_cast<float>(mat.Width())};
  205. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  206. static_cast<float>(mat.Width())};
  207. if (!Preprocess(&mat, &reused_input_tensors_[0], &im_info)) {
  208. FDERROR << "Failed to preprocess input image." << std::endl;
  209. return false;
  210. }
  211. reused_input_tensors_[0].name = InputInfoOfRuntime(0).name;
  212. if (!Infer()) {
  213. FDERROR << "Failed to inference." << std::endl;
  214. return false;
  215. }
  216. if (!Postprocess(reused_output_tensors_[0], result, im_info,
  217. conf_threshold)) {
  218. FDERROR << "Failed to post process." << std::endl;
  219. return false;
  220. }
  221. return true;
  222. }
  223. } // namespace detection
  224. } // namespace vision
  225. } // namespace ultra_infer