Thursday, May 17, 2012

Face Detection in Android

Here we go with the example of Face Detaction in android.
It is pretty much simpler then I expected.
1) Create a project… name it FaceDetection
2) Create A class
In your onCreate method write setContentView(new MyView(this)); after call to super.
public void onCreate(Bundle savedInstanceState)
    setContentView(new MyView(this));
So our next step is to create MyView Class.

public MyView(Context context)
     BitmapFactory.Options bitmapFatoryOptions=new BitmapFactory.Options();
     myBitmap=BitmapFactory.decodeResource(getResources(), R.drawable.faceswapping,bitmapFatoryOptions);
     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.

protected void onDraw(Canvas canvas)
     canvas.drawBitmap(myBitmap, 0,0, null);
     Paint myPaint = new Paint();

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

           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.
Find working example in and attachment.


  1. sorry for distrubing you, but i just want to share the article about face detection,
    let's check this link
    i wish that article can be usefull