Android Face Detection Example

Hi friends,

I was just sitting idle, and thinking to improve some skill. Face Detection came in my mind. I googled a bit. And I found it lot more easier then expected.

It just took one hour two understand and develop a demo. Google has provided the simplest API for Face Detection.

Here we go..

1) Create a project… name it FaceDetection

2) Create A class FaceDetectionActivity.java

In your onCreate method write setContentView(new MyView(this)); after call to super.

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setContentView(new MyView(this));
}

So our next step is to create MyView Class.

public MyView(Context context)
{
super(context);
BitmapFactory.Options bitmapFatoryOptions=new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig=Bitmap.Config.RGB_565;
myBitmap=BitmapFactory.decodeResource(getResources(), R.drawable.faceswapping,bitmapFatoryOptions);
width=myBitmap.getWidth();
height=myBitmap.getHeight();
detectedFaces=new FaceDetector.Face[NUMBER_OF_FACES];
faceDetector=new FaceDetector(width,height,NUMBER_OF_FACES);
NUMBER_OF_FACE_DETECTED=faceDetector.findFaces(myBitmap, detectedFaces);
}

Let me explain the constructor…

  • For FaceDetection we need to convert in bitmap format that too in RGB_565.
  • Now get the image from the drawable folder. Get the width and height of image.
  • Now the reason I feel this API the simplest is coming now.
  • You need to pass the number of faces you want to detect.It will return the array of Face type.Last three lines is having logic for that.So you must declare an array with the size of number of faces you want to detect.

Now when the face gets detected we will draw a red rectangle on it.For that we need to write few lines in our onDraw method.

@Override
protected void onDraw(Canvas canvas)
{
canvas.drawBitmap(myBitmap, 0,0, null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);

for(int count=0;count<NUMBER_OF_FACE_DETECTED;count++)
{
Face face=detectedFaces[count];
PointF midPoint=new PointF();
face.getMidPoint(midPoint);

eyeDistance=face.eyesDistance();
canvas.drawRect(midPoint.x-eyeDistance, midPoint.y-eyeDistance, midPoint.x+eyeDistance, midPoint.y+eyeDistance, myPaint);
}
}

  • drawRect is taking five parameter left x,y and top x,y coordinate.From that given pint it will start drawing rectangle.We need to pass paint object also.

For more help you can download source code here.

