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 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. ## Demo of Image Classification
  2. The following describes how to use the MindSpore Lite C++ APIs (Android JNIs) and MindSpore Lite image classification models to perform on-device inference, classify the content captured by a device camera, and display the most possible classification result on the application's image preview screen.
  3. ### Running Dependencies
  4. - Android Studio 3.2 or later (Android 4.0 or later is recommended.)
  5. - Native development kit (NDK) 21.3
  6. - CMake 3.10.2 [CMake](https://cmake.org/download)
  7. - Android software development kit (SDK) 26 or later
  8. - JDK 1.8 or later
  9. ### Building and Running
  10. 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.)
  11. ![start_home](images/home.png)
  12. 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.
  13. ![start_sdk](images/sdk_management.png)
  14. If you have any Android Studio configuration problem when trying this demo, please refer to item 5 to resolve it.
  15. 2. Connect to an Android device and runs the image classification application.
  16. Connect to the Android device through a USB cable for debugging. Click `Run 'app'` to run the sample project on your device.
  17. ![run_app](images/run_app.PNG)
  18. For details about how to connect the Android Studio to a device for debugging, see <https://developer.android.com/studio/run/device?hl=zh-cn>.
  19. The mobile phone needs to be turn on "USB debugging mode" before Android Studio can recognize the mobile phone. Huawei mobile phones generally turn on "USB debugging model" in Settings > system and update > developer Options > USB debugging.
  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/app_result.jpg)
  22. 4. The solutions of Android Studio configuration problems:
  23. | | Warning | Solution |
  24. | ---- | ------------------------------------------------------------ | ------------------------------------------------------------ |
  25. | 1 | Gradle sync failed: NDK not configured. | Specify the installed ndk directory in local.properties:ndk.dir={ndk的安装目录} |
  26. | 2 | Requested NDK version did not match the version requested by ndk.dir | Manually download corresponding [NDK Version](https://developer.android.com/ndk/downloads),and specify the sdk directory in Project Structure - Android NDK location.(You can refer to the figure below.) |
  27. | 3 | This version of Android Studio cannot open this project, please retry with Android Studio or newer. | Update Android Studio Version in Tools - help - Checkout for Updates. |
  28. | 4 | SSL peer shut down incorrectly | Run this demo again. |
  29. ![project_structure](images/project_structure.png)
  30. ## Detailed Description of the Sample Program
  31. This image classification 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 in [Runtime](https://www.mindspore.cn/tutorial/lite/en/master/use/runtime.html).
  32. ### Sample Program Structure
  33. ```text
  34. app
  35. ├── src/main
  36. │ ├── assets # resource files
  37. | | └── mobilenetv2.ms # model file
  38. │ |
  39. │ ├── cpp # main logic encapsulation classes for model loading and prediction
  40. | | |
  41. | | ├── MindSporeNetnative.cpp # JNI methods related to MindSpore calling
  42. │ | └── MindSporeNetnative.h # header file
  43. │ |
  44. │ ├── java # application code at the Java layer
  45. │ │ └── com.mindspore.himindsporedemo
  46. │ │ ├── gallery.classify # implementation related to image processing and MindSpore JNI calling
  47. │ │ │ └── ...
  48. │ │ └── widget # implementation related to camera enabling and drawing
  49. │ │ └── ...
  50. │ │
  51. │ ├── res # resource files related to Android
  52. │ └── AndroidManifest.xml # Android configuration file
  53. ├── CMakeList.txt # CMake compilation entry file
  54. ├── build.gradle # Other Android configuration file
  55. ├── download.gradle # MindSpore version download
  56. └── ...
  57. ```
  58. ### Configuring MindSpore Lite Dependencies
  59. When MindSpore C++ APIs are called at the Android JNI layer, related library files are required. You can use MindSpore Lite [source code compilation](https://www.mindspore.cn/tutorial/lite/en/master/use/build.html) to generate the MindSpore Lite version. In this case, you need to use the compile command of generate with image preprocessing module.
  60. In this example, the build process automatically downloads the `mindspore-lite-1.0.1-runtime-arm64-cpu` by the `app/download.gradle` file and saves in the `app/src/main/cpp` directory.
  61. Note: if the automatic download fails, please manually download the relevant library files and put them in the corresponding location.
  62. mindspore-lite-1.0.1-runtime-arm64-cpu.tar.gz [Download link](https://ms-release.obs.cn-north-4.myhuaweicloud.com/1.0.1/lite/android_aarch64/mindspore-lite-1.0.1-runtime-arm64-cpu.tar.gz)
  63. ```text
  64. android{
  65. defaultConfig{
  66. externalNativeBuild{
  67. cmake{
  68. arguments "-DANDROID_STL=c++_shared"
  69. }
  70. }
  71. ndk{
  72. abiFilters'armeabi-v7a', 'arm64-v8a'
  73. }
  74. }
  75. }
  76. ```
  77. Create a link to the `.so` library file in the `app/CMakeLists.txt` file:
  78. ```text
  79. # ============== Set MindSpore Dependencies. =============
  80. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp)
  81. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/third_party/flatbuffers/include)
  82. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION})
  83. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include)
  84. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/ir/dtype)
  85. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/schema)
  86. add_library(mindspore-lite SHARED IMPORTED )
  87. add_library(minddata-lite SHARED IMPORTED )
  88. set_target_properties(mindspore-lite PROPERTIES IMPORTED_LOCATION
  89. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libmindspore-lite.so)
  90. set_target_properties(minddata-lite PROPERTIES IMPORTED_LOCATION
  91. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libminddata-lite.so)
  92. # --------------- MindSpore Lite set End. --------------------
  93. # Link target library.
  94. target_link_libraries(
  95. ...
  96. # --- mindspore ---
  97. minddata-lite
  98. mindspore-lite
  99. ...
  100. )
  101. ```
  102. ### Downloading and Deploying a Model File
  103. In this example, the download.gradle File configuration auto download `mobilenetv2.ms`and placed in the 'app/libs/arm64-v8a' directory.
  104. Note: if the automatic download fails, please manually download the relevant library files and put them in the corresponding location.
  105. mobilenetv2.ms [mobilenetv2.ms]( https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_openimage_lite/mobilenetv2.ms)
  106. ### Compiling On-Device Inference Code
  107. Call MindSpore Lite C++ APIs at the JNI layer to implement on-device inference.
  108. The inference code process is as follows. For details about the complete code, see `src/cpp/MindSporeNetnative.cpp`.
  109. 1. Load the MindSpore Lite model file and build the context, session, and computational graph for inference.
  110. - Load a model file. Create and configure the context for model inference.
  111. ```cpp
  112. // Buffer is the model data passed in by the Java layer
  113. jlong bufferLen = env->GetDirectBufferCapacity(buffer);
  114. char *modelBuffer = CreateLocalModelBuffer(env, buffer);
  115. ```
  116. - Create a session.
  117. ```cpp
  118. void **labelEnv = new void *;
  119. MSNetWork *labelNet = new MSNetWork;
  120. *labelEnv = labelNet;
  121. // Create context.
  122. mindspore::lite::Context *context = new mindspore::lite::Context;
  123. context->thread_num_ = num_thread;
  124. // Create the mindspore session.
  125. labelNet->CreateSessionMS(modelBuffer, bufferLen, "device label", context);
  126. delete(context);
  127. ```
  128. - Load the model file and build a computational graph for inference.
  129. ```cpp
  130. void MSNetWork::CreateSessionMS(char* modelBuffer, size_t bufferLen, std::string name, mindspore::lite::Context* ctx)
  131. {
  132. CreateSession(modelBuffer, bufferLen, ctx);
  133. session = mindspore::session::LiteSession::CreateSession(ctx);
  134. auto model = mindspore::lite::Model::Import(modelBuffer, bufferLen);
  135. int ret = session->CompileGraph(model);
  136. }
  137. ```
  138. 2. Convert the input image into the Tensor format of the MindSpore model.
  139. Convert the image data to be detected into the Tensor format of the MindSpore model.
  140. ```cpp
  141. if (!BitmapToLiteMat(env, srcBitmap, &lite_mat_bgr)) {
  142. MS_PRINT("BitmapToLiteMat error");
  143. return NULL;
  144. }
  145. if (!PreProcessImageData(lite_mat_bgr, &lite_norm_mat_cut)) {
  146. MS_PRINT("PreProcessImageData error");
  147. return NULL;
  148. }
  149. ImgDims inputDims;
  150. inputDims.channel = lite_norm_mat_cut.channel_;
  151. inputDims.width = lite_norm_mat_cut.width_;
  152. inputDims.height = lite_norm_mat_cut.height_;
  153. // Get the mindsore inference environment which created in loadModel().
  154. void **labelEnv = reinterpret_cast<void **>(netEnv);
  155. if (labelEnv == nullptr) {
  156. MS_PRINT("MindSpore error, labelEnv is a nullptr.");
  157. return NULL;
  158. }
  159. MSNetWork *labelNet = static_cast<MSNetWork *>(*labelEnv);
  160. auto mSession = labelNet->session();
  161. if (mSession == nullptr) {
  162. MS_PRINT("MindSpore error, Session is a nullptr.");
  163. return NULL;
  164. }
  165. MS_PRINT("MindSpore get session.");
  166. auto msInputs = mSession->GetInputs();
  167. if (msInputs.size() == 0) {
  168. MS_PRINT("MindSpore error, msInputs.size() equals 0.");
  169. return NULL;
  170. }
  171. auto inTensor = msInputs.front();
  172. float *dataHWC = reinterpret_cast<float *>(lite_norm_mat_cut.data_ptr_);
  173. // Copy dataHWC to the model input tensor.
  174. memcpy(inTensor->MutableData(), dataHWC,
  175. inputDims.channel * inputDims.width * inputDims.height * sizeof(float));
  176. ```
  177. 3. Perform inference on the input tensor based on the model, obtain the output tensor, and perform post-processing.
  178. - Perform graph execution and on-device inference.
  179. ```cpp
  180. // After the model and image tensor data is loaded, run inference.
  181. auto status = mSession->RunGraph();
  182. ```
  183. - Obtain the output data.
  184. ```cpp
  185. auto names = mSession->GetOutputTensorNames();
  186. std::unordered_map<std::string,mindspore::tensor::MSTensor *> msOutputs;
  187. for (const auto &name : names) {
  188. auto temp_dat =mSession->GetOutputByTensorName(name);
  189. msOutputs.insert(std::pair<std::string, mindspore::tensor::MSTensor *> {name, temp_dat});
  190. }
  191. std::string retStr = ProcessRunnetResult(msOutputs, ret);
  192. ```
  193. - Perform post-processing of the output data.
  194. ```cpp
  195. std::string ProcessRunnetResult(const int RET_CATEGORY_SUM, const char *const labels_name_map[],
  196. std::unordered_map<std::string, mindspore::tensor::MSTensor *> msOutputs) {
  197. // Get the branch of the model output.
  198. // Use iterators to get map elements.
  199. std::unordered_map<std::string, mindspore::tensor::MSTensor *>::iterator iter;
  200. iter = msOutputs.begin();
  201. // The mobilenetv2.ms model output just one branch.
  202. auto outputTensor = iter->second;
  203. int tensorNum = outputTensor->ElementsNum();
  204. MS_PRINT("Number of tensor elements:%d", tensorNum);
  205. // Get a pointer to the first score.
  206. float *temp_scores = static_cast<float *>(outputTensor->MutableData());
  207. float scores[RET_CATEGORY_SUM];
  208. for (int i = 0; i < RET_CATEGORY_SUM; ++i) {
  209. scores[i] = temp_scores[i];
  210. }
  211. float unifiedThre = 0.5;
  212. float probMax = 1.0;
  213. for (size_t i = 0; i < RET_CATEGORY_SUM; ++i) {
  214. float threshold = g_thres_map[i];
  215. float tmpProb = scores[i];
  216. if (tmpProb < threshold) {
  217. tmpProb = tmpProb / threshold * unifiedThre;
  218. } else {
  219. tmpProb = (tmpProb - threshold) / (probMax - threshold) * unifiedThre + unifiedThre;
  220. }
  221. scores[i] = tmpProb;
  222. }
  223. for (int i = 0; i < RET_CATEGORY_SUM; ++i) {
  224. if (scores[i] > 0.5) {
  225. MS_PRINT("MindSpore scores[%d] : [%f]", i, scores[i]);
  226. }
  227. }
  228. // Score for each category.
  229. // Converted to text information that needs to be displayed in the APP.
  230. std::string categoryScore = "";
  231. for (int i = 0; i < RET_CATEGORY_SUM; ++i) {
  232. categoryScore += labels_name_map[i];
  233. categoryScore += ":";
  234. std::string score_str = std::to_string(scores[i]);
  235. categoryScore += score_str;
  236. categoryScore += ";";
  237. }
  238. return categoryScore;
  239. }
  240. ```