Get cropped Image Bitmap using U2Net Model in android

316 views Asked by At

I have implemented the code using this link and got the greyscaled masked bitmap successfully but cannot get the original background image bitmap from greyscaled masked bitmap. I have used this link for getting cropped image bitmap but it returns me the same scaled bitmap which i gave it as a parameter. So any help would be much appreciated and Thanks in Advance!

Here is the function with which black/white mask is applied after processing the image in model:

fun convertArrayToBitmapTensorFlow(
            imageArray: Array<Array<Array<FloatArray>>>,
            imageWidth: Int,
            imageHeight: Int
        ): Bitmap {
            val conf = Bitmap.Config.ARGB_8888 // see other conf types
            val grayToneImage = Bitmap.createBitmap(imageWidth, imageHeight, conf)

            for (x in imageArray[0].indices) {
                for (y in imageArray[0][0].indices) {
                    val color = Color.rgb(
                        //
                        (((imageArray[0][x][y][0]) * 255f).toInt()),
                        (((imageArray[0][x][y][0]) * 255f).toInt()),
                        (((imageArray[0][x][y][0]) * 255f).toInt())
                    )

                    // this y, x is in the correct order!!!
                    grayToneImage.setPixel(y, x, color)
                }
            }
            return grayToneImage
        }

and applied it like this:

val finalBitmapGrey = ImageUtils.convertArrayToBitmapTensorFlow(
              output1, imageSize,
              imageSize
      )

and then calling that porterduf function with the mask output and orignal:

  val cropped=cropBitmapWithMask(scaledBitmap,finalBitmapGrey)

  private fun cropBitmapWithMask(original: Bitmap, mask: Bitmap): Bitmap {
    if (original == null
            || mask == null) {
      return null
    }
    val w = mask.width
    val h = mask.height
    if (w <= 0 || h <= 0) {
      return null
    }

    val cropped = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(cropped)
    val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN)
    canvas.drawBitmap(original, 0.0f, 0.0f, null)
    canvas.drawBitmap(mask, 0.0f, 0.0f, paint)
    paint.xfermode = null
    canvas.drawBitmap(cropped, 0.0f, 0.0f, Paint())
    return cropped
  }

then it displays the full original image (which was given as input), but I want the cropped area of the original image to be displayed ..

0

There are 0 answers