yolox.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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/yolox.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. struct YOLOXAnchor {
  21. int grid0;
  22. int grid1;
  23. int stride;
  24. };
  25. void GenerateYOLOXAnchors(const std::vector<int> &size,
  26. const std::vector<int> &downsample_strides,
  27. std::vector<YOLOXAnchor> *anchors) {
  28. // size: tuple of input (width, height)
  29. // downsample_strides: downsample strides in YOLOX, e.g (8,16,32)
  30. const int width = size[0];
  31. const int height = size[1];
  32. for (const auto &ds : downsample_strides) {
  33. int num_grid_w = width / ds;
  34. int num_grid_h = height / ds;
  35. for (int g1 = 0; g1 < num_grid_h; ++g1) {
  36. for (int g0 = 0; g0 < num_grid_w; ++g0) {
  37. (*anchors).emplace_back(YOLOXAnchor{g0, g1, ds});
  38. }
  39. }
  40. }
  41. }
  42. void LetterBoxWithRightBottomPad(Mat *mat, std::vector<int> size,
  43. std::vector<float> color) {
  44. // specific pre process for YOLOX, not the same as YOLOv5
  45. // reference: YOLOX/yolox/data/data_augment.py#L142
  46. float r = std::min(size[1] * 1.0f / static_cast<float>(mat->Height()),
  47. size[0] * 1.0f / static_cast<float>(mat->Width()));
  48. int resize_h = int(round(static_cast<float>(mat->Height()) * r));
  49. int resize_w = int(round(static_cast<float>(mat->Width()) * r));
  50. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  51. Resize::Run(mat, resize_w, resize_h);
  52. }
  53. int pad_w = size[0] - resize_w;
  54. int pad_h = size[1] - resize_h;
  55. // right-bottom padding for YOLOX
  56. if (pad_h > 0 || pad_w > 0) {
  57. int top = 0;
  58. int left = 0;
  59. int right = pad_w;
  60. int bottom = pad_h;
  61. Pad::Run(mat, top, bottom, left, right, color);
  62. }
  63. }
  64. YOLOX::YOLOX(const std::string &model_file, const std::string &params_file,
  65. const RuntimeOption &custom_option,
  66. const ModelFormat &model_format) {
  67. if (model_format == ModelFormat::ONNX) {
  68. valid_cpu_backends = {Backend::OPENVINO, Backend::ORT};
  69. valid_gpu_backends = {Backend::ORT, Backend::TRT};
  70. } else {
  71. valid_cpu_backends = {Backend::PDINFER, Backend::ORT};
  72. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  73. }
  74. runtime_option = custom_option;
  75. runtime_option.model_format = model_format;
  76. runtime_option.model_file = model_file;
  77. runtime_option.params_file = params_file;
  78. initialized = Initialize();
  79. }
  80. bool YOLOX::Initialize() {
  81. // parameters for preprocess
  82. size = {640, 640};
  83. padding_value = {114.0, 114.0, 114.0};
  84. downsample_strides = {8, 16, 32};
  85. max_wh = 4096.0f;
  86. is_decode_exported = false;
  87. reused_input_tensors_.resize(1);
  88. if (!InitRuntime()) {
  89. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  90. return false;
  91. }
  92. // Check if the input shape is dynamic after Runtime already initialized.
  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. return true;
  103. }
  104. bool YOLOX::Preprocess(Mat *mat, FDTensor *output,
  105. std::map<std::string, std::array<float, 2>> *im_info) {
  106. // YOLOX ( >= v0.1.1) preprocess steps
  107. // 1. preproc
  108. // 2. HWC->CHW
  109. // 3. NO!!! BRG2GRB and Normalize needed in YOLOX
  110. LetterBoxWithRightBottomPad(mat, size, padding_value);
  111. // Record output shape of preprocessed image
  112. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  113. static_cast<float>(mat->Width())};
  114. HWC2CHW::Run(mat);
  115. Cast::Run(mat, "float");
  116. mat->ShareWithTensor(output);
  117. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  118. return true;
  119. }
  120. bool YOLOX::Postprocess(
  121. FDTensor &infer_result, DetectionResult *result,
  122. const std::map<std::string, std::array<float, 2>> &im_info,
  123. float conf_threshold, float nms_iou_threshold) {
  124. FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now.");
  125. result->Clear();
  126. result->Reserve(infer_result.shape[1]);
  127. if (infer_result.dtype != FDDataType::FP32) {
  128. FDERROR << "Only support post process with float32 data." << std::endl;
  129. return false;
  130. }
  131. float *data = static_cast<float *>(infer_result.Data());
  132. for (size_t i = 0; i < infer_result.shape[1]; ++i) {
  133. int s = i * infer_result.shape[2];
  134. float confidence = data[s + 4];
  135. float *max_class_score =
  136. std::max_element(data + s + 5, data + s + infer_result.shape[2]);
  137. confidence *= (*max_class_score);
  138. // filter boxes by conf_threshold
  139. if (confidence <= conf_threshold) {
  140. continue;
  141. }
  142. int32_t label_id = std::distance(data + s + 5, max_class_score);
  143. // convert from [x, y, w, h] to [x1, y1, x2, y2]
  144. result->boxes.emplace_back(std::array<float, 4>{
  145. data[s] - data[s + 2] / 2.0f + label_id * max_wh,
  146. data[s + 1] - data[s + 3] / 2.0f + label_id * max_wh,
  147. data[s + 0] + data[s + 2] / 2.0f + label_id * max_wh,
  148. data[s + 1] + data[s + 3] / 2.0f + label_id * max_wh});
  149. result->label_ids.push_back(label_id);
  150. result->scores.push_back(confidence);
  151. }
  152. utils::NMS(result, nms_iou_threshold);
  153. // scale the boxes to the origin image shape
  154. auto iter_out = im_info.find("output_shape");
  155. auto iter_ipt = im_info.find("input_shape");
  156. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  157. "Cannot find input_shape or output_shape from im_info.");
  158. float out_h = iter_out->second[0];
  159. float out_w = iter_out->second[1];
  160. float ipt_h = iter_ipt->second[0];
  161. float ipt_w = iter_ipt->second[1];
  162. float r = std::min(out_h / ipt_h, out_w / ipt_w);
  163. for (size_t i = 0; i < result->boxes.size(); ++i) {
  164. int32_t label_id = (result->label_ids)[i];
  165. // clip box
  166. result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id;
  167. result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id;
  168. result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id;
  169. result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id;
  170. result->boxes[i][0] = std::max(result->boxes[i][0] / r, 0.0f);
  171. result->boxes[i][1] = std::max(result->boxes[i][1] / r, 0.0f);
  172. result->boxes[i][2] = std::max(result->boxes[i][2] / r, 0.0f);
  173. result->boxes[i][3] = std::max(result->boxes[i][3] / r, 0.0f);
  174. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  175. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  176. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  177. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  178. }
  179. return true;
  180. }
  181. bool YOLOX::PostprocessWithDecode(
  182. FDTensor &infer_result, DetectionResult *result,
  183. const std::map<std::string, std::array<float, 2>> &im_info,
  184. float conf_threshold, float nms_iou_threshold) {
  185. FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now.");
  186. result->Clear();
  187. result->Reserve(infer_result.shape[1]);
  188. if (infer_result.dtype != FDDataType::FP32) {
  189. FDERROR << "Only support post process with float32 data." << std::endl;
  190. return false;
  191. }
  192. // generate anchors with dowmsample strides
  193. std::vector<YOLOXAnchor> anchors;
  194. GenerateYOLOXAnchors(size, downsample_strides, &anchors);
  195. // infer_result shape might look like (1,n,85=5+80)
  196. float *data = static_cast<float *>(infer_result.Data());
  197. for (size_t i = 0; i < infer_result.shape[1]; ++i) {
  198. int s = i * infer_result.shape[2];
  199. float confidence = data[s + 4];
  200. float *max_class_score =
  201. std::max_element(data + s + 5, data + s + infer_result.shape[2]);
  202. confidence *= (*max_class_score);
  203. // filter boxes by conf_threshold
  204. if (confidence <= conf_threshold) {
  205. continue;
  206. }
  207. int32_t label_id = std::distance(data + s + 5, max_class_score);
  208. // fetch i-th anchor
  209. float grid0 = static_cast<float>(anchors.at(i).grid0);
  210. float grid1 = static_cast<float>(anchors.at(i).grid1);
  211. float downsample_stride = static_cast<float>(anchors.at(i).stride);
  212. // convert from offsets to [x, y, w, h]
  213. float dx = data[s];
  214. float dy = data[s + 1];
  215. float dw = data[s + 2];
  216. float dh = data[s + 3];
  217. float x = (dx + grid0) * downsample_stride;
  218. float y = (dy + grid1) * downsample_stride;
  219. float w = std::exp(dw) * downsample_stride;
  220. float h = std::exp(dh) * downsample_stride;
  221. // convert from [x, y, w, h] to [x1, y1, x2, y2]
  222. result->boxes.emplace_back(std::array<float, 4>{
  223. x - w / 2.0f + label_id * max_wh, y - h / 2.0f + label_id * max_wh,
  224. x + w / 2.0f + label_id * max_wh, y + h / 2.0f + label_id * max_wh});
  225. // label_id * max_wh for multi classes NMS
  226. result->label_ids.push_back(label_id);
  227. result->scores.push_back(confidence);
  228. }
  229. utils::NMS(result, nms_iou_threshold);
  230. // scale the boxes to the origin image shape
  231. auto iter_out = im_info.find("output_shape");
  232. auto iter_ipt = im_info.find("input_shape");
  233. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  234. "Cannot find input_shape or output_shape from im_info.");
  235. float out_h = iter_out->second[0];
  236. float out_w = iter_out->second[1];
  237. float ipt_h = iter_ipt->second[0];
  238. float ipt_w = iter_ipt->second[1];
  239. float r = std::min(out_h / ipt_h, out_w / ipt_w);
  240. for (size_t i = 0; i < result->boxes.size(); ++i) {
  241. int32_t label_id = (result->label_ids)[i];
  242. // clip box
  243. result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id;
  244. result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id;
  245. result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id;
  246. result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id;
  247. result->boxes[i][0] = std::max(result->boxes[i][0] / r, 0.0f);
  248. result->boxes[i][1] = std::max(result->boxes[i][1] / r, 0.0f);
  249. result->boxes[i][2] = std::max(result->boxes[i][2] / r, 0.0f);
  250. result->boxes[i][3] = std::max(result->boxes[i][3] / r, 0.0f);
  251. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  252. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  253. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  254. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  255. }
  256. return true;
  257. }
  258. bool YOLOX::Predict(cv::Mat *im, DetectionResult *result, float conf_threshold,
  259. float nms_iou_threshold) {
  260. Mat mat(*im);
  261. std::map<std::string, std::array<float, 2>> im_info;
  262. // Record the shape of image and the shape of preprocessed image
  263. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  264. static_cast<float>(mat.Width())};
  265. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  266. static_cast<float>(mat.Width())};
  267. if (!Preprocess(&mat, &reused_input_tensors_[0], &im_info)) {
  268. FDERROR << "Failed to preprocess input image." << std::endl;
  269. return false;
  270. }
  271. reused_input_tensors_[0].name = InputInfoOfRuntime(0).name;
  272. if (!Infer()) {
  273. FDERROR << "Failed to inference." << std::endl;
  274. return false;
  275. }
  276. if (is_decode_exported) {
  277. if (!Postprocess(reused_output_tensors_[0], result, im_info, conf_threshold,
  278. nms_iou_threshold)) {
  279. FDERROR << "Failed to post process." << std::endl;
  280. return false;
  281. }
  282. } else {
  283. if (!PostprocessWithDecode(reused_output_tensors_[0], result, im_info,
  284. conf_threshold, nms_iou_threshold)) {
  285. FDERROR << "Failed to post process." << std::endl;
  286. return false;
  287. }
  288. }
  289. return true;
  290. }
  291. } // namespace detection
  292. } // namespace vision
  293. } // namespace ultra_infer