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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # MindSpore Lite Scene Detection Demo (Android)
  2. This sample application demonstrates how to use the MindSpore Lite C++ API (Android JNI) and MindSpore Lite scene detection model to perform inference on the device, detect the content captured by the device camera, and display the continuous objective detection result on the image preview screen of the app.
  3. ## Running Dependencies
  4. - Android Studio 3.2 or later (Android 4.0 or later is recommended.)
  5. ## Building and Running
  6. 1. Load the sample source code to Android Studio.
  7. ![start_home](images/home.png)
  8. Start Android Studio, click `File > Settings > System Settings > Android SDK`, and select the corresponding `SDK Tools`. As shown in the following figure, select an SDK and click `OK`. Android Studio automatically installs the SDK.
  9. ![start_sdk](images/sdk_management.jpg)
  10. > Android SDK Tools is the default installation. You can see this by unchecking the `Hide Obsolete Packages`box.
  11. >
  12. > If you have any Android Studio configuration problem when trying this demo, please refer to item 4 to resolve it.
  13. 2. Connect to an Android device and runs this application.
  14. Connect to the Android device through a USB cable for debugging. Click `Run 'app'` to run the sample project on your device.
  15. ![run_app](images/run_app.PNG)
  16. > Android Studio will automatically download MindSpore Lite, model files and other dependencies during the compilation process. Please be patient during this process.
  17. >
  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. >
  20. > 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.
  21. 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.
  22. ![result](images/app_result.jpg)
  23. 4. The solutions of configuration problems:
  24. 4.1 Problems of NDK, CMake, JDK Tools:
  25. If the tools installed in Android Studio are not recognized, you can re-download and install them from the corresponding official website, and configure the path.
  26. - NDK >= 21.3 [NDK](https://developer.android.google.cn/ndk/downloads?hl=zh-cn)
  27. - CMake >= 3.10.2 [CMake](https://cmake.org/download)
  28. - Android SDK >= 26 [SDK](https://developer.microsoft.com/zh-cn/windows/downloads/windows-10-sdk/)
  29. - JDK >= 1.8 [JDK](https://www.oracle.com/cn/java/technologies/javase/javase-jdk8-downloads.html)
  30. ![project_structure](images/project_structure.png)
  31. 4.2 NDK version does not match:
  32. Open `Android SDK`, click `Show Package Details`, and select the appropriate NDK version according to the error message.
  33. ![NDK_version](images/NDK_version.jpg)
  34. 4.3 Problem of Android Studio version:
  35. Update the Android Studio version in `Toolbar - Help - Checkout for Updates`.
  36. 4.4 Gradle dependencies installed too slowly:
  37. As shown in the picture, open the Demo root directory `build. Gradle` file, then add huawei mirror source address: `maven {url 'https://developer.huawei.com/repo/'}`, modify the classpath to 4.0.0 and click ` sync ` . Once the download is complete, restore the classpath version and synchronize it again.
  38. ![maven](images/maven.jpg)
  39. ## Detailed Description of the Sample Application
  40. The scene detection sample application 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 (drawing frames based on the inference result). At the JNI layer, the model inference process is completed in [runtime](https://www.mindspore.cn/tutorial/lite/en/master/use/runtime.html).
  41. > This following describes the JNI layer implementation of the sample application. At the Java layer, the Android Camera 2 API is used to enable a device camera and process image frames. Readers are expected to have the basic Android development knowledge.
  42. ### Sample Application Structure
  43. ```text
  44. app
  45. |
  46. ├── libs # Library files built by the demo JNI layer
  47. │ └── arm64-v8a
  48. │ │── libmlkit-label-MS.so #
  49. |
  50. ├── src/main
  51. │ ├── assets # Resource file
  52. | | └── mobilenetv2.ms # Model file
  53. │ |
  54. │ ├── cpp # Main logic encapsulation classes for model loading and prediction
  55. | | ├── mindspore-lite-x.x.x-mindata-arm64-cpu # Calling package built from the MindSpore source code, including the library files and related header files on which the demo JNI layer depends
  56. | | | └── ...
  57. │ | |
  58. | | ├── MindSporeNetnative.cpp # JNI methods related to MindSpore calling
  59. │ ├── java # Application code at the Java layer
  60. │ │ └── com.huawei.himindsporedemo
  61. │ │ ├── help # Implementation related to image processing and MindSpore JNI calling
  62. │ │ │ └── ...
  63. │ │ └── obejctdetect # Implementation related to camera enabling and drawing
  64. │ │ └── ...
  65. │ │
  66. │ ├── res # Resource files related to Android
  67. │ └── AndroidManifest.xml # Android configuration file
  68. ├── CMakeLists.txt # CMake compilation entry file
  69. ├── build.gradle # Other Android configuration file
  70. ├── download.gradle # During app building, the .gradle file automatically downloads the dependent library files and model files from the Huawei server.
  71. └── ...
  72. ```
  73. ### Configuring MindSpore Lite Dependencies
  74. When MindSpore C++ APIs are called at the Android JNI layer, related library files are required. You can refer to [Building MindSpore Lite](https://www.mindspore.cn/tutorial/lite/en/master/use/build.html) to generate the `mindspore-lite-{version}-minddata-{os}-{device}.tar.gz` library file package (including the `libmindspore-lite.so` library file and related header files) and decompress it. The following example uses the build command with the image preprocessing module.
  75. > version: version number in the output file, which is the same as the version number of the built branch code.
  76. >
  77. > device: The value can be cpu (built-in CPU operator) or gpu (built-in CPU and GPU operator).
  78. >
  79. > os: operating system to be deployed in the output file.
  80. In this example, the MindSpore Lite version file is automatically downloaded by the download.gradle file during the build process and stored in the `app/src/main/cpp/` directory.
  81. > If the automatic download fails, manually download the library file [mindspore-lite-1.0.1-runtime-arm64-cpu.tar.gz](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), and decompress and save it to the directory.
  82. In the `build.gradle` file of the app, configure the build support of both CMake and `arm64-v8a`:
  83. ```text
  84. android{
  85. defaultConfig{
  86. externalNativeBuild{
  87. cmake{
  88. arguments "-DANDROID_STL=c++_shared"
  89. }
  90. }
  91. ndk{
  92. abiFilters 'arm64-v8a'
  93. }
  94. }
  95. }
  96. ```
  97. Create a link to the `.so` library file in the `app/CMakeLists.txt` file:
  98. ```text
  99. # Set MindSpore Lite Dependencies.
  100. set(MINDSPORELITE_VERSION mindspore-lite-1.0.1-runtime-arm64-cpu)
  101. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION})
  102. add_library(mindspore-lite SHARED IMPORTED )
  103. add_library(minddata-lite SHARED IMPORTED )
  104. set_target_properties(mindspore-lite PROPERTIES IMPORTED_LOCATION
  105. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libmindspore-lite.so)
  106. set_target_properties(minddata-lite PROPERTIES IMPORTED_LOCATION
  107. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libminddata-lite.so)
  108. # Link target library.
  109. target_link_libraries(
  110. ...
  111. mindspore-lite
  112. minddata-lite
  113. ...
  114. )
  115. ```
  116. ### Downloading and Deploying the Model File
  117. Download the model file from MindSpore Model Hub. The scene detection model file used in this sample application is `mobilenetv2.ms`, which is automatically downloaded during app building using the `download.gradle` script and stored in the `app/src/main/assets` project directory.
  118. > If the download fails, manually download the model file [mobilenetv2.ms](https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_openimage_lite/mobilenetv2.ms).
  119. ### Writing On-Device Inference Code
  120. Call MindSpore Lite C++ APIs at the JNI layer to implement on-device inference.
  121. The inference code process is as follows. For details about the complete code, see `src/cpp/MindSporeNetnative.cpp`.
  122. 1. Load the MindSpore Lite model file and build the context, session, and computational graph for inference.
  123. - Load a model file.
  124. ```cpp
  125. jlong bufferLen = env->GetDirectBufferCapacity(model_buffer);
  126. if (0 == bufferLen) {
  127. MS_PRINT("error, bufferLen is 0!");
  128. return (jlong) nullptr;
  129. }
  130. char *modelBuffer = CreateLocalModelBuffer(env, model_buffer);
  131. if (modelBuffer == nullptr) {
  132. MS_PRINT("modelBuffer create failed!");
  133. return (jlong) nullptr;
  134. }
  135. ```
  136. - Create a session.
  137. ```cpp
  138. void **labelEnv = new void *;
  139. MSNetWork *labelNet = new MSNetWork;
  140. *labelEnv = labelNet;
  141. mindspore::lite::Context *context = new mindspore::lite::Context;
  142. context->thread_num_ = num_thread;
  143. context->device_list_[0].device_info_.cpu_device_info_.cpu_bind_mode_ = mindspore::lite::NO_BIND;
  144. context->device_list_[0].device_info_.cpu_device_info_.enable_float16_ = false;
  145. context->device_list_[0].device_type_ = mindspore::lite::DT_CPU;
  146. labelNet->CreateSessionMS(modelBuffer, bufferLen, context);
  147. delete context;
  148. ```
  149. - Load the model file and build a computational graph for inference.
  150. ```cpp
  151. void
  152. MSNetWork::CreateSessionMS(char *modelBuffer, size_t bufferLen, mindspore::lite::Context *ctx) {
  153. session_ = mindspore::session::LiteSession::CreateSession(ctx);
  154. if (session_ == nullptr) {
  155. MS_PRINT("Create Session failed.");
  156. return;
  157. }
  158. // Compile model.
  159. model_ = mindspore::lite::Model::Import(modelBuffer, bufferLen);
  160. if (model_ == nullptr) {
  161. ReleaseNets();
  162. MS_PRINT("Import model failed.");
  163. return;
  164. }
  165. int ret = session_->CompileGraph(model_);
  166. if (ret != mindspore::lite::RET_OK) {
  167. ReleaseNets();
  168. MS_PRINT("CompileGraph failed.");
  169. return;
  170. }
  171. }
  172. ```
  173. 2. Convert the input image into the Tensor format of the MindSpore model.
  174. ```cpp
  175. // Convert the Bitmap image passed in from the JAVA layer to Mat for OpenCV processing
  176. LiteMat lite_mat_bgr,lite_norm_mat_cut;
  177. if (!BitmapToLiteMat(env, srcBitmap, lite_mat_bgr)){
  178. MS_PRINT("BitmapToLiteMat error");
  179. return NULL;
  180. }
  181. int srcImageWidth = lite_mat_bgr.width_;
  182. int srcImageHeight = lite_mat_bgr.height_;
  183. if(!PreProcessImageData(lite_mat_bgr, lite_norm_mat_cut)){
  184. MS_PRINT("PreProcessImageData error");
  185. return NULL;
  186. }
  187. ImgDims inputDims;
  188. inputDims.channel =lite_norm_mat_cut.channel_;
  189. inputDims.width = lite_norm_mat_cut.width_;
  190. inputDims.height = lite_norm_mat_cut.height_;
  191. // Get the mindsore inference environment which created in loadModel().
  192. void **labelEnv = reinterpret_cast<void **>(netEnv);
  193. if (labelEnv == nullptr) {
  194. MS_PRINT("MindSpore error, labelEnv is a nullptr.");
  195. return NULL;
  196. }
  197. MSNetWork *labelNet = static_cast<MSNetWork *>(*labelEnv);
  198. auto mSession = labelNet->session;
  199. if (mSession == nullptr) {
  200. MS_PRINT("MindSpore error, Session is a nullptr.");
  201. return NULL;
  202. }
  203. MS_PRINT("MindSpore get session.");
  204. auto msInputs = mSession->GetInputs();
  205. auto inTensor = msInputs.front();
  206. float *dataHWC = reinterpret_cast<float *>(lite_norm_mat_cut.data_ptr_);
  207. // copy input Tensor
  208. memcpy(inTensor->MutableData(), dataHWC,
  209. inputDims.channel * inputDims.width * inputDims.height * sizeof(float));
  210. delete[] (dataHWC);
  211. ```
  212. 3. Perform inference on the input tensor based on the model to obtain the output tensor.
  213. - Perform graph execution and on-device inference.
  214. ```cpp
  215. // After the model and image tensor data is loaded, run inference.
  216. auto status = mSession->RunGraph();
  217. if (status != mindspore::lite::RET_OK) {
  218. MS_PRINT("MindSpore run net error.");
  219. return NULL;
  220. }
  221. ```
  222. - Obtain the output data.
  223. ```cpp
  224. /**
  225. * Get the mindspore inference results.
  226. * Return the map of output node name and MindSpore Lite MSTensor.
  227. */
  228. auto names = mSession->GetOutputTensorNames();
  229. std::unordered_map<std::string, mindspore::tensor::MSTensor *> msOutputs;
  230. for (const auto &name : names) {
  231. auto temp_dat = mSession->GetOutputByTensorName(name);
  232. msOutputs.insert(std::pair<std::string, mindspore::tensor::MSTensor *>{name, temp_dat});
  233. }
  234. ```