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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. ## MindSpore Lite 端侧图像分割demo(Android)
  2. 本示例程序演示了如何在端侧利用MindSpore Lite Java API 以及MindSpore Lite 图像分割模型完成端侧推理,实现对设备摄像头捕获的内容进行分割,并在App图像预览界面中显示出最可能的分割结果。
  3. ### 运行依赖
  4. - Android Studio >= 3.2 (推荐4.0以上版本)
  5. - NDK 21.3
  6. - CMake 3.10.2 [CMake](https://cmake.org/download)
  7. - Android SDK >= 26
  8. - JDK >= 1.8
  9. ### 构建与运行
  10. 1. 在Android Studio中加载本示例源码,并安装相应的SDK(指定SDK版本后,由Android Studio自动安装)。
  11. ![start_home](images/home.png)
  12. 启动Android Studio后,点击`File->Settings->System Settings->Android SDK`,勾选相应的SDK。如下图所示,勾选后,点击`OK`,Android Studio即可自动安装SDK。
  13. ![start_sdk](images/sdk_management.png)
  14. 使用过程中若出现Android Studio配置问题,可参考第4项解决。
  15. 2. 连接Android设备,运行图像分割应用程序。
  16. 通过USB连接Android设备调试,点击`Run 'app'`即可在您的设备上运行本示例项目。
  17. > 编译过程中Android Studio会自动下载MindSpore Lite、模型文件等相关依赖项,编译过程需做耐心等待。
  18. ![run_app](images/run_app.PNG)
  19. Android Studio连接设备调试操作,可参考<https://developer.android.com/studio/run/device?hl=zh-cn>。
  20. 手机需开启“USB调试模式”,Android Studio 才能识别到手机。 华为手机一般在设置->系统和更新->开发人员选项->USB调试中开始“USB调试模型”。
  21. 3. 在Android设备上,点击“继续安装”,安装完即可查看到设备摄像头捕获的内容和推理结果。
  22. ![install](images/install.jpg)
  23. 4. Android Studio 配置问题解决方案可参考下表:
  24. | | 报错 | 解决方案 |
  25. | ---- | ------------------------------------------------------------ | ------------------------------------------------------------ |
  26. | 1 | Gradle sync failed: NDK not configured. | 在local.properties中指定安装的ndk目录:ndk.dir={ndk的安装目录} |
  27. | 2 | Requested NDK version did not match the version requested by ndk.dir | 可手动下载相应的[NDK版本](https://developer.android.com/ndk/downloads?hl=zh-cn),并在Project Structure - Android NDK location设置中指定SDK的位置(可参考下图完成) |
  28. | 3 | This version of Android Studio cannot open this project, please retry with Android Studio or newer. | 在工具栏-help-Checkout for Updates中更新版本 |
  29. | 4 | SSL peer shut down incorrectly | 重新构建 |
  30. ![project_structure](images/project_structure.png)
  31. ## 示例程序详细说明
  32. 本端侧图像分割Android示例程序使用Java实现,Java层主要通过Android Camera 2 API实现摄像头获取图像帧,进行相应的图像处理,之后调用Java API 完成模型推理。
  33. > 此处详细说明示例程序的Java层图像处理及模型推理实现,Java层运用Android Camera 2 API实现开启设备摄像头以及图像帧处理等功能,需读者具备一定的Android开发基础知识。
  34. ### 示例程序结构
  35. ```text
  36. app
  37. ├── src/main
  38. │ ├── assets # 资源文件
  39. | | └── deeplabv3.ms # 存放模型文件
  40. │ |
  41. │ ├── java # java层应用代码
  42. │ │ └── com.mindspore.imagesegmentation
  43. │ │ ├── help # 图像处理及MindSpore Java调用相关实现
  44. │ │ │ └── ImageUtils # 图像预处理
  45. │ │ │ └── ModelTrackingResult # 推理数据后处理
  46. │ │ │ └── TrackingMobile # 模型加载、构建计算图和推理
  47. │ │ └── BitmapUtils # 图像处理
  48. │ │ └── MainActivity # 交互主页面
  49. │ │ └── OnBackgroundImageListener # 获取相册图像
  50. │ │ └── StyleRecycleViewAdapter # 获取相册图像
  51. │ │
  52. │ ├── res # 存放Android相关的资源文件
  53. │ └── AndroidManifest.xml # Android配置文件
  54. ├── CMakeList.txt # cmake编译入口文件
  55. ├── build.gradle # 其他Android配置文件
  56. ├── download.gradle # 工程依赖文件下载
  57. └── ...
  58. ```
  59. ### 配置MindSpore Lite依赖项
  60. Android 调用MindSpore Java API时,需要相关库文件支持。可通过MindSpore Lite[源码编译](https://www.mindspore.cn/tutorial/lite/zh-CN/master/use/build.html)生成`mindspore-lite-{version}-minddata-{os}-{device}.tar.gz`库文件包并解压缩(包含`libmindspore-lite.so`库文件和相关头文件),在本例中需使用生成带图像预处理模块的编译命令。
  61. > version:输出件版本号,与所编译的分支代码对应的版本一致。
  62. >
  63. > device:当前分为cpu(内置CPU算子)和gpu(内置CPU和GPU算子)。
  64. >
  65. > os:输出件应部署的操作系统。
  66. 本示例中,build过程由download.gradle文件自动下载MindSpore Lite 版本文件,并放置在`app/src/main/cpp/`目录下。
  67. > 若自动下载失败,请手动下载相关库文件,解压并放在对应位置:
  68. 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)
  69. 在app的`build.gradle`文件中配置CMake编译支持,以及`arm64-v8a`的编译支持,如下所示:
  70. ```text
  71. android{
  72. defaultConfig{
  73. externalNativeBuild{
  74. cmake{
  75. arguments "-DANDROID_STL=c++_shared"
  76. }
  77. }
  78. ndk{
  79. abiFilters 'arm64-v8a'
  80. }
  81. }
  82. }
  83. ```
  84. 在`app/CMakeLists.txt`文件中建立`.so`库文件链接,如下所示。
  85. ```text
  86. # ============== Set MindSpore Dependencies. =============
  87. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp)
  88. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/third_party/flatbuffers/include)
  89. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION})
  90. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include)
  91. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/ir/dtype)
  92. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/schema)
  93. add_library(mindspore-lite SHARED IMPORTED )
  94. add_library(minddata-lite SHARED IMPORTED )
  95. set_target_properties(mindspore-lite PROPERTIES IMPORTED_LOCATION
  96. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libmindspore-lite.so)
  97. set_target_properties(minddata-lite PROPERTIES IMPORTED_LOCATION
  98. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libminddata-lite.so)
  99. # --------------- MindSpore Lite set End. --------------------
  100. # Link target library.
  101. target_link_libraries(
  102. ...
  103. # --- mindspore ---
  104. minddata-lite
  105. mindspore-lite
  106. ...
  107. )
  108. ```
  109. ### 下载及部署模型文件
  110. 从MindSpore Model Hub中下载模型文件,本示例程序中使用的终端图像分割模型文件为`deeplabv3.ms`,同样通过download.gradle脚本在APP构建时自动下载,并放置在`app/src/main/assets`工程目录下。
  111. > 若下载失败请手动下载模型文件,deeplabv3.ms [下载链接](https://download.mindspore.cn/model_zoo/official/lite/deeplabv3_openimage_lite/deeplabv3.ms)。
  112. ### 编写端侧推理代码
  113. 调用MindSpore Lite Java API实现端测推理。
  114. 推理代码流程如下,完整代码请参见`src/java/TrackingMobile.java`。
  115. 1. 加载MindSpore Lite模型文件,构建上下文、会话以及用于推理的计算图。
  116. - 加载模型文件:创建并配置用于模型推理的上下文
  117. ```Java
  118. // Create context and load the .ms model named 'IMAGESEGMENTATIONMODEL'
  119. model = new Model();
  120. if (!model.loadModel(Context, IMAGESEGMENTATIONMODEL)) {
  121. Log.e(TAG, "Load Model failed");
  122. return;
  123. }
  124. ```
  125. - 创建会话
  126. ```Java
  127. // Create and init config.
  128. msConfig = new MSConfig();
  129. if (!msConfig.init(DeviceType.DT_CPU, 2, CpuBindMode.MID_CPU)) {
  130. Log.e(TAG, "Init context failed");
  131. return;
  132. }
  133. // Create the MindSpore lite session.
  134. session = new LiteSession();
  135. if (!session.init(msConfig)) {
  136. Log.e(TAG, "Create session failed");
  137. msConfig.free();
  138. return;
  139. }
  140. msConfig.free();
  141. ```
  142. - 构建计算图
  143. ```Java
  144. if (!session.compileGraph(model)) {
  145. Log.e(TAG, "Compile graph failed");
  146. model.freeBuffer();
  147. return;
  148. }
  149. // Note: when use model.freeBuffer(), the model can not be complile graph again.
  150. model.freeBuffer();
  151. ```
  152. 2. 将输入图片转换为传入MindSpore模型的Tensor格式。
  153. ```Java
  154. List<MSTensor> inputs = session.getInputs();
  155. if (inputs.size() != 1) {
  156. Log.e(TAG, "inputs.size() != 1");
  157. return null;
  158. }
  159. // `bitmap` is the picture used to infer.
  160. float resource_height = bitmap.getHeight();
  161. float resource_weight = bitmap.getWidth();
  162. ByteBuffer contentArray = bitmapToByteBuffer(bitmap, imageSize, imageSize, IMAGE_MEAN, IMAGE_STD);
  163. MSTensor inTensor = inputs.get(0);
  164. inTensor.setData(contentArray);
  165. ```
  166. 3. 对输入Tensor按照模型进行推理,获取输出Tensor,并进行后处理。
  167. - 图执行,端侧推理。
  168. ```Java
  169. // After the model and image tensor data is loaded, run inference.
  170. if (!session.runGraph()) {
  171. Log.e(TAG, "Run graph failed");
  172. return null;
  173. }
  174. ```
  175. - 获取输出数据。
  176. ```Java
  177. // Get output tensor values, the model only outputs one tensor.
  178. List<String> tensorNames = session.getOutputTensorNames();
  179. MSTensor output = session.getOutputByTensorName(tensorNames.front());
  180. if (output == null) {
  181. Log.e(TAG, "Can not find output " + tensorName);
  182. return null;
  183. }
  184. ```
  185. - 输出数据的后续处理。
  186. ```Java
  187. // Show output as pictures.
  188. float[] results = output.getFloatData();
  189. ByteBuffer bytebuffer_results = floatArrayToByteArray(results);
  190. Bitmap dstBitmap = convertBytebufferMaskToBitmap(bytebuffer_results, imageSize, imageSize, bitmap, dstBitmap, segmentColors);
  191. dstBitmap = scaleBitmapAndKeepRatio(dstBitmap, (int) resource_height, (int) resource_weight);
  192. ```
  193. 4. 图片处理及输出数据后处理请参考如下代码。
  194. ```Java
  195. Bitmap scaleBitmapAndKeepRatio(Bitmap targetBmp, int reqHeightInPixels, int reqWidthInPixels) {
  196. if (targetBmp.getHeight() == reqHeightInPixels && targetBmp.getWidth() == reqWidthInPixels) {
  197. return targetBmp;
  198. }
  199. Matrix matrix = new Matrix();
  200. matrix.setRectToRect(new RectF(0f, 0f, targetBmp.getWidth(), targetBmp.getHeight()),
  201. new RectF(0f, 0f, reqWidthInPixels, reqHeightInPixels), Matrix.ScaleToFit.FILL;
  202. return Bitmap.createBitmap(targetBmp, 0, 0, targetBmp.getWidth(), targetBmp.getHeight(), matrix, true);
  203. }
  204. ByteBuffer bitmapToByteBuffer(Bitmap bitmapIn, int width, int height, float mean, float std) {
  205. Bitmap bitmap = scaleBitmapAndKeepRatio(bitmapIn, width, height);
  206. ByteBuffer inputImage = ByteBuffer.allocateDirect(1 * width * height * 3 * 4);
  207. inputImage.order(ByteOrder.nativeOrder());
  208. inputImage.rewind();
  209. int[] intValues = new int[width * height];
  210. bitmap.getPixels(intValues, 0, width, 0, 0, width, height);
  211. int pixel = 0;
  212. for (int y = 0; y < height; y++) {
  213. for (int x = 0; x < width; x++) {
  214. int value = intValues[pixel++];
  215. inputImage.putFloat(((float) (value >> 16 & 255) - mean) / std);
  216. inputImage.putFloat(((float) (value >> 8 & 255) - mean) / std);
  217. inputImage.putFloat(((float) (value & 255) - mean) / std);
  218. }
  219. }
  220. inputImage.rewind();
  221. return inputImage;
  222. }
  223. ByteBuffer floatArrayToByteArray(float[] floats) {
  224. ByteBuffer buffer = ByteBuffer.allocate(4 * floats.length);
  225. FloatBuffer floatBuffer = buffer.asFloatBuffer();
  226. floatBuffer.put(floats);
  227. return buffer;
  228. }
  229. Bitmap convertBytebufferMaskToBitmap(ByteBuffer inputBuffer, int imageWidth, int imageHeight, Bitmap backgroundImage, int[] colors) {
  230. Bitmap.Config conf = Bitmap.Config.ARGB_8888;
  231. Bitmap dstBitmap = Bitmap.createBitmap(imageWidth, imageHeight, conf);
  232. Bitmap scaledBackgroundImage = scaleBitmapAndKeepRatio(backgroundImage, imageWidth, imageHeight);
  233. int[][] mSegmentBits = new int[imageWidth][imageHeight];
  234. inputBuffer.rewind();
  235. for (int y = 0; y < imageHeight; y++) {
  236. for (int x = 0; x < imageWidth; x++) {
  237. float maxVal = 0f;
  238. mSegmentBits[x][y] = 0;
  239. // NUM_CLASSES is the number of labels, the value here is 21.
  240. for (int i = 0; i < NUM_CLASSES; i++) {
  241. float value = inputBuffer.getFloat((y * imageWidth * NUM_CLASSES + x * NUM_CLASSES + i) * 4);
  242. if (i == 0 || value > maxVal) {
  243. maxVal = value;
  244. // Check wether a pixel belongs to a person whose label is 15.
  245. if (i == 15) {
  246. mSegmentBits[x][y] = i;
  247. } else {
  248. mSegmentBits[x][y] = 0;
  249. }
  250. }
  251. }
  252. itemsFound.add(mSegmentBits[x][y]);
  253. int newPixelColor = ColorUtils.compositeColors(
  254. colors[mSegmentBits[x][y] == 0 ? 0 : 1],
  255. scaledBackgroundImage.getPixel(x, y)
  256. );
  257. dstBitmap.setPixel(x, y, mSegmentBits[x][y] == 0 ? colors[0] : scaledBackgroundImage.getPixel(x, y));
  258. }
  259. }
  260. return dstBitmap;
  261. }
  262. ```