Android SDK from version 1.0 (API Level 1) has integrated the simple face recognition function, by calling Facedetector we can implement bitmap multi-face recognition on Android platform (can have multiple faces in a picture). It looks for the human face principle is: looks for the eye . It returns the face data of faces, by calling public float eyesdistance (), the public void Getmidpoint (PointF point), we can get the detected two-eye spacing, and the center point position of the two eyes (midpoint). Public float confidence () can return the confidence level of the face data (0~1), the greater the value, the more accurate the face data.
Process
1. Read a picture to bitmap (from the resource, or choose from a mobile album)
2. Using the Facedetector API to analyze the bitmap, the detected face data is stored in Facedetector.face in a list of faces;
3. Display the human face frame on the picture.
Source Code
Activity_main.xml
<linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" android:layout_width =" match_parent " android:layout_height =" match_parent " android:orientation =" vertical " android:padding = "10DP" ; <button android:id = "@+id/btn_select" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:text = "select Picture" /> <button android:id = "@+id/btn_detect" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margintop
= "5DP" android:text =" detection face "/> <ImageViewandroid:id= "@+id/image"android:layout_width="Fill_ Parent "android:layout_height=" Fill_parent "android:layout_margintop=" 5DP " /> </linearlayout>
Mainactivity.java
PackageCom.example.faceandroidtest;Importandroid.app.Activity;ImportAndroid.app.ProgressDialog;ImportAndroid.content.Intent;ImportAndroid.database.Cursor;ImportAndroid.graphics.Bitmap;ImportAndroid.graphics.BitmapFactory;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Color;ImportAndroid.graphics.Paint;ImportAndroid.graphics.PointF;ImportAndroid.media.FaceDetector;ImportAndroid.media.FaceDetector.Face;ImportAndroid.net.Uri;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.provider.MediaStore;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.ImageView;ImportAndroid.widget.Toast; Public class mainactivity extends Activity implements Onclicklistener { Private Static Final intRequest_code_select_pic = -;Private Static Final intMax_face_num =Ten;//maximum number of human faces to be detected Private intRealfacenum =0;//Actual number of human faces detected PrivateButton selectbtn;PrivateButton detectbtn;PrivateImageView image;PrivateProgressDialog PD;PrivateBitmap BM;//Bitmap object of the selected picture PrivatePaint paint;//Paint for face area Private Booleanhasdetected =false;//Mark whether a face is detected @Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Initview (); Paint =NewPaint (); Paint.setcolor (Color.Blue); Paint.setstrokewidth (2); Paint.setstyle (Paint.Style.STROKE);//Set the box to be empty instead of a solid blockPD =NewProgressDialog ( This); Pd.settitle ("Hint"); Pd.setmessage ("Testing, please wait a moment"); }/** * Control initialization * / Private void Initview() {selectbtn = (Button) Findviewbyid (r.id.btn_select); Selectbtn.setonclicklistener ( This); DETECTBTN = (Button) Findviewbyid (r.id.btn_detect); Detectbtn.setonclicklistener ( This); Image = (ImageView) Findviewbyid (r.id.image); }/** * Select picture from gallery */ Private void selectpicture() {Intent Intent =NewIntent (); Intent.setaction (intent.action_get_content); Intent.settype ("image/*"); Startactivityforresult (Intent, request_code_select_pic); }@Override protected void Onactivityresult(intRequestcode,intResultCode, Intent data) {Super. Onactivityresult (Requestcode, ResultCode, data);if(Requestcode = = Request_code_select_pic && ResultCode = = ACTIVITY.RESULT_OK) {//Get the selected pictureUri selectedimage = Data.getdata (); String[] Filepathcolumn = {MediaStore.Images.Media.DATA}; cursor cursor = getcontentresolver (). Query (SelectedImage, Filepathcolumn,NULL,NULL,NULL); Cursor.movetofirst ();intColumnIndex = Cursor.getcolumnindex (filepathcolumn[0]); String Selectedimagepath = cursor.getstring (columnindex); BM = Bitmapfactory.decodefile (Selectedimagepath);//To use Android built-in face recognition, the bitmap object needs to be converted to rgb_565 format, otherwise it will not be recognized .BM = Bm.copy (Bitmap.Config.RGB_565,true); Cursor.close (); Image.setimagebitmap (BM); hasdetected =false; } }//private void SelectPicture () {//BM = Bitmapfactory.decoderesource (Getresources (), r.drawable.test1);//BM = Bm.copy (Bitmap.Config.RGB_565, true);//Image.setimagebitmap (BM);//hasdetected = false;// } /** * Detect face * * Private void Detectface(){if(BM = =NULL) {Toast.maketext ( This,"Please select a picture first", Toast.length_short). Show ();return; }if(hasdetected) {Toast.maketext ( This,"Human face detected", Toast.length_short). Show (); }Else{NewFindfacetask (). Execute (); } }Private void Drawfacesarea(facedetector.face[] faces) {Toast.maketext ( This,"detected in picture"+ Realfacenum +"Zhang Man's face", Toast.length_short). Show ();floatEyesdistance =0F//two eye spacingCanvas Canvas =NewCanvas (BM); for(inti =0; i < faces.length; i++) {Facedetector.face face = faces[i];if(Face! =NULL) {PointF PointF =NewPointF (); Face.getmidpoint (PointF);//Get face center pointEyesdistance = Face.eyesdistance ();//Get the distance between the eyes of the human face //Draw the area of a human faceCanvas.drawrect (Pointf.x-eyesdistance, pointf.y-eyesdistance, pointf.x + eyesdistance, PointF.y + eyesDistance, paint) ; hasdetected =true; } }//Draw the face area to refresh ImageView.Image.invalidate (); }/** * Detecting the face in the image takes some time, so put it in the Asynctask to execute * @author Yubo * */ Private class findfacetask extends asynctask<void, void, Facedetector. Face []>{ @Override protected void OnPreExecute() {Super. OnPreExecute (); Pd.show (); }@Override protectedFace[]Doinbackground(Void ... arg0) {//The key is the following three lines of codeFacedetector Facedetector =NewFacedetector (Bm.getwidth (), Bm.getheight (), max_face_num); Facedetector.face[] faces =NewFacedetector.face[max_face_num]; Realfacenum = facedetector.findfaces (BM, faces);if(Realfacenum >0){returnFaces }return NULL; }@Override protected void OnPostExecute(face[] result) {Super. OnPostExecute (Result); Pd.dismiss ();if(Result = =NULL) {Toast.maketext (mainactivity. This,"Sorry, no face detected in the picture.", Toast.length_short). Show (); }Else{Drawfacesarea (result); } } } Public void OnClick(View arg0) {Switch(Arg0.getid ()) { CaseR.id.btn_select://Select PictureSelectPicture (); Break; CaseR.id.btn_detect://Detection of human faceDetectface (); Break; } }}
In the source of the first max_face_num can be detected by the maximum number of faces set to 5.
privatestaticfinalint5;//最大可以检测出的人脸数量
Test results
The guess should be the highest recognition rate in the population of the 5 avatar, because the maximum number of faces can be detected 5, so only the highest recognition rate of the top 5 avatars.
When the maximum number of faces max_face_num can be detected is set to 10.
privatestaticfinalint10;//最大可以检测出的人脸数量
Same picture test results
Reference reference
- Android API Facial detection (face Detect)
- Using face detector in ANDROIDSDK to realize facial recognition
- face++ official website
Facedetector Simple example of face recognition in Android