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 11 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
  1. #include "inference.h"
  2. #include <regex>
  3. #define benchmark
  4. DCSP_CORE::DCSP_CORE() {
  5. }
  6. DCSP_CORE::~DCSP_CORE() {
  7. delete session;
  8. }
  9. #ifdef USE_CUDA
  10. namespace Ort
  11. {
  12. template<>
  13. struct TypeToTensorType<half> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; };
  14. }
  15. #endif
  16. template<typename T>
  17. char *BlobFromImage(cv::Mat &iImg, T &iBlob) {
  18. int channels = iImg.channels();
  19. int imgHeight = iImg.rows;
  20. int imgWidth = iImg.cols;
  21. for (int c = 0; c < channels; c++) {
  22. for (int h = 0; h < imgHeight; h++) {
  23. for (int w = 0; w < imgWidth; w++) {
  24. iBlob[c * imgWidth * imgHeight + h * imgWidth + w] = typename std::remove_pointer<T>::type(
  25. (iImg.at<cv::Vec3b>(h, w)[c]) / 255.0f);
  26. }
  27. }
  28. }
  29. return RET_OK;
  30. }
  31. char *PostProcess(cv::Mat &iImg, std::vector<int> iImgSize, cv::Mat &oImg) {
  32. cv::Mat img = iImg.clone();
  33. cv::resize(iImg, oImg, cv::Size(iImgSize.at(0), iImgSize.at(1)));
  34. if (img.channels() == 1) {
  35. cv::cvtColor(oImg, oImg, cv::COLOR_GRAY2BGR);
  36. }
  37. cv::cvtColor(oImg, oImg, cv::COLOR_BGR2RGB);
  38. return RET_OK;
  39. }
  40. char *DCSP_CORE::CreateSession(DCSP_INIT_PARAM &iParams) {
  41. char *Ret = RET_OK;
  42. std::regex pattern("[\u4e00-\u9fa5]");
  43. bool result = std::regex_search(iParams.ModelPath, pattern);
  44. if (result) {
  45. Ret = "[DCSP_ONNX]:Model path error.Change your model path without chinese characters.";
  46. std::cout << Ret << std::endl;
  47. return Ret;
  48. }
  49. try {
  50. rectConfidenceThreshold = iParams.RectConfidenceThreshold;
  51. iouThreshold = iParams.iouThreshold;
  52. imgSize = iParams.imgSize;
  53. modelType = iParams.ModelType;
  54. env = Ort::Env(ORT_LOGGING_LEVEL_WARNING, "Yolo");
  55. Ort::SessionOptions sessionOption;
  56. if (iParams.CudaEnable) {
  57. cudaEnable = iParams.CudaEnable;
  58. OrtCUDAProviderOptions cudaOption;
  59. cudaOption.device_id = 0;
  60. sessionOption.AppendExecutionProvider_CUDA(cudaOption);
  61. }
  62. sessionOption.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
  63. sessionOption.SetIntraOpNumThreads(iParams.IntraOpNumThreads);
  64. sessionOption.SetLogSeverityLevel(iParams.LogSeverityLevel);
  65. #ifdef _WIN32
  66. int ModelPathSize = MultiByteToWideChar(CP_UTF8, 0, iParams.ModelPath.c_str(), static_cast<int>(iParams.ModelPath.length()), nullptr, 0);
  67. wchar_t* wide_cstr = new wchar_t[ModelPathSize + 1];
  68. MultiByteToWideChar(CP_UTF8, 0, iParams.ModelPath.c_str(), static_cast<int>(iParams.ModelPath.length()), wide_cstr, ModelPathSize);
  69. wide_cstr[ModelPathSize] = L'\0';
  70. const wchar_t* modelPath = wide_cstr;
  71. #else
  72. const char *modelPath = iParams.ModelPath.c_str();
  73. #endif // _WIN32
  74. session = new Ort::Session(env, modelPath, sessionOption);
  75. Ort::AllocatorWithDefaultOptions allocator;
  76. size_t inputNodesNum = session->GetInputCount();
  77. for (size_t i = 0; i < inputNodesNum; i++) {
  78. Ort::AllocatedStringPtr input_node_name = session->GetInputNameAllocated(i, allocator);
  79. char *temp_buf = new char[50];
  80. strcpy(temp_buf, input_node_name.get());
  81. inputNodeNames.push_back(temp_buf);
  82. }
  83. size_t OutputNodesNum = session->GetOutputCount();
  84. for (size_t i = 0; i < OutputNodesNum; i++) {
  85. Ort::AllocatedStringPtr output_node_name = session->GetOutputNameAllocated(i, allocator);
  86. char *temp_buf = new char[10];
  87. strcpy(temp_buf, output_node_name.get());
  88. outputNodeNames.push_back(temp_buf);
  89. }
  90. options = Ort::RunOptions{nullptr};
  91. WarmUpSession();
  92. return RET_OK;
  93. }
  94. catch (const std::exception &e) {
  95. const char *str1 = "[DCSP_ONNX]:";
  96. const char *str2 = e.what();
  97. std::string result = std::string(str1) + std::string(str2);
  98. char *merged = new char[result.length() + 1];
  99. std::strcpy(merged, result.c_str());
  100. std::cout << merged << std::endl;
  101. delete[] merged;
  102. return "[DCSP_ONNX]:Create session failed.";
  103. }
  104. }
  105. char *DCSP_CORE::RunSession(cv::Mat &iImg, std::vector<DCSP_RESULT> &oResult) {
  106. #ifdef benchmark
  107. clock_t starttime_1 = clock();
  108. #endif // benchmark
  109. char *Ret = RET_OK;
  110. cv::Mat processedImg;
  111. PostProcess(iImg, imgSize, processedImg);
  112. if (modelType < 4) {
  113. float *blob = new float[processedImg.total() * 3];
  114. BlobFromImage(processedImg, blob);
  115. std::vector<int64_t> inputNodeDims = {1, 3, imgSize.at(0), imgSize.at(1)};
  116. TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult);
  117. } else {
  118. #ifdef USE_CUDA
  119. half* blob = new half[processedImg.total() * 3];
  120. BlobFromImage(processedImg, blob);
  121. std::vector<int64_t> inputNodeDims = { 1,3,imgSize.at(0),imgSize.at(1) };
  122. TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult);
  123. #endif
  124. }
  125. return Ret;
  126. }
  127. template<typename N>
  128. char *DCSP_CORE::TensorProcess(clock_t &starttime_1, cv::Mat &iImg, N &blob, std::vector<int64_t> &inputNodeDims,
  129. std::vector<DCSP_RESULT> &oResult) {
  130. Ort::Value inputTensor = Ort::Value::CreateTensor<typename std::remove_pointer<N>::type>(
  131. Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1),
  132. inputNodeDims.data(), inputNodeDims.size());
  133. #ifdef benchmark
  134. clock_t starttime_2 = clock();
  135. #endif // benchmark
  136. auto outputTensor = session->Run(options, inputNodeNames.data(), &inputTensor, 1, outputNodeNames.data(),
  137. outputNodeNames.size());
  138. #ifdef benchmark
  139. clock_t starttime_3 = clock();
  140. #endif // benchmark
  141. Ort::TypeInfo typeInfo = outputTensor.front().GetTypeInfo();
  142. auto tensor_info = typeInfo.GetTensorTypeAndShapeInfo();
  143. std::vector<int64_t> outputNodeDims = tensor_info.GetShape();
  144. auto output = outputTensor.front().GetTensorMutableData<typename std::remove_pointer<N>::type>();
  145. delete blob;
  146. switch (modelType) {
  147. case 1://V8_ORIGIN_FP32
  148. case 4://V8_ORIGIN_FP16
  149. {
  150. int strideNum = outputNodeDims[2];
  151. int signalResultNum = outputNodeDims[1];
  152. std::vector<int> class_ids;
  153. std::vector<float> confidences;
  154. std::vector<cv::Rect> boxes;
  155. cv::Mat rawData;
  156. if (modelType == 1) {
  157. // FP32
  158. rawData = cv::Mat(signalResultNum, strideNum, CV_32F, output);
  159. } else {
  160. // FP16
  161. rawData = cv::Mat(signalResultNum, strideNum, CV_16F, output);
  162. rawData.convertTo(rawData, CV_32F);
  163. }
  164. rawData = rawData.t();
  165. float *data = (float *) rawData.data;
  166. float x_factor = iImg.cols / 640.;
  167. float y_factor = iImg.rows / 640.;
  168. for (int i = 0; i < strideNum; ++i) {
  169. float *classesScores = data + 4;
  170. cv::Mat scores(1, this->classes.size(), CV_32FC1, classesScores);
  171. cv::Point class_id;
  172. double maxClassScore;
  173. cv::minMaxLoc(scores, 0, &maxClassScore, 0, &class_id);
  174. if (maxClassScore > rectConfidenceThreshold) {
  175. confidences.push_back(maxClassScore);
  176. class_ids.push_back(class_id.x);
  177. float x = data[0];
  178. float y = data[1];
  179. float w = data[2];
  180. float h = data[3];
  181. int left = int((x - 0.5 * w) * x_factor);
  182. int top = int((y - 0.5 * h) * y_factor);
  183. int width = int(w * x_factor);
  184. int height = int(h * y_factor);
  185. boxes.emplace_back(left, top, width, height);
  186. }
  187. data += signalResultNum;
  188. }
  189. std::vector<int> nmsResult;
  190. cv::dnn::NMSBoxes(boxes, confidences, rectConfidenceThreshold, iouThreshold, nmsResult);
  191. for (int i = 0; i < nmsResult.size(); ++i) {
  192. int idx = nmsResult[i];
  193. DCSP_RESULT result;
  194. result.classId = class_ids[idx];
  195. result.confidence = confidences[idx];
  196. result.box = boxes[idx];
  197. oResult.push_back(result);
  198. }
  199. #ifdef benchmark
  200. clock_t starttime_4 = clock();
  201. double pre_process_time = (double) (starttime_2 - starttime_1) / CLOCKS_PER_SEC * 1000;
  202. double process_time = (double) (starttime_3 - starttime_2) / CLOCKS_PER_SEC * 1000;
  203. double post_process_time = (double) (starttime_4 - starttime_3) / CLOCKS_PER_SEC * 1000;
  204. if (cudaEnable) {
  205. std::cout << "[DCSP_ONNX(CUDA)]: " << pre_process_time << "ms pre-process, " << process_time
  206. << "ms inference, " << post_process_time << "ms post-process." << std::endl;
  207. } else {
  208. std::cout << "[DCSP_ONNX(CPU)]: " << pre_process_time << "ms pre-process, " << process_time
  209. << "ms inference, " << post_process_time << "ms post-process." << std::endl;
  210. }
  211. #endif // benchmark
  212. break;
  213. }
  214. }
  215. return RET_OK;
  216. }
  217. char *DCSP_CORE::WarmUpSession() {
  218. clock_t starttime_1 = clock();
  219. cv::Mat iImg = cv::Mat(cv::Size(imgSize.at(0), imgSize.at(1)), CV_8UC3);
  220. cv::Mat processedImg;
  221. PostProcess(iImg, imgSize, processedImg);
  222. if (modelType < 4) {
  223. float *blob = new float[iImg.total() * 3];
  224. BlobFromImage(processedImg, blob);
  225. std::vector<int64_t> YOLO_input_node_dims = {1, 3, imgSize.at(0), imgSize.at(1)};
  226. Ort::Value input_tensor = Ort::Value::CreateTensor<float>(
  227. Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1),
  228. YOLO_input_node_dims.data(), YOLO_input_node_dims.size());
  229. auto output_tensors = session->Run(options, inputNodeNames.data(), &input_tensor, 1, outputNodeNames.data(),
  230. outputNodeNames.size());
  231. delete[] blob;
  232. clock_t starttime_4 = clock();
  233. double post_process_time = (double) (starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000;
  234. if (cudaEnable) {
  235. std::cout << "[DCSP_ONNX(CUDA)]: " << "Cuda warm-up cost " << post_process_time << " ms. " << std::endl;
  236. }
  237. } else {
  238. #ifdef USE_CUDA
  239. half* blob = new half[iImg.total() * 3];
  240. BlobFromImage(processedImg, blob);
  241. std::vector<int64_t> YOLO_input_node_dims = { 1,3,imgSize.at(0),imgSize.at(1) };
  242. 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());
  243. auto output_tensors = session->Run(options, inputNodeNames.data(), &input_tensor, 1, outputNodeNames.data(), outputNodeNames.size());
  244. delete[] blob;
  245. clock_t starttime_4 = clock();
  246. double post_process_time = (double)(starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000;
  247. if (cudaEnable)
  248. {
  249. std::cout << "[DCSP_ONNX(CUDA)]: " << "Cuda warm-up cost " << post_process_time << " ms. " << std::endl;
  250. }
  251. #endif
  252. }
  253. return RET_OK;
  254. }
Tip!

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

Comments

Loading...