51 thoughts on “Android Face Detection Example

  1. How can we adjust the drawrect by detecting the face because i need to detect he exact face using this parameter and how to crop the selected area ???

    thks in advance

      1. haiiii …Thks for u’r reply actually i have to put a frame on top of the camera view and while saving that image it have to save with that particular frame is it possible??
        Right the current code its detecting the face its fine its working fine but what i am doing in my current project i need to Detect the whole Face(hair,cap what ever) not exact face….if u know the answer try to resolve my problem dude….

        Thks in advance…

        1. Ok. I got your point. You want to detect faces while camera preview is on, right ?
          I do not have much idea about it. Open CV is something related to images. You can spend some time searching on that. I will also look in to the problem and will tell you as soon as I get the solution

          1. Exactly i need to detect the face while camera preview is on and more over i can set a frame at top of camera preview..while taking photo the frame should embedded and should be save with that frame is it possible to that ????or is their any easy way to crop a face and fix into my frame …..
            Thks for replying …..i am new this concept that’s why i am not getting idea how to resolve this thing …however i am trying for that if i get i will update u soon and if u get any useful links pls share it .. TC

            1. For that I guess you need to make your own camera preview. And need to work a lot on bitmaps. Bit difficult task. (You might not getting any problem if you open camera using intent and camera supports face detection). For more queries mail me on hardik.trivedi_11@yahoo.com

              You too TC 🙂

  2. Hi… really very nice tutorial… I want to implement FaceRecognition login in my application… pls help me

    1. Hey, To login using face recognition is bit different then face detection. What I have implemented is face detection. Android 4.0 has some Face Recognition library. Need to dig into that.

  3. getting error
    10-26 18:19:17.726: E/(14065): ERROR: Return 0 faces because error exists in btk_FaceFinder_putDCR.
    ran the code in nexus 7

  4. hey, i wanted to extract the face(.i.e face inside the rectangle) to other image, is that possible without open cv? or, how can i do that?
    my aim of project is to recognize faces, detection is half part of project for me.

    1. Yea it is possible. What you need to do is image clipping.
      We are drawing a green rectangle over the face. If you observe loop in onDraw method. We have value of x,y axis. Apply the clipping algorithm there.

      1. sorry sir, i was not able to do that yet, i am still stuck on face detection!
        for recognition i went a lot through open cv, but later learned that android 4.0 is capable of ‘face recognition’, but at this moment i am totally confused, please help!

  5. hey dude m creating an app on face recognition and i want to know what are the basic steps to do dat. plzz do reply cuz its my project and very less tym isthere

    1. What kind of app you are making ? From 4.0 onwards Android itself providing powerful Face Recognition lib.

      You can use ‘open CV’ too.

      1. Android is totally a new concept for me, since m a beginer i dnt relly knw hw m i suppose to use all this library. wud u mind passing me the code for recognition of face using android..?? plz i need to do it for my project and i have got very less tym..:/ and if nt code plz guide me thru this. thnku

  6. Hi,

    I read your blog and I need a little help regarding face recognition in andoird.
    So in your blog you have showed how to detect a face in a picture . I need to detect as well as match that face from a database of pictures to see if the face is of a know entity or not.
    Do you know any step by step procedure of doing this ?

    Also can you please email me your source code that you have uploaded on mediafire, because mediafire is blocked in our college .
    email: rohit1272@iiitd.ac.in

  7. I am getting following error while running FaceDetection application, could anybody help me to resolve this issue

    [2013-04-28 21:47:47 – FaceDetection] Launching new emulator with compatible AVD ‘FaceDetector’
    [2013-04-28 21:47:47 – FaceDetection] Launching a new emulator with Virtual Device ‘FaceDetector’
    [2013-04-28 21:47:49 – Emulator] Failed to allocate memory: 8
    [2013-04-28 21:47:49 – Emulator]
    [2013-04-28 21:47:49 – Emulator] This application has requested the Runtime to terminate it in an unusual way.
    [2013-04-28 21:47:49 – Emulator] Please contact the application’s support team for more information.

    1. C:\Users\\.android\avd\.avd\config.ini

      Change
      hw.ramSize=1024

      to

      hw.ramSize=1024MB

      This will work p[robabaly 🙂

  8. thanks for this awesome code but can you please help me out for detecting barcode in similar manner as we detected faces here?

    1. Neha for barcode we have awesome libraries , like zxing and zbar.

      You can start exploring that. They are easy to integrate. I you face any problem I will help you.

      Thanks for visit.

  9. In face detection apps, why only face is detected? why hands or background is not detected? what is the logic that only face is detected?

    1. Good Question, and answer is very simple too.
      Well let me explain, what elements or parts are there on our face ? Its eyes, lips, nose, hair,eyebrow, chin, cheek

      All are have some kind of proportion ratio which tells distance to one organ to another. Now eyes and lips has some what different shade or darker complexion then any other element, that comes hair and eyebrow based upon these equations are set in algorithm. There are many face recognition algorithms are there. An efficient algo can recognize even a bald person’s face, becuase if u see a bald person will not have hair so normal algo will fail to identify forehead.

      You can refer opencv, its an open source project and very efficient.

      I hope I have gave you a satisfactory answer. I am not able to cover a much in comment’s reply.

  10. is it possible to get the image from sd card..i tried
    String Path = Environment.getExternalStorageDirectory() + “i.jpg”;
    myBitmap = BitmapFactory.decodeFile(Path);

    but its not working rather it closes with “unfortunately app has stopped”

    1. Hi Asha,

      I guess you are providing a wring path. Print Path in log and check whether path is coming correct or not.

      It should be something like

      String path = Environment.getExternalStorageDirectory().getAbsolePath() + File.separator + “i.jpg”;

      1. loading bitmap as such increases the memory usage right?? so we made use of intent so as to transfer the image…Any Way thanks for ur help…

        Is it possible to select from gallery a particular image and perform face detection over that…Any suggestions..

        1. Yes , you can definitely do it. Ultimately you need to create any image to Bitmap.

          Did my solution worked? There was a error of wrong path.

  11. Hie..When i perform face detection on stored png images inside drawable folder, it provides correct output. However, when i take an image from camera, load it into bitmap and perform face detection on it, i get an error in logcat saying facefinder returns 0 faces. Can u please help?? Do i need to convert the camera captured jpg images into png??

    1. .jpg or .png. You just need to provide the input in form of the Bitmap. Is your image is bright enough? Because android won’t detect the faces in image with bad light.

      1. Yea the same image got detected when put inside drawable folder. However, for bitmap i tried compressing it, yet it doesnt seem to detect the face.. Does the facedetection function works only on images inside drawable n not on camera captured images? Can u please provide a solution?

  12. hii.. thanks for the wonderful post…
    if possible help me how to implement face detection for ,login measure

  13. hello sir,
    thankyou so much for the post….i the problem is that the facedetection function works only on images inside drawable but not on camera captured images or gallery images? Can u please provide a solution?

    1. Hi Ekta, this simpy requires any type of bitmap image to detect the faces. So what ou need to do is convert any gallery or camera captured image to bitmap which is very easy. And pass it to my code. It will work perfectly.

  14. Hardik, what’s the reason you have taken ‘distance between eyes’ as a measure to draw rect. Is it just a random or is there any proportion/maths behind it ? I want to cut the face but without hair, only till forehead, till both the ears and till chin. Play services api can help achieving that but that includes hair as well. As you see here https://4.bp.blogspot.com/-33wqNN52EKk/Vcz0kT51vgI/AAAAAAAAB7w/l7JGPWT2hgk/s1600/image01.png
    How can I cut only till forehead, any clue ?

Leave a reply to Hardik Trivedi Cancel reply