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

2 comments:

  1. sorry for distrubing you, but i just want to share the article about face detection,
    let's check this link http://repository.gunadarma.ac.id/bitstream/123456789/3365/1/Automed%20Face%20Detection%20and%20Feature%20Extraction%20Using%20Color%20Feret%20Image%20Database.pdf
    i wish that article can be usefull

    ReplyDelete