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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. ## Demo of Image Segmentation
  2. The following describes how to use the MindSpore Lite C++ APIs (Android JNIs) and MindSpore Lite image segmentation models to perform on-device inference, classify the content captured by a device camera, and display the most possible segmentation 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 segmentation 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 segmentation 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. | | └── deeplabv3.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 `deeplabv3.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. deeplabv3.ms [deeplabv3.ms]( https://download.mindspore.cn/model_zoo/official/lite/deeplabv3_openimage_lite/deeplabv3.ms)
  106. ### Compiling On-Device Inference Code
  107. Call MindSpore Lite Java APIs to implement on-device inference.
  108. The inference code process is as follows. For details about the complete code, see `src/java/TrackingMobile.java`.
  109. 1. Load the MindSpore Lite model file and build the context, session, and computational graph for inference.
  110. - Load a model file. Import and configure the context for model inference.
  111. ```Java
  112. // Create context and load the .ms model named 'IMAGESEGMENTATIONMODEL'
  113. model = new Model();
  114. if (!model.loadModel(Context, IMAGESEGMENTATIONMODEL)) {
  115. Log.e(TAG, "Load Model failed");
  116. return;
  117. }
  118. ```
  119. - Create a session.
  120. ```Java
  121. // Create and init config.
  122. msConfig = new MSConfig();
  123. if (!msConfig.init(DeviceType.DT_CPU, 2, CpuBindMode.MID_CPU)) {
  124. Log.e(TAG, "Init context failed");
  125. return;
  126. }
  127. // Create the MindSpore lite session.
  128. session = new LiteSession();
  129. if (!session.init(msConfig)) {
  130. Log.e(TAG, "Create session failed");
  131. msConfig.free();
  132. return;
  133. }
  134. msConfig.free();
  135. ```
  136. - Compile graph for inference.
  137. ```Java
  138. if (!session.compileGraph(model)) {
  139. Log.e(TAG, "Compile graph failed");
  140. model.freeBuffer();
  141. return;
  142. }
  143. // Note: when use model.freeBuffer(), the model can not be complile graph again.
  144. model.freeBuffer();
  145. ```
  146. 2. Convert the input image into the Tensor format of the MindSpore model.
  147. ```Java
  148. List<MSTensor> inputs = session.getInputs();
  149. if (inputs.size() != 1) {
  150. Log.e(TAG, "inputs.size() != 1");
  151. return null;
  152. }
  153. // `bitmap` is the picture used to infer.
  154. float resource_height = bitmap.getHeight();
  155. float resource_weight = bitmap.getWidth();
  156. ByteBuffer contentArray = bitmapToByteBuffer(bitmap, imageSize, imageSize, IMAGE_MEAN, IMAGE_STD);
  157. MSTensor inTensor = inputs.get(0);
  158. inTensor.setData(contentArray);
  159. ```
  160. 3. Perform inference on the input tensor based on the model, obtain the output tensor, and perform post-processing.
  161. - Perform graph execution and on-device inference.
  162. ```Java
  163. // After the model and image tensor data is loaded, run inference.
  164. if (!session.runGraph()) {
  165. Log.e(TAG, "Run graph failed");
  166. return null;
  167. }
  168. ```
  169. - Obtain the output data.
  170. ```Java
  171. // Get output tensor values, the model only outputs one tensor.
  172. List<String> tensorNames = session.getOutputTensorNames();
  173. MSTensor output = session.getOutputByTensorName(tensorNames.front());
  174. if (output == null) {
  175. Log.e(TAG, "Can not find output " + tensorName);
  176. return null;
  177. }
  178. ```
  179. - Perform post-processing of the output data.
  180. ```Java
  181. // Show output as pictures.
  182. float[] results = output.getFloatData();
  183. ByteBuffer bytebuffer_results = floatArrayToByteArray(results);
  184. Bitmap dstBitmap = convertBytebufferMaskToBitmap(bytebuffer_results, imageSize, imageSize, bitmap, dstBitmap, segmentColors);
  185. dstBitmap = scaleBitmapAndKeepRatio(dstBitmap, (int) resource_height, (int) resource_weight);
  186. ```
  187. 4. The process of image and output data can refer to methods showing bellow.
  188. ```Java
  189. Bitmap scaleBitmapAndKeepRatio(Bitmap targetBmp, int reqHeightInPixels, int reqWidthInPixels) {
  190. if (targetBmp.getHeight() == reqHeightInPixels && targetBmp.getWidth() == reqWidthInPixels) {
  191. return targetBmp;
  192. }
  193. Matrix matrix = new Matrix();
  194. matrix.setRectToRect(new RectF(0f, 0f, targetBmp.getWidth(), targetBmp.getHeight()),
  195. new RectF(0f, 0f, reqWidthInPixels, reqHeightInPixels), Matrix.ScaleToFit.FILL;
  196. return Bitmap.createBitmap(targetBmp, 0, 0, targetBmp.getWidth(), targetBmp.getHeight(), matrix, true);
  197. }
  198. ByteBuffer bitmapToByteBuffer(Bitmap bitmapIn, int width, int height, float mean, float std) {
  199. Bitmap bitmap = scaleBitmapAndKeepRatio(bitmapIn, width, height);
  200. ByteBuffer inputImage = ByteBuffer.allocateDirect(1 * width * height * 3 * 4);
  201. inputImage.order(ByteOrder.nativeOrder());
  202. inputImage.rewind();
  203. int[] intValues = new int[width * height];
  204. bitmap.getPixels(intValues, 0, width, 0, 0, width, height);
  205. int pixel = 0;
  206. for (int y = 0; y < height; y++) {
  207. for (int x = 0; x < width; x++) {
  208. int value = intValues[pixel++];
  209. inputImage.putFloat(((float) (value >> 16 & 255) - mean) / std);
  210. inputImage.putFloat(((float) (value >> 8 & 255) - mean) / std);
  211. inputImage.putFloat(((float) (value & 255) - mean) / std);
  212. }
  213. }
  214. inputImage.rewind();
  215. return inputImage;
  216. }
  217. ByteBuffer floatArrayToByteArray(float[] floats) {
  218. ByteBuffer buffer = ByteBuffer.allocate(4 * floats.length);
  219. FloatBuffer floatBuffer = buffer.asFloatBuffer();
  220. floatBuffer.put(floats);
  221. return buffer;
  222. }
  223. Bitmap convertBytebufferMaskToBitmap(ByteBuffer inputBuffer, int imageWidth, int imageHeight, Bitmap backgroundImage, int[] colors) {
  224. Bitmap.Config conf = Bitmap.Config.ARGB_8888;
  225. Bitmap dstBitmap = Bitmap.createBitmap(imageWidth, imageHeight, conf);
  226. Bitmap scaledBackgroundImage = scaleBitmapAndKeepRatio(backgroundImage, imageWidth, imageHeight);
  227. int[][] mSegmentBits = new int[imageWidth][imageHeight];
  228. inputBuffer.rewind();
  229. for (int y = 0; y < imageHeight; y++) {
  230. for (int x = 0; x < imageWidth; x++) {
  231. float maxVal = 0f;
  232. mSegmentBits[x][y] = 0;
  233. // NUM_CLASSES is the number of labels, the value here is 21.
  234. for (int i = 0; i < NUM_CLASSES; i++) {
  235. float value = inputBuffer.getFloat((y * imageWidth * NUM_CLASSES + x * NUM_CLASSES + i) * 4);
  236. if (i == 0 || value > maxVal) {
  237. maxVal = value;
  238. // Check wether a pixel belongs to a person whose label is 15.
  239. if (i == 15) {
  240. mSegmentBits[x][y] = i;
  241. } else {
  242. mSegmentBits[x][y] = 0;
  243. }
  244. }
  245. }
  246. itemsFound.add(mSegmentBits[x][y]);
  247. int newPixelColor = ColorUtils.compositeColors(
  248. colors[mSegmentBits[x][y] == 0 ? 0 : 1],
  249. scaledBackgroundImage.getPixel(x, y)
  250. );
  251. dstBitmap.setPixel(x, y, mSegmentBits[x][y] == 0 ? colors[0] : scaledBackgroundImage.getPixel(x, y));
  252. }
  253. }
  254. return dstBitmap;
  255. }
  256. ```