Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

inference.cpp 13 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
  1. // Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. #include "inference.h"
  3. #include <regex>
  4. #define benchmark
  5. #define min(a,b) (((a) < (b)) ? (a) : (b))
  6. YOLO_V8::YOLO_V8() {
  7. }
  8. YOLO_V8::~YOLO_V8() {
  9. delete session;
  10. }
  11. #ifdef USE_CUDA
  12. namespace Ort
  13. {
  14. template<>
  15. struct TypeToTensorType<half> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; };
  16. }
  17. #endif
  18. template<typename T>
  19. char* BlobFromImage(cv::Mat& iImg, T& iBlob) {
  20. int channels = iImg.channels();
  21. int imgHeight = iImg.rows;
  22. int imgWidth = iImg.cols;
  23. for (int c = 0; c < channels; c++)
  24. {
  25. for (int h = 0; h < imgHeight; h++)
  26. {
  27. for (int w = 0; w < imgWidth; w++)
  28. {
  29. iBlob[c * imgWidth * imgHeight + h * imgWidth + w] = typename std::remove_pointer<T>::type(
  30. (iImg.at<cv::Vec3b>(h, w)[c]) / 255.0f);
  31. }
  32. }
  33. }
  34. return RET_OK;
  35. }
  36. char* YOLO_V8::PreProcess(cv::Mat& iImg, std::vector<int> iImgSize, cv::Mat& oImg)
  37. {
  38. if (iImg.channels() == 3)
  39. {
  40. oImg = iImg.clone();
  41. cv::cvtColor(oImg, oImg, cv::COLOR_BGR2RGB);
  42. }
  43. else
  44. {
  45. cv::cvtColor(iImg, oImg, cv::COLOR_GRAY2RGB);
  46. }
  47. switch (modelType)
  48. {
  49. case YOLO_DETECT_V8:
  50. case YOLO_POSE:
  51. case YOLO_DETECT_V8_HALF:
  52. case YOLO_POSE_V8_HALF://LetterBox
  53. {
  54. if (iImg.cols >= iImg.rows)
  55. {
  56. resizeScales = iImg.cols / (float)iImgSize.at(0);
  57. cv::resize(oImg, oImg, cv::Size(iImgSize.at(0), int(iImg.rows / resizeScales)));
  58. }
  59. else
  60. {
  61. resizeScales = iImg.rows / (float)iImgSize.at(0);
  62. cv::resize(oImg, oImg, cv::Size(int(iImg.cols / resizeScales), iImgSize.at(1)));
  63. }
  64. cv::Mat tempImg = cv::Mat::zeros(iImgSize.at(0), iImgSize.at(1), CV_8UC3);
  65. oImg.copyTo(tempImg(cv::Rect(0, 0, oImg.cols, oImg.rows)));
  66. oImg = tempImg;
  67. break;
  68. }
  69. case YOLO_CLS://CenterCrop
  70. {
  71. int h = iImg.rows;
  72. int w = iImg.cols;
  73. int m = min(h, w);
  74. int top = (h - m) / 2;
  75. int left = (w - m) / 2;
  76. cv::resize(oImg(cv::Rect(left, top, m, m)), oImg, cv::Size(iImgSize.at(0), iImgSize.at(1)));
  77. break;
  78. }
  79. }
  80. return RET_OK;
  81. }
  82. char* YOLO_V8::CreateSession(DL_INIT_PARAM& iParams) {
  83. char* Ret = RET_OK;
  84. std::regex pattern("[\u4e00-\u9fa5]");
  85. bool result = std::regex_search(iParams.modelPath, pattern);
  86. if (result)
  87. {
  88. Ret = "[YOLO_V8]:Your model path is error.Change your model path without chinese characters.";
  89. std::cout << Ret << std::endl;
  90. return Ret;
  91. }
  92. try
  93. {
  94. rectConfidenceThreshold = iParams.rectConfidenceThreshold;
  95. iouThreshold = iParams.iouThreshold;
  96. imgSize = iParams.imgSize;
  97. modelType = iParams.modelType;
  98. cudaEnable = iParams.cudaEnable;
  99. env = Ort::Env(ORT_LOGGING_LEVEL_WARNING, "Yolo");
  100. Ort::SessionOptions sessionOption;
  101. if (iParams.cudaEnable)
  102. {
  103. OrtCUDAProviderOptions cudaOption;
  104. cudaOption.device_id = 0;
  105. sessionOption.AppendExecutionProvider_CUDA(cudaOption);
  106. }
  107. sessionOption.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
  108. sessionOption.SetIntraOpNumThreads(iParams.intraOpNumThreads);
  109. sessionOption.SetLogSeverityLevel(iParams.logSeverityLevel);
  110. #ifdef _WIN32
  111. int ModelPathSize = MultiByteToWideChar(CP_UTF8, 0, iParams.modelPath.c_str(), static_cast<int>(iParams.modelPath.length()), nullptr, 0);
  112. wchar_t* wide_cstr = new wchar_t[ModelPathSize + 1];
  113. MultiByteToWideChar(CP_UTF8, 0, iParams.modelPath.c_str(), static_cast<int>(iParams.modelPath.length()), wide_cstr, ModelPathSize);
  114. wide_cstr[ModelPathSize] = L'\0';
  115. const wchar_t* modelPath = wide_cstr;
  116. #else
  117. const char* modelPath = iParams.modelPath.c_str();
  118. #endif // _WIN32
  119. session = new Ort::Session(env, modelPath, sessionOption);
  120. Ort::AllocatorWithDefaultOptions allocator;
  121. size_t inputNodesNum = session->GetInputCount();
  122. for (size_t i = 0; i < inputNodesNum; i++)
  123. {
  124. Ort::AllocatedStringPtr input_node_name = session->GetInputNameAllocated(i, allocator);
  125. char* temp_buf = new char[50];
  126. strcpy(temp_buf, input_node_name.get());
  127. inputNodeNames.push_back(temp_buf);
  128. }
  129. size_t OutputNodesNum = session->GetOutputCount();
  130. for (size_t i = 0; i < OutputNodesNum; i++)
  131. {
  132. Ort::AllocatedStringPtr output_node_name = session->GetOutputNameAllocated(i, allocator);
  133. char* temp_buf = new char[10];
  134. strcpy(temp_buf, output_node_name.get());
  135. outputNodeNames.push_back(temp_buf);
  136. }
  137. options = Ort::RunOptions{ nullptr };
  138. WarmUpSession();
  139. return RET_OK;
  140. }
  141. catch (const std::exception& e)
  142. {
  143. const char* str1 = "[YOLO_V8]:";
  144. const char* str2 = e.what();
  145. std::string result = std::string(str1) + std::string(str2);
  146. char* merged = new char[result.length() + 1];
  147. std::strcpy(merged, result.c_str());
  148. std::cout << merged << std::endl;
  149. delete[] merged;
  150. return "[YOLO_V8]:Create session failed.";
  151. }
  152. }
  153. char* YOLO_V8::RunSession(cv::Mat& iImg, std::vector<DL_RESULT>& oResult) {
  154. #ifdef benchmark
  155. clock_t starttime_1 = clock();
  156. #endif // benchmark
  157. char* Ret = RET_OK;
  158. cv::Mat processedImg;
  159. PreProcess(iImg, imgSize, processedImg);
  160. if (modelType < 4)
  161. {
  162. float* blob = new float[processedImg.total() * 3];
  163. BlobFromImage(processedImg, blob);
  164. std::vector<int64_t> inputNodeDims = { 1, 3, imgSize.at(0), imgSize.at(1) };
  165. TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult);
  166. }
  167. else
  168. {
  169. #ifdef USE_CUDA
  170. half* blob = new half[processedImg.total() * 3];
  171. BlobFromImage(processedImg, blob);
  172. std::vector<int64_t> inputNodeDims = { 1,3,imgSize.at(0),imgSize.at(1) };
  173. TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult);
  174. #endif
  175. }
  176. return Ret;
  177. }
  178. template<typename N>
  179. char* YOLO_V8::TensorProcess(clock_t& starttime_1, cv::Mat& iImg, N& blob, std::vector<int64_t>& inputNodeDims,
  180. std::vector<DL_RESULT>& oResult) {
  181. Ort::Value inputTensor = Ort::Value::CreateTensor<typename std::remove_pointer<N>::type>(
  182. Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1),
  183. inputNodeDims.data(), inputNodeDims.size());
  184. #ifdef benchmark
  185. clock_t starttime_2 = clock();
  186. #endif // benchmark
  187. auto outputTensor = session->Run(options, inputNodeNames.data(), &inputTensor, 1, outputNodeNames.data(),
  188. outputNodeNames.size());
  189. #ifdef benchmark
  190. clock_t starttime_3 = clock();
  191. #endif // benchmark
  192. Ort::TypeInfo typeInfo = outputTensor.front().GetTypeInfo();
  193. auto tensor_info = typeInfo.GetTensorTypeAndShapeInfo();
  194. std::vector<int64_t> outputNodeDims = tensor_info.GetShape();
  195. auto output = outputTensor.front().GetTensorMutableData<typename std::remove_pointer<N>::type>();
  196. delete[] blob;
  197. switch (modelType)
  198. {
  199. case YOLO_DETECT_V8:
  200. case YOLO_DETECT_V8_HALF:
  201. {
  202. int signalResultNum = outputNodeDims[1];//84
  203. int strideNum = outputNodeDims[2];//8400
  204. std::vector<int> class_ids;
  205. std::vector<float> confidences;
  206. std::vector<cv::Rect> boxes;
  207. cv::Mat rawData;
  208. if (modelType == YOLO_DETECT_V8)
  209. {
  210. // FP32
  211. rawData = cv::Mat(signalResultNum, strideNum, CV_32F, output);
  212. }
  213. else
  214. {
  215. // FP16
  216. rawData = cv::Mat(signalResultNum, strideNum, CV_16F, output);
  217. rawData.convertTo(rawData, CV_32F);
  218. }
  219. // Note:
  220. // ultralytics add transpose operator to the output of yolov8 model.which make yolov8/v5/v7 has same shape
  221. // https://github.com/ultralytics/assets/releases/download/v8.3.0/yolov8n.pt
  222. rawData = rawData.t();
  223. float* data = (float*)rawData.data;
  224. for (int i = 0; i < strideNum; ++i)
  225. {
  226. float* classesScores = data + 4;
  227. cv::Mat scores(1, this->classes.size(), CV_32FC1, classesScores);
  228. cv::Point class_id;
  229. double maxClassScore;
  230. cv::minMaxLoc(scores, 0, &maxClassScore, 0, &class_id);
  231. if (maxClassScore > rectConfidenceThreshold)
  232. {
  233. confidences.push_back(maxClassScore);
  234. class_ids.push_back(class_id.x);
  235. float x = data[0];
  236. float y = data[1];
  237. float w = data[2];
  238. float h = data[3];
  239. int left = int((x - 0.5 * w) * resizeScales);
  240. int top = int((y - 0.5 * h) * resizeScales);
  241. int width = int(w * resizeScales);
  242. int height = int(h * resizeScales);
  243. boxes.push_back(cv::Rect(left, top, width, height));
  244. }
  245. data += signalResultNum;
  246. }
  247. std::vector<int> nmsResult;
  248. cv::dnn::NMSBoxes(boxes, confidences, rectConfidenceThreshold, iouThreshold, nmsResult);
  249. for (int i = 0; i < nmsResult.size(); ++i)
  250. {
  251. int idx = nmsResult[i];
  252. DL_RESULT result;
  253. result.classId = class_ids[idx];
  254. result.confidence = confidences[idx];
  255. result.box = boxes[idx];
  256. oResult.push_back(result);
  257. }
  258. #ifdef benchmark
  259. clock_t starttime_4 = clock();
  260. double pre_process_time = (double)(starttime_2 - starttime_1) / CLOCKS_PER_SEC * 1000;
  261. double process_time = (double)(starttime_3 - starttime_2) / CLOCKS_PER_SEC * 1000;
  262. double post_process_time = (double)(starttime_4 - starttime_3) / CLOCKS_PER_SEC * 1000;
  263. if (cudaEnable)
  264. {
  265. std::cout << "[YOLO_V8(CUDA)]: " << pre_process_time << "ms pre-process, " << process_time << "ms inference, " << post_process_time << "ms post-process." << std::endl;
  266. }
  267. else
  268. {
  269. std::cout << "[YOLO_V8(CPU)]: " << pre_process_time << "ms pre-process, " << process_time << "ms inference, " << post_process_time << "ms post-process." << std::endl;
  270. }
  271. #endif // benchmark
  272. break;
  273. }
  274. case YOLO_CLS:
  275. case YOLO_CLS_HALF:
  276. {
  277. cv::Mat rawData;
  278. if (modelType == YOLO_CLS) {
  279. // FP32
  280. rawData = cv::Mat(1, this->classes.size(), CV_32F, output);
  281. } else {
  282. // FP16
  283. rawData = cv::Mat(1, this->classes.size(), CV_16F, output);
  284. rawData.convertTo(rawData, CV_32F);
  285. }
  286. float *data = (float *) rawData.data;
  287. DL_RESULT result;
  288. for (int i = 0; i < this->classes.size(); i++)
  289. {
  290. result.classId = i;
  291. result.confidence = data[i];
  292. oResult.push_back(result);
  293. }
  294. break;
  295. }
  296. default:
  297. std::cout << "[YOLO_V8]: " << "Not support model type." << std::endl;
  298. }
  299. return RET_OK;
  300. }
  301. char* YOLO_V8::WarmUpSession() {
  302. clock_t starttime_1 = clock();
  303. cv::Mat iImg = cv::Mat(cv::Size(imgSize.at(0), imgSize.at(1)), CV_8UC3);
  304. cv::Mat processedImg;
  305. PreProcess(iImg, imgSize, processedImg);
  306. if (modelType < 4)
  307. {
  308. float* blob = new float[iImg.total() * 3];
  309. BlobFromImage(processedImg, blob);
  310. std::vector<int64_t> YOLO_input_node_dims = { 1, 3, imgSize.at(0), imgSize.at(1) };
  311. Ort::Value input_tensor = Ort::Value::CreateTensor<float>(
  312. Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1),
  313. YOLO_input_node_dims.data(), YOLO_input_node_dims.size());
  314. auto output_tensors = session->Run(options, inputNodeNames.data(), &input_tensor, 1, outputNodeNames.data(),
  315. outputNodeNames.size());
  316. delete[] blob;
  317. clock_t starttime_4 = clock();
  318. double post_process_time = (double)(starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000;
  319. if (cudaEnable)
  320. {
  321. std::cout << "[YOLO_V8(CUDA)]: " << "Cuda warm-up cost " << post_process_time << " ms. " << std::endl;
  322. }
  323. }
  324. else
  325. {
  326. #ifdef USE_CUDA
  327. half* blob = new half[iImg.total() * 3];
  328. BlobFromImage(processedImg, blob);
  329. std::vector<int64_t> YOLO_input_node_dims = { 1,3,imgSize.at(0),imgSize.at(1) };
  330. Ort::Value input_tensor = Ort::Value::CreateTensor<half>(Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1), YOLO_input_node_dims.data(), YOLO_input_node_dims.size());
  331. auto output_tensors = session->Run(options, inputNodeNames.data(), &input_tensor, 1, outputNodeNames.data(), outputNodeNames.size());
  332. delete[] blob;
  333. clock_t starttime_4 = clock();
  334. double post_process_time = (double)(starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000;
  335. if (cudaEnable)
  336. {
  337. std::cout << "[YOLO_V8(CUDA)]: " << "Cuda warm-up cost " << post_process_time << " ms. " << std::endl;
  338. }
  339. #endif
  340. }
  341. return RET_OK;
  342. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...