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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. ## MindSpore Lite 端侧图像分类demo(Android)
  2. 本示例程序演示了如何在端侧利用MindSpore Lite C++ API(Android JNI)以及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 [JDK]( https://www.oracle.com/downloads/otn-pub/java/JDK/)
  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. (可选)若安装时出现NDK版本问题,可手动下载相应的[NDK版本](https://developer.android.com/ndk/downloads?hl=zh-cn)(本示例代码使用的NDK版本为21.3),并在`Project Structure`的`Android NDK location`设置中指定SDK的位置。
  15. ![project_structure](images/project_structure.png)
  16. 2. 连接Android设备,运行图像分类应用程序。
  17. 通过USB连接Android设备调试,点击`Run 'app'`即可在您的设备上运行本示例项目。
  18. * 注:编译过程中Android Studio会自动下载MindSpore Lite、模型文件等相关依赖项,编译过程需做耐心等待。
  19. ![run_app](images/run_app.PNG)
  20. Android Studio连接设备调试操作,可参考<https://developer.android.com/studio/run/device?hl=zh-cn>。
  21. 手机需开启“USB调试模式”,Android Studio 才能识别到手机。 华为手机一般在设置->系统和更新->开发人员选项->USB调试中开始“USB调试模型”。
  22. 3. 在Android设备上,点击“继续安装”,安装完即可查看到设备摄像头捕获的内容和推理结果。
  23. ![install](images/install.jpg)
  24. 如下图所示,识别出的概率最高的物体是植物。
  25. ![result](images/app_result.jpg)
  26. ## 示例程序详细说明
  27. 本端侧图像分类Android示例程序分为JAVA层和JNI层,其中,JAVA层主要通过Android Camera 2 API实现摄像头获取图像帧,以及相应的图像处理等功能;JNI层完成模型推理的过程。
  28. > 此处详细说明示例程序的JNI层实现,JAVA层运用Android Camera 2 API实现开启设备摄像头以及图像帧处理等功能,需读者具备一定的Android开发基础知识。
  29. ### 示例程序结构
  30. ```
  31. app
  32. ├── src/main
  33. │ ├── assets # 资源文件
  34. | | └── mobilenetv2.ms # 存放模型文件
  35. │ |
  36. │ ├── cpp # 模型加载和预测主要逻辑封装类
  37. | | ├── ..
  38. | | ├── mindspore_lite_x.x.x-minddata-arm64-cpu #MindSpore Lite版本
  39. | | ├── MindSporeNetnative.cpp # MindSpore调用相关的JNI方法
  40. │ | └── MindSporeNetnative.h # 头文件
  41. | | └── MsNetWork.cpp # MindSpre接口封装
  42. │ |
  43. │ ├── java # java层应用代码
  44. │ │ └── com.huawei.himindsporedemo
  45. │ │ ├── gallery.classify # 图像处理及MindSpore JNI调用相关实现
  46. │ │ │ └── ...
  47. │ │ └── widget # 开启摄像头及绘制相关实现
  48. │ │ └── ...
  49. │ │
  50. │ ├── res # 存放Android相关的资源文件
  51. │ └── AndroidManifest.xml # Android配置文件
  52. ├── CMakeList.txt # cmake编译入口文件
  53. ├── build.gradle # 其他Android配置文件
  54. ├── download.gradle # 工程依赖文件下载
  55. └── ...
  56. ```
  57. ### 配置MindSpore Lite依赖项
  58. Android JNI层调用MindSpore C++ API时,需要相关库文件支持。可通过MindSpore Lite源码编译生成`libmindspore-lite.so`库文件。
  59. 本示例中,build过程由download.gradle文件自动从华为服务器下载MindSpore Lite 版本文件,并放置在`app / src / main/cpp/mindspore_lite_x.x.x-minddata-arm64-cpu`目录下。
  60. * 注:若自动下载失败,请手动下载相关库文件并将其放在对应位置:
  61. MindSpore Lite版本 [下载链接](https://download.mindspore.cn/model_zoo/official/lite/lib/mindspore%20version%200.7/libmindspore-lite.so)
  62. ```
  63. android{
  64. defaultConfig{
  65. externalNativeBuild{
  66. cmake{
  67. arguments "-DANDROID_STL=c++_shared"
  68. }
  69. }
  70. ndk{
  71. abiFilters 'arm64-v8a'
  72. }
  73. }
  74. }
  75. ```
  76. 在`app/CMakeLists.txt`文件中建立`.so`库文件链接,如下所示。
  77. ```
  78. # ============== Set MindSpore Dependencies. =============
  79. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp)
  80. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/third_party/flatbuffers/include)
  81. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION})
  82. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include)
  83. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/ir/dtype)
  84. include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/schema)
  85. add_library(mindspore-lite SHARED IMPORTED )
  86. add_library(minddata-lite SHARED IMPORTED )
  87. set_target_properties(mindspore-lite PROPERTIES IMPORTED_LOCATION
  88. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libmindspore-lite.so)
  89. set_target_properties(minddata-lite PROPERTIES IMPORTED_LOCATION
  90. ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libminddata-lite.so)
  91. # --------------- MindSpore Lite set End. --------------------
  92. # Link target library.
  93. target_link_libraries(
  94. ...
  95. # --- mindspore ---
  96. minddata-lite
  97. mindspore-lite
  98. ...
  99. )
  100. ```
  101. ### 下载及部署模型文件
  102. 从MindSpore Model Hub中下载模型文件,本示例程序中使用的终端图像分类模型文件为`mobilenetv2.ms`,同样通过download.gradle脚本在APP构建时自动下载,并放置在`app/src/main/assets`工程目录下。
  103. * 注:若下载失败请手动下载模型文件,mobilenetv2.ms [下载链接](https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_openimage_lite/mobilenetv2.ms)。
  104. ### 编写端侧推理代码
  105. 在JNI层调用MindSpore Lite C++ API实现端测推理。
  106. 推理代码流程如下,完整代码请参见`src/cpp/MindSporeNetnative.cpp`。
  107. 1. 加载MindSpore Lite模型文件,构建上下文、会话以及用于推理的计算图。
  108. - 加载模型文件:创建并配置用于模型推理的上下文
  109. ```cpp
  110. // Buffer is the model data passed in by the Java layer
  111. jlong bufferLen = env->GetDirectBufferCapacity(buffer);
  112. char *modelBuffer = CreateLocalModelBuffer(env, buffer);
  113. ```
  114. - 创建会话
  115. ```cpp
  116. void **labelEnv = new void *;
  117. MSNetWork *labelNet = new MSNetWork;
  118. *labelEnv = labelNet;
  119. // Create context.
  120. lite::Context *context = new lite::Context;
  121. context->thread_num_ = numThread; //Specify the number of threads to run inference
  122. // Create the mindspore session.
  123. labelNet->CreateSessionMS(modelBuffer, bufferLen, context);
  124. delete(context);
  125. ```
  126. - 加载模型文件并构建用于推理的计算图
  127. ```cpp
  128. void MSNetWork::CreateSessionMS(char* modelBuffer, size_t bufferLen, std::string name, mindspore::lite::Context* ctx)
  129. {
  130. CreateSession(modelBuffer, bufferLen, ctx);
  131. session = mindspore::session::LiteSession::CreateSession(ctx);
  132. auto model = mindspore::lite::Model::Import(modelBuffer, bufferLen);
  133. int ret = session->CompileGraph(model);
  134. }
  135. ```
  136. 2. 将输入图片转换为传入MindSpore模型的Tensor格式。
  137. 将待检测图片数据转换为输入MindSpore模型的Tensor。
  138. ```cpp
  139. // Convert the Bitmap image passed in from the JAVA layer to Mat for OpenCV processing
  140. BitmapToMat(env, srcBitmap, matImageSrc);
  141. // Processing such as zooming the picture size.
  142. matImgPreprocessed = PreProcessImageData(matImageSrc);
  143. ImgDims inputDims;
  144. inputDims.channel = matImgPreprocessed.channels();
  145. inputDims.width = matImgPreprocessed.cols;
  146. inputDims.height = matImgPreprocessed.rows;
  147. float *dataHWC = new float[inputDims.channel * inputDims.width * inputDims.height]
  148. // Copy the image data to be detected to the dataHWC array.
  149. // The dataHWC[image_size] array here is the intermediate variable of the input MindSpore model tensor.
  150. float *ptrTmp = reinterpret_cast<float *>(matImgPreprocessed.data);
  151. for(int i = 0; i < inputDims.channel * inputDims.width * inputDims.height; i++){
  152. dataHWC[i] = ptrTmp[i];
  153. }
  154. // Assign dataHWC[image_size] to the input tensor variable.
  155. auto msInputs = mSession->GetInputs();
  156. auto inTensor = msInputs.front();
  157. memcpy(inTensor->MutableData(), dataHWC,
  158. inputDims.channel * inputDims.width * inputDims.height * sizeof(float));
  159. delete[] (dataHWC);
  160. ```
  161. 3. 对输入Tensor按照模型进行推理,获取输出Tensor,并进行后处理。
  162. - 图执行,端测推理。
  163. ```cpp
  164. // After the model and image tensor data is loaded, run inference.
  165. auto status = mSession->RunGraph();
  166. ```
  167. - 获取输出数据。
  168. ```cpp
  169. auto names = mSession->GetOutputTensorNames();
  170. std::unordered_map<std::string,mindspore::tensor::MSTensor *> msOutputs;
  171. for (const auto &name : names) {
  172. auto temp_dat =mSession->GetOutputByTensorName(name);
  173. msOutputs.insert(std::pair<std::string, mindspore::tensor::MSTensor *> {name, temp_dat});
  174. }
  175. std::string retStr = ProcessRunnetResult(msOutputs, ret);
  176. ```
  177. - 输出数据的后续处理。
  178. ```cpp
  179. std::string ProcessRunnetResult(std::unordered_map<std::string,
  180. mindspore::tensor::MSTensor *> msOutputs, int runnetRet) {
  181. std::unordered_map<std::string, mindspore::tensor::MSTensor *>::iterator iter;
  182. iter = msOutputs.begin();
  183. // The mobilenetv2.ms model output just one branch.
  184. auto outputTensor = iter->second;
  185. int tensorNum = outputTensor->ElementsNum();
  186. MS_PRINT("Number of tensor elements:%d", tensorNum);
  187. // Get a pointer to the first score.
  188. float *temp_scores = static_cast<float * >(outputTensor->MutableData());
  189. float scores[RET_CATEGORY_SUM];
  190. for (int i = 0; i < RET_CATEGORY_SUM; ++i) {
  191. if (temp_scores[i] > 0.5) {
  192. MS_PRINT("MindSpore scores[%d] : [%f]", i, temp_scores[i]);
  193. }
  194. scores[i] = temp_scores[i];
  195. }
  196. // Score for each category.
  197. // Converted to text information that needs to be displayed in the APP.
  198. std::string categoryScore = "";
  199. for (int i = 0; i < RET_CATEGORY_SUM; ++i) {
  200. categoryScore += labels_name_map[i];
  201. categoryScore += ":";
  202. std::string score_str = std::to_string(scores[i]);
  203. categoryScore += score_str;
  204. categoryScore += ";";
  205. }
  206. return categoryScore;
  207. }
  208. ```