| Image Segmentation DeepLabV3 on Android |
| ================================================= |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| try { |
| module = Module.load(assetFilePath(this, "deeplabv3_scripted.pt")); |
| } catch (IOException e) { |
| Log.e("ImageSegmentation", "Error loading model!", e); |
| finish(); |
| } |
|
|
| Then set a breakpoint at the line `finish()` and build and run the app. If the app doesn't stop at the breakpoint, it means that the scripted model in Step 1 has been successfully loaded on Android. |
| |
| 4. Process the model input and output for model inference |
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| |
| After the model loads in the previous step, let's verify that it works with expected inputs and can generate expected outputs. As the model input for the DeepLabV3 model is an image the same as that of the MobileNet v2 in the HelloWorld example, we will reuse some of the code in the `MainActivity.java <https://github.com/pytorch/android-demo-app/blob/master/HelloWorldApp/app/src/main/java/org/pytorch/helloworld/MainActivity.java>`_ file from HelloWorld for input processing. Replace the code snippet between `line 50 <https://github.com/pytorch/android-demo-app/blob/master/HelloWorldApp/app/src/main/java/org/pytorch/helloworld/MainActivity.java#L50>`_ and 73 in `MainActivity.java` with the following code: |
|
|
| .. code-block:: java |
|
|
| final Tensor inputTensor = TensorImageUtils.bitmapToFloat32Tensor(bitmap, |
| TensorImageUtils.TORCHVISION_NORM_MEAN_RGB, |
| TensorImageUtils.TORCHVISION_NORM_STD_RGB); |
| final float[] inputs = inputTensor.getDataAsFloatArray(); |
|
|
| Map<String, IValue> outTensors = |
| module.forward(IValue.from(inputTensor)).toDictStringKey(); |
|
|
| // the key "out" of the output tensor contains the semantic masks |
| // see https://pytorch.org/hub/pytorch_vision_deeplabv3_resnet101 |
| final Tensor outputTensor = outTensors.get("out").toTensor(); |
| final float[] outputs = outputTensor.getDataAsFloatArray(); |
|
|
| int width = bitmap.getWidth(); |
| int height = bitmap.getHeight(); |
|
|
| .. note:: |
| The model output is a dictionary for the DeepLabV3 model so we use `toDictStringKey` to correctly extract the result. For other models, the model output may also be a single tensor or a tuple of tensors, among other things. |
|
|
| With the code changes shown above, you can set breakpoints after `final float[] inputs` and `final float[] outputs`, which populate the input tensor and output tensor data to float arrays for easy debugging. Run the app and when it stops at the breakpoints, compare the numbers in `inputs` and `outputs` with the model input and output data you see in Step 2 to see if they match. For the same inputs to the models running on Android and Python, you should get the same outputs. |
|
|
| .. warning:: |
| You may see different model outputs with the same image input when running on an Android emulator due to some Android emulator's floating point implementation issue. So it is best to test the app on a real Android device. |
| |
| All we have done so far is to confirm that the model of our interest can be scripted and run correctly in our Android app as in Python. The steps we walked through so far for using a model in an iOS app consumes the bulk, if not most, of our app development time, similar to how data preprocessing is the heaviest lift for a typical machine learning project. |
| |
| 5. Complete the UI, refactor, build and run the app |
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| |
| Now we are ready to complete the app and the UI to actually see the processed result as a new image. The output processing code should be like this, added to the end of the code snippet in Step 4: |
| |
| .. code-block:: java |
| |
| int[] intValues = new int[width * height]; |
| // go through each element in the output of size [WIDTH, HEIGHT] and |
| // set different color for different classnum |
| for (int j = 0; j < width; j++) { |
| for (int k = 0; k < height; k++) { |
| // maxi: the index of the 21 CLASSNUM with the max probability |
| int maxi = 0, maxj = 0, maxk = 0; |
| double maxnum = -100000.0; |
| for (int i=0; i < CLASSNUM; i++) { |
| if (outputs[i*(width*height) + j*width + k] > maxnum) { |
| maxnum = outputs[i*(width*height) + j*width + k]; |
| maxi = i; maxj = j; maxk= k; |
| } |
| } |
| // color coding for person (red), dog (green), sheep (blue) |
| // black color for background and other classes |
| if (maxi == PERSON) |
| intValues[maxj*width + maxk] = 0xFFFF0000; // red |
| else if (maxi == DOG) |
| intValues[maxj*width + maxk] = 0xFF00FF00; // green |
| else if (maxi == SHEEP) |
| intValues[maxj*width + maxk] = 0xFF0000FF; // blue |
| else |
| intValues[maxj*width + maxk] = 0xFF000000; // black |
| } |
| } |
| |
| The constants used in the code above are defined in the beginning of the class `MainActivity`: |
| |
| .. code-block:: java |
| |
| private static final int CLASSNUM = 21; |
| private static final int DOG = 12; |
| private static final int PERSON = 15; |
| private static final int SHEEP = 17; |
| |
| |
| The implementation here is based on the understanding of the DeepLabV3 model which outputs a tensor of size [21, width, height] for an input image of width*height. Each element in the width*height output array is a value between 0 and 20 (for a total of 21 semantic labels described in Introduction) and the value is used to set a specific color. Color coding of the segmentation here is based on the class with the highest probability, and you can extend the color coding for all classes in your own dataset. |
| |
| After the output processing, you will also need to call the code below to render the RGB `intValues` array to a bitmap instance `outputBitmap` before displaying it on an `ImageView`: |
| |
| .. code-block:: java |
| |
| Bitmap bmpSegmentation = Bitmap.createScaledBitmap(bitmap, width, height, true); |
| Bitmap outputBitmap = bmpSegmentation.copy(bmpSegmentation.getConfig(), true); |
| outputBitmap.setPixels(intValues, 0, outputBitmap.getWidth(), 0, 0, |
| outputBitmap.getWidth(), outputBitmap.getHeight()); |
| imageView.setImageBitmap(outputBitmap); |
| |
| The UI for this app is also similar to that for HelloWorld, except that you do not need the `TextView` to show the image classification result. You can also add two buttons `Segment` and `Restart` as shown in the code repo to run the model inference and to show back the original image after the segmentation result is shown. |
| |
| Now when you run the app on an Android emulator or preferably an actual device, you will see screens like the following: |
| |
| .. image:: /_static/img/deeplabv3_android.png |
| :width: 300 px |
| .. image:: /_static/img/deeplabv3_android2.png |
| :width: 300 px |
| |
| |
| Recap |
| -------- |
| |
| In this tutorial, we described what it takes to convert a pre-trained PyTorch DeepLabV3 model for Android and how to make sure the model can run successfully on Android. Our focus was to help you understand the process of confirming that a model can indeed run on Android. The complete code repo is available `here <https://github.com/pytorch/android-demo-app/ImageSegmentation>`_. |
| |
| More advanced topics such as quantization and using models via transfer learning or of your own on Android will be covered soon in future demo apps and tutorials. |
| |
| |
| Learn More |
| ------------ |
| |
| 1. `PyTorch Mobile site <https://pytorch.org/mobile>`_ |
| 2. `DeepLabV3 model <https://pytorch.org/hub/pytorch_vision_deeplabv3_resnet101>`_ |
| 3. `DeepLabV3 paper <https://arxiv.org/pdf/1706.05587.pdf>`_ |
| |