yolov8_pose_onnx.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. #include "yolov8_pose_onnx.h"
  2. //using namespace std;
  3. //using namespace cv;
  4. //using namespace cv::dnn;
  5. using namespace Ort;
  6. bool Yolov8PoseOnnx::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 Yolov8PoseOnnx::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 Yolov8PoseOnnx::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 Yolov8PoseOnnx::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[1];
  184. int key_point_length = net_width - 5;
  185. //int key_point_num = 17; //_bodyKeyPoints.size(), shape[x, y, confidence]
  186. if (key_point_num * 2 != key_point_length) {
  187. std::cout << "Pose should be shape [x, y, confidence] with 17-points" << std::endl;
  188. return false;
  189. }
  190. int64_t one_output_length = VectorProduct(_outputTensorShape) / _outputTensorShape[0];
  191. for (int img_index = 0; img_index < srcImgs.size(); ++img_index) {
  192. cv::Mat output0 = cv::Mat(cv::Size((int)_outputTensorShape[2], (int)_outputTensorShape[1]), CV_32F, all_data).t(); //[bs,116,8400]=>[bs,8400,116]
  193. all_data += one_output_length;
  194. float* pdata = (float*)output0.data;
  195. int rows = output0.rows;
  196. std::vector<int> class_ids;//结果id数组
  197. std::vector<float> confidences;//结果每个id对应置信度数组
  198. std::vector<cv::Rect> boxes;//每个id矩形框
  199. std::vector<std::vector<PoseKeyPoint>> pose_key_points; //保存kpt
  200. for (int r = 0; r < rows; ++r) {
  201. float max_class_socre= pdata[4];
  202. if (max_class_socre >= _classThreshold) {
  203. //rect [x,y,w,h]
  204. float x = (pdata[0] - params[img_index][2]) / params[img_index][0]; //x
  205. float y = (pdata[1] - params[img_index][3]) / params[img_index][1]; //y
  206. float w = pdata[2] / params[img_index][0]; //w
  207. float h = pdata[3] / params[img_index][1]; //h
  208. int left = MAX(int(x - 0.5 * w + 0.5), 0);
  209. int top = MAX(int(y - 0.5 * h + 0.5), 0);
  210. class_ids.push_back(0);
  211. confidences.push_back(max_class_socre);
  212. boxes.push_back(cv::Rect(left, top, int(w + 0.5), int(h + 0.5)));
  213. std::vector<PoseKeyPoint> temp_kpts;
  214. for (int kpt = 0; kpt < key_point_length; kpt += 3) {
  215. PoseKeyPoint temp_kp;
  216. temp_kp.x = (pdata[5 + kpt]- params[img_index][2]) / params[img_index][0];
  217. temp_kp.y = (pdata[6 + kpt] - params[img_index][3]) / params[img_index][1];
  218. temp_kp.confidence = pdata[7 + kpt];
  219. temp_kpts.push_back(temp_kp);
  220. }
  221. pose_key_points.push_back(temp_kpts);
  222. }
  223. pdata += net_width;//下一行
  224. }
  225. std::vector<int> nms_result;
  226. cv::dnn::NMSBoxes(boxes, confidences, _classThreshold, _nmsThreshold, nms_result);
  227. std::vector<std::vector<float>> temp_mask_proposals;
  228. cv::Rect holeImgRect(0, 0, srcImgs[img_index].cols, srcImgs[img_index].rows);
  229. std::vector<OutputParams> temp_output;
  230. for (int i = 0; i < nms_result.size(); ++i) {
  231. int idx = nms_result[i];
  232. OutputParams result;
  233. result.id = class_ids[idx];
  234. result.confidence = confidences[idx];
  235. result.box = boxes[idx] & holeImgRect;
  236. result.keyPoints = pose_key_points[idx];
  237. if (result.box.area() < 1)
  238. continue;
  239. temp_output.push_back(result);
  240. }
  241. output.push_back(temp_output);
  242. }
  243. if (output.size())
  244. return true;
  245. else
  246. return false;
  247. }