MindSpore部署图像分割示例程序

MindSpore部署图像分割示例程序

本端侧图像分割Android示例程序使用Java实现,Java层主要通过Android Camera 2 API实现摄像头获取图像帧,进行相应的图像处理,之后调用Java API 完成模型推理。

此处详细说明示例程序的Java层图像处理及模型推理实现,Java层运用Android Camera 2 API实现开启设备摄像头以及图像帧处理等功能,需读者具备一定的Android开发基础知识。

示例程序结构

app

├── src/main

│   ├── assets # 资源文件

|   |   └── deeplabv3.ms # 存放模型文件

│   |

│   ├── java # java层应用代码

│   │   └── com.mindspore.imagesegmentation

│   │       ├── help # 图像处理及MindSpore Java调用相关实现

│   │       │   └── ImageUtils # 图像预处理

│   │       │   └── ModelTrackingResult # 推理数据后处理

│   │       │   └── TrackingMobile # 模型加载、构建计算图和推理

│   │       └── BitmapUtils # 图像处理

│   │       └── MainActivity # 交互主页面

│   │       └── OnBackgroundImageListener # 获取相册图像

│   │       └── StyleRecycleViewAdapter # 获取相册图像

│   │

│   ├── res # 存放Android相关的资源文件

│   └── AndroidManifest.xml # Android配置文件

├── CMakeList.txt # cmake编译入口文件

├── build.gradle # 其他Android配置文件

├── download.gradle # 工程依赖文件下载

└── ...

配置MindSpore Lite依赖项

Android 调用MindSpore Java API时,需要相关库文件支持。可通过MindSpore Lite源码编译生成mindspore-lite-{version}-minddata-{os}-{device}.tar.gz库文件包并解压缩(包含libmindspore-lite.so库文件和相关头文件),在本例中需使用生成带图像预处理模块的编译命令。

version:输出件版本号,与所编译的分支代码对应的版本一致。

device:当前分为cpu(内置CPU算子)和gpu(内置CPU和GPU算子)。

os:输出件应部署的操作系统。

本示例中,build过程由download.gradle文件自动下载MindSpore Lite 版本文件,并放置在app/src/main/cpp/目录下。

若自动下载失败,请手动下载相关库文件,解压并放在对应位置:

mindspore-lite-1.0.1-runtime-arm64-cpu.tar.gz 下载链接

在app的build.gradle文件中配置CMake编译支持,以及arm64-v8a的编译支持,如下所示:

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中下载模型文件,本示例程序中使用的终端图像分割模型文件为deeplabv3.ms,同样通过download.gradle脚本在APP构建时自动下载,并放置在app/src/main/assets工程目录下。

若下载失败请手动下载模型文件,deeplabv3.ms 下载链接

编写端侧推理代码

调用MindSpore Lite Java API实现端测推理。

推理代码流程如下,完整代码请参见src/java/TrackingMobile.java。

  1. 加载MindSpore Lite模型文件,构建上下文、会话以及用于推理的计算图。
    • 加载模型文件:创建并配置用于模型推理的上下文
  1. // Create context and load the .ms model named 'IMAGESEGMENTATIONMODEL'
  2. model = new Model();
  3. if (!model.loadModel(Context, IMAGESEGMENTATIONMODEL)) {
  4.   Log.e(TAG, "Load Model failed");
  5.   return;

}

    • 创建会话

// Create and init config.

msConfig = new MSConfig();

if (!msConfig.init(DeviceType.DT_CPU, 2, CpuBindMode.MID_CPU)) {

  Log.e(TAG, "Init context failed");

  return;

}

 

// Create the MindSpore lite session.

session = new LiteSession();

if (!session.init(msConfig)) {

  Log.e(TAG, "Create session failed");

  msConfig.free();

  return;

}

msConfig.free();

    • 构建计算图

if (!session.compileGraph(model)) {

  Log.e(TAG, "Compile graph failed");

  model.freeBuffer();

  return;

}

// Note: when use model.freeBuffer(), the model can not be compile graph again.

model.freeBuffer();

  1. 将输入图片转换为传入MindSpore模型的Tensor格式。
  1. List<MSTensor> inputs = session.getInputs();
  2. if (inputs.size() != 1) {
  3. 10.   Log.e(TAG, "inputs.size() != 1");
  4. 11.   return null;

12. }

  1. 13.  

14. // `bitmap` is the picture used to infer.

15. float resource_height = bitmap.getHeight();

16. float resource_weight = bitmap.getWidth();

17. ByteBuffer contentArray = bitmapToByteBuffer(bitmap, imageSize, imageSize, IMAGE_MEAN, IMAGE_STD);

  1. 18.  

19. MSTensor inTensor = inputs.get(0);

inTensor.setData(contentArray);

  1. 对输入Tensor按照模型进行推理,获取输出Tensor,并进行后处理。
    • 图执行,端侧推理。

21. // After the model and image tensor data is loaded, run inference.

22. if (!session.runGraph()) {

  1. 23.   Log.e(TAG, "Run graph failed");
  2. 24.   return null;

}

    • 获取输出数据。

// Get output tensor values, the model only outputs one tensor.

List<String> tensorNames = session.getOutputTensorNames();

MSTensor output = session.getOutputByTensorName(tensorNames.front());

if (output == null) {

  Log.e(TAG, "Can not find output " + tensorName);

  return null;

}

    • 输出数据的后续处理。

