Skip to content

Instantly share code, notes, and snippets.

@SurajBahadur
Created July 15, 2024 07:10
Show Gist options
  • Save SurajBahadur/805218a365ed95a34d58932abcf6c4d3 to your computer and use it in GitHub Desktop.
Save SurajBahadur/805218a365ed95a34d58932abcf6c4d3 to your computer and use it in GitHub Desktop.
Detect the people face from the image and crop only the face
var detector: FaceDetector? = null
val highAccuracyOpts =
FaceDetectorOptions.Builder()
.setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
.setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_NONE)
.setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_NONE)
.build()
detector = FaceDetection.getClient(highAccuracyOpts)
fun performFaceDetection(inputImage: Bitmap) {
val mutableBmp = inputImage.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(mutableBmp)
val image = InputImage.fromBitmap(inputImage, 0)
val result: Task<List<Face>> =
detector!!.process(image)
.addOnSuccessListener { faces ->
for (face in faces) {
val bounds = face.boundingBox
val p = Paint()
p.style = Paint.Style.STROKE
p.strokeWidth = 3f
p.color = Color.RED
canvas.drawRect(bounds, p)
performFaceRecognition(bounds, inputImage)
}
//imageView.setImageBitmap(mutableBmp)
}
.addOnFailureListener(
OnFailureListener {
// Task failed with an exception
// ...
})
}
fun performFaceRecognition(bounds: Rect, inputImage: Bitmap) {
if (bounds.top < 0) {
bounds.top = 0
}
if (bounds.left < 0) {
bounds.left = 0
}
if (bounds.right > inputImage.width) {
bounds.right = inputImage.width - 1
}
if (bounds.bottom > inputImage.height) {
bounds.bottom = inputImage.height - 1
}
var croppedFace = Bitmap.createBitmap(
inputImage,
bounds.left,
bounds.top,
bounds.width(),
bounds.height()
)
croppedFace = Bitmap.createScaledBitmap(
croppedFace!!,
160,
160,
false
)
binding.faceRecog.setImageBitmap(croppedFace)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment