yolov8_seg_onnx.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. #include "yolov8_seg_onnx.h"
  2. //using namespace std;
  3. //using namespace cv;
  4. //using namespace cv::dnn;
  5. using namespace Ort;
  6. bool Yolov8SegOnnx::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. Ort::TypeInfo inputTypeInfo = _OrtSession->GetInputTypeInfo(0);
  53. auto input_tensor_info = inputTypeInfo.GetTensorTypeAndShapeInfo();
  54. _inputNodeDataType = input_tensor_info.GetElementType();
  55. _inputTensorShape = input_tensor_info.GetShape();
  56. if (_inputTensorShape[0] == -1)
  57. {
  58. _isDynamicShape = true;
  59. _inputTensorShape[0] = _batchSize;
  60. }
  61. if (_inputTensorShape[2] == -1 || _inputTensorShape[3] == -1) {
  62. _isDynamicShape = true;
  63. _inputTensorShape[2] = _netHeight;
  64. _inputTensorShape[3] = _netWidth;
  65. }
  66. //init output
  67. _outputNodesNum = _OrtSession->GetOutputCount();
  68. if (_outputNodesNum != 2) {
  69. std::cout << "This model has " << _outputNodesNum << "output, which is not a segmentation model.Please check your model name or path!" << std::endl;
  70. return false;
  71. }
  72. #if ORT_API_VERSION < ORT_OLD_VISON
  73. _output_name0 = _OrtSession->GetOutputName(0, allocator);
  74. _output_name1 = _OrtSession->GetOutputName(1, allocator);
  75. #else
  76. _output_name0 = std::move(_OrtSession->GetOutputNameAllocated(0, allocator));
  77. _output_name1 = std::move(_OrtSession->GetOutputNameAllocated(1, allocator));
  78. #endif
  79. Ort::TypeInfo type_info_output0(nullptr);
  80. Ort::TypeInfo type_info_output1(nullptr);
  81. bool flag = false;
  82. #if ORT_API_VERSION < ORT_OLD_VISON
  83. flag = strcmp(_output_name0, _output_name1) < 0;
  84. #else
  85. flag = strcmp(_output_name0.get(), _output_name1.get()) < 0;
  86. #endif
  87. if (flag) //make sure "output0" is in front of "output1"
  88. {
  89. type_info_output0 = _OrtSession->GetOutputTypeInfo(0); //output0
  90. type_info_output1 = _OrtSession->GetOutputTypeInfo(1); //output1
  91. #if ORT_API_VERSION < ORT_OLD_VISON
  92. _outputNodeNames.push_back(_output_name0);
  93. _outputNodeNames.push_back(_output_name1);
  94. #else
  95. _outputNodeNames.push_back(_output_name0.get());
  96. _outputNodeNames.push_back(_output_name1.get());
  97. #endif
  98. }
  99. else {
  100. type_info_output0 = _OrtSession->GetOutputTypeInfo(1); //output0
  101. type_info_output1 = _OrtSession->GetOutputTypeInfo(0); //output1
  102. #if ORT_API_VERSION < ORT_OLD_VISON
  103. _outputNodeNames.push_back(_output_name1);
  104. _outputNodeNames.push_back(_output_name0);
  105. #else
  106. _outputNodeNames.push_back(_output_name1.get());
  107. _outputNodeNames.push_back(_output_name0.get());
  108. #endif
  109. }
  110. auto tensor_info_output0 = type_info_output0.GetTensorTypeAndShapeInfo();
  111. _outputNodeDataType = tensor_info_output0.GetElementType();
  112. _outputTensorShape = tensor_info_output0.GetShape();
  113. auto tensor_info_output1 = type_info_output1.GetTensorTypeAndShapeInfo();
  114. //_outputMaskNodeDataType = tensor_info_output1.GetElementType(); //the same as output0
  115. //_outputMaskTensorShape = tensor_info_output1.GetShape();
  116. //if (_outputTensorShape[0] == -1)
  117. //{
  118. // _outputTensorShape[0] = _batchSize;
  119. // _outputMaskTensorShape[0] = _batchSize;
  120. //}
  121. //if (_outputMaskTensorShape[2] == -1) {
  122. // //size_t ouput_rows = 0;
  123. // //for (int i = 0; i < _strideSize; ++i) {
  124. // // ouput_rows += 3 * (_netWidth / _netStride[i]) * _netHeight / _netStride[i];
  125. // //}
  126. // //_outputTensorShape[1] = ouput_rows;
  127. // _outputMaskTensorShape[2] = _segHeight;
  128. // _outputMaskTensorShape[3] = _segWidth;
  129. //}
  130. //warm up
  131. if (isCuda && warmUp) {
  132. //draw run
  133. std::cout << "Start warming up" << std::endl;
  134. size_t input_tensor_length = VectorProduct(_inputTensorShape);
  135. float* temp = new float[input_tensor_length];
  136. std::vector<Ort::Value> input_tensors;
  137. std::vector<Ort::Value> output_tensors;
  138. input_tensors.push_back(Ort::Value::CreateTensor<float>(
  139. _OrtMemoryInfo, temp, input_tensor_length, _inputTensorShape.data(),
  140. _inputTensorShape.size()));
  141. for (int i = 0; i < 3; ++i) {
  142. output_tensors = _OrtSession->Run(Ort::RunOptions{ nullptr },
  143. _inputNodeNames.data(),
  144. input_tensors.data(),
  145. _inputNodeNames.size(),
  146. _outputNodeNames.data(),
  147. _outputNodeNames.size());
  148. }
  149. delete[]temp;
  150. }
  151. }
  152. catch (const std::exception&) {
  153. return false;
  154. }
  155. return true;
  156. }
  157. int Yolov8SegOnnx::PreProcessing(const std::vector<cv::Mat>& srcImgs, std::vector<cv::Mat>& outSrcImgs, std::vector<cv::Vec4d>& params) {
  158. outSrcImgs.clear();
  159. cv::Size input_size = cv::Size(_netWidth, _netHeight);
  160. for (int i = 0; i < srcImgs.size(); ++i) {
  161. cv::Mat temp_img = srcImgs[i];
  162. cv::Vec4d temp_param = { 1,1,0,0 };
  163. if (temp_img.size() != input_size) {
  164. cv::Mat borderImg;
  165. LetterBox(temp_img, borderImg, temp_param, input_size, false, false, true, 32);
  166. //std::cout << borderImg.size() << std::endl;
  167. outSrcImgs.push_back(borderImg);
  168. params.push_back(temp_param);
  169. }
  170. else {
  171. outSrcImgs.push_back(temp_img);
  172. params.push_back(temp_param);
  173. }
  174. }
  175. int lack_num = srcImgs.size() % _batchSize;
  176. if (lack_num != 0) {
  177. for (int i = 0; i < lack_num; ++i) {
  178. cv::Mat temp_img = cv::Mat::zeros(input_size, CV_8UC3);
  179. cv::Vec4d temp_param = { 1,1,0,0 };
  180. outSrcImgs.push_back(temp_img);
  181. params.push_back(temp_param);
  182. }
  183. }
  184. return 0;
  185. }
  186. bool Yolov8SegOnnx::OnnxDetect(cv::Mat& srcImg, std::vector<OutputParams>& output) {
  187. std::vector<cv::Mat> input_data = { srcImg };
  188. std::vector<std::vector<OutputParams>> tenp_output;
  189. if (OnnxBatchDetect(input_data, tenp_output)) {
  190. output = tenp_output[0];
  191. return true;
  192. }
  193. else return false;
  194. }
  195. bool Yolov8SegOnnx::OnnxBatchDetect(std::vector<cv::Mat>& srcImgs, std::vector<std::vector<OutputParams>>& output) {
  196. std::vector<cv::Vec4d> params;
  197. std::vector<cv::Mat> input_images;
  198. cv::Size input_size(_netWidth, _netHeight);
  199. //preprocessing
  200. PreProcessing(srcImgs, input_images, params);
  201. cv::Mat blob = cv::dnn::blobFromImages(input_images, 1 / 255.0, input_size, cv::Scalar(0, 0, 0), true, false);
  202. int64_t input_tensor_length = VectorProduct(_inputTensorShape);
  203. std::vector<Ort::Value> input_tensors;
  204. std::vector<Ort::Value> output_tensors;
  205. input_tensors.push_back(Ort::Value::CreateTensor<float>(_OrtMemoryInfo, (float*)blob.data, input_tensor_length, _inputTensorShape.data(), _inputTensorShape.size()));
  206. output_tensors = _OrtSession->Run(Ort::RunOptions{ nullptr },
  207. _inputNodeNames.data(),
  208. input_tensors.data(),
  209. _inputNodeNames.size(),
  210. _outputNodeNames.data(),
  211. _outputNodeNames.size()
  212. );
  213. //post-process
  214. float* all_data = output_tensors[0].GetTensorMutableData<float>();
  215. _outputTensorShape = output_tensors[0].GetTensorTypeAndShapeInfo().GetShape();
  216. _outputMaskTensorShape = output_tensors[1].GetTensorTypeAndShapeInfo().GetShape();
  217. std::vector<int> mask_protos_shape = { 1,(int)_outputMaskTensorShape[1],(int)_outputMaskTensorShape[2],(int)_outputMaskTensorShape[3] };
  218. int mask_protos_length = VectorProduct(mask_protos_shape);
  219. int64_t one_output_length = VectorProduct(_outputTensorShape) / _outputTensorShape[0];
  220. int net_width = (int)_outputTensorShape[1];
  221. int socre_array_length = net_width - 4 - _outputMaskTensorShape[1];
  222. for (int img_index = 0; img_index < srcImgs.size(); ++img_index) {
  223. cv::Mat output0 = cv::Mat(cv::Size((int)_outputTensorShape[2], (int)_outputTensorShape[1]), CV_32F, all_data).t(); //[bs,116,8400]=>[bs,8400,116]
  224. all_data += one_output_length;
  225. float* pdata = (float*)output0.data;
  226. int rows = output0.rows;
  227. std::vector<int> class_ids;//结果id数组
  228. std::vector<float> confidences;//结果每个id对应置信度数组
  229. std::vector<cv::Rect> boxes;//每个id矩形框
  230. std::vector<std::vector<float>> picked_proposals; //output0[:,:, 5 + _className.size():net_width]===> for mask
  231. for (int r = 0; r < rows; ++r) { //stride
  232. cv::Mat scores(1, socre_array_length, CV_32F, pdata + 4);
  233. cv::Point classIdPoint;
  234. double max_class_socre;
  235. minMaxLoc(scores, 0, &max_class_socre, 0, &classIdPoint);
  236. max_class_socre = (float)max_class_socre;
  237. if (max_class_socre >= _classThreshold) {
  238. std::vector<float> temp_proto(pdata + 4 + socre_array_length, pdata + net_width);
  239. picked_proposals.push_back(temp_proto);
  240. //rect [x,y,w,h]
  241. float x = (pdata[0] - params[img_index][2]) / params[img_index][0]; //x
  242. float y = (pdata[1] - params[img_index][3]) / params[img_index][1]; //y
  243. float w = pdata[2] / params[img_index][0]; //w
  244. float h = pdata[3] / params[img_index][1]; //h
  245. int left = MAX(int(x - 0.5 * w + 0.5), 0);
  246. int top = MAX(int(y - 0.5 * h + 0.5), 0);
  247. class_ids.push_back(classIdPoint.x);
  248. confidences.push_back(max_class_socre);
  249. boxes.push_back(cv::Rect(left, top, int(w + 0.5), int(h + 0.5)));
  250. }
  251. pdata += net_width;//下一行
  252. }
  253. std::vector<int> nms_result;
  254. cv::dnn::NMSBoxes(boxes, confidences, _classThreshold, _nmsThreshold, nms_result);
  255. std::vector<std::vector<float>> temp_mask_proposals;
  256. cv::Rect holeImgRect(0, 0, srcImgs[img_index].cols, srcImgs[img_index].rows);
  257. std::vector<OutputParams> temp_output;
  258. for (int i = 0; i < nms_result.size(); ++i) {
  259. int idx = nms_result[i];
  260. OutputParams result;
  261. result.id = class_ids[idx];
  262. result.confidence = confidences[idx];
  263. result.box = boxes[idx] & holeImgRect;
  264. if (result.box.area() < 1)
  265. continue;
  266. temp_mask_proposals.push_back(picked_proposals[idx]);
  267. temp_output.push_back(result);
  268. }
  269. MaskParams mask_params;
  270. mask_params.params = params[img_index];
  271. mask_params.srcImgShape = srcImgs[img_index].size();
  272. mask_params.netHeight = _netHeight;
  273. mask_params.netWidth = _netWidth;
  274. mask_params.maskThreshold = _maskThreshold;
  275. cv::Mat mask_protos = cv::Mat(mask_protos_shape, CV_32F, output_tensors[1].GetTensorMutableData<float>() + img_index * mask_protos_length);
  276. for (int i = 0; i < temp_mask_proposals.size(); ++i) {
  277. GetMask2(cv::Mat(temp_mask_proposals[i]).t(), mask_protos, temp_output[i], mask_params);
  278. }
  279. //******************** ****************
  280. // 老版本的方案,如果上面在开启我注释的部分之后还一直报错,建议使用这个。
  281. // If the GetMask2() still reports errors , it is recommended to use GetMask().
  282. //cv::Mat mask_proposals;
  283. //for (int i = 0; i < temp_mask_proposals.size(); ++i) {
  284. // mask_proposals.push_back(cv::Mat(temp_mask_proposals[i]).t());
  285. //}
  286. //GetMask(mask_proposals, mask_protos, temp_output, mask_params);
  287. //*****************************************************/
  288. output.push_back(temp_output);
  289. }
  290. if (output.size())
  291. return true;
  292. else
  293. return false;
  294. }