3

I'm trying to develop face detection using google-mlkit. After setup camera, analyzer, detector etc following docs from google-mlkit https://developers.google.com/ml-kit/vision/face-detection/android, I'm able to detect face. After detect face I'm trying to extract detected face image.

Get detected face boundingBox, extract full bitmap into detected face bitmap using boundingBox. Code below.

Bitmap bmp = Bitmap.createBitmap(mediaImage.getWidth(), mediaImage.getHeight(), Bitmap.Config.ARGB_8888);                                             
YuvToRgbConverter converter = new YuvToRgbConverter(context);
converter.yuvToRgb(mediaImage, bmp);
Bitmap extractedBmp = extractFace(
   bmp,
   (int) (face.getBoundingBox().exactCenterX() / 2),
   (int) (face.getBoundingBox().exactCenterY() / 2),
   face.getBoundingBox().width(),
   face.getBoundingBox().height()
);

private Bitmap extractFace(Bitmap bmp, int x, int y, int width, int height) {
  return Bitmap.createBitmap(bmp, x, y, width, height);
}

Sometimes It's success and sometimes also failed. After debugging I found it's error because of x + width must be <= bitmap.width(). What I'm doing wrong?

BIlly Sutomo
  • 407
  • 1
  • 6
  • 20

2 Answers2

0

Exception is correct.

It happens because face boundingBox can go outside of the image (bitmap).

Also it possible for x and y as well. Try this simple recalculation.

private fun extractFace(bmp: Bitmap, x: Int, y: Int, width: Int, height: Int): Bitmap? {
    val originX = if (x + width > bmp.width) (bmp.width - width) else x
    val originY = if (y + height > bmp.height) (bmp.height - height) else y
    return Bitmap.createBitmap(bmp, originX, originY, width, height)
}

PS: Please check this calculation someone, it should work, thank you

Shwarz Andrei
  • 647
  • 14
  • 17
-1

Could you try util methods provided in the mlkit sample here to create a bimap from YUV image?

Chenxi Song
  • 557
  • 3
  • 6