diff --git a/FaceDetectorSample/.gitignore b/FaceDetectorSample/.gitignore
new file mode 100644
index 0000000..d45a8b4
--- /dev/null
+++ b/FaceDetectorSample/.gitignore
@@ -0,0 +1,9 @@
+*.iml
+.gradle
+/local.properties
+/.idea/*
+.DS_Store
+/build
+/captures
+.externalNativeBuild
+.cxx
diff --git a/FaceDetectorSample/app/.gitignore b/FaceDetectorSample/app/.gitignore
new file mode 100644
index 0000000..42afabf
--- /dev/null
+++ b/FaceDetectorSample/app/.gitignore
@@ -0,0 +1 @@
+/build
\ No newline at end of file
diff --git a/FaceDetectorSample/app/build.gradle b/FaceDetectorSample/app/build.gradle
new file mode 100644
index 0000000..30a806b
--- /dev/null
+++ b/FaceDetectorSample/app/build.gradle
@@ -0,0 +1,38 @@
+apply plugin: "com.android.application"
+apply plugin: "kotlin-android"
+apply plugin: "kotlin-android-extensions"
+
+android {
+ compileSdkVersion 30
+ buildToolsVersion "29.0.3"
+
+ defaultConfig {
+ applicationId "com.husaynhakeem.facedetectorsample"
+ minSdkVersion 21
+ targetSdkVersion 30
+ versionCode 1
+ }
+
+ // CameraX uses java8 features
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ }
+}
+
+dependencies {
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
+ implementation "androidx.core:core-ktx:1.3.0"
+ implementation "androidx.appcompat:appcompat:1.1.0"
+ implementation "androidx.constraintlayout:constraintlayout:1.1.3"
+ implementation "androidx.activity:activity-ktx:1.2.0-alpha06"
+ implementation "androidx.fragment:fragment-ktx:1.3.0-alpha06"
+
+ // CameraX
+ implementation "androidx.camera:camera-camera2:1.0.0-beta06"
+ implementation "androidx.camera:camera-lifecycle:1.0.0-beta06"
+ implementation "androidx.camera:camera-view:1.0.0-alpha13"
+
+ // MLKit
+ implementation "com.google.mlkit:face-detection:16.0.0"
+}
\ No newline at end of file
diff --git a/FaceDetectorSample/app/src/main/AndroidManifest.xml b/FaceDetectorSample/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..493bc5c
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/AndroidManifest.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/AnalysisFaceDetector.kt b/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/AnalysisFaceDetector.kt
new file mode 100644
index 0000000..22fd5c6
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/AnalysisFaceDetector.kt
@@ -0,0 +1,84 @@
+package com.husaynhakeem.facedetectorsample
+
+import android.annotation.SuppressLint
+import android.graphics.Rect
+import android.graphics.RectF
+import androidx.camera.core.ImageAnalysis
+import androidx.camera.core.ImageProxy
+import com.google.mlkit.vision.common.InputImage
+import com.google.mlkit.vision.face.Face
+import com.google.mlkit.vision.face.FaceDetection
+import com.google.mlkit.vision.face.FaceDetector
+
+/** CameraX Analyzer that wraps MLKit's FaceDetector. */
+internal class AnalysisFaceDetector(
+ private val previewWidth: Int,
+ private val previewHeight: Int,
+ private val isFrontLens: Boolean
+) : ImageAnalysis.Analyzer {
+
+ private val faceDetector: FaceDetector = FaceDetection.getClient()
+
+ /** Listener to receive callbacks for when faces are detected, or an error occurs. */
+ var listener: Listener? = null
+
+ @SuppressLint("UnsafeExperimentalUsageError")
+ override fun analyze(imageProxy: ImageProxy) {
+ val image = imageProxy.image
+ if (image == null) {
+ imageProxy.close()
+ return
+ }
+
+ val rotation = imageProxy.imageInfo.rotationDegrees
+ val inputImage = InputImage.fromMediaImage(image, rotation)
+ faceDetector
+ .process(inputImage)
+ .addOnSuccessListener { faces: List ->
+ val listener = listener ?: return@addOnSuccessListener
+
+ // In order to correctly display the face bounds, the orientation of the analyzed
+ // image and that of the viewfinder have to match. Which is why the dimensions of
+ // the analyzed image are reversed if its rotation information is 90 or 270.
+ val reverseDimens = rotation == 90 || rotation == 270
+ val width = if (reverseDimens) imageProxy.height else imageProxy.width
+ val height = if (reverseDimens) imageProxy.width else imageProxy.height
+
+ val faceBounds = faces.map { it.boundingBox.transform(width, height) }
+ listener.onFacesDetected(faceBounds)
+ imageProxy.close()
+ }
+ .addOnFailureListener { exception ->
+ listener?.onError(exception)
+ imageProxy.close()
+ }
+ }
+
+ private fun Rect.transform(width: Int, height: Int): RectF {
+ val scaleX = previewWidth / width.toFloat()
+ val scaleY = previewHeight / height.toFloat()
+
+ // If the front camera lens is being used, reverse the right/left coordinates
+ val flippedLeft = if (isFrontLens) width - right else left
+ val flippedRight = if (isFrontLens) width - left else right
+
+ // Scale all coordinates to match preview
+ val scaledLeft = scaleX * flippedLeft
+ val scaledTop = scaleY * top
+ val scaledRight = scaleX * flippedRight
+ val scaledBottom = scaleY * bottom
+ return RectF(scaledLeft, scaledTop, scaledRight, scaledBottom)
+ }
+
+ /**
+ * Interface to register callbacks for when the face detector provides detected face bounds, or
+ * when it encounters an error.
+ */
+ internal interface Listener {
+ /** Callback that receives face bounds that can be drawn on top of the viewfinder. */
+ fun onFacesDetected(faceBounds: List)
+
+ /** Invoked when an error is encounter during face detection. */
+ fun onError(exception: Exception)
+ }
+}
diff --git a/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/CameraViewModel.kt b/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/CameraViewModel.kt
new file mode 100644
index 0000000..a2b4f42
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/CameraViewModel.kt
@@ -0,0 +1,37 @@
+package com.husaynhakeem.facedetectorsample
+
+import android.app.Application
+import androidx.camera.lifecycle.ProcessCameraProvider
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.LiveData
+import androidx.lifecycle.MutableLiveData
+import java.util.concurrent.ExecutionException
+
+/** ViewModel that provides a [ProcessCameraProvider] to interact with the camera. */
+class CameraViewModel(application: Application) : AndroidViewModel(application) {
+
+ private val _getProcessCameraProvider by lazy {
+ MutableLiveData().apply {
+ val cameraProviderFuture = ProcessCameraProvider.getInstance(getApplication())
+ cameraProviderFuture.addListener(
+ Runnable {
+ try {
+ value = cameraProviderFuture.get()
+ } catch (exception: ExecutionException) {
+ throw IllegalStateException(
+ "Failed to retrieve a ProcessCameraProvider instance", exception
+ )
+ } catch (exception: InterruptedException) {
+ throw IllegalStateException(
+ "Failed to retrieve a ProcessCameraProvider instance", exception
+ )
+ }
+ },
+ ContextCompat.getMainExecutor(getApplication())
+ )
+ }
+ }
+ val processCameraProvider: LiveData
+ get() = _getProcessCameraProvider
+}
diff --git a/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/FaceBoundsOverlay.kt b/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/FaceBoundsOverlay.kt
new file mode 100644
index 0000000..f84419f
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/FaceBoundsOverlay.kt
@@ -0,0 +1,32 @@
+package com.husaynhakeem.facedetectorsample
+
+import android.content.Context
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.RectF
+import android.util.AttributeSet
+import android.view.View
+import androidx.core.content.ContextCompat
+
+/** Overlay where face bounds are drawn. */
+class FaceBoundsOverlay constructor(context: Context?, attributeSet: AttributeSet?) :
+ View(context, attributeSet) {
+
+ private val faceBounds: MutableList = mutableListOf()
+ private val paint = Paint().apply {
+ style = Paint.Style.STROKE
+ color = ContextCompat.getColor(context!!, android.R.color.black)
+ strokeWidth = 10f
+ }
+
+ override fun onDraw(canvas: Canvas) {
+ super.onDraw(canvas)
+ faceBounds.forEach { canvas.drawRect(it, paint) }
+ }
+
+ fun drawFaceBounds(faceBounds: List) {
+ this.faceBounds.clear()
+ this.faceBounds.addAll(faceBounds)
+ invalidate()
+ }
+}
diff --git a/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/MainActivity.kt b/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/MainActivity.kt
new file mode 100644
index 0000000..14c7cf8
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/java/com/husaynhakeem/facedetectorsample/MainActivity.kt
@@ -0,0 +1,217 @@
+package com.husaynhakeem.facedetectorsample
+
+import android.Manifest.permission
+import android.content.Context
+import android.content.pm.PackageManager
+import android.graphics.RectF
+import android.hardware.display.DisplayManager
+import android.hardware.display.DisplayManager.DisplayListener
+import android.os.Bundle
+import android.util.Log
+import android.view.Surface
+import android.view.View
+import android.widget.Toast
+import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
+import androidx.appcompat.app.AppCompatActivity
+import androidx.camera.core.*
+import androidx.camera.lifecycle.ProcessCameraProvider
+import androidx.camera.view.PreviewView.StreamState
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.Observer
+import androidx.lifecycle.ViewModelProvider
+import kotlinx.android.synthetic.main.activity_main.*
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
+
+/** An Activity that runs a camera preview and image analysis on camera frames. */
+class MainActivity : AppCompatActivity() {
+
+ private lateinit var cameraProvider: ProcessCameraProvider
+ private lateinit var executor: ExecutorService
+ private lateinit var imageAnalysis: ImageAnalysis
+
+ /**
+ * The display listener is used to update the ImageAnalysis's target rotation for cases where the
+ * Activity isn't recreated after a device rotation, for example a 180 degree rotation from
+ * landscape to reverse-landscape on a portrait oriented device.
+ */
+ private val displayListener: DisplayListener = object : DisplayListener {
+ override fun onDisplayAdded(displayId: Int) {}
+ override fun onDisplayRemoved(displayId: Int) {}
+ override fun onDisplayChanged(displayId: Int) {
+ val rootView = findViewById(android.R.id.content)
+ if (::imageAnalysis.isInitialized && displayId == rootView.display.displayId) {
+ imageAnalysis.targetRotation = rootView.display.rotation
+ }
+ }
+ }
+
+ override fun onCreate(bundle: Bundle?) {
+ super.onCreate(bundle)
+ setContentView(R.layout.activity_main)
+
+ // Initialize analysis executor
+ executor = Executors.newSingleThreadExecutor()
+
+ // Set up camera
+ setUpCameraViewModel()
+
+ // Request permissions if not already granted
+ if (!arePermissionsGranted()) {
+ requestPermissions()
+ }
+
+ // Register the display listener
+ val manager = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
+ manager.registerDisplayListener(displayListener, null)
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+
+ // Shutdown analysis executor
+ executor.shutdown()
+
+ // Unregister the display listener
+ val manager = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
+ manager.unregisterDisplayListener(displayListener)
+ }
+
+ private fun arePermissionsGranted(): Boolean {
+ return REQUIRED_PERMISSIONS.all {
+ ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
+ }
+ }
+
+ private fun requestPermissions() {
+ val launcher = registerForActivityResult(RequestMultiplePermissions()) {
+ if (arePermissionsGranted()) {
+ tryStartCamera()
+ } else {
+ Toast.makeText(this, R.string.permissions_not_granted, Toast.LENGTH_LONG).show()
+ finish()
+ }
+ }
+ launcher.launch(REQUIRED_PERMISSIONS)
+ }
+
+ private fun setUpCameraViewModel() {
+ val viewModel = ViewModelProvider(this).get(CameraViewModel::class.java)
+ viewModel
+ .processCameraProvider
+ .observe(
+ this,
+ Observer { provider: ProcessCameraProvider? ->
+ cameraProvider = provider ?: return@Observer
+ tryStartCamera()
+ }
+ )
+ }
+
+ private fun tryStartCamera() {
+ if (::cameraProvider.isInitialized && arePermissionsGranted()) {
+ startCamera(cameraProvider)
+ }
+ }
+
+ /**
+ * Sets up both preview and image analysis use cases, both with the same target aspect ratio
+ * (4:3). The viewfinder also has an aspect ratio of 4:3. This makes it so that the frames the
+ * ImageAnalysis use case receives from the camera match (in aspect ratio) the frames the
+ * viewfinder displays (through the Preview use case), and guarantees the face bounds drawn on
+ * top of the viewfinder have the correct coordinates.
+ */
+ private fun startCamera(cameraProvider: ProcessCameraProvider) {
+ // Build Preview use case, and set its SurfaceProvider
+ val preview = Preview.Builder()
+ .setTargetAspectRatio(AspectRatio.RATIO_4_3)
+ .build()
+ preview.setSurfaceProvider(viewfinder.createSurfaceProvider())
+
+ val lensFacing = getCameraLensFacing(cameraProvider)
+ val cameraSelector = CameraSelector.Builder()
+ .requireLensFacing(lensFacing)
+ .build()
+
+ // Build an ImageAnalysis use case, and hook it up with a FaceDetector
+ imageAnalysis = ImageAnalysis.Builder()
+ .setTargetAspectRatio(AspectRatio.RATIO_4_3)
+ .build()
+ setFaceDetector(imageAnalysis, lensFacing)
+
+ cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis)
+ }
+
+ /**
+ * The face detector provides face bounds whose coordinates, width and height depend on the
+ * preview's width and height, which is guaranteed to be available after the preview starts
+ * streaming.
+ */
+ private fun setFaceDetector(imageAnalysis: ImageAnalysis, lensFacing: Int) {
+ viewfinder.previewStreamState.observe(this, object : Observer {
+ override fun onChanged(streamState: StreamState?) {
+ if (streamState != StreamState.STREAMING) {
+ return
+ }
+
+ val preview = viewfinder.getChildAt(0)
+ var width = preview.width * preview.scaleX
+ var height = preview.height * preview.scaleY
+ val rotation = preview.display.rotation
+ if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
+ val temp = width
+ width = height
+ height = temp
+ }
+
+ imageAnalysis.setAnalyzer(
+ executor,
+ createFaceDetector(width.toInt(), height.toInt(), lensFacing)
+ )
+ viewfinder.previewStreamState.removeObserver(this)
+ }
+ })
+ }
+
+ private fun createFaceDetector(
+ viewfinderWidth: Int,
+ viewfinderHeight: Int,
+ lensFacing: Int
+ ): ImageAnalysis.Analyzer {
+ val isFrontLens = lensFacing == CameraSelector.LENS_FACING_FRONT
+ val faceDetector = AnalysisFaceDetector(viewfinderWidth, viewfinderHeight, isFrontLens)
+ faceDetector.listener = object : AnalysisFaceDetector.Listener {
+ override fun onFacesDetected(faceBounds: List) {
+ faceBoundsOverlay.post { faceBoundsOverlay.drawFaceBounds(faceBounds) }
+ }
+
+ override fun onError(exception: Exception) {
+ Log.d(TAG, "Face detection error", exception)
+ }
+ }
+ return faceDetector
+ }
+
+ private fun getCameraLensFacing(cameraProvider: ProcessCameraProvider): Int {
+ try {
+ if (cameraProvider.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)) {
+ return CameraSelector.LENS_FACING_FRONT
+ }
+ if (cameraProvider.hasCamera(CameraSelector.DEFAULT_BACK_CAMERA)) {
+ return CameraSelector.LENS_FACING_BACK
+ }
+ Toast.makeText(this, R.string.no_available_camera, Toast.LENGTH_LONG).show()
+ finish()
+ } catch (exception: CameraInfoUnavailableException) {
+ Toast.makeText(this, R.string.camera_selection_error, Toast.LENGTH_LONG).show()
+ Log.e(TAG, "An error occurred while choosing a CameraSelector ", exception)
+ finish()
+ }
+ throw IllegalStateException("An error occurred while choosing a CameraSelector ")
+ }
+
+ companion object {
+ private const val TAG = "MainActivity"
+ private val REQUIRED_PERMISSIONS = arrayOf(permission.CAMERA)
+ }
+}
diff --git a/FaceDetectorSample/app/src/main/res/layout-land/activity_main.xml b/FaceDetectorSample/app/src/main/res/layout-land/activity_main.xml
new file mode 100644
index 0000000..782cfab
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/res/layout-land/activity_main.xml
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
diff --git a/FaceDetectorSample/app/src/main/res/layout/activity_main.xml b/FaceDetectorSample/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..607a012
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
diff --git a/FaceDetectorSample/app/src/main/res/values/colors.xml b/FaceDetectorSample/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..4faecfa
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/res/values/colors.xml
@@ -0,0 +1,6 @@
+
+
+ #6200EE
+ #3700B3
+ #03DAC5
+
\ No newline at end of file
diff --git a/FaceDetectorSample/app/src/main/res/values/strings.xml b/FaceDetectorSample/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..37c66b8
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/res/values/strings.xml
@@ -0,0 +1,6 @@
+
+ FaceDetector Sample
+ Required permissions not granted by user.
+ No available cameras for usage.
+ An error occurred while choosing a camera lens facing.
+
\ No newline at end of file
diff --git a/FaceDetectorSample/app/src/main/res/values/styles.xml b/FaceDetectorSample/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..d7f47a4
--- /dev/null
+++ b/FaceDetectorSample/app/src/main/res/values/styles.xml
@@ -0,0 +1,11 @@
+
+
+
\ No newline at end of file
diff --git a/FaceDetectorSample/art/art_landscape.png b/FaceDetectorSample/art/art_landscape.png
new file mode 100644
index 0000000..fb50bdc
Binary files /dev/null and b/FaceDetectorSample/art/art_landscape.png differ
diff --git a/FaceDetectorSample/art/art_portrait.png b/FaceDetectorSample/art/art_portrait.png
new file mode 100644
index 0000000..3054bb4
Binary files /dev/null and b/FaceDetectorSample/art/art_portrait.png differ
diff --git a/FaceDetectorSample/build.gradle b/FaceDetectorSample/build.gradle
new file mode 100644
index 0000000..5a7202d
--- /dev/null
+++ b/FaceDetectorSample/build.gradle
@@ -0,0 +1,23 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+buildscript {
+ ext.kotlin_version = "1.3.70"
+ repositories {
+ google()
+ jcenter()
+ }
+ dependencies {
+ classpath "com.android.tools.build:gradle:4.0.0-beta02"
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+ }
+}
+
+allprojects {
+ repositories {
+ google()
+ jcenter()
+ }
+}
+
+task clean(type: Delete) {
+ delete rootProject.buildDir
+}
\ No newline at end of file
diff --git a/FaceDetectorSample/gradle.properties b/FaceDetectorSample/gradle.properties
new file mode 100644
index 0000000..c52ac9b
--- /dev/null
+++ b/FaceDetectorSample/gradle.properties
@@ -0,0 +1,19 @@
+# Project-wide Gradle settings.
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx2048m
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
+# AndroidX package structure to make it clearer which packages are bundled with the
+# Android operating system, and which are packaged with your app"s APK
+# https://developer.android.com/topic/libraries/support-library/androidx-rn
+android.useAndroidX=true
+# Automatically convert third-party libraries to use AndroidX
+android.enableJetifier=true
\ No newline at end of file
diff --git a/FaceDetectorSample/gradle/wrapper/gradle-wrapper.jar b/FaceDetectorSample/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..f6b961f
Binary files /dev/null and b/FaceDetectorSample/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/FaceDetectorSample/gradle/wrapper/gradle-wrapper.properties b/FaceDetectorSample/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..87558ee
--- /dev/null
+++ b/FaceDetectorSample/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Mon Jun 29 19:46:06 PDT 2020
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
diff --git a/FaceDetectorSample/gradlew b/FaceDetectorSample/gradlew
new file mode 100755
index 0000000..cccdd3d
--- /dev/null
+++ b/FaceDetectorSample/gradlew
@@ -0,0 +1,172 @@
+#!/usr/bin/env sh
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=$(save "$@")
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
+ cd "$(dirname "$0")"
+fi
+
+exec "$JAVACMD" "$@"
diff --git a/FaceDetectorSample/gradlew.bat b/FaceDetectorSample/gradlew.bat
new file mode 100644
index 0000000..e95643d
--- /dev/null
+++ b/FaceDetectorSample/gradlew.bat
@@ -0,0 +1,84 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/FaceDetectorSample/settings.gradle b/FaceDetectorSample/settings.gradle
new file mode 100644
index 0000000..c1f8838
--- /dev/null
+++ b/FaceDetectorSample/settings.gradle
@@ -0,0 +1,2 @@
+include ':app'
+rootProject.name = "FaceDetectorSample"
\ No newline at end of file
diff --git a/README.md b/README.md
index 3b000f8..d029c95 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,20 @@
-# Android Playground
+# Face Detection with CameraX + MLKit
-Playground for Android samples, mainly for [articles](https://medium.com/@husayn.hakeem) I write.
+Android sample app for face detection that uses CameraX and MLKit APIs.
+
+![alt text](https://github.com/husaynhakeem/android-playground/blob/master/FaceDetectorSample/art/art_portrait.png)
+![alt text](https://github.com/husaynhakeem/android-playground/blob/master/FaceDetectorSample/art/art_landscape.png)
+
+It mainly showcases:
+- Setting up the camera correctly with a Preview and ImageAnalysis use case.
+- Setting up MLKit's face detector.
+- Handling face bounds coordinates conversion (taking into account the display rotation).
+- Drawing the face bounds around detected faces on top of the viewfinder.
+
+### Resources to learn about CameraX
+- [CameraX codelab](codelabs.developers.google.com/codelabs/camerax-getting-started)
+- [CameraX documentation](developer.android.com/training/camerax)
+- [Displaying a camera preview with PreviewView](medium.com/androiddevelopers/display-a-camera-preview-with-previewview-86562433d86c)
+
+### Resources to learn about MLKit
+- [MLKit documentation](developers.google.com/ml-kit/vision/face-detection)