You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.en.md 21 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. # demo_object_detection
  2. The following describes how to use the MindSpore Lite C++ APIs (Android JNIs) and MindSpore Lite object detection models to perform on-device inference, detect the content captured by a device camera, and display the most possible detection result on the application's image preview screen.
  3. ## Deploying an Application
  4. The following section describes how to build and execute an on-device object detecion task on MindSpore Lite.
  5. ### Running Dependencies
  6. - Android Studio 3.2 or later (Android 4.0 or later is recommended.)
  7. - Native development kit (NDK) 21.3
  8. - CMake 3.10.2
  9. - Android software development kit (SDK) 26 or later
  10. - OpenCV 4.0.0 or later (included in the sample code)
  11. ### Building and Running
  12. 1. Load the sample source code to Android Studio and install the corresponding SDK. (After the SDK version is specified, Android Studio automatically installs the SDK.)
  13. ![start_home](images/home.png)
  14. Start Android Studio, click `File > Settings > System Settings > Android SDK`, and select the corresponding SDK. As shown in the following figure, select an SDK and click `OK`. Android Studio automatically installs the SDK.
  15. ![start_sdk](images/sdk_management.png)
  16. 2. Connect to an Android device and runs the object detection application.
  17. Connect to the Android device through a USB cable for debugging. Click `Run 'app'` to run the sample project on your device.
  18. ![run_app](images/project_structure.png)
  19. For details about how to connect the Android Studio to a device for debugging, see <https://developer.android.com/studio/run/device>.
  20. 3. Continue the installation on the Android device. After the installation is complete, you can view the content captured by a camera and the inference result.
  21. ![result](images/object_detection.png)
  22. ## Detailed Description of the Sample Program
  23. This object detection sample program on the Android device includes a Java layer and a JNI layer. At the Java layer, the Android Camera 2 API is used to enable a camera to obtain image frames and process images. At the JNI layer, the model inference process is completed .
  24. ### Configuring MindSpore Lite Dependencies
  25. In Android Studio, place the compiled `libmindspore-lite.so` library file (which can contain multiple compatible architectures) in the `app/libs/ARM64-V8a` (Arm64) or `app/libs/armeabi-v7a` (Arm32) directory of the application project. In the `build.gradle` file of the application, configure the compilation support of CMake, `arm64-v8a`, and `armeabi-v7a`.  
  26. ```
  27. android{
  28. defaultConfig{
  29. externalNativeBuild{
  30. cmake{
  31. arguments "-DANDROID_STL=c++_shared"
  32. }
  33. }
  34. ndk{
  35. abiFilters'armeabi-v7a', 'arm64-v8a'
  36. }
  37. }
  38. }
  39. ```
  40. Create a link to the `.so` library file in the `app/CMakeLists.txt` file:
  41. ```
  42. # Set MindSpore Lite Dependencies.
  43. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include/MindSpore)
  44. add_library(mindspore-lite SHARED IMPORTED )
  45. set_target_properties(mindspore-lite PROPERTIES
  46. IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/libs/libmindspore-lite.so")
  47. # Link target library.
  48. target_link_libraries(
  49. ...
  50. mindspore-lite
  51. minddata-lite
  52. ...
  53. )
  54. ```
  55. In this example, the download.gradle File configuration auto download library file, placed in the 'app / libs / arm64-v8a' directory.
  56. Note: if the automatic download fails, please manually download the relevant library files and put them in the corresponding location.
  57. libmindspore-lite.so [libmindspore-lite.so]( https://download.mindspore.cn/model_zoo/official/lite/lib/mindspore%20version%200.7/libmindspore-lite.so)
  58. ### Downloading and Deploying a Model File
  59. In this example, the download.gradle File configuration auto download `ssd.ms `and placed in the 'app / libs / arm64-v8a' directory.
  60. Note: if the automatic download fails, please manually download the relevant library files and put them in the corresponding location.
  61. ssd.ms [ssd.ms]( https://download.mindspore.cn/model_zoo/official/lite/ssd_mobilenetv2_lite/ssd.ms)
  62. ### Compiling On-Device Inference Code
  63. Call MindSpore Lite C++ APIs at the JNI layer to implement on-device inference.
  64. The inference code process is as follows. For details about the complete code, see `src/cpp/MindSporeNetnative.cpp`.
  65. 1. Load the MindSpore Lite model file and build the context, session, and computational graph for inference.
  66. - Load a model file. Create and configure the context for model inference.
  67. ```cpp
  68. // Buffer is the model data passed in by the Java layer
  69. jlong bufferLen = env->GetDirectBufferCapacity(buffer);
  70. char *modelBuffer = CreateLocalModelBuffer(env, buffer);
  71. ```
  72. - Create a session.
  73. ```cpp
  74. void **labelEnv = new void *;
  75. MSNetWork *labelNet = new MSNetWork;
  76. *labelEnv = labelNet;
  77. // Create context.
  78. lite::Context *context = new lite::Context;
  79. context->device_ctx_.type = lite::DT_CPU;
  80. context->thread_num_ = numThread; //Specify the number of threads to run inference
  81. // Create the mindspore session.
  82. labelNet->CreateSessionMS(modelBuffer, bufferLen, "device label", context);
  83. delete(context);
  84. ```
  85. - Load the model file and build a computational graph for inference.
  86. ```cpp
  87. void MSNetWork::CreateSessionMS(char* modelBuffer, size_t bufferLen, std::string name, mindspore::lite::Context* ctx)
  88. {
  89. CreateSession(modelBuffer, bufferLen, ctx);
  90. session = mindspore::session::LiteSession::CreateSession(ctx);
  91. auto model = mindspore::lite::Model::Import(modelBuffer, bufferLen);
  92. int ret = session->CompileGraph(model);
  93. }
  94. ```
  95. 2. Pre-Process the imagedata and convert the input image into the Tensor format of the MindSpore model.
  96. ```cpp
  97. // Convert the Bitmap image passed in from the JAVA layer to Mat for OpenCV processing
  98. LiteMat lite_mat_bgr,lite_norm_mat_cut;
  99. if (!BitmapToLiteMat(env, srcBitmap, lite_mat_bgr)){
  100. MS_PRINT("BitmapToLiteMat error");
  101. return NULL;
  102. }
  103. int srcImageWidth = lite_mat_bgr.width_;
  104. int srcImageHeight = lite_mat_bgr.height_;
  105. if(!PreProcessImageData(lite_mat_bgr, lite_norm_mat_cut)){
  106. MS_PRINT("PreProcessImageData error");
  107. return NULL;
  108. }
  109. ImgDims inputDims;
  110. inputDims.channel =lite_norm_mat_cut.channel_;
  111. inputDims.width = lite_norm_mat_cut.width_;
  112. inputDims.height = lite_norm_mat_cut.height_;
  113. // Get the mindsore inference environment which created in loadModel().
  114. void **labelEnv = reinterpret_cast<void **>(netEnv);
  115. if (labelEnv == nullptr) {
  116. MS_PRINT("MindSpore error, labelEnv is a nullptr.");
  117. return NULL;
  118. }
  119. MSNetWork *labelNet = static_cast<MSNetWork *>(*labelEnv);
  120. auto mSession = labelNet->session;
  121. if (mSession == nullptr) {
  122. MS_PRINT("MindSpore error, Session is a nullptr.");
  123. return NULL;
  124. }
  125. MS_PRINT("MindSpore get session.");
  126. auto msInputs = mSession->GetInputs();
  127. auto inTensor = msInputs.front();
  128. float *dataHWC = reinterpret_cast<float *>(lite_norm_mat_cut.data_ptr_);
  129. // copy input Tensor
  130. memcpy(inTensor->MutableData(), dataHWC,
  131. inputDims.channel * inputDims.width * inputDims.height * sizeof(float));
  132. delete[] (dataHWC);
  133. ```
  134. 3. The input image shall be NHWC(1:300:300:3).
  135. ```cpp
  136. bool PreProcessImageData(const LiteMat &lite_mat_bgr, LiteMat *lite_norm_mat_ptr) {
  137. bool ret = false;
  138. LiteMat lite_mat_resize;
  139. LiteMat &lite_norm_mat_cut = *lite_norm_mat_ptr;
  140. ret = ResizeBilinear(lite_mat_bgr, lite_mat_resize, 300, 300);
  141. if (!ret) {
  142. MS_PRINT("ResizeBilinear error");
  143. return false;
  144. }
  145. LiteMat lite_mat_convert_float;
  146. ret = ConvertTo(lite_mat_resize, lite_mat_convert_float, 1.0 / 255.0);
  147. if (!ret) {
  148. MS_PRINT("ConvertTo error");
  149. return false;
  150. }
  151. float means[3] = {0.485, 0.456, 0.406};
  152. float vars[3] = {1.0 / 0.229, 1.0 / 0.224, 1.0 / 0.225};
  153. SubStractMeanNormalize(lite_mat_convert_float, lite_norm_mat_cut, means, vars);
  154. return true;
  155. }
  156. ```
  157. 4. Perform inference on the input tensor based on the model, obtain the output tensor, and perform post-processing.
  158. Perform graph execution and on-device inference.
  159. ```cpp
  160. // After the model and image tensor data is loaded, run inference.
  161. auto status = mSession->RunGraph();
  162. ```
  163. Obtain the output data.
  164. ```cpp
  165. auto names = mSession->GetOutputTensorNames();
  166. typedef std::unordered_map<std::string,
  167. std::vector<mindspore::tensor::MSTensor *>> Msout;
  168. std::unordered_map<std::string,
  169. mindspore::tensor::MSTensor *> msOutputs;
  170. for (const auto &name : names) {
  171. auto temp_dat =mSession->GetOutputByTensorName(name);
  172. msOutputs.insert(std::pair<std::string, mindspore::tensor::MSTensor *> {name, temp_dat});
  173. }
  174. std::string retStr = ProcessRunnetResult(msOutputs, ret);
  175. ```
  176. The model output the object category scores (1:1917:81) and the object detection location offset (1:1917:4). The location offset can be calcalation the object location in getDefaultBoxes function .
  177. ```cpp
  178. void SSDModelUtil::getDefaultBoxes() {
  179. float fk[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  180. std::vector<struct WHBox> all_sizes;
  181. struct Product mProductData[19 * 19] = {0};
  182. for (int i = 0; i < 6; i++) {
  183. fk[i] = config.model_input_height / config.steps[i];
  184. }
  185. float scale_rate =
  186. (config.max_scale - config.min_scale) / (sizeof(config.num_default) / sizeof(int) - 1);
  187. float scales[7] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0};
  188. for (int i = 0; i < sizeof(config.num_default) / sizeof(int); i++) {
  189. scales[i] = config.min_scale + scale_rate * i;
  190. }
  191. for (int idex = 0; idex < sizeof(config.feature_size) / sizeof(int); idex++) {
  192. float sk1 = scales[idex];
  193. float sk2 = scales[idex + 1];
  194. float sk3 = sqrt(sk1 * sk2);
  195. struct WHBox tempWHBox;
  196. all_sizes.clear();
  197. if (idex == 0) {
  198. float w = sk1 * sqrt(2);
  199. float h = sk1 / sqrt(2);
  200. tempWHBox.boxw = 0.1;
  201. tempWHBox.boxh = 0.1;
  202. all_sizes.push_back(tempWHBox);
  203. tempWHBox.boxw = w;
  204. tempWHBox.boxh = h;
  205. all_sizes.push_back(tempWHBox);
  206. tempWHBox.boxw = h;
  207. tempWHBox.boxh = w;
  208. all_sizes.push_back(tempWHBox);
  209. } else {
  210. tempWHBox.boxw = sk1;
  211. tempWHBox.boxh = sk1;
  212. all_sizes.push_back(tempWHBox);
  213. for (int j = 0; j < sizeof(config.aspect_ratios[idex]) / sizeof(int); j++) {
  214. float w = sk1 * sqrt(config.aspect_ratios[idex][j]);
  215. float h = sk1 / sqrt(config.aspect_ratios[idex][j]);
  216. tempWHBox.boxw = w;
  217. tempWHBox.boxh = h;
  218. all_sizes.push_back(tempWHBox);
  219. tempWHBox.boxw = h;
  220. tempWHBox.boxh = w;
  221. all_sizes.push_back(tempWHBox);
  222. }
  223. tempWHBox.boxw = sk3;
  224. tempWHBox.boxh = sk3;
  225. all_sizes.push_back(tempWHBox);
  226. }
  227. for (int i = 0; i < config.feature_size[idex]; i++) {
  228. for (int j = 0; j < config.feature_size[idex]; j++) {
  229. mProductData[i * config.feature_size[idex] + j].x = i;
  230. mProductData[i * config.feature_size[idex] + j].y = j;
  231. }
  232. }
  233. int productLen = config.feature_size[idex] * config.feature_size[idex];
  234. for (int i = 0; i < productLen; i++) {
  235. for (int j = 0; j < all_sizes.size(); j++) {
  236. struct NormalBox tempBox;
  237. float cx = (mProductData[i].y + 0.5) / fk[idex];
  238. float cy = (mProductData[i].x + 0.5) / fk[idex];
  239. tempBox.y = cy;
  240. tempBox.x = cx;
  241. tempBox.h = all_sizes[j].boxh;
  242. tempBox.w = all_sizes[j].boxw;
  243. mDefaultBoxes.push_back(tempBox);
  244. }
  245. }
  246. }
  247. }
  248. ```
  249. - The higher scores and location of category can be calcluted by the nonMaximumSuppression function.
  250. ```cpp
  251. void SSDModelUtil::nonMaximumSuppression(const YXBoxes *const decoded_boxes,
  252. const float *const scores,
  253. const std::vector<int> &in_indexes,
  254. std::vector<int> &out_indexes, const float nmsThreshold,
  255. const int count, const int max_results) {
  256. int nR = 0; //number of results
  257. std::vector<bool> del(count, false);
  258. for (size_t i = 0; i < in_indexes.size(); i++) {
  259. if (!del[in_indexes[i]]) {
  260. out_indexes.push_back(in_indexes[i]);
  261. if (++nR == max_results) {
  262. break;
  263. }
  264. for (size_t j = i + 1; j < in_indexes.size(); j++) {
  265. const auto boxi = decoded_boxes[in_indexes[i]], boxj = decoded_boxes[in_indexes[j]];
  266. float a[4] = {boxi.xmin, boxi.ymin, boxi.xmax, boxi.ymax};
  267. float b[4] = {boxj.xmin, boxj.ymin, boxj.xmax, boxj.ymax};
  268. if (IOU(a, b) > nmsThreshold) {
  269. del[in_indexes[j]] = true;
  270. }
  271. }
  272. }
  273. }
  274. }
  275. ```
  276. - For the targets whose probability is greater than the threshold value, the output rectangle box needs to be restored to the original size after the rectangular box is filtered by NMS algorithm.
  277. ```cpp
  278. std::string SSDModelUtil::getDecodeResult(float *branchScores, float *branchBoxData) {
  279. std::string result = "";
  280. NormalBox tmpBox[1917] = {0};
  281. float mScores[1917][81] = {0};
  282. float outBuff[1917][7] = {0};
  283. float scoreWithOneClass[1917] = {0};
  284. int outBoxNum = 0;
  285. YXBoxes decodedBoxes[1917] = {0};
  286. // Copy branch outputs box data to tmpBox.
  287. for (int i = 0; i < 1917; ++i) {
  288. tmpBox[i].y = branchBoxData[i * 4 + 0];
  289. tmpBox[i].x = branchBoxData[i * 4 + 1];
  290. tmpBox[i].h = branchBoxData[i * 4 + 2];
  291. tmpBox[i].w = branchBoxData[i * 4 + 3];
  292. }
  293. // Copy branch outputs score to mScores.
  294. for (int i = 0; i < 1917; ++i) {
  295. for (int j = 0; j < 81; ++j) {
  296. mScores[i][j] = branchScores[i * 81 + j];
  297. }
  298. }
  299. // NMS processing.
  300. ssd_boxes_decode(tmpBox, decodedBoxes);
  301. // const float nms_threshold = 0.6;
  302. const float nms_threshold = 0.3;
  303. for (int i = 1; i < 81; i++) {
  304. std::vector<int> in_indexes;
  305. for (int j = 0; j < 1917; j++) {
  306. scoreWithOneClass[j] = mScores[j][i];
  307. // if (mScores[j][i] > 0.1) {
  308. if (mScores[j][i] > g_thres_map[i]) {
  309. in_indexes.push_back(j);
  310. }
  311. }
  312. if (in_indexes.size() == 0) {
  313. continue;
  314. }
  315. sort(in_indexes.begin(), in_indexes.end(),
  316. [&](int a, int b) { return scoreWithOneClass[a] > scoreWithOneClass[b]; });
  317. std::vector<int> out_indexes;
  318. nonMaximumSuppression(decodedBoxes, scoreWithOneClass, in_indexes, out_indexes,
  319. nms_threshold);
  320. for (int k = 0; k < out_indexes.size(); k++) {
  321. outBuff[outBoxNum][0] = out_indexes[k]; //image id
  322. outBuff[outBoxNum][1] = i; //labelid
  323. outBuff[outBoxNum][2] = scoreWithOneClass[out_indexes[k]]; //scores
  324. outBuff[outBoxNum][3] =
  325. decodedBoxes[out_indexes[k]].xmin * inputImageWidth / 300;
  326. outBuff[outBoxNum][4] =
  327. decodedBoxes[out_indexes[k]].ymin * inputImageHeight / 300;
  328. outBuff[outBoxNum][5] =
  329. decodedBoxes[out_indexes[k]].xmax * inputImageWidth / 300;
  330. outBuff[outBoxNum][6] =
  331. decodedBoxes[out_indexes[k]].ymax * inputImageHeight / 300;
  332. outBoxNum++;
  333. }
  334. }
  335. MS_PRINT("outBoxNum %d", outBoxNum);
  336. for (int i = 0; i < outBoxNum; ++i) {
  337. std::string tmpid_str = std::to_string(outBuff[i][0]);
  338. result += tmpid_str; // image ID
  339. result += "_";
  340. // tmpid_str = std::to_string(outBuff[i][1]);
  341. MS_PRINT("label_classes i %d, outBuff %d",i, (int) outBuff[i][1]);
  342. tmpid_str = label_classes[(int) outBuff[i][1]];
  343. result += tmpid_str; // label id
  344. result += "_";
  345. tmpid_str = std::to_string(outBuff[i][2]);
  346. result += tmpid_str; // scores
  347. result += "_";
  348. tmpid_str = std::to_string(outBuff[i][3]);
  349. result += tmpid_str; // xmin
  350. result += "_";
  351. tmpid_str = std::to_string(outBuff[i][4]);
  352. result += tmpid_str; // ymin
  353. result += "_";
  354. tmpid_str = std::to_string(outBuff[i][5]);
  355. result += tmpid_str; // xmax
  356. result += "_";
  357. tmpid_str = std::to_string(outBuff[i][6]);
  358. result += tmpid_str; // ymax
  359. result += ";";
  360. }
  361. return result;
  362. }
  363. std::string SSDModelUtil::getDecodeResult(float *branchScores, float *branchBoxData) {
  364. std::string result = "";
  365. NormalBox tmpBox[1917] = {0};
  366. float mScores[1917][81] = {0};
  367. float outBuff[1917][7] = {0};
  368. float scoreWithOneClass[1917] = {0};
  369. int outBoxNum = 0;
  370. YXBoxes decodedBoxes[1917] = {0};
  371. // Copy branch outputs box data to tmpBox.
  372. for (int i = 0; i < 1917; ++i) {
  373. tmpBox[i].y = branchBoxData[i * 4 + 0];
  374. tmpBox[i].x = branchBoxData[i * 4 + 1];
  375. tmpBox[i].h = branchBoxData[i * 4 + 2];
  376. tmpBox[i].w = branchBoxData[i * 4 + 3];
  377. }
  378. // Copy branch outputs score to mScores.
  379. for (int i = 0; i < 1917; ++i) {
  380. for (int j = 0; j < 81; ++j) {
  381. mScores[i][j] = branchScores[i * 81 + j];
  382. }
  383. }
  384. ssd_boxes_decode(tmpBox, decodedBoxes);
  385. const float nms_threshold = 0.3;
  386. for (int i = 1; i < 81; i++) {
  387. std::vector<int> in_indexes;
  388. for (int j = 0; j < 1917; j++) {
  389. scoreWithOneClass[j] = mScores[j][i];
  390. if (mScores[j][i] > g_thres_map[i]) {
  391. in_indexes.push_back(j);
  392. }
  393. }
  394. if (in_indexes.size() == 0) {
  395. continue;
  396. }
  397. sort(in_indexes.begin(), in_indexes.end(),
  398. [&](int a, int b) { return scoreWithOneClass[a] > scoreWithOneClass[b]; });
  399. std::vector<int> out_indexes;
  400. nonMaximumSuppression(decodedBoxes, scoreWithOneClass, in_indexes, out_indexes,
  401. nms_threshold);
  402. for (int k = 0; k < out_indexes.size(); k++) {
  403. outBuff[outBoxNum][0] = out_indexes[k]; //image id
  404. outBuff[outBoxNum][1] = i; //labelid
  405. outBuff[outBoxNum][2] = scoreWithOneClass[out_indexes[k]]; //scores
  406. outBuff[outBoxNum][3] =
  407. decodedBoxes[out_indexes[k]].xmin * inputImageWidth / 300;
  408. outBuff[outBoxNum][4] =
  409. decodedBoxes[out_indexes[k]].ymin * inputImageHeight / 300;
  410. outBuff[outBoxNum][5] =
  411. decodedBoxes[out_indexes[k]].xmax * inputImageWidth / 300;
  412. outBuff[outBoxNum][6] =
  413. decodedBoxes[out_indexes[k]].ymax * inputImageHeight / 300;
  414. outBoxNum++;
  415. }
  416. }
  417. MS_PRINT("outBoxNum %d", outBoxNum);
  418. for (int i = 0; i < outBoxNum; ++i) {
  419. std::string tmpid_str = std::to_string(outBuff[i][0]);
  420. result += tmpid_str; // image ID
  421. result += "_";
  422. // tmpid_str = std::to_string(outBuff[i][1]);
  423. MS_PRINT("label_classes i %d, outBuff %d",i, (int) outBuff[i][1]);
  424. tmpid_str = label_classes[(int) outBuff[i][1]];
  425. result += tmpid_str; // label id
  426. result += "_";
  427. tmpid_str = std::to_string(outBuff[i][2]);
  428. result += tmpid_str; // scores
  429. result += "_";
  430. tmpid_str = std::to_string(outBuff[i][3]);
  431. result += tmpid_str; // xmin
  432. result += "_";
  433. tmpid_str = std::to_string(outBuff[i][4]);
  434. result += tmpid_str; // ymin
  435. result += "_";
  436. tmpid_str = std::to_string(outBuff[i][5]);
  437. result += tmpid_str; // xmax
  438. result += "_";
  439. tmpid_str = std::to_string(outBuff[i][6]);
  440. result += tmpid_str; // ymax
  441. result += ";";
  442. }
  443. return result;
  444. }
  445. ```