// Show output as pictures.

float[] results = output.getFloatData();

 

ByteBuffer bytebuffer_results = floatArrayToByteArray(results);

 

Bitmap dstBitmap = convertBytebufferMaskToBitmap(bytebuffer_results, imageSize, imageSize, bitmap, dstBitmap, segmentColors);

dstBitmap = scaleBitmapAndKeepRatio(dstBitmap, (int) resource_height, (int) resource_weight);

  1. 图片处理及输出数据后处理请参考如下代码。

26. Bitmap scaleBitmapAndKeepRatio(Bitmap targetBmp, int reqHeightInPixels, int reqWidthInPixels) {

  1. 27.   if (targetBmp.getHeight() == reqHeightInPixels && targetBmp.getWidth() == reqWidthInPixels) {
  2. 28.     return targetBmp;
  3. 29.   }
  4. 30.  
  5. 31.   Matrix matrix = new Matrix();
  6. 32.   matrix.setRectToRect(new RectF(0f, 0f, targetBmp.getWidth(), targetBmp.getHeight()),
  7. 33.                        new RectF(0f, 0f, reqWidthInPixels, reqHeightInPixels), Matrix.ScaleToFit.FILL;
  8. 34.  
  9. 35.     return Bitmap.createBitmap(targetBmp, 0, 0, targetBmp.getWidth(), targetBmp.getHeight(), matrix, true);

36. }

  1. 37.  

38. ByteBuffer bitmapToByteBuffer(Bitmap bitmapIn, int width, int height, float mean, float std) {

  1. 39.   Bitmap bitmap = scaleBitmapAndKeepRatio(bitmapIn, width, height);
  2. 40.   ByteBuffer inputImage = ByteBuffer.allocateDirect(1 * width * height * 3 * 4);
  3. 41.   inputImage.order(ByteOrder.nativeOrder());
  4. 42.   inputImage.rewind();
  5. 43.   int[] intValues = new int[width * height];
  6. 44.   bitmap.getPixels(intValues, 0, width, 0, 0, width, height);
  7. 45.   int pixel = 0;
  8. 46.   for (int y = 0; y < height; y++) {
  9. 47.     for (int x = 0; x < width; x++) {
  10. 48.       int value = intValues[pixel++];
  11. 49.       inputImage.putFloat(((float) (value >> 16 & 255) - mean) / std);
  12. 50.       inputImage.putFloat(((float) (value >> 8 & 255) - mean) / std);
  13. 51.       inputImage.putFloat(((float) (value & 255) - mean) / std);
  14. 52.     }
  15. 53.   }
  16. 54.   inputImage.rewind();
  17. 55.   return inputImage;

56. }

  1. 57.  

58. ByteBuffer floatArrayToByteArray(float[] floats) {

  1. 59.   ByteBuffer buffer = ByteBuffer.allocate(4 * floats.length);
  2. 60.   FloatBuffer floatBuffer = buffer.asFloatBuffer();
  3. 61.   floatBuffer.put(floats);
  4. 62.   return buffer;

63. }

  1. 64.  

65. Bitmap convertBytebufferMaskToBitmap(ByteBuffer inputBuffer, int imageWidth, int imageHeight, Bitmap backgroundImage, int[] colors) {

  1. 66.   Bitmap.Config conf = Bitmap.Config.ARGB_8888;
  2. 67.   Bitmap dstBitmap = Bitmap.createBitmap(imageWidth, imageHeight, conf);
  3. 68.   Bitmap scaledBackgroundImage = scaleBitmapAndKeepRatio(backgroundImage, imageWidth, imageHeight);
  4. 69.   int[][] mSegmentBits = new int[imageWidth][imageHeight];
  5. 70.   inputBuffer.rewind();
  6. 71.   for (int y = 0; y < imageHeight; y++) {
  7. 72.     for (int x = 0; x < imageWidth; x++) {
  8. 73.       float maxVal = 0f;
  9. 74.       mSegmentBits[x][y] = 0;
  10. 75.       // NUM_CLASSES is the number of labels, the value here is 21.
  11. 76.       for (int i = 0; i < NUM_CLASSES; i++) {
  12. 77.         float value = inputBuffer.getFloat((y * imageWidth * NUM_CLASSES + x * NUM_CLASSES + i) * 4);
  13. 78.         if (i == 0 || value > maxVal) {
  14. 79.           maxVal = value;
  15. 80.           // Check whether a pixel belongs to a person whose label is 15.
  16. 81.           if (i == 15) {
  17. 82.             mSegmentBits[x][y] = i;
  18. 83.           } else {
  19. 84.             mSegmentBits[x][y] = 0;
  20. 85.           }
  21. 86.         }
  22. 87.       }
  23. 88.       itemsFound.add(mSegmentBits[x][y]);
  24. 89.  
  25. 90.       int newPixelColor = ColorUtils.compositeColors(
  26. 91.               colors[mSegmentBits[x][y] == 0 ? 0 : 1],
  27. 92.               scaledBackgroundImage.getPixel(x, y)
  28. 93.       );
  29. 94.       dstBitmap.setPixel(x, y, mSegmentBits[x][y] == 0 ? colors[0] : scaledBackgroundImage.getPixel(x, y));
  30. 95.     }
  31. 96.   }
  32. 97.   return dstBitmap;

}

人工智能芯片与自动驾驶
原文地址:https://www.cnblogs.com/wujianming-110117/p/14320012.html