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

main.cpp 9.1 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
  1. // Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <vector>
  5. #include <string>
  6. #include <algorithm>
  7. #include <regex>
  8. #include <sstream>
  9. #include <MNN/ImageProcess.hpp>
  10. #include <MNN/expr/Module.hpp>
  11. #include <MNN/expr/Executor.hpp>
  12. #include <MNN/expr/ExprCreator.hpp>
  13. #include <cv/cv.hpp>
  14. using namespace MNN;
  15. using namespace MNN::Express;
  16. using namespace MNN::CV;
  17. class Inference {
  18. public:
  19. // Load model: Create runtime, set cache if needed, and load the model file.
  20. bool loadModel(const std::string &modelPath,
  21. int forwardType = MNN_FORWARD_CPU,
  22. int precision = 0,
  23. int thread = 4) {
  24. MNN::ScheduleConfig sConfig;
  25. sConfig.type = static_cast<MNNForwardType>(forwardType);
  26. sConfig.numThread = thread;
  27. BackendConfig bConfig;
  28. bConfig.precision = static_cast<BackendConfig::PrecisionMode>(precision);
  29. sConfig.backendConfig = &bConfig;
  30. std::shared_ptr<Executor::RuntimeManager> rtmgr(
  31. Executor::RuntimeManager::createRuntimeManager(sConfig)
  32. );
  33. if (rtmgr == nullptr) {
  34. MNN_ERROR("Empty RuntimeManager\n");
  35. return false;
  36. }
  37. rtmgr->setCache(".cachefile");
  38. net = std::shared_ptr<Module>(Module::load(std::vector<std::string>{},
  39. std::vector<std::string>{}, modelPath.c_str(), rtmgr));
  40. if (net == nullptr) {
  41. return false;
  42. }
  43. runtimeManager = rtmgr;
  44. const Module::Info* info = net->getInfo();
  45. if (info == nullptr) {
  46. MNN_ERROR("Empty Module Info\n");
  47. return false;
  48. }
  49. // Parse bizCode to extract class names.
  50. if (info->bizCode.empty()) {
  51. MNN_ERROR("Empty bizCode\n");
  52. classNames.clear();
  53. return false;
  54. }
  55. // Get imgsz from bizCode.
  56. auto imgsz_start = info->bizCode.find("\"imgsz\": [");
  57. if (imgsz_start == std::string::npos) {
  58. MNN_PRINT("No imgsz found in bizCode, setting classNames empty.\n");
  59. } else {
  60. auto imgsz_end = info->bizCode.find("]", imgsz_start);
  61. if (imgsz_end == std::string::npos) {
  62. MNN_PRINT("No closing bracket for imgsz in bizCode, setting classNames empty.\n");
  63. } else {
  64. std::string imgszText = info->bizCode.substr(imgsz_start + 10, imgsz_end - imgsz_start - 10);
  65. std::vector<std::string> imgszVec;
  66. std::stringstream ss(imgszText);
  67. std::string item;
  68. while (std::getline(ss, item, ',')) {
  69. imgszVec.push_back(item);
  70. }
  71. }
  72. }
  73. // Get names from bizCode.
  74. auto names_start = info->bizCode.find("\"names\": {");
  75. if (names_start == std::string::npos) {
  76. MNN_PRINT("No names found in bizCode, setting classNames empty.\n");
  77. classNames.clear();
  78. } else {
  79. auto names_end = info->bizCode.find("}", names_start);
  80. if (names_end == std::string::npos) {
  81. MNN_PRINT("No closing brace for names in bizCode, setting classNames empty.\n");
  82. classNames.clear();
  83. } else {
  84. std::string namesDict = info->bizCode.substr(names_start + 10, names_end - names_start - 10);
  85. parseClassNamesFromBizCode(namesDict);
  86. }
  87. }
  88. return true;
  89. }
  90. void parseImgszFromBizCode(const std::string& bizText) {
  91. std::regex rgx("\"imgsz\":\\s*\\[(\\d+),\\s*(\\d+)\\]");
  92. std::smatch match;
  93. if (std::regex_search(bizText, match, rgx)) {
  94. int ih = std::stoi(match[1].str());
  95. int iw = std::stoi(match[2].str());
  96. MNN_PRINT("Input size: %d x %d\n", iw, ih);
  97. } else {
  98. MNN_PRINT("No imgsz found in bizCode.\n");
  99. }
  100. }
  101. void parseClassNamesFromBizCode(const std::string& bizText) {
  102. std::regex rgx("\"(\\d+)\"\\s*:\\s*\"([^\"]+)\"");
  103. std::smatch match;
  104. std::string s = bizText;
  105. classNames.clear();
  106. while (std::regex_search(s, match, rgx)) {
  107. int index = std::stoi(match[1].str());
  108. std::string name = match[2].str();
  109. if (classNames.size() <= static_cast<size_t>(index)) {
  110. classNames.resize(index + 1);
  111. }
  112. classNames[index] = name;
  113. s = match.suffix().str();
  114. }
  115. }
  116. VARP preprocess(VARP &originalImage, float &scale) {
  117. auto dims = originalImage->getInfo()->dim;
  118. int ih = dims[0];
  119. int iw = dims[1];
  120. int targetWidth = std::stoi(imgszVec[0]);
  121. int targetHeight = std::stoi(imgszVec[1]);
  122. int len = ih > iw ? ih : iw;
  123. scale = static_cast<float>(len) / std::max(targetWidth, targetHeight);
  124. std::vector<int> padvals { 0, len - ih, 0, len - iw, 0, 0 };
  125. auto pads = _Const(static_cast<void*>(padvals.data()), {3, 2}, NCHW, halide_type_of<int>());
  126. auto image = _Pad(originalImage, pads, CONSTANT);
  127. image = resize(image, Size(targetWidth, targetHeight), 0, 0, INTER_LINEAR, -1, {0., 0., 0.}, {1./255., 1./255., 1./255.});
  128. auto input = _Unsqueeze(image, {0});
  129. input = _Convert(input, NC4HW4);
  130. return input;
  131. }
  132. void runInference(VARP input) {
  133. std::vector<VARP> outputs = net->onForward({input});
  134. mOutput = outputs[0];
  135. }
  136. void postprocess(float scale, VARP originalImage, float iouThreshold = 0.45, float scoreThreshold = 0.25) {
  137. auto output = _Convert(mOutput, NCHW);
  138. output = _Squeeze(output);
  139. // Expected output shape: [84, 8400]
  140. auto cx = _Gather(output, _Scalar<int>(0));
  141. auto cy = _Gather(output, _Scalar<int>(1));
  142. auto w = _Gather(output, _Scalar<int>(2));
  143. auto h = _Gather(output, _Scalar<int>(3));
  144. std::vector<int> startvals { 4, 0 };
  145. auto start = _Const(static_cast<void*>(startvals.data()), {2}, NCHW, halide_type_of<int>());
  146. std::vector<int> sizevals { -1, -1 };
  147. auto size = _Const(static_cast<void*>(sizevals.data()), {2}, NCHW, halide_type_of<int>());
  148. auto probs = _Slice(output, start, size);
  149. // [cx, cy, w, h] -> [x1, y1, x2, y2]
  150. auto x1 = cx - w * _Const(0.5);
  151. auto y1 = cy - h * _Const(0.5);
  152. auto x2 = cx + w * _Const(0.5);
  153. auto y2 = cy + h * _Const(0.5);
  154. auto boxes = _Stack({x1, y1, x2, y2}, 1);
  155. auto scores = _ReduceMax(probs, {0});
  156. auto ids = _ArgMax(probs, 0);
  157. auto result_ids = _Nms(boxes, scores, 100, 0.45, 0.25);
  158. auto result_ptr = result_ids->readMap<int>();
  159. auto box_ptr = boxes->readMap<float>();
  160. auto ids_ptr = ids->readMap<int>();
  161. auto score_ptr = scores->readMap<float>();
  162. for (int i = 0; i < 100; i++) {
  163. auto idx = result_ptr[i];
  164. if (idx < 0) break;
  165. auto x1 = box_ptr[idx * 4 + 0] * scale;
  166. auto y1 = box_ptr[idx * 4 + 1] * scale;
  167. auto x2 = box_ptr[idx * 4 + 2] * scale;
  168. auto y2 = box_ptr[idx * 4 + 3] * scale;
  169. auto class_idx = ids_ptr[idx];
  170. auto score = score_ptr[idx];
  171. printf("Detection: box = {%.2f, %.2f, %.2f, %.2f}, class = %s, score = %.2f\n",
  172. x1, y1, x2, y2, classNames[class_idx].c_str(), score);
  173. rectangle(originalImage, { x1, y1 }, { x2, y2 }, { 0, 255, 0 }, 2);
  174. }
  175. if (imwrite("mnn_yolov8_cpp.jpg", originalImage)) {
  176. MNN_PRINT("Result image write to `mnn_yolov8_cpp.jpg`.\n");
  177. }
  178. }
  179. // Update runtime cache.
  180. void updateCache() {
  181. if (runtimeManager)
  182. runtimeManager->updateCache();
  183. }
  184. private:
  185. std::shared_ptr<Module> net;
  186. VARP mOutput;
  187. std::shared_ptr<Executor::RuntimeManager> runtimeManager;
  188. std::vector<std::string> classNames;
  189. std::vector<std::string> imgszVec { "640", "640" };
  190. };
  191. int main(int argc, const char* argv[]) {
  192. if (argc < 3) {
  193. MNN_PRINT("Usage: ./main yolov8n.mnn bus.jpg [forwardType] [precision] [thread]\n");
  194. return 0;
  195. }
  196. int thread = 4;
  197. int precision = 0;
  198. int forwardType = MNN_FORWARD_CPU;
  199. if (argc >= 4) {
  200. forwardType = atoi(argv[3]);
  201. }
  202. if (argc >= 5) {
  203. precision = atoi(argv[4]);
  204. }
  205. if (argc >= 6) {
  206. thread = atoi(argv[5]);
  207. }
  208. Inference infer;
  209. if (!infer.loadModel(argv[1], forwardType, precision, thread))
  210. return 1;
  211. const clock_t t0 = clock();
  212. float scale = 1.0f;
  213. VARP originalImage = imread(argv[2]);
  214. VARP input = infer.preprocess(originalImage, scale);
  215. double preprocess_time = 1000.0 * (clock() - t0) / CLOCKS_PER_SEC;
  216. const clock_t t1 = clock();
  217. infer.runInference(input);
  218. double inference_time = 1000.0 * (clock() - t1) / CLOCKS_PER_SEC;
  219. const clock_t t2 = clock();
  220. infer.postprocess(scale, originalImage);
  221. double postprocess_time = 1000.0 * (clock() - t2) / CLOCKS_PER_SEC;
  222. printf("Speed: %.1fms preprocess, %.1fms inference, %.1fms postprocess\n",
  223. preprocess_time, inference_time, postprocess_time);
  224. infer.updateCache();
  225. return 0;
  226. }
Tip!

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

Comments

Loading...