Skip to content

Instantly share code, notes, and snippets.

@shubham0204
Created February 22, 2022 01:22
Show Gist options
  • Save shubham0204/c6e82e190961a3c0c576ee29e3fca3b9 to your computer and use it in GitHub Desktop.
Save shubham0204/c6e82e190961a3c0c576ee29e3fca3b9 to your computer and use it in GitHub Desktop.
// Detect faces in the given image and crop them.
// Pass the cropped faces to the AgeDetectionModel
private fun detectFaces(image: Bitmap) {
val inputImage = InputImage.fromBitmap(image, 0)
firebaseFaceDetector.process(inputImage)
.addOnSuccessListener { faces ->
if ( faces.size != 0 ) {
progressDialog.apply {
dismiss()
setMessage( "📍 Posting to server ...")
show()
}
// Crop the image using the boundingBox predicted by the face detector
val inputImage = cropToBBox( image , faces[ 0 ].boundingBox )
activityMainBinding.imageView.setImageBitmap( inputImage )
// Pass the cropped face to AgeDetectionModel
ageDetectionModel.pass( inputImage , predictionCallback )
}
else {
// Display a warning to the user
val dialog = AlertDialog.Builder( this ).apply {
title = "No Faces Found"
setMessage( "We could not find any faces in the image you just clicked. " +
"Try clicking another image or improve the lightning or the device rotation." )
setPositiveButton( "OK") { dialog, which ->
dialog.dismiss()
}
setCancelable( false )
create()
}
dialog.show()
}
}
}
// A callback to get the age detection results from the AgeDetectionModel
// This callback is passed to the `AgeDetectionModel.pass` method in `detectFaces()`
private val predictionCallback = object : AgeDetectionModel.PredictionCallback {
override fun onError(error: String) {
runOnUiThread {
progressDialog.dismiss()
val dialog = AlertDialog.Builder( this@MainActivity ).apply {
title = "An error unoccured"
setMessage( error )
setPositiveButton( "OK") { dialog, which ->
dialog.dismiss()
}
setCancelable( false )
create()
}
dialog.show()
}
}
override fun onResult(age: Int) {
runOnUiThread {
progressDialog.dismiss()
val dialog = AlertDialog.Builder( this@MainActivity ).apply {
title = "Result"
setMessage( "The result is $age years" )
setPositiveButton( "OK") { dialog, which ->
dialog.dismiss()
}
setCancelable( false )
create()
}
dialog.show()
}
}
}
// Crop the given image using bbox
private fun cropToBBox(image: Bitmap, bbox: Rect) : Bitmap {
return Bitmap.createBitmap(
image,
bbox.left - 0,
bbox.top,
bbox.width() ,
bbox.height()
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment