Face Detection Example Tutorials In Android

This example will help you to create face detection application.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it FaceDetectionExample.

2.) Write following into res/values/strings.xml:

 

<resources>

<string name="app_name">FaceDetectionExample</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_face_detection_example">FaceDetectionExample</string>
<string name="app_info">Click on the 'Take Picture' to take a picture using Camera and detect the face(s) in the picture taken.</string>
<string name="take_picture">Take Picture</string>
<string name="detect_face">Detect Face</string>
</resources>

 

 

3.) Create and write following into res/layout/detectlayout.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/image_view"
android:layout_weight="1.0"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/detect_face"
android:text="@string/detect_face"
android:layout_gravity="center_horizontal"/>

</LinearLayout>

 

 

4.) Write following into main.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/app_info"
android:gravity="center_horizontal"
android:layout_weight="1.0"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/take_picture"
android:layout_margin="5dip"
android:text="@string/take_picture"
android:layout_gravity="center_horizontal"/>
</LinearLayout>

 

 

5.) Write following into AndroidManifest.xml:

 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.facedetectionexample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".FaceDetectionExample"
android:label="@string/title_activity_face_detection_example" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

 

 

6.) Run for output.

Steps:

1.) Create a project named FaceDetectionExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: FaceDetectionExample
Package Name: com. example. FaceDetectionExample
Activity Name: FaceDetectionExample
Min SDK Version: 2.2

2.) Open FaceDetectionExample.java file and write following code there:

 

package com.example.facedetectionexample;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class FaceDetectionExample extends Activity {
private static final int TAKE_PICTURE_CODE = 100;
private static final int MAX_FACES = 5;

private Bitmap cameraBitmap = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

((Button)findViewById(R.id.take_picture)).setOnClickListener(btnClick);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if(TAKE_PICTURE_CODE == requestCode){
processCameraImage(data);
}
}

private void openCamera(){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(intent, TAKE_PICTURE_CODE);
}

private void processCameraImage(Intent intent){
setContentView(R.layout.detectlayout);

((Button)findViewById(R.id.detect_face)).setOnClickListener(btnClick);

ImageView imageView = (ImageView)findViewById(R.id.image_view);

cameraBitmap = (Bitmap)intent.getExtras().get("data");

imageView.setImageBitmap(cameraBitmap);
}

private void detectFaces(){
if(null != cameraBitmap){
int width = cameraBitmap.getWidth();
int height = cameraBitmap.getHeight();

FaceDetector detector = new FaceDetector(width, height,FaceDetectionExample.MAX_FACES);
Face[] faces = new Face[FaceDetectionExample.MAX_FACES];

Bitmap bitmap565 = Bitmap.createBitmap(width, height, Config.RGB_565);
Paint ditherPaint = new Paint();
Paint drawPaint = new Paint();

ditherPaint.setDither(true);
drawPaint.setColor(Color.RED);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(2);

Canvas canvas = new Canvas();
canvas.setBitmap(bitmap565);
canvas.drawBitmap(cameraBitmap, 0, 0, ditherPaint);

int facesFound = detector.findFaces(bitmap565, faces);
PointF midPoint = new PointF();
float eyeDistance = 0.0f;
float confidence = 0.0f;

Log.i("FaceDetector", "Number of faces found: " + facesFound);

if(facesFound > 0)
{
for(int index=0; index<facesFound; ++index){
faces[index].getMidPoint(midPoint);
eyeDistance = faces[index].eyesDistance();
confidence = faces[index].confidence();

Log.i("FaceDetector",
"Confidence: " + confidence +
", Eye distance: " + eyeDistance +
", Mid Point: (" + midPoint.x + ", " + midPoint.y + ")");

canvas.drawRect((int)midPoint.x - eyeDistance ,
(int)midPoint.y - eyeDistance ,
(int)midPoint.x + eyeDistance,
(int)midPoint.y + eyeDistance, drawPaint);
}
}

String filepath = Environment.getExternalStorageDirectory() + "/facedetect" + System.currentTimeMillis() + ".jpg";

try {
FileOutputStream fos = new FileOutputStream(filepath);

bitmap565.compress(CompressFormat.JPEG, 90, fos);

fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

ImageView imageView = (ImageView)findViewById(R.id.image_view);

imageView.setImageBitmap(bitmap565);
}
}

private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.take_picture: openCamera(); break;
case R.id.detect_face: detectFaces(); break;
}
}
};
}

 

 

3.) Compile and build the project.

Note:- For better results check on device.

Output

Leave a Comment:

16 comments
Nikhil Baliga says December 20, 2012

Thanks for the tutorial 🙂 Worked great!

Reply
Rajesh Patil says December 24, 2012

Hi,
its not working on my phone.(LGP500)

Reply
Rob says January 10, 2013

Hi,

Great example thanks

But I can’t seem to get it to detect a face. Any idea what I could be doing wrong?

Reply
devang says January 25, 2013

i am getting the error again n again dt “unfortunately facedetection example has stopeed”
wats da resn??

Reply
devang says January 25, 2013

i am getting the error again n again dt “unfortunately facedetection example has stopeed”
wats da resn?????

Reply
Itu Doben says March 28, 2013

This demo worked great on my Nexus w/ Android 4.2.
Good work! It’s rare to see something I can just copy and works right away very helpful.
i

Reply
Blues says July 9, 2013

This sounds like good tutorial so I tried it out but I am getting an error
“R cannot be resolved to a variable

Please help. THanks!

Reply
anta says August 27, 2013

what methode you use in this application ?

Reply
joy says September 5, 2013

Hi,

Thank you so much for posting this tutorial because i’ve been looking for this for a long time ago for my studies.. May I ask if you can also help me with my project regarding face detection as a form of login for online quizzes as to avoid students will cheat or someone else will answer for them. Or maybe use face detection to vote?

Joy

Reply
Nikesh says September 25, 2013

Does this code then store the face?

Reply
tendai says October 24, 2013

nice tutorial, did i miss anything coz the FaceDetectorExample.MAX_FACES is giving me an error how do i go about it to fix the error

Reply
tendai says October 24, 2013

i got it never mind the question

Reply
Druvho says November 2, 2013

good one… thanks

Reply
Hemant says February 5, 2015

Hi Sir/Madam,

Your site are very helpful for face detection app and its work properly but when i try to test on HTC mobile this app are not work properly. It’s not very big issue. Actually my problem is that i have want to know the name of image which is compare internally if you resolve this issue please help me or any one who can resolved my problem please help me by E-mail.

Thanks All

Reply
Rudy says February 25, 2015

Will I create two FaceDetectionExample project? I created the first one and eclipse won’t allow me to create a new one with the same project name. Help please?

Reply
Wallace says March 12, 2015

Thank you very much ! I’m from Brazilian and i am very happy by helping people !
I’m doing my science course conclusion work computer and it helped me a lot ! Thanks again

Reply
Add Your Reply