| @@ -1,6 +1,8 @@ | |||
| # MindSpore | |||
| build/ | |||
| mindspore/lib | |||
| app/src/main/assets/model/ | |||
| app/src/main/cpp/mindspore-lite-0.7.0-minddata-arm64-cpu | |||
| output | |||
| *.ir | |||
| mindspore/ccsrc/schema/inner/* | |||
| @@ -0,0 +1,278 @@ | |||
| ## Demo_image_classification | |||
| The following describes how to use the MindSpore Lite C++ APIs (Android JNIs) and MindSpore Lite image classification models to perform on-device inference, classify the content captured by a device camera, and display the most possible classification result on the application's image preview screen. | |||
| ### 运行依赖 | |||
| - Android Studio 3.2 or later (Android 4.0 or later is recommended.) | |||
| - Native development kit (NDK) 21.3 | |||
| - CMake 3.10.2 [CMake](https://cmake.org/download) | |||
| - Android software development kit (SDK) 26 or later | |||
| - JDK 1.8 or later [JDK]( https://www.oracle.com/downloads/otn-pub/java/JDK/) | |||
| ### 构建与运行 | |||
| 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.) | |||
|  | |||
| 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. | |||
|  | |||
| (Optional) If an NDK version issue occurs during the installation, manually download the corresponding [NDK version](https://developer.android.com/ndk/downloads) (the version used in the sample code is 21.3). Specify the SDK location in `Android NDK location` of `Project Structure`. | |||
|  | |||
| 2. Connect to an Android device and runs the image classification application. | |||
| Connect to the Android device through a USB cable for debugging. Click `Run 'app'` to run the sample project on your device. | |||
|  | |||
| 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>. | |||
| 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. | |||
| 3. 在Android设备上,点击“继续安装”,安装完即可查看到设备摄像头捕获的内容和推理结果。 | |||
| 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. | |||
|  | |||
| ## Detailed Description of the Sample Program | |||
| This image classification 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/lite/tutorial/en/master/use/runtime.html). | |||
| ### Sample Program Structure | |||
| ``` | |||
| app | |||
| │ | |||
| ├── src/main | |||
| │ ├── assets # resource files | |||
| | | └── mobilenetv2.ms # model file | |||
| │ | | |||
| │ ├── cpp # main logic encapsulation classes for model loading and prediction | |||
| | | | | |||
| | | ├── MindSporeNetnative.cpp # JNI methods related to MindSpore calling | |||
| │ | └── MindSporeNetnative.h # header file | |||
| │ | | |||
| │ ├── java # application code at the Java layer | |||
| │ │ └── com.huawei.himindsporedemo | |||
| │ │ ├── gallery.classify # implementation related to image processing and MindSpore JNI calling | |||
| │ │ │ └── ... | |||
| │ │ └── widget # implementation related to camera enabling and drawing | |||
| │ │ └── ... | |||
| │ │ | |||
| │ ├── res # resource files related to Android | |||
| │ └── AndroidManifest.xml # Android configuration file | |||
| │ | |||
| ├── CMakeList.txt # CMake compilation entry file | |||
| │ | |||
| ├── build.gradle # Other Android configuration file | |||
| ├── download.gradle # MindSpore version download | |||
| └── ... | |||
| ``` | |||
| ### Configuring MindSpore Lite Dependencies | |||
| 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/lite/tutorial/en/master/build.html) to generate the MindSpore Lite version. | |||
| ``` | |||
| android{ | |||
| defaultConfig{ | |||
| externalNativeBuild{ | |||
| cmake{ | |||
| arguments "-DANDROID_STL=c++_shared" | |||
| } | |||
| } | |||
| ndk{ | |||
| abiFilters'armeabi-v7a', 'arm64-v8a' | |||
| } | |||
| } | |||
| } | |||
| ``` | |||
| Create a link to the `.so` library file in the `app/CMakeLists.txt` file: | |||
| ``` | |||
| # ============== Set MindSpore Dependencies. ============= | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/third_party/flatbuffers/include) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/ir/dtype) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/schema) | |||
| add_library(mindspore-lite SHARED IMPORTED ) | |||
| add_library(minddata-lite SHARED IMPORTED ) | |||
| set_target_properties(mindspore-lite PROPERTIES IMPORTED_LOCATION | |||
| ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libmindspore-lite.so) | |||
| set_target_properties(minddata-lite PROPERTIES IMPORTED_LOCATION | |||
| ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libminddata-lite.so) | |||
| # --------------- MindSpore Lite set End. -------------------- | |||
| # Link target library. | |||
| target_link_libraries( | |||
| ... | |||
| # --- mindspore --- | |||
| minddata-lite | |||
| mindspore-lite | |||
| ... | |||
| ) | |||
| ``` | |||
| * In this example, the download.gradle File configuration auto download MindSpore Lite version, placed in the 'app / src / main/cpp/mindspore_lite_x.x.x-minddata-arm64-cpu' directory. | |||
| Note: if the automatic download fails, please manually download the relevant library files and put them in the corresponding location. | |||
| MindSpore Lite version [MindSpore Lite version]( https://download.mindspore.cn/model_zoo/official/lite/lib/mindspore%20version%200.7/libmindspore-lite.so) | |||
| ### Downloading and Deploying a Model File | |||
| In this example, the download.gradle File configuration auto download `mobilenetv2.ms `and placed in the 'app / libs / arm64-v8a' directory. | |||
| Note: if the automatic download fails, please manually download the relevant library files and put them in the corresponding location. | |||
| mobilenetv2.ms [mobilenetv2.ms]( https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_openimage_lite/mobilenetv2.ms) | |||
| ### Compiling On-Device Inference Code | |||
| Call MindSpore Lite C++ APIs at the JNI layer to implement on-device inference. | |||
| The inference code process is as follows. For details about the complete code, see `src/cpp/MindSporeNetnative.cpp`. | |||
| 1. Load the MindSpore Lite model file and build the context, session, and computational graph for inference. | |||
| - Load a model file. Create and configure the context for model inference. | |||
| ```cpp | |||
| // Buffer is the model data passed in by the Java layer | |||
| jlong bufferLen = env->GetDirectBufferCapacity(buffer); | |||
| char *modelBuffer = CreateLocalModelBuffer(env, buffer); | |||
| ``` | |||
| - Create a session. | |||
| ```cpp | |||
| void **labelEnv = new void *; | |||
| MSNetWork *labelNet = new MSNetWork; | |||
| *labelEnv = labelNet; | |||
| // Create context. | |||
| mindspore::lite::Context *context = new mindspore::lite::Context; | |||
| context->thread_num_ = num_thread; | |||
| // Create the mindspore session. | |||
| labelNet->CreateSessionMS(modelBuffer, bufferLen, "device label", context); | |||
| delete(context); | |||
| ``` | |||
| - Load the model file and build a computational graph for inference. | |||
| ```cpp | |||
| void MSNetWork::CreateSessionMS(char* modelBuffer, size_t bufferLen, std::string name, mindspore::lite::Context* ctx) | |||
| { | |||
| CreateSession(modelBuffer, bufferLen, ctx); | |||
| session = mindspore::session::LiteSession::CreateSession(ctx); | |||
| auto model = mindspore::lite::Model::Import(modelBuffer, bufferLen); | |||
| int ret = session->CompileGraph(model); | |||
| } | |||
| ``` | |||
| 2. Convert the input image into the Tensor format of the MindSpore model. | |||
| Convert the image data to be detected into the Tensor format of the MindSpore model. | |||
| ```cpp | |||
| // Convert the Bitmap image passed in from the JAVA layer to Mat for OpenCV processing | |||
| BitmapToMat(env, srcBitmap, matImageSrc); | |||
| // Processing such as zooming the picture size. | |||
| matImgPreprocessed = PreProcessImageData(matImageSrc); | |||
| ImgDims inputDims; | |||
| inputDims.channel = matImgPreprocessed.channels(); | |||
| inputDims.width = matImgPreprocessed.cols; | |||
| inputDims.height = matImgPreprocessed.rows; | |||
| float *dataHWC = new float[inputDims.channel * inputDims.width * inputDims.height] | |||
| // Copy the image data to be detected to the dataHWC array. | |||
| // The dataHWC[image_size] array here is the intermediate variable of the input MindSpore model tensor. | |||
| float *ptrTmp = reinterpret_cast<float *>(matImgPreprocessed.data); | |||
| for(int i = 0; i < inputDims.channel * inputDims.width * inputDims.height; i++){ | |||
| dataHWC[i] = ptrTmp[i]; | |||
| } | |||
| // Assign dataHWC[image_size] to the input tensor variable. | |||
| auto msInputs = mSession->GetInputs(); | |||
| auto inTensor = msInputs.front(); | |||
| memcpy(inTensor->MutableData(), dataHWC, | |||
| inputDims.channel * inputDims.width * inputDims.height * sizeof(float)); | |||
| delete[] (dataHWC); | |||
| ``` | |||
| 3. Perform inference on the input tensor based on the model, obtain the output tensor, and perform post-processing. | |||
| - Perform graph execution and on-device inference. | |||
| ```cpp | |||
| // After the model and image tensor data is loaded, run inference. | |||
| auto status = mSession->RunGraph(); | |||
| ``` | |||
| - Obtain the output data. | |||
| ```cpp | |||
| auto names = mSession->GetOutputTensorNames(); | |||
| std::unordered_map<std::string,mindspore::tensor::MSTensor *> msOutputs; | |||
| for (const auto &name : names) { | |||
| auto temp_dat =mSession->GetOutputByTensorName(name); | |||
| msOutputs.insert(std::pair<std::string, mindspore::tensor::MSTensor *> {name, temp_dat}); | |||
| } | |||
| std::string retStr = ProcessRunnetResult(msOutputs, ret); | |||
| ``` | |||
| - Perform post-processing of the output data. | |||
| ```cpp | |||
| std::string ProcessRunnetResult(std::unordered_map<std::string, | |||
| mindspore::tensor::MSTensor *> msOutputs, int runnetRet) { | |||
| std::unordered_map<std::string, mindspore::tensor::MSTensor *>::iterator iter; | |||
| iter = msOutputs.begin(); | |||
| // The mobilenetv2.ms model output just one branch. | |||
| auto outputTensor = iter->second; | |||
| int tensorNum = outputTensor->ElementsNum(); | |||
| MS_PRINT("Number of tensor elements:%d", tensorNum); | |||
| // Get a pointer to the first score. | |||
| float *temp_scores = static_cast<float * >(outputTensor->MutableData()); | |||
| float scores[RET_CATEGORY_SUM]; | |||
| for (int i = 0; i < RET_CATEGORY_SUM; ++i) { | |||
| if (temp_scores[i] > 0.5) { | |||
| MS_PRINT("MindSpore scores[%d] : [%f]", i, temp_scores[i]); | |||
| } | |||
| scores[i] = temp_scores[i]; | |||
| } | |||
| // Score for each category. | |||
| // Converted to text information that needs to be displayed in the APP. | |||
| std::string categoryScore = ""; | |||
| for (int i = 0; i < RET_CATEGORY_SUM; ++i) { | |||
| categoryScore += labels_name_map[i]; | |||
| categoryScore += ":"; | |||
| std::string score_str = std::to_string(scores[i]); | |||
| categoryScore += score_str; | |||
| categoryScore += ";"; | |||
| } | |||
| return categoryScore; | |||
| } | |||
| ``` | |||
| @@ -1,283 +1,280 @@ | |||
| ## MindSpore Lite 端侧图像分类demo(Android) | |||
| 本示例程序演示了如何在端侧利用MindSpore Lite C++ API(Android JNI)以及MindSpore Lite 图像分类模型完成端侧推理,实现对设备摄像头捕获的内容进行分类,并在App图像预览界面中显示出最可能的分类结果。 | |||
| ### 运行依赖 | |||
| - Android Studio >= 3.2 (推荐4.0以上版本) | |||
| - NDK 21.3 | |||
| - CMake 3.10 | |||
| - Android SDK >= 26 | |||
| - OpenCV >= 4.0.0 | |||
| ### 构建与运行 | |||
| 1. 在Android Studio中加载本示例源码,并安装相应的SDK(指定SDK版本后,由Android Studio自动安装)。 | |||
|  | |||
| 启动Android Studio后,点击`File->Settings->System Settings->Android SDK`,勾选相应的SDK。如下图所示,勾选后,点击`OK`,Android Studio即可自动安装SDK。 | |||
|  | |||
| (可选)若安装时出现NDK版本问题,可手动下载相应的[NDK版本](https://developer.android.com/ndk/downloads?hl=zh-cn)(本示例代码使用的NDK版本为21.3),并在`Project Structure`的`Android NDK location`设置中指定SDK的位置。 | |||
|  | |||
| 2. 连接Android设备,运行图像分类应用程序。 | |||
| 通过USB连接Android设备调试,点击`Run 'app'`即可在您的设备上运行本示例项目。 | |||
| * 注:编译过程中Android Studio会自动下载MindSpore Lite、OpenCV、模型文件等相关依赖项,编译过程需做耐心等待。 | |||
|  | |||
| Android Studio连接设备调试操作,可参考<https://developer.android.com/studio/run/device?hl=zh-cn>。 | |||
| 3. 在Android设备上,点击“继续安装”,安装完即可查看到设备摄像头捕获的内容和推理结果。 | |||
|  | |||
| 如下图所示,识别出的概率最高的物体是植物。 | |||
|  | |||
| ## 示例程序详细说明 | |||
| 本端侧图像分类Android示例程序分为JAVA层和JNI层,其中,JAVA层主要通过Android Camera 2 API实现摄像头获取图像帧,以及相应的图像处理等功能;JNI层完成模型推理的过程。 | |||
| > 此处详细说明示例程序的JNI层实现,JAVA层运用Android Camera 2 API实现开启设备摄像头以及图像帧处理等功能,需读者具备一定的Android开发基础知识。 | |||
| ### 示例程序结构 | |||
| ``` | |||
| app | |||
| | | |||
| ├── libs # 存放demo jni层依赖的库文件 | |||
| │ └── arm64-v8a | |||
| │ ├── libopencv_java4.so # opencv | |||
| │ ├── libmlkit-label-MS.so # ndk编译生成的库文件 | |||
| │ └── libmindspore-lite.so # mindspore lite | |||
| | | |||
| ├── src/main | |||
| │ ├── assets # 资源文件 | |||
| | | └── mobilenetv2.ms # 存放模型文件 | |||
| │ | | |||
| │ ├── cpp # 模型加载和预测主要逻辑封装类 | |||
| | | ├── include # 存放MindSpore调用相关的头文件 | |||
| | | | └── ... | |||
| │ | | | |||
| | | ├── MindSporeNetnative.cpp # MindSpore调用相关的JNI方法 | |||
| │ | └── MindSporeNetnative.h # 头文件 | |||
| │ | | |||
| │ ├── java # java层应用代码 | |||
| │ │ └── com.huawei.himindsporedemo | |||
| │ │ ├── gallery.classify # 图像处理及MindSpore JNI调用相关实现 | |||
| │ │ │ └── ... | |||
| │ │ └── obejctdetect # 开启摄像头及绘制相关实现 | |||
| │ │ └── ... | |||
| │ │ | |||
| │ ├── res # 存放Android相关的资源文件 | |||
| │ └── AndroidManifest.xml # Android配置文件 | |||
| │ | |||
| ├── CMakeList.txt # cmake编译入口文件 | |||
| │ | |||
| ├── build.gradle # 其他Android配置文件 | |||
| ├── download.gradle # APP构建时由gradle自动从HuaWei Server下载依赖的库文件及模型文件 | |||
| └── ... | |||
| ``` | |||
| ### 配置MindSpore Lite依赖项 | |||
| Android JNI层调用MindSpore C++ API时,需要相关库文件支持。可通过MindSpore Lite源码编译生成`libmindspore-lite.so`库文件。 | |||
| 在Android Studio中将编译完成的`libmindspore-lite.so`库文件(可包含多个兼容架构),分别放置在APP工程的`app/libs/arm64-v8a`(ARM64)或`app/libs/armeabi-v7a`(ARM32)目录下,并在应用的`build.gradle`文件中配置CMake编译支持,以及`arm64-v8a`和`armeabi-v7a`的编译支持。 | |||
| 本示例中,build过程由download.gradle文件自动从华为服务器下载libmindspore-lite.so以及OpenCV的libopencv_java4.so库文件,并放置在`app/libs/arm64-v8a`目录下。 | |||
| * 注:若自动下载失败,请手动下载相关库文件并将其放在对应位置: | |||
| libmindspore-lite.so [下载链接](https://download.mindspore.cn/model_zoo/official/lite/lib/mindspore%20version%200.7/libmindspore-lite.so) | |||
| libmindspore-lite include文件 [下载链接](https://download.mindspore.cn/model_zoo/official/lite/lib/mindspore%20version%200.7/include.zip) | |||
| libopencv_java4.so [下载链接](https://download.mindspore.cn/model_zoo/official/lite/lib/opencv%204.4.0/libopencv_java4.so) | |||
| libopencv include文件 [下载链接](https://download.mindspore.cn/model_zoo/official/lite/lib/opencv%204.4.0/include.zip) | |||
| ``` | |||
| android{ | |||
| defaultConfig{ | |||
| externalNativeBuild{ | |||
| cmake{ | |||
| arguments "-DANDROID_STL=c++_shared" | |||
| } | |||
| } | |||
| ndk{ | |||
| abiFilters 'arm64-v8a' | |||
| } | |||
| } | |||
| } | |||
| ``` | |||
| 在`app/CMakeLists.txt`文件中建立`.so`库文件链接,如下所示。 | |||
| ``` | |||
| # Set MindSpore Lite Dependencies. | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include/MindSpore) | |||
| add_library(mindspore-lite SHARED IMPORTED ) | |||
| set_target_properties(mindspore-lite PROPERTIES | |||
| IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/libs/libmindspore-lite.so") | |||
| # Set OpenCV Dependecies. | |||
| include_directories(${CMAKE_SOURCE_DIR}/opencv/sdk/native/jni/include) | |||
| add_library(lib-opencv SHARED IMPORTED ) | |||
| set_target_properties(lib-opencv PROPERTIES | |||
| IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/libs/libopencv_java4.so") | |||
| # Link target library. | |||
| target_link_libraries( | |||
| ... | |||
| mindspore-lite | |||
| lib-opencv | |||
| ... | |||
| ) | |||
| ``` | |||
| ### 下载及部署模型文件 | |||
| 从MindSpore Model Hub中下载模型文件,本示例程序中使用的终端图像分类模型文件为`mobilenetv2.ms`,同样通过download.gradle脚本在APP构建时自动下载,并放置在`app/src/main/assets`工程目录下。 | |||
| * 注:若下载失败请手动下载模型文件,mobilenetv2.ms [下载链接](https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_openimage_lite/mobilenetv2.ms)。 | |||
| ### 编写端侧推理代码 | |||
| 在JNI层调用MindSpore Lite C++ API实现端测推理。 | |||
| 推理代码流程如下,完整代码请参见`src/cpp/MindSporeNetnative.cpp`。 | |||
| 1. 加载MindSpore Lite模型文件,构建上下文、会话以及用于推理的计算图。 | |||
| - 加载模型文件:创建并配置用于模型推理的上下文 | |||
| ```cpp | |||
| // Buffer is the model data passed in by the Java layer | |||
| jlong bufferLen = env->GetDirectBufferCapacity(buffer); | |||
| char *modelBuffer = CreateLocalModelBuffer(env, buffer); | |||
| ``` | |||
| - 创建会话 | |||
| ```cpp | |||
| void **labelEnv = new void *; | |||
| MSNetWork *labelNet = new MSNetWork; | |||
| *labelEnv = labelNet; | |||
| // Create context. | |||
| lite::Context *context = new lite::Context; | |||
| context->thread_num_ = numThread; //Specify the number of threads to run inference | |||
| // Create the mindspore session. | |||
| labelNet->CreateSessionMS(modelBuffer, bufferLen, context); | |||
| delete(context); | |||
| ``` | |||
| - 加载模型文件并构建用于推理的计算图 | |||
| ```cpp | |||
| void MSNetWork::CreateSessionMS(char* modelBuffer, size_t bufferLen, mindspore::lite::Context* ctx) | |||
| { | |||
| CreateSession(modelBuffer, bufferLen, ctx); | |||
| session = mindspore::session::LiteSession::CreateSession(ctx); | |||
| auto model = mindspore::lite::Model::Import(modelBuffer, bufferLen); | |||
| int ret = session->CompileGraph(model); // Compile Graph | |||
| } | |||
| ``` | |||
| 2. 将输入图片转换为传入MindSpore模型的Tensor格式。 | |||
| 将待检测图片数据转换为输入MindSpore模型的Tensor。 | |||
| ```cpp | |||
| // Convert the Bitmap image passed in from the JAVA layer to Mat for OpenCV processing | |||
| BitmapToMat(env, srcBitmap, matImageSrc); | |||
| // Processing such as zooming the picture size. | |||
| matImgPreprocessed = PreProcessImageData(matImageSrc); | |||
| ImgDims inputDims; | |||
| inputDims.channel = matImgPreprocessed.channels(); | |||
| inputDims.width = matImgPreprocessed.cols; | |||
| inputDims.height = matImgPreprocessed.rows; | |||
| float *dataHWC = new float[inputDims.channel * inputDims.width * inputDims.height] | |||
| // Copy the image data to be detected to the dataHWC array. | |||
| // The dataHWC[image_size] array here is the intermediate variable of the input MindSpore model tensor. | |||
| float *ptrTmp = reinterpret_cast<float *>(matImgPreprocessed.data); | |||
| for(int i = 0; i < inputDims.channel * inputDims.width * inputDims.height; i++){ | |||
| dataHWC[i] = ptrTmp[i]; | |||
| } | |||
| // Assign dataHWC[image_size] to the input tensor variable. | |||
| auto msInputs = mSession->GetInputs(); | |||
| auto inTensor = msInputs.front(); | |||
| memcpy(inTensor->MutableData(), dataHWC, | |||
| inputDims.channel * inputDims.width * inputDims.height * sizeof(float)); | |||
| delete[] (dataHWC); | |||
| ``` | |||
| 3. 对输入Tensor按照模型进行推理,获取输出Tensor,并进行后处理。 | |||
| - 图执行,端测推理。 | |||
| ```cpp | |||
| // After the model and image tensor data is loaded, run inference. | |||
| auto status = mSession->RunGraph(); | |||
| ``` | |||
| - 获取输出数据。 | |||
| ```cpp | |||
| // Get the mindspore inference results. | |||
| auto msOutputs = mSession->GetOutputMapByNode(); | |||
| std::string retStr = ProcessRunnetResult(msOutputs); | |||
| ``` | |||
| - 输出数据的后续处理。 | |||
| ```cpp | |||
| std::string ProcessRunnetResult( | |||
| std::unordered_map<std::string, std::vector<mindspore::tensor::MSTensor *>> msOutputs){ | |||
| // Get the branch of the model output. | |||
| // Use iterators to get map elements. | |||
| std::unordered_map<std::string, std::vector<mindspore::tensor::MSTensor *>>::iterator iter; | |||
| iter = msOutputs.begin(); | |||
| // The mobilenetv2.ms model output just one branch. | |||
| auto outputString = iter->first; | |||
| auto outputTensor = iter->second; | |||
| float *temp_scores = static_cast<float * >(branch1_tensor[0]->MutableData()); | |||
| float scores[RET_CATEGORY_SUM]; | |||
| for (int i = 0; i < RET_CATEGORY_SUM; ++i) { | |||
| if (temp_scores[i] > 0.5){ | |||
| MS_PRINT("MindSpore scores[%d] : [%f]", i, temp_scores[i]); | |||
| } | |||
| scores[i] = temp_scores[i]; | |||
| } | |||
| // Converted to text information that needs to be displayed in the APP. | |||
| std::string categoryScore = ""; | |||
| for (int i = 0; i < RET_CATEGORY_SUM; ++i) { | |||
| categoryScore += g_labels_name_map[i]; | |||
| categoryScore += ":"; | |||
| std::string score_str = std::to_string(scores[i]); | |||
| categoryScore += score_str; | |||
| categoryScore += ";"; | |||
| } | |||
| return categoryScore; | |||
| } | |||
| ``` | |||
| ## MindSpore Lite 端侧图像分类demo(Android) | |||
| 本示例程序演示了如何在端侧利用MindSpore Lite C++ API(Android JNI)以及MindSpore Lite 图像分类模型完成端侧推理,实现对设备摄像头捕获的内容进行分类,并在App图像预览界面中显示出最可能的分类结果。 | |||
| ### 运行依赖 | |||
| - Android Studio >= 3.2 (推荐4.0以上版本) | |||
| - NDK 21.3 | |||
| - CMake 3.10.2 [CMake](https://cmake.org/download) | |||
| - Android SDK >= 26 | |||
| - JDK >= 1.8 [JDK]( https://www.oracle.com/downloads/otn-pub/java/JDK/) | |||
| ### 构建与运行 | |||
| 1. 在Android Studio中加载本示例源码,并安装相应的SDK(指定SDK版本后,由Android Studio自动安装)。 | |||
|  | |||
| 启动Android Studio后,点击`File->Settings->System Settings->Android SDK`,勾选相应的SDK。如下图所示,勾选后,点击`OK`,Android Studio即可自动安装SDK。 | |||
|  | |||
| (可选)若安装时出现NDK版本问题,可手动下载相应的[NDK版本](https://developer.android.com/ndk/downloads?hl=zh-cn)(本示例代码使用的NDK版本为21.3),并在`Project Structure`的`Android NDK location`设置中指定SDK的位置。 | |||
|  | |||
| 2. 连接Android设备,运行图像分类应用程序。 | |||
| 通过USB连接Android设备调试,点击`Run 'app'`即可在您的设备上运行本示例项目。 | |||
| * 注:编译过程中Android Studio会自动下载MindSpore Lite、模型文件等相关依赖项,编译过程需做耐心等待。 | |||
|  | |||
| Android Studio连接设备调试操作,可参考<https://developer.android.com/studio/run/device?hl=zh-cn>。 | |||
| 手机需开启“USB调试模式”,Android Studio 才能识别到手机。 华为手机一般在设置->系统和更新->开发人员选项->USB调试中开始“USB调试模型”。 | |||
| 3. 在Android设备上,点击“继续安装”,安装完即可查看到设备摄像头捕获的内容和推理结果。 | |||
|  | |||
| 如下图所示,识别出的概率最高的物体是植物。 | |||
|  | |||
| ## 示例程序详细说明 | |||
| 本端侧图像分类Android示例程序分为JAVA层和JNI层,其中,JAVA层主要通过Android Camera 2 API实现摄像头获取图像帧,以及相应的图像处理等功能;JNI层完成模型推理的过程。 | |||
| > 此处详细说明示例程序的JNI层实现,JAVA层运用Android Camera 2 API实现开启设备摄像头以及图像帧处理等功能,需读者具备一定的Android开发基础知识。 | |||
| ### 示例程序结构 | |||
| ``` | |||
| app | |||
| ├── src/main | |||
| │ ├── assets # 资源文件 | |||
| | | └── mobilenetv2.ms # 存放模型文件 | |||
| │ | | |||
| │ ├── cpp # 模型加载和预测主要逻辑封装类 | |||
| | | ├── .. | |||
| | | ├── mindspore_lite_x.x.x-minddata-arm64-cpu #MindSpore Lite版本 | |||
| | | ├── MindSporeNetnative.cpp # MindSpore调用相关的JNI方法 | |||
| │ | └── MindSporeNetnative.h # 头文件 | |||
| | | └── MsNetWork.cpp # MindSpre接口封装 | |||
| │ | | |||
| │ ├── java # java层应用代码 | |||
| │ │ └── com.huawei.himindsporedemo | |||
| │ │ ├── gallery.classify # 图像处理及MindSpore JNI调用相关实现 | |||
| │ │ │ └── ... | |||
| │ │ └── widget # 开启摄像头及绘制相关实现 | |||
| │ │ └── ... | |||
| │ │ | |||
| │ ├── res # 存放Android相关的资源文件 | |||
| │ └── AndroidManifest.xml # Android配置文件 | |||
| │ | |||
| ├── CMakeList.txt # cmake编译入口文件 | |||
| │ | |||
| ├── build.gradle # 其他Android配置文件 | |||
| ├── download.gradle # 工程依赖文件下载 | |||
| └── ... | |||
| ``` | |||
| ### 配置MindSpore Lite依赖项 | |||
| Android JNI层调用MindSpore C++ API时,需要相关库文件支持。可通过MindSpore Lite源码编译生成`libmindspore-lite.so`库文件。 | |||
| 本示例中,build过程由download.gradle文件自动从华为服务器下载MindSpore Lite 版本文件,并放置在`app / src / main/cpp/mindspore_lite_x.x.x-minddata-arm64-cpu`目录下。 | |||
| * 注:若自动下载失败,请手动下载相关库文件并将其放在对应位置: | |||
| MindSpore Lite版本 [下载链接](https://download.mindspore.cn/model_zoo/official/lite/lib/mindspore%20version%200.7/libmindspore-lite.so) | |||
| ``` | |||
| android{ | |||
| defaultConfig{ | |||
| externalNativeBuild{ | |||
| cmake{ | |||
| arguments "-DANDROID_STL=c++_shared" | |||
| } | |||
| } | |||
| ndk{ | |||
| abiFilters 'arm64-v8a' | |||
| } | |||
| } | |||
| } | |||
| ``` | |||
| 在`app/CMakeLists.txt`文件中建立`.so`库文件链接,如下所示。 | |||
| ``` | |||
| # ============== Set MindSpore Dependencies. ============= | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/third_party/flatbuffers/include) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/ir/dtype) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/schema) | |||
| add_library(mindspore-lite SHARED IMPORTED ) | |||
| add_library(minddata-lite SHARED IMPORTED ) | |||
| set_target_properties(mindspore-lite PROPERTIES IMPORTED_LOCATION | |||
| ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libmindspore-lite.so) | |||
| set_target_properties(minddata-lite PROPERTIES IMPORTED_LOCATION | |||
| ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libminddata-lite.so) | |||
| # --------------- MindSpore Lite set End. -------------------- | |||
| # Link target library. | |||
| target_link_libraries( | |||
| ... | |||
| # --- mindspore --- | |||
| minddata-lite | |||
| mindspore-lite | |||
| ... | |||
| ) | |||
| ``` | |||
| ### 下载及部署模型文件 | |||
| 从MindSpore Model Hub中下载模型文件,本示例程序中使用的终端图像分类模型文件为`mobilenetv2.ms`,同样通过download.gradle脚本在APP构建时自动下载,并放置在`app/src/main/assets`工程目录下。 | |||
| * 注:若下载失败请手动下载模型文件,mobilenetv2.ms [下载链接](https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_openimage_lite/mobilenetv2.ms)。 | |||
| ### 编写端侧推理代码 | |||
| 在JNI层调用MindSpore Lite C++ API实现端测推理。 | |||
| 推理代码流程如下,完整代码请参见`src/cpp/MindSporeNetnative.cpp`。 | |||
| 1. 加载MindSpore Lite模型文件,构建上下文、会话以及用于推理的计算图。 | |||
| - 加载模型文件:创建并配置用于模型推理的上下文 | |||
| ```cpp | |||
| // Buffer is the model data passed in by the Java layer | |||
| jlong bufferLen = env->GetDirectBufferCapacity(buffer); | |||
| char *modelBuffer = CreateLocalModelBuffer(env, buffer); | |||
| ``` | |||
| - 创建会话 | |||
| ```cpp | |||
| void **labelEnv = new void *; | |||
| MSNetWork *labelNet = new MSNetWork; | |||
| *labelEnv = labelNet; | |||
| // Create context. | |||
| lite::Context *context = new lite::Context; | |||
| context->thread_num_ = numThread; //Specify the number of threads to run inference | |||
| // Create the mindspore session. | |||
| labelNet->CreateSessionMS(modelBuffer, bufferLen, context); | |||
| delete(context); | |||
| ``` | |||
| - 加载模型文件并构建用于推理的计算图 | |||
| ```cpp | |||
| void MSNetWork::CreateSessionMS(char* modelBuffer, size_t bufferLen, std::string name, mindspore::lite::Context* ctx) | |||
| { | |||
| CreateSession(modelBuffer, bufferLen, ctx); | |||
| session = mindspore::session::LiteSession::CreateSession(ctx); | |||
| auto model = mindspore::lite::Model::Import(modelBuffer, bufferLen); | |||
| int ret = session->CompileGraph(model); | |||
| } | |||
| ``` | |||
| 2. 将输入图片转换为传入MindSpore模型的Tensor格式。 | |||
| 将待检测图片数据转换为输入MindSpore模型的Tensor。 | |||
| ```cpp | |||
| // Convert the Bitmap image passed in from the JAVA layer to Mat for OpenCV processing | |||
| BitmapToMat(env, srcBitmap, matImageSrc); | |||
| // Processing such as zooming the picture size. | |||
| matImgPreprocessed = PreProcessImageData(matImageSrc); | |||
| ImgDims inputDims; | |||
| inputDims.channel = matImgPreprocessed.channels(); | |||
| inputDims.width = matImgPreprocessed.cols; | |||
| inputDims.height = matImgPreprocessed.rows; | |||
| float *dataHWC = new float[inputDims.channel * inputDims.width * inputDims.height] | |||
| // Copy the image data to be detected to the dataHWC array. | |||
| // The dataHWC[image_size] array here is the intermediate variable of the input MindSpore model tensor. | |||
| float *ptrTmp = reinterpret_cast<float *>(matImgPreprocessed.data); | |||
| for(int i = 0; i < inputDims.channel * inputDims.width * inputDims.height; i++){ | |||
| dataHWC[i] = ptrTmp[i]; | |||
| } | |||
| // Assign dataHWC[image_size] to the input tensor variable. | |||
| auto msInputs = mSession->GetInputs(); | |||
| auto inTensor = msInputs.front(); | |||
| memcpy(inTensor->MutableData(), dataHWC, | |||
| inputDims.channel * inputDims.width * inputDims.height * sizeof(float)); | |||
| delete[] (dataHWC); | |||
| ``` | |||
| 3. 对输入Tensor按照模型进行推理,获取输出Tensor,并进行后处理。 | |||
| - 图执行,端测推理。 | |||
| ```cpp | |||
| // After the model and image tensor data is loaded, run inference. | |||
| auto status = mSession->RunGraph(); | |||
| ``` | |||
| - 获取输出数据。 | |||
| ```cpp | |||
| auto names = mSession->GetOutputTensorNames(); | |||
| std::unordered_map<std::string,mindspore::tensor::MSTensor *> msOutputs; | |||
| for (const auto &name : names) { | |||
| auto temp_dat =mSession->GetOutputByTensorName(name); | |||
| msOutputs.insert(std::pair<std::string, mindspore::tensor::MSTensor *> {name, temp_dat}); | |||
| } | |||
| std::string retStr = ProcessRunnetResult(msOutputs, ret); | |||
| ``` | |||
| - 输出数据的后续处理。 | |||
| ```cpp | |||
| std::string ProcessRunnetResult(std::unordered_map<std::string, | |||
| mindspore::tensor::MSTensor *> msOutputs, int runnetRet) { | |||
| std::unordered_map<std::string, mindspore::tensor::MSTensor *>::iterator iter; | |||
| iter = msOutputs.begin(); | |||
| // The mobilenetv2.ms model output just one branch. | |||
| auto outputTensor = iter->second; | |||
| int tensorNum = outputTensor->ElementsNum(); | |||
| MS_PRINT("Number of tensor elements:%d", tensorNum); | |||
| // Get a pointer to the first score. | |||
| float *temp_scores = static_cast<float * >(outputTensor->MutableData()); | |||
| float scores[RET_CATEGORY_SUM]; | |||
| for (int i = 0; i < RET_CATEGORY_SUM; ++i) { | |||
| if (temp_scores[i] > 0.5) { | |||
| MS_PRINT("MindSpore scores[%d] : [%f]", i, temp_scores[i]); | |||
| } | |||
| scores[i] = temp_scores[i]; | |||
| } | |||
| // Score for each category. | |||
| // Converted to text information that needs to be displayed in the APP. | |||
| std::string categoryScore = ""; | |||
| for (int i = 0; i < RET_CATEGORY_SUM; ++i) { | |||
| categoryScore += labels_name_map[i]; | |||
| categoryScore += ":"; | |||
| std::string score_str = std::to_string(scores[i]); | |||
| categoryScore += score_str; | |||
| categoryScore += ";"; | |||
| } | |||
| return categoryScore; | |||
| } | |||
| ``` | |||
| @@ -6,39 +6,28 @@ | |||
| cmake_minimum_required(VERSION 3.4.1) | |||
| set(CMAKE_VERBOSE_MAKEFILE on) | |||
| set(libs ${CMAKE_SOURCE_DIR}/libs) | |||
| set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}) | |||
| set(MINDSPORELITE_VERSION mindspore-lite-0.7.0-minddata-arm64-cpu) | |||
| # ============== Set MindSpore Dependencies. ============= | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include/MindSpore) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include/MindSpore/flatbuffers) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include/MindSpore/ir/dtype) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include/MindSpore/schema) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/third_party/flatbuffers/include) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/ir/dtype) | |||
| include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/include/schema) | |||
| add_library(mindspore-lite SHARED IMPORTED ) | |||
| add_library(minddata-lite SHARED IMPORTED ) | |||
| set_target_properties(mindspore-lite PROPERTIES IMPORTED_LOCATION | |||
| ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libmindspore-lite.so) | |||
| ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libmindspore-lite.so) | |||
| set_target_properties(minddata-lite PROPERTIES IMPORTED_LOCATION | |||
| ${CMAKE_SOURCE_DIR}/src/main/cpp/${MINDSPORELITE_VERSION}/lib/libminddata-lite.so) | |||
| # --------------- MindSpore Lite set End. -------------------- | |||
| # =============== Set OpenCV Dependencies =================== | |||
| include_directories(${CMAKE_SOURCE_DIR}/opencv/sdk/native/jni/include/) | |||
| add_library(lib-opencv SHARED IMPORTED ) | |||
| set_target_properties(lib-opencv PROPERTIES IMPORTED_LOCATION | |||
| ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libopencv_java4.so) | |||
| # --------------- OpenCV set End. --------------------------- | |||
| # Creates and names a library, sets it as either STATIC | |||
| # or SHARED, and provides the relative paths to its source code. | |||
| # You can define multiple libraries, and CMake builds them for you. | |||
| @@ -79,10 +68,8 @@ add_definitions(-DMNN_USE_LOGCAT) | |||
| target_link_libraries( # Specifies the target library. | |||
| mlkit-label-MS | |||
| # --- opencv --- | |||
| lib-opencv | |||
| # --- mindspore --- | |||
| minddata-lite | |||
| mindspore-lite | |||
| # --- other dependencies.--- | |||
| @@ -49,7 +49,7 @@ android { | |||
| } | |||
| } | |||
| packagingOptions{ | |||
| pickFirst 'lib/arm64-v8a/libopencv_java4.so' | |||
| pickFirst 'lib/arm64-v8a/libminddata-lite.so' | |||
| pickFirst 'lib/arm64-v8a/libmindspore-lite.so' | |||
| pickFirst 'lib/arm64-v8a/libmlkit-label-MS.so' | |||
| } | |||
| @@ -1,27 +1,18 @@ | |||
| /** | |||
| * To download necessary library from HuaWei server. | |||
| * Including mindspore-lite .so file, opencv .so file and model file. | |||
| * Including mindspore-lite .so file, minddata-lite .so file and model file. | |||
| * The libraries can be downloaded manually. | |||
| */ | |||
| def targetopenCVInclude = "src/main/cpp/include" | |||
| def targetMindSporeInclude = "src/main/cpp/include" | |||
| def targetMindSporeInclude = "src/main/cpp/" | |||
| def mindsporeLite_Version = "mindspore-lite-0.7.0-minddata-arm64-cpu" | |||
| def targetModelFile = "src/main/assets/model/mobilenetv2.ms" | |||
| def openCVLibrary_arm64 = "libs/arm64-v8a/libopencv_java4.so" | |||
| def mindSporeLibrary_arm64 = "libs/arm64-v8a/libmindspore-lite.so" | |||
| def openCVlibIncluding_arm64 = "src/main/cpp/include/opencv2/include.zip" | |||
| def mindSporeLibIncluding_arm64 = "src/main/cpp/include/MindSpore/include.zip" | |||
| def mindSporeLibrary_arm64 = "src/main/cpp/${mindsporeLite_Version}.tar.gz" | |||
| def modelDownloadUrl = "https://download.mindspore.cn/model_zoo/official/lite/mobilenetv2_openimage_lite/mobilenetv2.ms" | |||
| def opencvDownloadUrl = "https://download.mindspore.cn/model_zoo/official/lite/lib/opencv%204.4.0/libopencv_java4.so" | |||
| def mindsporeLiteDownloadUrl = "https://download.mindspore.cn/model_zoo/official/lite/lib/mindspore%20version%200.7/libmindspore-lite.so" | |||
| def opencvincludeDownloadUrl = "https://download.mindspore.cn/model_zoo/official/lite/lib/opencv%204.4.0/include.zip" | |||
| def mindsporeIncludeDownloadUrl = "https://download.mindspore.cn/model_zoo/official/lite/lib/mindspore%20version%200.7/include.zip" | |||
| def mindsporeLiteDownloadUrl = "https://download.mindspore.cn/model_zoo/official/lite/lib/mindspore%20version%201.0/${mindsporeLite_Version}.tar.gz" | |||
| def cleantargetopenCVInclude = "src/main/cpp/include/opencv2" | |||
| def cleantargetMindSporeInclude = "src/main/cpp/include/MindSpore" | |||
| def cleantargetMindSporeInclude = "src/main/cpp" | |||
| task downloadModelFile(type: DownloadUrlTask) { | |||
| @@ -32,15 +23,6 @@ task downloadModelFile(type: DownloadUrlTask) { | |||
| target = file("${targetModelFile}") | |||
| } | |||
| task downloadOpenCVLibrary(type: DownloadUrlTask) { | |||
| doFirst { | |||
| println "Downloading ${opencvDownloadUrl}" | |||
| } | |||
| sourceUrl = "${opencvDownloadUrl}" | |||
| target = file("${openCVLibrary_arm64}") | |||
| } | |||
| task downloadMindSporeLibrary(type: DownloadUrlTask) { | |||
| doFirst { | |||
| println "Downloading ${mindsporeLiteDownloadUrl}" | |||
| @@ -49,80 +31,36 @@ task downloadMindSporeLibrary(type: DownloadUrlTask) { | |||
| target = file("${mindSporeLibrary_arm64}") | |||
| } | |||
| task downloadopecvIncludeLibrary(type: DownloadUrlTask) { | |||
| doFirst { | |||
| println "Downloading ${opencvincludeDownloadUrl}" | |||
| } | |||
| sourceUrl = "${opencvincludeDownloadUrl}" | |||
| target = file("${openCVlibIncluding_arm64}") | |||
| } | |||
| task downloadMindSporeIncludeLibrary(type: DownloadUrlTask) { | |||
| doFirst { | |||
| println "Downloading ${mindsporeIncludeDownloadUrl}" | |||
| } | |||
| sourceUrl = "${mindsporeIncludeDownloadUrl}" | |||
| target = file("${mindSporeLibIncluding_arm64}") | |||
| } | |||
| task unzipopencvInclude(type: Copy, dependsOn: 'downloadopecvIncludeLibrary') { | |||
| task unzipMindSporeInclude(type: Copy, dependsOn: 'downloadMindSporeLibrary') { | |||
| doFirst { | |||
| println "Unzipping ${openCVlibIncluding_arm64}" | |||
| println "Unzipping ${mindSporeLibrary_arm64}" | |||
| } | |||
| from zipTree("${openCVlibIncluding_arm64}") | |||
| into "${targetopenCVInclude}" | |||
| } | |||
| task unzipMindSporeInclude(type: Copy, dependsOn: 'downloadMindSporeIncludeLibrary') { | |||
| doFirst { | |||
| println "Unzipping ${mindSporeLibIncluding_arm64}" | |||
| } | |||
| from zipTree("${mindSporeLibIncluding_arm64}") | |||
| from tarTree(resources.gzip("${mindSporeLibrary_arm64}")) | |||
| into "${targetMindSporeInclude}" | |||
| } | |||
| task cleanUnusedopencvFiles(type: Delete, dependsOn: ['unzipopencvInclude']) { | |||
| delete fileTree("${cleantargetopenCVInclude}").matching { | |||
| include "*.zip" | |||
| } | |||
| } | |||
| task cleanUnusedmindsporeFiles(type: Delete, dependsOn: ['unzipMindSporeInclude']) { | |||
| delete fileTree("${cleantargetMindSporeInclude}").matching { | |||
| include "*.zip" | |||
| include "*.tar.gz" | |||
| } | |||
| } | |||
| /* | |||
| * Using preBuild to download mindspore library, opencv library and model file. | |||
| * Run before gradle build. | |||
| */ | |||
| if (file("libs/arm64-v8a/libmindspore-lite.so").exists()){ | |||
| if (file("src/main/cpp/${mindsporeLite_Version}/lib/libmindspore-lite.so").exists()){ | |||
| downloadMindSporeLibrary.enabled = false | |||
| unzipMindSporeInclude.enabled = false | |||
| cleanUnusedmindsporeFiles.enabled = false | |||
| } | |||
| if (file("libs/arm64-v8a/libopencv_java4.so").exists()){ | |||
| downloadOpenCVLibrary.enabled = false | |||
| } | |||
| if (file("src/main/assets/model/mobilenetv2.ms").exists()){ | |||
| downloadModelFile.enabled = false | |||
| } | |||
| if (file("src/main/cpp/include/MindSpore/lite_session.h").exists()){ | |||
| downloadMindSporeIncludeLibrary.enabled = false | |||
| unzipopencvInclude.enabled = false | |||
| cleanUnusedopencvFiles.enabled =false | |||
| } | |||
| if (file("src/main/cpp/include/opencv2/core.hpp").exists()){ | |||
| downloadopecvIncludeLibrary.enabled = false | |||
| unzipMindSporeInclude.enabled = false | |||
| cleanUnusedmindsporeFiles.enabled =false | |||
| } | |||
| preBuild.dependsOn downloadMindSporeLibrary | |||
| preBuild.dependsOn downloadOpenCVLibrary | |||
| preBuild.dependsOn downloadModelFile | |||
| preBuild.dependsOn unzipopencvInclude | |||
| preBuild.dependsOn downloadMindSporeLibrary | |||
| preBuild.dependsOn unzipMindSporeInclude | |||
| preBuild.dependsOn cleanUnusedopencvFiles | |||
| preBuild.dependsOn cleanUnusedmindsporeFiles | |||
| class DownloadUrlTask extends DefaultTask { | |||
| @@ -18,7 +18,7 @@ | |||
| #include <android/log.h> | |||
| #include <iostream> | |||
| #include <string> | |||
| #include "include/MindSpore/errorcode.h" | |||
| #include "include/errorcode.h" | |||
| #define MS_PRINT(format, ...) __android_log_print(ANDROID_LOG_INFO, "MSJNI", format, ##__VA_ARGS__) | |||
| @@ -54,8 +54,6 @@ int MSNetWork::ReleaseNets(void) { | |||
| return 0; | |||
| } | |||
| const int MSNetWork::RET_CATEGORY_SUM = 601; | |||
| const char *MSNetWork::labels_name_map[MSNetWork::RET_CATEGORY_SUM] = { | |||
| {"Tortoise"}, {"Container"}, {"Magpie"}, {"Seaturtle"}, {"Football"}, {"Ambulance"}, {"Ladder"}, | |||
| {"Toothbrush"}, {"Syringe"}, {"Sink"}, {"Toy"}, {"Organ(MusicalInstrument) "}, {"Cassettedeck"}, | |||
| @@ -52,10 +52,9 @@ class MSNetWork { | |||
| int ReleaseNets(void); | |||
| private: | |||
| mindspore::session::LiteSession *session; | |||
| mindspore::lite::Model *model; | |||
| static const int RET_CATEGORY_SUM; | |||
| static const int RET_CATEGORY_SUM = 601; | |||
| static const char *labels_name_map[RET_CATEGORY_SUM]; | |||
| }; | |||
| #endif | |||
| @@ -13,104 +13,27 @@ | |||
| * See the License for the specific language governing permissions and | |||
| * limitations under the License. | |||
| */ | |||
| #include <jni.h> | |||
| #include <android/bitmap.h> | |||
| #include <android/asset_manager_jni.h> | |||
| #include <android/log.h> | |||
| #include <MindSpore/errorcode.h> | |||
| #include <MindSpore/ms_tensor.h> | |||
| #include <jni.h> | |||
| #include <cstring> | |||
| #include <vector> | |||
| #include <string> | |||
| #include <unordered_map> | |||
| #include <set> | |||
| #include "include/errorcode.h" | |||
| #include "include/ms_tensor.h" | |||
| #include "MindSporeNetnative.h" | |||
| #include "opencv2/core.hpp" | |||
| #include "opencv2/imgproc.hpp" | |||
| #include "MSNetWork.h" | |||
| #include "lite_cv/lite_mat.h" | |||
| #include "lite_cv/image_process.h" | |||
| using mindspore::dataset::LiteMat; | |||
| using mindspore::dataset::LPixelType; | |||
| using mindspore::dataset::LDataType; | |||
| #define MS_PRINT(format, ...) __android_log_print(ANDROID_LOG_INFO, "MSJNI", format, ##__VA_ARGS__) | |||
| void BitmapToMat2(JNIEnv *env, const jobject &bitmap, cv::Mat *mat, | |||
| jboolean needUnPremultiplyAlpha) { | |||
| AndroidBitmapInfo info; | |||
| void *pixels = nullptr; | |||
| cv::Mat &dst = *mat; | |||
| CV_Assert(AndroidBitmap_getInfo(env, bitmap, &info) >= 0); | |||
| CV_Assert(info.format == ANDROID_BITMAP_FORMAT_RGBA_8888 || | |||
| info.format == ANDROID_BITMAP_FORMAT_RGB_565); | |||
| CV_Assert(AndroidBitmap_lockPixels(env, bitmap, &pixels) >= 0); | |||
| CV_Assert(pixels); | |||
| dst.create(info.height, info.width, CV_8UC4); | |||
| if (info.format == ANDROID_BITMAP_FORMAT_RGBA_8888) { | |||
| cv::Mat tmp(info.height, info.width, CV_8UC4, pixels); | |||
| if (needUnPremultiplyAlpha) { | |||
| cvtColor(tmp, dst, cv::COLOR_RGBA2BGR); | |||
| } else { | |||
| tmp.copyTo(dst); | |||
| } | |||
| } else { | |||
| cv::Mat tmp(info.height, info.width, CV_8UC4, pixels); | |||
| cvtColor(tmp, dst, cv::COLOR_BGR5652RGBA); | |||
| } | |||
| AndroidBitmap_unlockPixels(env, bitmap); | |||
| return; | |||
| } | |||
| void BitmapToMat(JNIEnv *env, const jobject &bitmap, cv::Mat *mat) { | |||
| BitmapToMat2(env, bitmap, mat, true); | |||
| } | |||
| /** | |||
| * Processing image with resize and normalize. | |||
| */ | |||
| cv::Mat PreProcessImageData(cv::Mat input) { | |||
| cv::Mat imgFloatTmp, imgResized256, imgResized224; | |||
| int resizeWidth = 256; | |||
| int resizeHeight = 256; | |||
| float normalizMin = 1.0; | |||
| float normalizMax = 255.0; | |||
| cv::resize(input, imgFloatTmp, cv::Size(resizeWidth, resizeHeight)); | |||
| imgFloatTmp.convertTo(imgResized256, CV_32FC3, normalizMin / normalizMax); | |||
| const int offsetX = 16; | |||
| const int offsetY = 16; | |||
| const int cropWidth = 224; | |||
| const int cropHeight = 224; | |||
| // Standardization processing. | |||
| float meanR = 0.485; | |||
| float meanG = 0.456; | |||
| float meanB = 0.406; | |||
| float varR = 0.229; | |||
| float varG = 0.224; | |||
| float varB = 0.225; | |||
| cv::Rect roi; | |||
| roi.x = offsetX; | |||
| roi.y = offsetY; | |||
| roi.width = cropWidth; | |||
| roi.height = cropHeight; | |||
| // The final image size of the incoming model is 224*224. | |||
| imgResized256(roi).copyTo(imgResized224); | |||
| cv::Scalar mean = cv::Scalar(meanR, meanG, meanB); | |||
| cv::Scalar var = cv::Scalar(varR, varG, varB); | |||
| cv::Mat imgResized1; | |||
| cv::Mat imgResized2; | |||
| cv::Mat imgMean(imgResized224.size(), CV_32FC3, | |||
| mean); // imgMean Each pixel channel is (0.485, 0.456, 0.406) | |||
| cv::Mat imgVar(imgResized224.size(), CV_32FC3, | |||
| var); // imgVar Each pixel channel is (0.229, 0.224, 0.225) | |||
| imgResized1 = imgResized224 - imgMean; | |||
| imgResized2 = imgResized1 / imgVar; | |||
| return imgResized2; | |||
| } | |||
| char *CreateLocalModelBuffer(JNIEnv *env, jobject modelBuffer) { | |||
| jbyte *modelAddr = static_cast<jbyte *>(env->GetDirectBufferAddress(modelBuffer)); | |||
| int modelLen = static_cast<int>(env->GetDirectBufferCapacity(modelBuffer)); | |||
| @@ -126,21 +49,20 @@ char *CreateLocalModelBuffer(JNIEnv *env, jobject modelBuffer) { | |||
| */ | |||
| std::string | |||
| ProcessRunnetResult(const int RET_CATEGORY_SUM, const char *const labels_name_map[], | |||
| std::unordered_map<std::string, | |||
| std::vector<mindspore::tensor::MSTensor *>> msOutputs) { | |||
| std::unordered_map<std::string, mindspore::tensor::MSTensor *> msOutputs) { | |||
| // Get the branch of the model output. | |||
| // Use iterators to get map elements. | |||
| std::unordered_map<std::string, std::vector<mindspore::tensor::MSTensor *>>::iterator iter; | |||
| std::unordered_map<std::string, mindspore::tensor::MSTensor *>::iterator iter; | |||
| iter = msOutputs.begin(); | |||
| // The mobilenetv2.ms model output just one branch. | |||
| auto outputTensor = iter->second; | |||
| int tensorNum = outputTensor[0]->ElementsNum(); | |||
| int tensorNum = outputTensor->ElementsNum(); | |||
| MS_PRINT("Number of tensor elements:%d", tensorNum); | |||
| // Get a pointer to the first score. | |||
| float *temp_scores = static_cast<float * >(outputTensor[0]->MutableData()); | |||
| float *temp_scores = static_cast<float * >(outputTensor->MutableData()); | |||
| float scores[RET_CATEGORY_SUM]; | |||
| for (int i = 0; i < RET_CATEGORY_SUM; ++i) { | |||
| @@ -163,6 +85,72 @@ ProcessRunnetResult(const int RET_CATEGORY_SUM, const char *const labels_name_ma | |||
| return categoryScore; | |||
| } | |||
| bool BitmapToLiteMat(JNIEnv *env, const jobject &srcBitmap, LiteMat *lite_mat) { | |||
| bool ret = false; | |||
| AndroidBitmapInfo info; | |||
| void *pixels = nullptr; | |||
| LiteMat &lite_mat_bgr = *lite_mat; | |||
| AndroidBitmap_getInfo(env, srcBitmap, &info); | |||
| if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) { | |||
| MS_PRINT("Image Err, Request RGBA"); | |||
| return false; | |||
| } | |||
| AndroidBitmap_lockPixels(env, srcBitmap, &pixels); | |||
| if (info.stride == info.width*4) { | |||
| ret = InitFromPixel(reinterpret_cast<const unsigned char *>(pixels), | |||
| LPixelType::RGBA2RGB, LDataType::UINT8, | |||
| info.width, info.height, lite_mat_bgr); | |||
| if (!ret) { | |||
| MS_PRINT("Init From RGBA error"); | |||
| } | |||
| } else { | |||
| unsigned char *pixels_ptr = new unsigned char[info.width*info.height*4]; | |||
| unsigned char *ptr = pixels_ptr; | |||
| unsigned char *data = reinterpret_cast<unsigned char *>(pixels); | |||
| for (int i = 0; i < info.height; i++) { | |||
| memcpy(ptr, data, info.width*4); | |||
| ptr += info.width*4; | |||
| data += info.stride; | |||
| } | |||
| ret = InitFromPixel(reinterpret_cast<const unsigned char *>(pixels_ptr), | |||
| LPixelType::RGBA2RGB, LDataType::UINT8, | |||
| info.width, info.height, lite_mat_bgr); | |||
| if (!ret) { | |||
| MS_PRINT("Init From RGBA error"); | |||
| } | |||
| delete[] (pixels_ptr); | |||
| } | |||
| AndroidBitmap_unlockPixels(env, srcBitmap); | |||
| return ret; | |||
| } | |||
| bool PreProcessImageData(const LiteMat &lite_mat_bgr, LiteMat *lite_norm_mat_ptr) { | |||
| bool ret = false; | |||
| LiteMat lite_mat_resize; | |||
| LiteMat &lite_norm_mat_cut = *lite_norm_mat_ptr; | |||
| ret = ResizeBilinear(lite_mat_bgr, lite_mat_resize, 256, 256); | |||
| if (!ret) { | |||
| MS_PRINT("ResizeBilinear error"); | |||
| return false; | |||
| } | |||
| LiteMat lite_mat_convert_float; | |||
| ret = ConvertTo(lite_mat_resize, lite_mat_convert_float, 1.0 / 255.0); | |||
| if (!ret) { | |||
| MS_PRINT("ConvertTo error"); | |||
| return false; | |||
| } | |||
| LiteMat lite_mat_cut; | |||
| ret = Crop(lite_mat_convert_float, lite_mat_cut, 16, 16, 224, 224); | |||
| if (!ret) { | |||
| MS_PRINT("Crop error"); | |||
| return false; | |||
| } | |||
| float means[3] = {0.485, 0.456, 0.406}; | |||
| float vars[3] = {1.0 / 0.229, 1.0 / 0.224, 1.0 / 0.225}; | |||
| SubStractMeanNormalize(lite_mat_cut, lite_norm_mat_cut, means, vars); | |||
| return true; | |||
| } | |||
| /** | |||
| * The Java layer reads the model into MappedByteBuffer or ByteBuffer to load the model. | |||
| @@ -170,9 +158,9 @@ ProcessRunnetResult(const int RET_CATEGORY_SUM, const char *const labels_name_ma | |||
| extern "C" | |||
| JNIEXPORT jlong JNICALL | |||
| Java_com_mindspore_himindsporedemo_gallery_classify_TrackingMobile_loadModel(JNIEnv *env, | |||
| jobject thiz, | |||
| jobject model_buffer, | |||
| jint num_thread) { | |||
| jobject thiz, | |||
| jobject model_buffer, | |||
| jint num_thread) { | |||
| if (nullptr == model_buffer) { | |||
| MS_PRINT("error, buffer is nullptr!"); | |||
| return (jlong) nullptr; | |||
| @@ -220,16 +208,23 @@ Java_com_mindspore_himindsporedemo_gallery_classify_TrackingMobile_loadModel(JNI | |||
| */ | |||
| extern "C" JNIEXPORT jstring JNICALL | |||
| Java_com_mindspore_himindsporedemo_gallery_classify_TrackingMobile_runNet(JNIEnv *env, jclass type, | |||
| jlong netEnv, | |||
| jobject srcBitmap) { | |||
| cv::Mat matImageSrc; | |||
| BitmapToMat(env, srcBitmap, &matImageSrc); | |||
| cv::Mat matImgPreprocessed = PreProcessImageData(matImageSrc); | |||
| jlong netEnv, | |||
| jobject srcBitmap) { | |||
| LiteMat lite_mat_bgr, lite_norm_mat_cut; | |||
| if (!BitmapToLiteMat(env, srcBitmap, &lite_mat_bgr)) { | |||
| MS_PRINT("BitmapToLiteMat error"); | |||
| return NULL; | |||
| } | |||
| if (!PreProcessImageData(lite_mat_bgr, &lite_norm_mat_cut)) { | |||
| MS_PRINT("PreProcessImageData error"); | |||
| return NULL; | |||
| } | |||
| ImgDims inputDims; | |||
| inputDims.channel = matImgPreprocessed.channels(); | |||
| inputDims.width = matImgPreprocessed.cols; | |||
| inputDims.height = matImgPreprocessed.rows; | |||
| inputDims.channel = lite_norm_mat_cut.channel_; | |||
| inputDims.width = lite_norm_mat_cut.width_; | |||
| inputDims.height = lite_norm_mat_cut.height_; | |||
| // Get the mindsore inference environment which created in loadModel(). | |||
| void **labelEnv = reinterpret_cast<void **>(netEnv); | |||
| @@ -253,17 +248,10 @@ Java_com_mindspore_himindsporedemo_gallery_classify_TrackingMobile_runNet(JNIEnv | |||
| } | |||
| auto inTensor = msInputs.front(); | |||
| // dataHWC is the tensor format. | |||
| float *dataHWC = new float[inputDims.channel * inputDims.width * inputDims.height]; | |||
| float *ptrTmp = reinterpret_cast<float *>(matImgPreprocessed.data); | |||
| for (int i = 0; i < inputDims.channel * inputDims.width * inputDims.height; ++i) { | |||
| dataHWC[i] = ptrTmp[i]; | |||
| } | |||
| float *dataHWC = reinterpret_cast<float *>(lite_norm_mat_cut.data_ptr_); | |||
| // Copy dataHWC to the model input tensor. | |||
| memcpy(inTensor->MutableData(), dataHWC, | |||
| inputDims.channel * inputDims.width * inputDims.height * sizeof(float)); | |||
| delete[] (dataHWC); | |||
| // After the model and image tensor data is loaded, run inference. | |||
| auto status = mSession->RunGraph(); | |||
| @@ -277,7 +265,12 @@ Java_com_mindspore_himindsporedemo_gallery_classify_TrackingMobile_runNet(JNIEnv | |||
| * Get the mindspore inference results. | |||
| * Return the map of output node name and MindSpore Lite MSTensor. | |||
| */ | |||
| auto msOutputs = mSession->GetOutputMapByNode(); | |||
| auto names = mSession->GetOutputTensorNames(); | |||
| std::unordered_map<std::string, mindspore::tensor::MSTensor *> msOutputs; | |||
| for (const auto &name : names) { | |||
| auto temp_dat = mSession->GetOutputByTensorName(name); | |||
| msOutputs.insert(std::pair<std::string, mindspore::tensor::MSTensor *> {name, temp_dat}); | |||
| } | |||
| std::string resultStr = ProcessRunnetResult(MSNetWork::RET_CATEGORY_SUM, | |||
| MSNetWork::labels_name_map, msOutputs); | |||
| @@ -288,8 +281,8 @@ Java_com_mindspore_himindsporedemo_gallery_classify_TrackingMobile_runNet(JNIEnv | |||
| extern "C" JNIEXPORT jboolean JNICALL | |||
| Java_com_mindspore_himindsporedemo_gallery_classify_TrackingMobile_unloadModel(JNIEnv *env, | |||
| jclass type, | |||
| jlong netEnv) { | |||
| jclass type, | |||
| jlong netEnv) { | |||
| MS_PRINT("MindSpore release net."); | |||
| void **labelEnv = reinterpret_cast<void **>(netEnv); | |||
| if (labelEnv == nullptr) { | |||