yolov5lite.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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/yolov5lite.h"
  15. #include "ultra_infer/utils/perf.h"
  16. #include "ultra_infer/vision/utils/utils.h"
  17. #ifdef WITH_GPU
  18. #include "ultra_infer/vision/utils/cuda_utils.h"
  19. #endif // WITH_GPU
  20. namespace ultra_infer {
  21. namespace vision {
  22. namespace detection {
  23. void YOLOv5Lite::LetterBox(Mat *mat, const std::vector<int> &size,
  24. const std::vector<float> &color, bool _auto,
  25. bool scale_fill, bool scale_up, int stride) {
  26. float scale =
  27. std::min(size[1] * 1.0 / mat->Height(), size[0] * 1.0 / mat->Width());
  28. if (!scale_up) {
  29. scale = std::min(scale, 1.0f);
  30. }
  31. int resize_h = int(round(mat->Height() * scale));
  32. int resize_w = int(round(mat->Width() * scale));
  33. int pad_w = size[0] - resize_w;
  34. int pad_h = size[1] - resize_h;
  35. if (_auto) {
  36. pad_h = pad_h % stride;
  37. pad_w = pad_w % stride;
  38. } else if (scale_fill) {
  39. pad_h = 0;
  40. pad_w = 0;
  41. resize_h = size[1];
  42. resize_w = size[0];
  43. }
  44. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  45. Resize::Run(mat, resize_w, resize_h);
  46. }
  47. if (pad_h > 0 || pad_w > 0) {
  48. float half_h = pad_h * 1.0 / 2;
  49. int top = int(round(half_h - 0.1));
  50. int bottom = int(round(half_h + 0.1));
  51. float half_w = pad_w * 1.0 / 2;
  52. int left = int(round(half_w - 0.1));
  53. int right = int(round(half_w + 0.1));
  54. Pad::Run(mat, top, bottom, left, right, color);
  55. }
  56. }
  57. void YOLOv5Lite::GenerateAnchors(const std::vector<int> &size,
  58. const std::vector<int> &downsample_strides,
  59. std::vector<Anchor> *anchors,
  60. int num_anchors) {
  61. // size: tuple of input (width, height)
  62. // downsample_strides: downsample strides in YOLOv5Lite, e.g (8,16,32)
  63. const int width = size[0];
  64. const int height = size[1];
  65. for (int i = 0; i < downsample_strides.size(); ++i) {
  66. const int ds = downsample_strides[i];
  67. int num_grid_w = width / ds;
  68. int num_grid_h = height / ds;
  69. for (int an = 0; an < num_anchors; ++an) {
  70. float anchor_w = anchor_config[i][an * 2];
  71. float anchor_h = anchor_config[i][an * 2 + 1];
  72. for (int g1 = 0; g1 < num_grid_h; ++g1) {
  73. for (int g0 = 0; g0 < num_grid_w; ++g0) {
  74. (*anchors).emplace_back(Anchor{g0, g1, ds, anchor_w, anchor_h});
  75. }
  76. }
  77. }
  78. }
  79. }
  80. YOLOv5Lite::YOLOv5Lite(const std::string &model_file,
  81. const std::string &params_file,
  82. const RuntimeOption &custom_option,
  83. const ModelFormat &model_format) {
  84. if (model_format == ModelFormat::ONNX) {
  85. valid_cpu_backends = {Backend::ORT};
  86. valid_gpu_backends = {Backend::ORT, Backend::TRT};
  87. } else {
  88. valid_cpu_backends = {Backend::PDINFER, Backend::ORT};
  89. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  90. }
  91. runtime_option = custom_option;
  92. runtime_option.model_format = model_format;
  93. runtime_option.model_file = model_file;
  94. runtime_option.params_file = params_file;
  95. #ifdef WITH_GPU
  96. cudaSetDevice(runtime_option.device_id);
  97. cudaStream_t stream;
  98. CUDA_CHECK(cudaStreamCreate(&stream));
  99. cuda_stream_ = reinterpret_cast<void *>(stream);
  100. runtime_option.SetExternalStream(cuda_stream_);
  101. #endif // WITH_GPU
  102. initialized = Initialize();
  103. }
  104. bool YOLOv5Lite::Initialize() {
  105. // parameters for preprocess
  106. size = {640, 640};
  107. padding_value = {114.0, 114.0, 114.0};
  108. downsample_strides = {8, 16, 32};
  109. is_mini_pad = false;
  110. is_no_pad = false;
  111. is_scale_up = false;
  112. stride = 32;
  113. max_wh = 7680.0;
  114. is_decode_exported = false;
  115. anchor_config = {{10.0, 13.0, 16.0, 30.0, 33.0, 23.0},
  116. {30.0, 61.0, 62.0, 45.0, 59.0, 119.0},
  117. {116.0, 90.0, 156.0, 198.0, 373.0, 326.0}};
  118. reused_input_tensors_.resize(1);
  119. if (!InitRuntime()) {
  120. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  121. return false;
  122. }
  123. // Check if the input shape is dynamic after Runtime already initialized,
  124. // Note that, We need to force is_mini_pad 'false' to keep static
  125. // shape after padding (LetterBox) when the is_dynamic_shape is 'false'.
  126. is_dynamic_input_ = false;
  127. auto shape = InputInfoOfRuntime(0).shape;
  128. for (int i = 0; i < shape.size(); ++i) {
  129. // if height or width is dynamic
  130. if (i >= 2 && shape[i] <= 0) {
  131. is_dynamic_input_ = true;
  132. break;
  133. }
  134. }
  135. if (!is_dynamic_input_) {
  136. is_mini_pad = false;
  137. }
  138. return true;
  139. }
  140. YOLOv5Lite::~YOLOv5Lite() {
  141. #ifdef WITH_GPU
  142. if (use_cuda_preprocessing_) {
  143. CUDA_CHECK(cudaFreeHost(input_img_cuda_buffer_host_));
  144. CUDA_CHECK(cudaFree(input_img_cuda_buffer_device_));
  145. CUDA_CHECK(cudaFree(input_tensor_cuda_buffer_device_));
  146. CUDA_CHECK(cudaStreamDestroy(reinterpret_cast<cudaStream_t>(cuda_stream_)));
  147. }
  148. #endif // WITH_GPU
  149. }
  150. bool YOLOv5Lite::Preprocess(
  151. Mat *mat, FDTensor *output,
  152. std::map<std::string, std::array<float, 2>> *im_info) {
  153. // process after image load
  154. float ratio = std::min(size[1] * 1.0f / static_cast<float>(mat->Height()),
  155. size[0] * 1.0f / static_cast<float>(mat->Width()));
  156. if (std::fabs(ratio - 1.0f) > 1e-06) {
  157. int interp = cv::INTER_AREA;
  158. if (ratio > 1.0) {
  159. interp = cv::INTER_LINEAR;
  160. }
  161. int resize_h = int(mat->Height() * ratio);
  162. int resize_w = int(mat->Width() * ratio);
  163. Resize::Run(mat, resize_w, resize_h, -1, -1, interp);
  164. }
  165. // yolov5lite's preprocess steps
  166. // 1. letterbox
  167. // 2. BGR->RGB
  168. // 3. HWC->CHW
  169. YOLOv5Lite::LetterBox(mat, size, padding_value, is_mini_pad, is_no_pad,
  170. is_scale_up, stride);
  171. BGR2RGB::Run(mat);
  172. // Normalize::Run(mat, std::vector<float>(mat->Channels(), 0.0),
  173. // std::vector<float>(mat->Channels(), 1.0));
  174. // Compute `result = mat * alpha + beta` directly by channel
  175. std::vector<float> alpha = {1.0f / 255.0f, 1.0f / 255.0f, 1.0f / 255.0f};
  176. std::vector<float> beta = {0.0f, 0.0f, 0.0f};
  177. Convert::Run(mat, alpha, beta);
  178. // Record output shape of preprocessed image
  179. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  180. static_cast<float>(mat->Width())};
  181. HWC2CHW::Run(mat);
  182. Cast::Run(mat, "float");
  183. mat->ShareWithTensor(output);
  184. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  185. return true;
  186. }
  187. void YOLOv5Lite::UseCudaPreprocessing(int max_image_size) {
  188. #ifdef WITH_GPU
  189. use_cuda_preprocessing_ = true;
  190. is_scale_up = true;
  191. if (input_img_cuda_buffer_host_ == nullptr) {
  192. // prepare input data cache in GPU pinned memory
  193. CUDA_CHECK(cudaMallocHost((void **)&input_img_cuda_buffer_host_,
  194. max_image_size * 3));
  195. // prepare input data cache in GPU device memory
  196. CUDA_CHECK(cudaMalloc((void **)&input_img_cuda_buffer_device_,
  197. max_image_size * 3));
  198. CUDA_CHECK(cudaMalloc((void **)&input_tensor_cuda_buffer_device_,
  199. 3 * size[0] * size[1] * sizeof(float)));
  200. }
  201. #else
  202. FDWARNING << "The UltraInfer didn't compile with WITH_GPU=ON." << std::endl;
  203. use_cuda_preprocessing_ = false;
  204. #endif
  205. }
  206. bool YOLOv5Lite::CudaPreprocess(
  207. Mat *mat, FDTensor *output,
  208. std::map<std::string, std::array<float, 2>> *im_info) {
  209. #ifdef WITH_GPU
  210. if (is_mini_pad != false || is_no_pad != false || is_scale_up != true) {
  211. FDERROR << "Preprocessing with CUDA is only available when the arguments "
  212. "satisfy (is_mini_pad=false, is_no_pad=false, is_scale_up=true)."
  213. << std::endl;
  214. return false;
  215. }
  216. // Record the shape of image and the shape of preprocessed image
  217. (*im_info)["input_shape"] = {static_cast<float>(mat->Height()),
  218. static_cast<float>(mat->Width())};
  219. (*im_info)["output_shape"] = {static_cast<float>(mat->Height()),
  220. static_cast<float>(mat->Width())};
  221. cudaStream_t stream = reinterpret_cast<cudaStream_t>(cuda_stream_);
  222. int src_img_buf_size = mat->Height() * mat->Width() * mat->Channels();
  223. memcpy(input_img_cuda_buffer_host_, mat->Data(), src_img_buf_size);
  224. CUDA_CHECK(cudaMemcpyAsync(input_img_cuda_buffer_device_,
  225. input_img_cuda_buffer_host_, src_img_buf_size,
  226. cudaMemcpyHostToDevice, stream));
  227. utils::CudaYoloPreprocess(input_img_cuda_buffer_device_, mat->Width(),
  228. mat->Height(), input_tensor_cuda_buffer_device_,
  229. size[0], size[1], padding_value, stream);
  230. // Record output shape of preprocessed image
  231. (*im_info)["output_shape"] = {static_cast<float>(size[0]),
  232. static_cast<float>(size[1])};
  233. output->SetExternalData({mat->Channels(), size[0], size[1]}, FDDataType::FP32,
  234. input_tensor_cuda_buffer_device_);
  235. output->device = Device::GPU;
  236. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  237. return true;
  238. #else
  239. FDERROR << "CUDA src code was not enabled." << std::endl;
  240. return false;
  241. #endif // WITH_GPU
  242. }
  243. bool YOLOv5Lite::PostprocessWithDecode(
  244. FDTensor &infer_result, DetectionResult *result,
  245. const std::map<std::string, std::array<float, 2>> &im_info,
  246. float conf_threshold, float nms_iou_threshold) {
  247. FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now.");
  248. result->Clear();
  249. result->Reserve(infer_result.shape[1]);
  250. if (infer_result.dtype != FDDataType::FP32) {
  251. FDERROR << "Only support post process with float32 data." << std::endl;
  252. return false;
  253. }
  254. // generate anchors with dowmsample strides
  255. std::vector<YOLOv5Lite::Anchor> anchors;
  256. int num_anchors = anchor_config[0].size() / 2;
  257. GenerateAnchors(size, downsample_strides, &anchors, num_anchors);
  258. // infer_result shape might look like (1,n,85=5+80)
  259. float *data = static_cast<float *>(infer_result.Data());
  260. for (size_t i = 0; i < infer_result.shape[1]; ++i) {
  261. int s = i * infer_result.shape[2];
  262. float confidence = data[s + 4];
  263. float *max_class_score =
  264. std::max_element(data + s + 5, data + s + infer_result.shape[2]);
  265. confidence *= (*max_class_score);
  266. // filter boxes by conf_threshold
  267. if (confidence <= conf_threshold) {
  268. continue;
  269. }
  270. int32_t label_id = std::distance(data + s + 5, max_class_score);
  271. // fetch i-th anchor
  272. float grid0 = static_cast<float>(anchors.at(i).grid0);
  273. float grid1 = static_cast<float>(anchors.at(i).grid1);
  274. float downsample_stride = static_cast<float>(anchors.at(i).stride);
  275. float anchor_w = static_cast<float>(anchors.at(i).anchor_w);
  276. float anchor_h = static_cast<float>(anchors.at(i).anchor_h);
  277. // convert from offsets to [x, y, w, h]
  278. float dx = data[s];
  279. float dy = data[s + 1];
  280. float dw = data[s + 2];
  281. float dh = data[s + 3];
  282. float x = (dx * 2.0f - 0.5f + grid0) * downsample_stride;
  283. float y = (dy * 2.0f - 0.5f + grid1) * downsample_stride;
  284. float w = std::pow(dw * 2.0f, 2.0f) * anchor_w;
  285. float h = std::pow(dh * 2.0f, 2.0f) * anchor_h;
  286. // convert from [x, y, w, h] to [x1, y1, x2, y2]
  287. result->boxes.emplace_back(std::array<float, 4>{
  288. x - w / 2.0f + label_id * max_wh, y - h / 2.0f + label_id * max_wh,
  289. x + w / 2.0f + label_id * max_wh, y + h / 2.0f + label_id * max_wh});
  290. // label_id * max_wh for multi classes NMS
  291. result->label_ids.push_back(label_id);
  292. result->scores.push_back(confidence);
  293. }
  294. utils::NMS(result, nms_iou_threshold);
  295. // scale the boxes to the origin image shape
  296. auto iter_out = im_info.find("output_shape");
  297. auto iter_ipt = im_info.find("input_shape");
  298. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  299. "Cannot find input_shape or output_shape from im_info.");
  300. float out_h = iter_out->second[0];
  301. float out_w = iter_out->second[1];
  302. float ipt_h = iter_ipt->second[0];
  303. float ipt_w = iter_ipt->second[1];
  304. float scale = std::min(out_h / ipt_h, out_w / ipt_w);
  305. float pad_h = (out_h - ipt_h * scale) / 2.0f;
  306. float pad_w = (out_w - ipt_w * scale) / 2.0f;
  307. if (is_mini_pad) {
  308. pad_h = static_cast<float>(static_cast<int>(pad_h) % stride);
  309. pad_w = static_cast<float>(static_cast<int>(pad_w) % stride);
  310. }
  311. for (size_t i = 0; i < result->boxes.size(); ++i) {
  312. int32_t label_id = (result->label_ids)[i];
  313. // clip box
  314. result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id;
  315. result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id;
  316. result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id;
  317. result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id;
  318. result->boxes[i][0] = std::max((result->boxes[i][0] - pad_w) / scale, 0.0f);
  319. result->boxes[i][1] = std::max((result->boxes[i][1] - pad_h) / scale, 0.0f);
  320. result->boxes[i][2] = std::max((result->boxes[i][2] - pad_w) / scale, 0.0f);
  321. result->boxes[i][3] = std::max((result->boxes[i][3] - pad_h) / scale, 0.0f);
  322. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  323. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  324. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  325. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  326. }
  327. return true;
  328. }
  329. bool YOLOv5Lite::Postprocess(
  330. FDTensor &infer_result, DetectionResult *result,
  331. const std::map<std::string, std::array<float, 2>> &im_info,
  332. float conf_threshold, float nms_iou_threshold) {
  333. FDASSERT(infer_result.shape[0] == 1, "Only support batch =1 now.");
  334. result->Clear();
  335. result->Reserve(infer_result.shape[1]);
  336. if (infer_result.dtype != FDDataType::FP32) {
  337. FDERROR << "Only support post process with float32 data." << std::endl;
  338. return false;
  339. }
  340. float *data = static_cast<float *>(infer_result.Data());
  341. for (size_t i = 0; i < infer_result.shape[1]; ++i) {
  342. int s = i * infer_result.shape[2];
  343. float confidence = data[s + 4];
  344. float *max_class_score =
  345. std::max_element(data + s + 5, data + s + infer_result.shape[2]);
  346. confidence *= (*max_class_score);
  347. // filter boxes by conf_threshold
  348. if (confidence <= conf_threshold) {
  349. continue;
  350. }
  351. int32_t label_id = std::distance(data + s + 5, max_class_score);
  352. // convert from [x, y, w, h] to [x1, y1, x2, y2]
  353. result->boxes.emplace_back(std::array<float, 4>{
  354. data[s] - data[s + 2] / 2.0f + label_id * max_wh,
  355. data[s + 1] - data[s + 3] / 2.0f + label_id * max_wh,
  356. data[s + 0] + data[s + 2] / 2.0f + label_id * max_wh,
  357. data[s + 1] + data[s + 3] / 2.0f + label_id * max_wh});
  358. result->label_ids.push_back(label_id);
  359. result->scores.push_back(confidence);
  360. }
  361. utils::NMS(result, nms_iou_threshold);
  362. // scale the boxes to the origin image shape
  363. auto iter_out = im_info.find("output_shape");
  364. auto iter_ipt = im_info.find("input_shape");
  365. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  366. "Cannot find input_shape or output_shape from im_info.");
  367. float out_h = iter_out->second[0];
  368. float out_w = iter_out->second[1];
  369. float ipt_h = iter_ipt->second[0];
  370. float ipt_w = iter_ipt->second[1];
  371. float scale = std::min(out_h / ipt_h, out_w / ipt_w);
  372. float pad_h = (out_h - ipt_h * scale) / 2.0f;
  373. float pad_w = (out_w - ipt_w * scale) / 2.0f;
  374. if (is_mini_pad) {
  375. pad_h = static_cast<float>(static_cast<int>(pad_h) % stride);
  376. pad_w = static_cast<float>(static_cast<int>(pad_w) % stride);
  377. }
  378. for (size_t i = 0; i < result->boxes.size(); ++i) {
  379. int32_t label_id = (result->label_ids)[i];
  380. // clip box
  381. result->boxes[i][0] = result->boxes[i][0] - max_wh * label_id;
  382. result->boxes[i][1] = result->boxes[i][1] - max_wh * label_id;
  383. result->boxes[i][2] = result->boxes[i][2] - max_wh * label_id;
  384. result->boxes[i][3] = result->boxes[i][3] - max_wh * label_id;
  385. result->boxes[i][0] = std::max((result->boxes[i][0] - pad_w) / scale, 0.0f);
  386. result->boxes[i][1] = std::max((result->boxes[i][1] - pad_h) / scale, 0.0f);
  387. result->boxes[i][2] = std::max((result->boxes[i][2] - pad_w) / scale, 0.0f);
  388. result->boxes[i][3] = std::max((result->boxes[i][3] - pad_h) / scale, 0.0f);
  389. result->boxes[i][0] = std::min(result->boxes[i][0], ipt_w - 1.0f);
  390. result->boxes[i][1] = std::min(result->boxes[i][1], ipt_h - 1.0f);
  391. result->boxes[i][2] = std::min(result->boxes[i][2], ipt_w - 1.0f);
  392. result->boxes[i][3] = std::min(result->boxes[i][3], ipt_h - 1.0f);
  393. }
  394. return true;
  395. }
  396. bool YOLOv5Lite::Predict(cv::Mat *im, DetectionResult *result,
  397. float conf_threshold, float nms_iou_threshold) {
  398. Mat mat(*im);
  399. std::map<std::string, std::array<float, 2>> im_info;
  400. // Record the shape of image and the shape of preprocessed image
  401. im_info["input_shape"] = {static_cast<float>(mat.Height()),
  402. static_cast<float>(mat.Width())};
  403. im_info["output_shape"] = {static_cast<float>(mat.Height()),
  404. static_cast<float>(mat.Width())};
  405. if (use_cuda_preprocessing_) {
  406. if (!CudaPreprocess(&mat, &reused_input_tensors_[0], &im_info)) {
  407. FDERROR << "Failed to preprocess input image." << std::endl;
  408. return false;
  409. }
  410. } else {
  411. if (!Preprocess(&mat, &reused_input_tensors_[0], &im_info)) {
  412. FDERROR << "Failed to preprocess input image." << std::endl;
  413. return false;
  414. }
  415. }
  416. reused_input_tensors_[0].name = InputInfoOfRuntime(0).name;
  417. if (!Infer()) {
  418. FDERROR << "Failed to inference." << std::endl;
  419. return false;
  420. }
  421. if (is_decode_exported) {
  422. if (!Postprocess(reused_output_tensors_[0], result, im_info, conf_threshold,
  423. nms_iou_threshold)) {
  424. FDERROR << "Failed to post process." << std::endl;
  425. return false;
  426. }
  427. } else {
  428. if (!PostprocessWithDecode(reused_output_tensors_[0], result, im_info,
  429. conf_threshold, nms_iou_threshold)) {
  430. FDERROR << "Failed to post process." << std::endl;
  431. return false;
  432. }
  433. }
  434. return true;
  435. }
  436. } // namespace detection
  437. } // namespace vision
  438. } // namespace ultra_infer