之前看到有人在博客写用face++做人脸识别app,后来我也照着教程去试了一遍,发现根本行不通,原因在于他调用的库是旧版本,face++已经全面更新了版本.后来我照着face++官网新版本的API文档打了一遍代码,发现识别的结果还算差强人意,但要识别多个人脸属性,需要重复调用几个函数,太麻烦了,这也是小编今天写这篇文章的初衷,因为小编发现有一个网站提供的第三方库不仅能识别人脸,而且调用方法简便,识别多个人脸属性如性别、年龄、肤色、笑容等只需要几行代码搞定。
使用工具:Android Studio
一、打开百度云网站:http://console.bce.baidu.com/ai/?fromai=1#/ai/ocr/app/list
(1)注册、登录后,点击“创建应用”
(2)填写人脸识别模块信息(应用名称随便写)
填写完毕后,就会得到它的APPID、API Key和secret key,如下
二、将第三方库jar包加入Android studio项目里面去
网盘下载:识别jar包(通用) 提取密码:e13p
(1)将Android Studio由Android模式调成Project模式,可以看到libs文件夹,将jar包放入里面
(2)右击鼠标,选择“Add As Library”,
之后,build.gradle(Module:app)会自动出现以下指令,说明jar包添加成功
三、调用jar包里面的AipOcr函数进行人脸识别
(1)从libs文件夹里面的新添加 jar包可以看到具体函数,其中我们需要调用的函数是AipOcr,调用参数有APPID、apiKey、secretKey、图片的二进制数据流以及需要查询的人脸属性(如性别、年龄、肤色等)
(2)获取图片,该app选用两种途径:从相册中选择和调用手机相机拍摄
从相册中选择:
getImage=(Button)findViewById(R.id.getImage);
getImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent(Intent.ACTION_PICK);
in.setType("image/*");
startActivityForResult(in,PHOTO_ALBUM);
}
});
调用相机拍摄:
获取调用权限
void readRequest(){
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
}
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},2);
}
}
Camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File outputImage=new File(Environment.getExternalStorageDirectory()+File.separator+"face.jpg");
try{
if(outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
imageUri=Uri.fromFile(outputImage);
ImagePath=outputImage.getAbsolutePath();//拍摄后图片的存储路径
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,CAMERA);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//从相册中选择的图片
if(requestCode==PHOTO_ALBUM){
if(data!=null){
Uri uri=data.getData();
Cursor cursor=getContentResolver().query(uri,null,null,null,null);
cursor.moveToNext();
ImagePath=cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
cursor.close();
resizePhoto();
myPhoto.setImageBitmap(myBitmapImage);
Log.i("图片路径",ImagePath);
}
}
//相机拍摄的图片
else if(requestCode==CAMERA){
try{
resizePhoto();
myPhoto.setImageBitmap(myBitmapImage);
}catch (Exception e){
e.printStackTrace();
}
}
}
//调整图片的比例,使其大小小于1M,能够显示在手机屏幕上
public void resizePhoto(){
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;//返回图片宽高信息
BitmapFactory.decodeFile(ImagePath,options);
//让图片小于1024
double radio=Math.max(options.outWidth*1.0d/1024f,options.outHeight*1.0d/1024f);
options.inSampleSize=(int)Math.ceil(radio);//向上取整倍数
options.inJustDecodeBounds=false;//显示图片
myBitmapImage=BitmapFactory.decodeFile(ImagePath,options);
}
(3)调用函数进行人脸识别
detect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
res=null;
detect_tip.setVisibility(View.VISIBLE);
detect_tip.setText("识别中...");
if(myBitmapImage==null){
myBitmapImage=BitmapFactory.decodeResource(getResources(),R.mipmap.face2);
bitmapSmall=Bitmap.createBitmap(myBitmapImage,0,0,myBitmapImage.getWidth(),myBitmapImage.getHeight());
}
else{//由于有些图片在一些型号手机角度会倾斜,需要进行摆正
int degree=getPicRotate(ImagePath);
Matrix m=new Matrix();
m.setRotate(degree);
bitmapSmall=Bitmap.createBitmap(myBitmapImage,0,0,myBitmapImage.getWidth(),myBitmapImage.getHeight(),m,true);
}
//将图片由路径转为二进制数据流
ByteArrayOutputStream stream=new ByteArrayOutputStream();
//图片转数据流
bitmapSmall.compress(Bitmap.CompressFormat.JPEG,100,stream);
final byte[] arrays=stream.toByteArray();
//网络申请调用函数进行人脸识别
new Thread(new Runnable() {
@Override
public void run() {
HashMap<String,String> options=new HashMap<>();
options.put("face_fields","age,gender,race,beauty,expression");//人脸属性:年龄,性别,肤色,颜值,笑容
AipFace client=new AipFace("10734368","6cvleSFbyRIRHzhijfYrHZFj","SDnCUfrtH0lgrK01HgTe2ZRLNsmCx5xy");
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(6000);
res=client.detect(arrays,options);
try{
Message message = Message.obtain();
message.what = 1;
message.obj = res;
handler.sendMessage(message);
}catch (Exception e){
e.printStackTrace();
Message message = Message.obtain();
message.what = 2;
handler.sendMessage(message);
}
}
}).start();
}
});
}
(4)将返回来的网络数据进行处理
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==1){
JSONObject res=(JSONObject) msg.obj;
face_resultNum=res.optString("result_num");
if(Integer.parseInt(face_resultNum)>=1) {
try {
JSONArray js = new JSONArray(res.optString("result"));
face_age = js.optJSONObject(0).optString("age");
face_gender = js.optJSONObject(0).optString("gender");
if (face_gender.equals("female")) {
face_gender = "女";
} else {
face_gender = "男";
}
face_race = js.optJSONObject(0).optString("race");
if (face_race.equals("yellow")) {
face_race = "黄种人";
} else if (face_race.equals("white")) {
face_race = "白种人";
} else if (face_race.equals("black")) {
face_race = "黑种人";
}else if(face_race.equals("arabs")){
face_race = "阿拉伯人";
}
int express = Integer.parseInt(js.optJSONObject(0).optString("expression"));
if (express == 0) {
face_expression = "无";
} else if (express == 1) {
face_expression = "微笑";
} else {
face_expression = "大笑";
}
face_beauty = js.optJSONObject(0).optString("beauty");
double beauty=Math.ceil(Double.parseDouble(face_beauty)+25);
if(beauty>=100){//对获得的颜值数据进行一定处理,使得结果更为合理
beauty=99.0;
}
else if(beauty<70){
beauty+=10;
}
else if(beauty>80 && beauty<90){
beauty+=5;
}
else if(beauty>=90 && beauty<95){
beauty+=2;
}
face_beauty=String.valueOf(beauty);
} catch (JSONException e) {
e.printStackTrace();
}
detect_tip.setVisibility(View.GONE);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(faceRecognition.this);
String[] mItems = {"性别:" + face_gender, "年龄:" + face_age, "肤色:" + face_race, "颜值:" + face_beauty, "笑容:" + face_expression};
alertDialog.setTitle("人脸识别报告").setItems(mItems, null).create().show();
}else{
detect_tip.setVisibility(View.VISIBLE);
detect_tip.setText("图片不够清晰,请重新选择");
}
}else{
detect_tip.setVisibility(View.VISIBLE);
detect_tip.setText("图片不够清晰,请重新选择");
}
}
};
由于有些图片在一些型号手机角度会倾斜(如三星),需要获取图片的角度
public int getPicRotate(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
layout布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:background="@color/color2"
android:padding="5sp"
android:gravity="center"
android:text="火眼金睛:一张图看穿你的岁月"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/face2"
android:layout_gravity="center"
android:layout_weight="1"
android:id="@+id/myPhoto"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_gravity="center"
android:gravity="center"
android:id="@+id/detect_tip"
android:text="识别中..."/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="选图"
android:background="@drawable/button_decoration"
android:textColor="@color/white"
android:textSize="25sp"
android:layout_weight="1"
android:id="@+id/getImage"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="拍照"
android:background="@drawable/button_decoration"
android:textColor="@color/white"
android:textSize="25sp"
android:layout_weight="1"
android:id="@+id/Camera"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:background="@drawable/button_decoration"
android:textColor="@color/white"
android:textSize="25sp"
android:id="@+id/detect"
android:text="识别"/>
</LinearLayout>
</LinearLayout>
四、调试结果
完整代码下载: