'Save segmentation result of Selfie segmentation with ML Kit on Android as A Bitmap with transparent background

Save segmentation result of Selfie segmentation with ML Kit on Android as A Bitmap with transparent background

I am following this tutorial and code for Selfie segmentation

Here

I have referred this code from the tutorial

ByteBuffer mask = segmentationMask.getBuffer();
int maskWidth = segmentationMask.getWidth();
int maskHeight = segmentationMask.getHeight();

for (int y = 0; y < maskHeight; y++) {
  for (int x = 0; x < maskWidth; x++) {
    // Gets the confidence of the (x,y) pixel in the mask being in the foreground.
    float foregroundConfidence = mask.getFloat();
  }
}

Which generates a Mask

Then I have Referred the Sample app Which generates a purple background Mask

Here

using this code

@ColorInt
  private int[] maskColorsFromByteBuffer(ByteBuffer byteBuffer) {
    @ColorInt int[] colors = new int[maskWidth * maskHeight];
    for (int i = 0; i < maskWidth * maskHeight; i++) {
      float backgroundLikelihood = 1 - byteBuffer.getFloat();
      if (backgroundLikelihood > 0.9) {
        colors[i] = Color.argb(128, 255, 0, 255);
      } else if (backgroundLikelihood > 0.2) {
        // Linear interpolation to make sure when backgroundLikelihood is 0.2, the alpha is 0 and
        // when backgroundLikelihood is 0.9, the alpha is 128.
        // +0.5 to round the float value to the nearest int.
        int alpha = (int) (182.9 * backgroundLikelihood - 36.6 + 0.5);
        colors[i] = Color.argb(alpha, 255, 0, 255);
      }
    }
    return colors;
  }

Now I want to generate an Image with the original images detected mask and Overlay it on a Transparent Image and save that bitmap for this I am using this code

 public Bitmap generateMaskBgImage(Bitmap image, Bitmap bg) {
//Bg is Transparent Png Image.
            Bitmap bgBitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), image.getConfig());
            for (int y = 0; y < maskHeight; y++) {
                for (int x = 0; x < maskWidth; x++) {
                    int bgConfidence = (int) ((1.0 - maskBuffer.getFloat()) * 255);
                    int bgPixel = bg.getPixel(x, y);
                    bgPixel = ColorUtils.setAlphaComponent(bgPixel, bgConfidence);
                    bgBitmap.setPixel(x, y, bgPixel);
                }
            }
            maskBuffer.rewind();
            return bitmapUtils.mergeBitmaps(image, bgBitmap);
        }

However it generates an Image with the desired mask but with a Black back ground, How can we save that image with Transparent background.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source