Welcome reprint, when reproduced please indicate the source: http://blog.csdn.net/android_for_james/article/details/51016170
Today brings us a feature that uses face++ to realize face recognition
Let's go to this face++ official website to see: http://www.faceplusplus.com.cn
We open the case to see many of the software we know is used by the company provided by the SDK
We then click the Developer Center Developer tools and SDK to download the SDK we need
Then click Create app in my app and he'll give us two keys.
To save these two values, we'll use them in the program.
What I realized today was to achieve facial capture and identify gender and age to see
No more gossip, let's take a look at the implementation.
1. Tool class constant for storing keys
public class Constant { //set two previously obtained two constants public static final String key= "2029451928755e97039b8138cfa8f8ca"; public static final String secret= "5rnoyatb9vqpa5kerpmo6bp2aw9fxml0";}
2.Tool Class Internetdetect
Import Android.graphics.bitmap;import Com.facepp.error.faceppparseexception;import com.facepp.http.HttpRequests; Import Com.facepp.http.postparameters;import Org.json.jsonobject;import Java.io.bytearrayoutputstream;public class Internetdetect {public interface CallBack {void success (Jsonobject jsonobject); void error (Faceppparseexception exception); } public static void Dectect (Final Bitmap Bitmap, final CallBack CallBack) {//Because it is a time-consuming operation to send data to the network, it is performed in a new thread New Thread (New Runnable () {@Override public void run () {/*1. Set request * 2. Create a bitmap * 3. Create a character array stream * 4. Convert bitmap to characters and pass in the stream * 5. New character Array Accept stream * 6. Create a Send packet * 7. Create an accepted packet * * * * * * * Prequests httprequests=new httprequests (constant.key,constant.secret,true,true); Dig the entire view from 0, 0, and the latter two are the target size. Bitmap Bitmapsmall = Bitmap.createbitmap (Bitmap, 0, 0, bitmap.getwidth (), Bitmap.getheight ()); Here the API requires passing in a byte array of data, so the byte array output stream Bytearrayoutputstream stream=new bytearrayoutputstream (); The/*bitmap.compress () method can be used to compress bitmap-->byte[] both the bitmap and the specified outputstream. If true, the bitmap can be set by passing a corresponding InputStream Bitmapfactory.decodestream (rebuild) first parameter to the JPEG or P ng format, the second parameter is the picture quality, the third parameter is a stream information */bitmapsmall.compress (Bitmap.CompressFormat.JPEG, +, stream); Byte[] Arrays=stream.tobytearray (); Implement the Send Parameters function Postparameters parameters=new postparameters (); Send data parameters.setimg (arrays); The server returns a Jsonobject data jsonobject jsonobject=httprequests.detectiondetect (parameters); System.out.println ("Jsonobject:" +jsonobject.tostring ()); if (callback!=null) {//Set callback Callback.su Ccess (Jsonobject); }} catch (Faceppparseexception e) {System.out.println ("error"); E.printstacktrace (); if (callback!=null) {callback.error (e); }}}). Start (); }}
3.MainActivity
Import Android.content.intent;import Android.database.cursor;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.paint;import Android.net.uri;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.provider.mediastore;import Android.support.v7.app.actionbaractivity;import Android.text.method.scrollingmovementmethod;import Android.view.view;import Android.widget.button;import Android.widget.imageview;import Android.widget.textview;import Com.facepp.error.faceppparseexception;import Org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsonobject;public class MainActivity extends Actionbaractivity implements View.onclicklistener {private static final int pick_code = 1; Private ImageView Myphoto; Private Button getImage; Private Button detect; Private TextView tip; Private View mwaitting; Private String Imagepath=null; Private Paint Mypaint; PriVate Bitmap Mybitmapimage; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mypaint=new Paint (); Initviews (); Initevent (); } private void Initviews () {myphoto= (ImageView) Findviewbyid (R.id.id_photo); Getimage= (Button) Findviewbyid (r.id.get_image); detect= (Button) Findviewbyid (r.id.detect); tip= (TextView) Findviewbyid (R.id.id_tip); Mwaitting=findviewbyid (r.id.id_waitting); Tip.setmovementmethod (Scrollingmovementmethod.getinstance ()); } private void Initevent () {Getimage.setonclicklistener (this); Detect.setonclicklistener (this); } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.get_image: Get system selection Picture Intent Intent intent=new Intent (Intent.action_pick); Intent.settype ("image/*"); Open Select Image function Response code is Pick_code Startactivityforresult (Intent,pick_code); Break Case R.id.detect://Show progress bar round mwaitting.setvisibility (view.visible); Here you need to be aware of whether the user has not selected the image directly clicked the Detect button//otherwise will be reported a null pointer exception cause the program crashes if (imagepath!=null&&! Imagepath.trim (). Equals ("")) {//If the picture is not directly clicked, compress the currently selected picture Resizephoto (); }else {//otherwise the default background image is passed in as bitmap MYBITMAPIMAGE=BITMAPFAC Tory.decoderesource (Getresources (), r.drawable.test1); }//Set callback Internetdetect.dectect (Mybitmapimage, New Internetdetect.callback () { @Override public void Success (Jsonobject jsonobject) {Message message=mes Sage.obtain (); message.what=msg_sucess; Message.obj=jSonobject; Myhandler.sendmessage (message); } @Override public void error (Faceppparseexception exception) { Message Message=message.obtain (); Message.what=msg_error; Message.obj=exception; Myhandler.sendmessage (message); } }); Break }}//Set response Intent request @Override protected void Onactivityresult (int requestcode, int resultcode, Intent Intent) { Super.onactivityresult (Requestcode, ResultCode, intent); if (Requestcode==pick_code) {if (intent!=null) {//Get Picture path//Get all Picture Resource Uri uri=intent.getdata (); Set the pointer to get an instance of Contentresolver Cursor cursor=getcontentresolver (). query (Uri,null,null,null,null); Cursor.movetofirst (); Returns the index entry position int index=cursor.getcolumnindex (MediaStore.Images.ImageColumns.DATA); Returns the index entry path imagepath=cursor.getstring (index); Cursor.close (); This jar package requires the requested image size not to exceed 3m, so a compressed picture operation Resizephoto (); Myphoto.setimagebitmap (Mybitmapimage); Tip.settext ("click detect==>"); }}} private void Resizephoto () {//Get bitmapfactory operation right bitmapfactory.options Options = new Bi Tmapfactory.options (); If set to True, the picture is not fetched, memory is not allocated, but the high-width information of the picture is returned. Options.injustdecodebounds = true; Bitmapfactory.decodefile (imagepath,options); Calculate the width of the Gaoyao as much as possible than the Ratio=math.max double (options.outwidth*1.0d/1024f,options.outheight*1.0d/1024f); Sets the multiple of the picture's zoom. If set to 4, then the width and height are the original 1/4, then the figure is the original 1/16. options.insamplesize= (int) Math.ceil (ratio); We're here and want him to display the picture so this place is set to false options.injustdecodebounds=false; The use of the optionsTo get a thumbnail image efficiently. Mybitmapimage=bitmapfactory.decodefile (imagepath,options); } private static final int msg_sucess=11; private static final int msg_error=22; Private Handler myhandler=new Handler () {@Override public void Handlemessage (Message msg) {s Uper.handlemessage (msg); Switch (msg.what) {case msg_sucess://close buffer bar Mwaitting.set Visibility (View.gone); Get the Jsonobject data returned in the new thread Jsonobject rsobj= (jsonobject) msg.obj; Prepare the bitmap, this will parse the data preparebitmap (rsobj) that Jsonobject returns; Let the main thread of the frame refresh Myphoto.setimagebitmap (mybitmapimage); Break Case MSG_ERROR:mWaitting.setVisibility (View.gone); String errormsg= (String) msg.obj; Break } } }; private void PREparebitmap (Jsonobject JS) {//Create a new object Bitmap use it as a canvas operation Bitmap Bitmap=bitmap.createbitmap (mybitmapimage.ge Twidth (), Mybitmapimage.getheight (), Mybitmapimage.getconfig ()); Instantiate a canvas canvas=new canvas (bitmap); Draw the original image to the canvas above Canvas.drawbitmap (mybitmapimage, 0, 0, NULL); Parsing the returned jsonobject data try {//jsonobject contains many Jsonarray, but here we need the information in the array with the keyword face Jsonarr Ay faces=js.getjsonarray ("face"); Get several face int facecount=faces.length (); Let the hint text show the face number Tip.settext ("Find" +facecount); The following is a separate piece of information for each face. for (int i=0;i<facecount;i++) {//Get information on each person's face Jsonobject Face=faces.getjsonobject (i); Get the details of the face location information Jsonobject position=face.getjsonobject ("position"); float x= (float) position.getjsonobject ("center"). GetDouble ("X"); float y= (float) position.getjsonobject ("center"). GetDouble ("Y"); float w= (float) position.getdouble ("width"); float h= (float) position.getdouble ("height"); Note that the parameters you get here are not actual pixel values, but a scale, which is relative to the entire screen.//So we're going to do a little bit of data processing when we use X=X/100*BITMAP.G Etwidth (); Y=y/100*bitmap.getheight (); W=w/100*bitmap.getwidth (); H=h/100*bitmap.getheight (); Set Brush color Mypaint.setcolor (0xFFFFFFFF); Set the brush width mypaint.setstrokewidth (3); Draw a rectangular box canvas.drawline (x-w/2,y-h/2,x-w/2,y+h/2,mypaint); Canvas.drawline (X-w/2,y-h/2,x+w/2,y-h/2,mypaint); Canvas.drawline (X+w/2,y-h/2,x+w/2,y+h/2,mypaint); Canvas.drawline (X-w/2,y+h/2,x+w/2,y+h/2,mypaint); Get age Information int age=face.getjsonobject ("attribute"). Getjsonobject ("Age"). GetInt ("value"); Get the gender information String gender=face.getjsonobject ("attribute"). Getjsonobject ("Gender"). GetString ("value"); System.out.println ("Age:" +age); System.out.println ("Gender:" +gender); Now to convert the resulting text information into an image message, we write a special function to deal with Bitmap Agebitmap=buildagebitmap (age, ("Male"). Equals (gender)); To make a picture of the bubble zoom, this is necessary, when the face is very small we need to turn the hint bubble also small int agewidth=agebitmap.getwidth (); int Agehight=agebitmap.getheight (); if (Bitmap.getwidth () <myphoto.getwidth () &&bitmap.getheight () <myphoto.getheight ()) { Set the zoom ratio to float Ratio=math.max (bitmap.getwidth () *1.0f/ Myphoto.getwidth (), Bitmap.getheight () *1.0f/myphoto.getheight ()); Finish zooming Agebitmap=bitmap.createscaledbitmap (Agebitmap, (int) (agewidth*ratio*0.8), (int) (agehight*ratio*0.5), false) ; }//Draw a hint bubble canvas.drawbitmap (agebitmap,x-agebitmap.getwidth ()/2,y-h/2-agebitmap on the canvas. GetHeight (), NULL); Get the new bitmap mybitmapimage=bitmap; }} catch (Jsonexception e) {e.printstacktrace (); }} private Bitmap buildagebitmap (int age, Boolean Ismale) {//here to convert the text information into image information, if you take canvas directly to draw the amount of operation is too large//because Here are some tricks that will prompt the bubble to set it to a TextView, his background is the bubble background//his content to the left is the picture showing gender right is the age TextView tv= (TextView) Mwaitting.findviewbyid (R.id.id_age_and_gender); Here to remember to display the number when the best followed by a "" or sometimes will not show out tv.settext (age + "); if (Ismale) {//Judge gender Tv.setcompounddrawableswithintrinsicbounds (Getresources (). Getdrawable (R.D Rawable.male), null,null,null); }else {tv.setcompounddrawableSwithintrinsicbounds (Getresources (). Getdrawable (R.drawable.female), null,null,null); }//Use Setdrawingcacheenabled (Boolean flag) to increase the drawing speed//view the contents of the component can be saved by the cache mechanism as bitmap//here to get its cache first through The Setdrawingcacheenable method opens the cache,//and then calls the Getdrawingcache method to get the cache image of the view. Tv.setdrawingcacheenabled (TRUE); Bitmap Bitmap=bitmap.createbitmap (Tv.getdrawingcache ()); Close license Tv.destroydrawingcache (); return bitmap; }}Layout file is relatively simple so the code I don't upload
Here I use the red font to mark the problems I encountered in the implementation of the process I hope you can avoid:
1. When writing the button response, you should pay attention to determine whether the user did not select the image and directly clicked the Detect button, so that the picture to avoid the existence of a null pointer exception problem
2. When uploading a picture, make sure that the image is less than 3M so note the compression of the image
3. The bubble treatment has the skill, treats it as textview more convenient
4. When drawing bubbles, also pay attention to scaling otherwise, when the face is very small, the bubble will occupy the entire picture resulting in a reduced user experience
Hope to have some help, welcome reprint but to mark the source, thank you!
There is any shortage of places can leave a message to me I will reply and correct as soon as possible!
Welcome to follow my blog: http://blog.csdn.net/android_for_james
Android uses face++ architecture package for face recognition