Home > Net >  Android - Unable to crop mask from original image
Android - Unable to crop mask from original image

Time:05-09

I'm trying to remove the background from an image. For that, I'm using TensorFlow which provides me mask of an object. After that, I'm cropping the mask from the image but the result is not as good as I wanted. Little help will be appreciated.

Using TensorFlow for masking:

CodePudding user response:

After cropping the mask from an original bitmap. I'm SRC_OVER the result bitmap twice which hides the transparency issue.

fun creatingMasking(original: Bitmap?, mask: Bitmap?): Bitmap? {
            return try {
                var result: Bitmap? =
                    mask?.let { original?.let { it1 -> croppingMaskFromOriginal(it, it1) } }
                val final = result
                result = result?.let { overlay(it, it) }
                result = result?.let { final?.let { it1 -> overlay(it, it1) } }
                result
            } catch (e: Exception) {
                original
            } catch (e: OutOfMemoryError) {
                original
            }
        }


        private fun croppingMaskFromOriginal(base: Bitmap, blend1: Bitmap): Bitmap {
            return try {
                val result: Bitmap =
                    base.copy(Bitmap.Config.ARGB_8888, true)
                val blend = Bitmap.createScaledBitmap(blend1, base.width, base.height, false)
                val p = Paint()
                p.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
                p.shader = BitmapShader(blend, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR)
                p.alpha = 255
                val c = Canvas()
                c.setBitmap(result)
                c.drawBitmap(base, 0f, 0f, null)
                c.drawRect(0f, 0f, base.width.toFloat(), base.height.toFloat(), p)
                result
            } catch (e: Exception) {
                base
            } catch (e: OutOfMemoryError) {
                base
            }
        }

        private fun overlay(base: Bitmap, blend1: Bitmap): Bitmap {
            return try {
                val result: Bitmap =
                    base.copy(Bitmap.Config.ARGB_8888, true)
                val blend = Bitmap.createScaledBitmap(blend1, base.width, base.height, false)
                val p = Paint()
                p.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)
                p.shader = BitmapShader(blend, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR)
                val c = Canvas()
                c.setBitmap(result)
                c.drawBitmap(base, 0f, 0f, null)
                c.drawRect(0f, 0f, base.width.toFloat(), base.height.toFloat(), p)
                result
            } catch (e: Exception) {

                base
            } catch (e: OutOfMemoryError) {
                base
            }
        }
  • Related