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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. # Demo of Image Segmentation
  2. The following describes how to use the MindSpore Lite JAVA APIs 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. ## 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 Program
  40. This image segmentation sample program on the Android device is implemented through Java. At the Java layer, the Android Camera 2 API is used to enable a camera to obtain image frames and process images. Then Java API is called to infer.[Runtime](https://www.mindspore.cn/tutorial/lite/en/master/use/runtime.html).
  41. ### Sample Program Structure
  42. ```text
  43. app
  44. ├── src/main
  45. │ ├── assets # resource files
  46. | | └── deeplabv3.ms # model file
  47. │ |
  48. │ ├── java # application code at the Java layer
  49. │ │ └── com.mindspore.imagesegmentation
  50. │ │ ├── help # pre-process of image and inference of model
  51. │ │ │ └── ImageUtils # image pre-process
  52. │ │ │ └── ModelTrackingResult # post-process of result of inference
  53. │ │ │ └── TrackingMobile # load model, compile graph and perform
  54. │ │ └── BitmapUtils # image process
  55. │ │ └── MainActivity # interactive page
  56. │ │ └── OnBackgroundImageListener # get images from the photo album
  57. │ │ └── StyleRecycleViewAdapter # get images from the photo album
  58. │ │
  59. │ ├── res # resource files related to Android
  60. │ └── AndroidManifest.xml # Android configuration file
  61. ├── CMakeList.txt # CMake compilation entry file
  62. ├── build.gradle # Other Android configuration file
  63. ├── download.gradle # MindSpore version download
  64. └── ...
  65. ```
  66. ### Configuring MindSpore Lite Dependencies
  67. When MindSpore Java APIs are called, 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.
  68. 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.
  69. Note: if the automatic download fails, please manually download the relevant library files and put them in the corresponding location.
  70. 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)
  71. ```text
  72. android{
  73. defaultConfig{
  74. externalNativeBuild{
  75. cmake{
  76. arguments "-DANDROID_STL=c++_shared"
  77. }
  78. }
  79. ndk{
  80. abiFilters'armeabi-v7a', 'arm64-v8a'
  81. }
  82. }
  83. }
  84. ```
  85. Create a link to the `.so` library file in the `app/CMakeLists.txt` file:
  86. ```text
  87. # ============== Set MindSpore Dependencies. =============
  88. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp)
  89. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/third_party/flatbuffers/include)
  90. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION})
  91. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include)
  92. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/ir/dtype)
  93. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/schema)
  94. add_library(mindspore-lite SHARED IMPORTED )
  95. add_library(minddata-lite SHARED IMPORTED )
  96. set_target_properties(mindspore-lite PROPERTIES IMPORTED_LOCATION
  97. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libmindspore-lite.so)
  98. set_target_properties(minddata-lite PROPERTIES IMPORTED_LOCATION
  99. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libminddata-lite.so)
  100. # --------------- MindSpore Lite set End. --------------------
  101. # Link target library.
  102. target_link_libraries(
  103. ...
  104. # --- mindspore ---
  105. minddata-lite
  106. mindspore-lite
  107. ...
  108. )
  109. ```
  110. ### Downloading and Deploying a Model File
  111. In this example, the download.gradle File configuration auto download `deeplabv3.ms`and placed in the 'app/libs/arm64-v8a' directory.
  112. Note: if the automatic download fails, please manually download the relevant library files and put them in the corresponding location.
  113. deeplabv3.ms [deeplabv3.ms]( https://download.mindspore.cn/model_zoo/official/lite/deeplabv3_openimage_lite/deeplabv3.ms)
  114. ### Compiling On-Device Inference Code
  115. Call MindSpore Lite Java APIs to implement on-device inference.
  116. The inference code process is as follows. For details about the complete code, see `src/java/TrackingMobile.java`.
  117. 1. Load the MindSpore Lite model file and build the context, session, and computational graph for inference.
  118. - Load a model file. Import and configure the context for model inference.
  119. ```Java
  120. // Create context and load the .ms model named 'IMAGESEGMENTATIONMODEL'
  121. model = new Model();
  122. if (!model.loadModel(Context, IMAGESEGMENTATIONMODEL)) {
  123. Log.e(TAG, "Load Model failed");
  124. return;
  125. }
  126. ```
  127. - Create a session.
  128. ```Java
  129. // Create and init config.
  130. msConfig = new MSConfig();
  131. if (!msConfig.init(DeviceType.DT_CPU, 2, CpuBindMode.MID_CPU)) {
  132. Log.e(TAG, "Init context failed");
  133. return;
  134. }
  135. // Create the MindSpore lite session.
  136. session = new LiteSession();
  137. if (!session.init(msConfig)) {
  138. Log.e(TAG, "Create session failed");
  139. msConfig.free();
  140. return;
  141. }
  142. msConfig.free();
  143. ```
  144. - Compile graph for inference.
  145. ```Java
  146. if (!session.compileGraph(model)) {
  147. Log.e(TAG, "Compile graph failed");
  148. model.freeBuffer();
  149. return;
  150. }
  151. // Note: when use model.freeBuffer(), the model can not be complile graph again.
  152. model.freeBuffer();
  153. ```
  154. 2. Convert the input image into the Tensor format of the MindSpore model.
  155. ```Java
  156. List<MSTensor> inputs = session.getInputs();
  157. if (inputs.size() != 1) {
  158. Log.e(TAG, "inputs.size() != 1");
  159. return null;
  160. }
  161. // `bitmap` is the picture used to infer.
  162. float resource_height = bitmap.getHeight();
  163. float resource_weight = bitmap.getWidth();
  164. ByteBuffer contentArray = bitmapToByteBuffer(bitmap, imageSize, imageSize, IMAGE_MEAN, IMAGE_STD);
  165. MSTensor inTensor = inputs.get(0);
  166. inTensor.setData(contentArray);
  167. ```
  168. 3. Perform inference on the input tensor based on the model, obtain the output tensor, and perform post-processing.
  169. - Perform graph execution and on-device inference.
  170. ```Java
  171. // After the model and image tensor data is loaded, run inference.
  172. if (!session.runGraph()) {
  173. Log.e(TAG, "Run graph failed");
  174. return null;
  175. }
  176. ```
  177. - Obtain the output data.
  178. ```Java
  179. // Get output tensor values, the model only outputs one tensor.
  180. List<String> tensorNames = session.getOutputTensorNames();
  181. MSTensor output = session.getOutputByTensorName(tensorNames.front());
  182. if (output == null) {
  183. Log.e(TAG, "Can not find output " + tensorName);
  184. return null;
  185. }
  186. ```
  187. - Perform post-processing of the output data.
  188. ```Java
  189. // Show output as pictures.
  190. float[] results = output.getFloatData();
  191. ByteBuffer bytebuffer_results = floatArrayToByteArray(results);
  192. Bitmap dstBitmap = convertBytebufferMaskToBitmap(bytebuffer_results, imageSize, imageSize, bitmap, dstBitmap, segmentColors);
  193. dstBitmap = scaleBitmapAndKeepRatio(dstBitmap, (int) resource_height, (int) resource_weight);
  194. ```
  195. 4. The process of image and output data can refer to methods showing bellow.
  196. ```Java
  197. Bitmap scaleBitmapAndKeepRatio(Bitmap targetBmp, int reqHeightInPixels, int reqWidthInPixels) {
  198. if (targetBmp.getHeight() == reqHeightInPixels && targetBmp.getWidth() == reqWidthInPixels) {
  199. return targetBmp;
  200. }
  201. Matrix matrix = new Matrix();
  202. matrix.setRectToRect(new RectF(0f, 0f, targetBmp.getWidth(), targetBmp.getHeight()),
  203. new RectF(0f, 0f, reqWidthInPixels, reqHeightInPixels), Matrix.ScaleToFit.FILL;
  204. return Bitmap.createBitmap(targetBmp, 0, 0, targetBmp.getWidth(), targetBmp.getHeight(), matrix, true);
  205. }
  206. ByteBuffer bitmapToByteBuffer(Bitmap bitmapIn, int width, int height, float mean, float std) {
  207. Bitmap bitmap = scaleBitmapAndKeepRatio(bitmapIn, width, height);
  208. ByteBuffer inputImage = ByteBuffer.allocateDirect(1 * width * height * 3 * 4);
  209. inputImage.order(ByteOrder.nativeOrder());
  210. inputImage.rewind();
  211. int[] intValues = new int[width * height];
  212. bitmap.getPixels(intValues, 0, width, 0, 0, width, height);
  213. int pixel = 0;
  214. for (int y = 0; y < height; y++) {
  215. for (int x = 0; x < width; x++) {
  216. int value = intValues[pixel++];
  217. inputImage.putFloat(((float) (value >> 16 & 255) - mean) / std);
  218. inputImage.putFloat(((float) (value >> 8 & 255) - mean) / std);
  219. inputImage.putFloat(((float) (value & 255) - mean) / std);
  220. }
  221. }
  222. inputImage.rewind();
  223. return inputImage;
  224. }
  225. ByteBuffer floatArrayToByteArray(float[] floats) {
  226. ByteBuffer buffer = ByteBuffer.allocate(4 * floats.length);
  227. FloatBuffer floatBuffer = buffer.asFloatBuffer();
  228. floatBuffer.put(floats);
  229. return buffer;
  230. }
  231. Bitmap convertBytebufferMaskToBitmap(ByteBuffer inputBuffer, int imageWidth, int imageHeight, Bitmap backgroundImage, int[] colors) {
  232. Bitmap.Config conf = Bitmap.Config.ARGB_8888;
  233. Bitmap dstBitmap = Bitmap.createBitmap(imageWidth, imageHeight, conf);
  234. Bitmap scaledBackgroundImage = scaleBitmapAndKeepRatio(backgroundImage, imageWidth, imageHeight);
  235. int[][] mSegmentBits = new int[imageWidth][imageHeight];
  236. inputBuffer.rewind();
  237. for (int y = 0; y < imageHeight; y++) {
  238. for (int x = 0; x < imageWidth; x++) {
  239. float maxVal = 0f;
  240. mSegmentBits[x][y] = 0;
  241. // NUM_CLASSES is the number of labels, the value here is 21.
  242. for (int i = 0; i < NUM_CLASSES; i++) {
  243. float value = inputBuffer.getFloat((y * imageWidth * NUM_CLASSES + x * NUM_CLASSES + i) * 4);
  244. if (i == 0 || value > maxVal) {
  245. maxVal = value;
  246. // Check wether a pixel belongs to a person whose label is 15.
  247. if (i == 15) {
  248. mSegmentBits[x][y] = i;
  249. } else {
  250. mSegmentBits[x][y] = 0;
  251. }
  252. }
  253. }
  254. itemsFound.add(mSegmentBits[x][y]);
  255. int newPixelColor = ColorUtils.compositeColors(
  256. colors[mSegmentBits[x][y] == 0 ? 0 : 1],
  257. scaledBackgroundImage.getPixel(x, y)
  258. );
  259. dstBitmap.setPixel(x, y, mSegmentBits[x][y] == 0 ? colors[0] : scaledBackgroundImage.getPixel(x, y));
  260. }
  261. }
  262. return dstBitmap;
  263. }
  264. ```