rtdetr_onnx.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. #include "rtdetr_onnx.h"
  2. //using namespace std;
  3. //using namespace cv;
  4. //using namespace cv::dnn;
  5. using namespace Ort;
  6. bool RTDETROnnx::ReadModel(const std::string& modelPath, bool isCuda, int cudaID, bool warmUp) {
  7. if (_batchSize < 1) _batchSize = 1;
  8. try
  9. {
  10. if (!CheckModelPath(modelPath))
  11. return false;
  12. std::vector<std::string> available_providers = GetAvailableProviders();
  13. auto cuda_available = std::find(available_providers.begin(), available_providers.end(), "CUDAExecutionProvider");
  14. if (isCuda && (cuda_available == available_providers.end()))
  15. {
  16. std::cout << "Your ORT build without GPU. Change to CPU." << std::endl;
  17. std::cout << "************* Infer model on CPU! *************" << std::endl;
  18. }
  19. else if (isCuda && (cuda_available != available_providers.end()))
  20. {
  21. std::cout << "************* Infer model on GPU! *************" << std::endl;
  22. #if ORT_API_VERSION < ORT_OLD_VISON
  23. OrtCUDAProviderOptions cudaOption;
  24. cudaOption.device_id = cudaID;
  25. _OrtSessionOptions.AppendExecutionProvider_CUDA(cudaOption);
  26. #else
  27. OrtStatus* status = OrtSessionOptionsAppendExecutionProvider_CUDA(_OrtSessionOptions, cudaID);
  28. #endif
  29. }
  30. else
  31. {
  32. std::cout << "************* Infer model on CPU! *************" << std::endl;
  33. }
  34. //
  35. _OrtSessionOptions.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_EXTENDED);
  36. #ifdef _WIN32
  37. std::wstring model_path(modelPath.begin(), modelPath.end());
  38. _OrtSession = new Ort::Session(_OrtEnv, model_path.c_str(), _OrtSessionOptions);
  39. #else
  40. _OrtSession = new Ort::Session(_OrtEnv, modelPath.c_str(), _OrtSessionOptions);
  41. #endif
  42. Ort::AllocatorWithDefaultOptions allocator;
  43. //init input
  44. _inputNodesNum = _OrtSession->GetInputCount();
  45. #if ORT_API_VERSION < ORT_OLD_VISON
  46. _inputName = _OrtSession->GetInputName(0, allocator);
  47. _inputNodeNames.push_back(_inputName);
  48. #else
  49. _inputName = std::move(_OrtSession->GetInputNameAllocated(0, allocator));
  50. _inputNodeNames.push_back(_inputName.get());
  51. #endif
  52. //std::cout << _inputNodeNames[0] << std::endl;
  53. Ort::TypeInfo inputTypeInfo = _OrtSession->GetInputTypeInfo(0);
  54. auto input_tensor_info = inputTypeInfo.GetTensorTypeAndShapeInfo();
  55. _inputNodeDataType = input_tensor_info.GetElementType();
  56. _inputTensorShape = input_tensor_info.GetShape();
  57. if (_inputTensorShape[0] == -1)
  58. {
  59. _isDynamicShape = true;
  60. _inputTensorShape[0] = _batchSize;
  61. }
  62. if (_inputTensorShape[2] == -1 || _inputTensorShape[3] == -1) {
  63. _isDynamicShape = true;
  64. _inputTensorShape[2] = _netHeight;
  65. _inputTensorShape[3] = _netWidth;
  66. }
  67. //init output
  68. _outputNodesNum = _OrtSession->GetOutputCount();
  69. #if ORT_API_VERSION < ORT_OLD_VISON
  70. _output_name0 = _OrtSession->GetOutputName(0, allocator);
  71. _outputNodeNames.push_back(_output_name0);
  72. #else
  73. _output_name0 = std::move(_OrtSession->GetOutputNameAllocated(0, allocator));
  74. _outputNodeNames.push_back(_output_name0.get());
  75. #endif
  76. Ort::TypeInfo type_info_output0(nullptr);
  77. type_info_output0 = _OrtSession->GetOutputTypeInfo(0); //output0
  78. auto tensor_info_output0 = type_info_output0.GetTensorTypeAndShapeInfo();
  79. _outputNodeDataType = tensor_info_output0.GetElementType();
  80. _outputTensorShape = tensor_info_output0.GetShape();
  81. //_outputMaskNodeDataType = tensor_info_output1.GetElementType(); //the same as output0
  82. //_outputMaskTensorShape = tensor_info_output1.GetShape();
  83. //if (_outputTensorShape[0] == -1)
  84. //{
  85. // _outputTensorShape[0] = _batchSize;
  86. // _outputMaskTensorShape[0] = _batchSize;
  87. //}
  88. //if (_outputMaskTensorShape[2] == -1) {
  89. // //size_t ouput_rows = 0;
  90. // //for (int i = 0; i < _strideSize; ++i) {
  91. // // ouput_rows += 3 * (_netWidth / _netStride[i]) * _netHeight / _netStride[i];
  92. // //}
  93. // //_outputTensorShape[1] = ouput_rows;
  94. // _outputMaskTensorShape[2] = _segHeight;
  95. // _outputMaskTensorShape[3] = _segWidth;
  96. //}
  97. //warm up
  98. if (isCuda && warmUp) {
  99. //draw run
  100. std::cout << "Start warming up" << std::endl;
  101. size_t input_tensor_length = VectorProduct(_inputTensorShape);
  102. float* temp = new float[input_tensor_length];
  103. std::vector<Ort::Value> input_tensors;
  104. std::vector<Ort::Value> output_tensors;
  105. input_tensors.push_back(Ort::Value::CreateTensor<float>(
  106. _OrtMemoryInfo, temp, input_tensor_length, _inputTensorShape.data(),
  107. _inputTensorShape.size()));
  108. for (int i = 0; i < 3; ++i) {
  109. output_tensors = _OrtSession->Run(Ort::RunOptions{ nullptr },
  110. _inputNodeNames.data(),
  111. input_tensors.data(),
  112. _inputNodeNames.size(),
  113. _outputNodeNames.data(),
  114. _outputNodeNames.size());
  115. }
  116. delete[]temp;
  117. }
  118. }
  119. catch (const std::exception&) {
  120. return false;
  121. }
  122. return true;
  123. }
  124. int RTDETROnnx::PreProcessing(const std::vector<cv::Mat>& srcImgs, std::vector<cv::Mat>& outSrcImgs, std::vector<cv::Vec4d>& params) {
  125. outSrcImgs.clear();
  126. cv::Size input_size = cv::Size(_netWidth, _netHeight);
  127. for (int i = 0; i < srcImgs.size(); ++i) {
  128. cv::Mat temp_img = srcImgs[i];
  129. cv::Vec4d temp_param = { 1,1,0,0 };
  130. if (temp_img.size() != input_size) {
  131. cv::Mat borderImg;
  132. LetterBox(temp_img, borderImg, temp_param, input_size, false, false, true, 32);
  133. //std::cout << borderImg.size() << std::endl;
  134. outSrcImgs.push_back(borderImg);
  135. params.push_back(temp_param);
  136. }
  137. else {
  138. outSrcImgs.push_back(temp_img);
  139. params.push_back(temp_param);
  140. }
  141. }
  142. int lack_num = _batchSize - srcImgs.size();
  143. if (lack_num > 0) {
  144. for (int i = 0; i < lack_num; ++i) {
  145. cv::Mat temp_img = cv::Mat::zeros(input_size, CV_8UC3);
  146. cv::Vec4d temp_param = { 1,1,0,0 };
  147. outSrcImgs.push_back(temp_img);
  148. params.push_back(temp_param);
  149. }
  150. }
  151. return 0;
  152. }
  153. bool RTDETROnnx::OnnxDetect(cv::Mat& srcImg, std::vector<OutputParams>& output) {
  154. std::vector<cv::Mat> input_data = { srcImg };
  155. std::vector<std::vector<OutputParams>> tenp_output;
  156. if (OnnxBatchDetect(input_data, tenp_output)) {
  157. output = tenp_output[0];
  158. return true;
  159. }
  160. else return false;
  161. }
  162. bool RTDETROnnx::OnnxBatchDetect(std::vector<cv::Mat>& srcImgs, std::vector<std::vector<OutputParams>>& output) {
  163. std::vector<cv::Vec4d> params;
  164. std::vector<cv::Mat> input_images;
  165. cv::Size input_size(_netWidth, _netHeight);
  166. //preprocessing
  167. PreProcessing(srcImgs, input_images, params);
  168. cv::Mat blob = cv::dnn::blobFromImages(input_images, 1 / 255.0, input_size, cv::Scalar(0, 0, 0), true, false);
  169. int64_t input_tensor_length = VectorProduct(_inputTensorShape);
  170. std::vector<Ort::Value> input_tensors;
  171. std::vector<Ort::Value> output_tensors;
  172. input_tensors.push_back(Ort::Value::CreateTensor<float>(_OrtMemoryInfo, (float*)blob.data, input_tensor_length, _inputTensorShape.data(), _inputTensorShape.size()));
  173. output_tensors = _OrtSession->Run(Ort::RunOptions{ nullptr },
  174. _inputNodeNames.data(),
  175. input_tensors.data(),
  176. _inputNodeNames.size(),
  177. _outputNodeNames.data(),
  178. _outputNodeNames.size()
  179. );
  180. //post-process
  181. float* all_data = output_tensors[0].GetTensorMutableData<float>();
  182. _outputTensorShape = output_tensors[0].GetTensorTypeAndShapeInfo().GetShape();
  183. int net_width = _outputTensorShape[2];
  184. int socre_array_length = net_width - 4;
  185. int input_tensor_width = _inputTensorShape[2];
  186. int input_tensor_height = _inputTensorShape[3];
  187. int64_t one_output_length = VectorProduct(_outputTensorShape) / _outputTensorShape[0];
  188. for (int img_index = 0; img_index < srcImgs.size(); ++img_index) {
  189. cv::Mat output0 = cv::Mat(cv::Size((int)_outputTensorShape[2], (int)_outputTensorShape[1]), CV_32F, all_data);
  190. all_data += one_output_length;
  191. float* pdata = (float*)output0.data;
  192. int rows = output0.rows;
  193. cv::Rect holeImgRect(0, 0, srcImgs[img_index].cols, srcImgs[img_index].rows);
  194. std::vector<OutputParams> temp_output;
  195. for (int r = 0; r < rows; ++r) { //stride
  196. cv::Mat scores(1, socre_array_length, CV_32F, pdata + 4);
  197. cv::Point classIdPoint;
  198. double max_class_socre;
  199. minMaxLoc(scores, 0, &max_class_socre, 0, &classIdPoint);
  200. max_class_socre = (float)max_class_socre;
  201. if (max_class_socre >= _classThreshold) {
  202. //rect [x,y,w,h]
  203. float x = (pdata[0] * input_tensor_width - params[img_index][2]) / params[img_index][0]; //x
  204. float y = (pdata[1] * input_tensor_height - params[img_index][3]) / params[img_index][1]; //y
  205. float w = pdata[2] / params[img_index][0] * input_tensor_width; //w
  206. float h = pdata[3] / params[img_index][1] * input_tensor_height; //h
  207. int left = MAX(int(x - 0.5 * w + 0.5), 0);
  208. int top = MAX(int(y - 0.5 * h + 0.5), 0);
  209. cv::Rect box = cv::Rect(left, top, int(w + 0.5), int(h + 0.5));
  210. OutputParams result;
  211. result.id = classIdPoint.x;
  212. result.confidence = max_class_socre;
  213. result.box = box & holeImgRect;
  214. if (result.box.area() < 1)
  215. continue;
  216. temp_output.push_back(result);
  217. }
  218. pdata += net_width;//ÏÂÒ»ÐÐ
  219. }
  220. output.push_back(temp_output);
  221. }
  222. if (output.size())
  223. return true;
  224. else
  225. return false;
  226. }