本文的目标是介绍android中人脸识别API。
在翻看Android API的时候无意间发现Android自带了人脸识别的接口:android.media.FaceDetector,于是就实验了一下,下面是过程:
1.布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.yongyida.robot.speech.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_toEndOf="@+id/textView"
android:layout_marginTop="70dp"
android:onClick="onClickButtonOne"/>
</RelativeLayout>
2.业务代码
package com.yongyida.robot.speech;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.FaceDetector;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
}
int imgs[]={R.drawable.th,R.drawable.th2,R.drawable.th3,R.drawable.th4,R.drawable.th5,R.drawable.th6,R.drawable.th7};
public void onClickButtonOne(View v){
for (int i:imgs){
BitmapFactory.Options mOption = new BitmapFactory.Options();
mOption.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap mBitmap= BitmapFactory.decodeResource(getResources(), i,mOption);
int maxFaces = 5;
FaceDetector mFaceDetector = new FaceDetector(mBitmap.getWidth(),mBitmap.getHeight(),maxFaces);
FaceDetector.Face[] mFace = new FaceDetector.Face[maxFaces];
maxFaces = mFaceDetector.findFaces(mBitmap, mFace);
Log.v("xzh","No."+i+"face:"+"face number:"+maxFaces+" width:"+mBitmap.getWidth()+"height:"+mBitmap.getWidth());
}
}
3.实现效果
face number:1 width:102 height:102
face number:0 width:1247 height:1247
face number:1 width:182 height:182
face number:3 width:450 height:450
face number:0 width:1019 height:1019
face number:0 width:278 height:278
4.总结:从实验的结果来看,得到效果还是不太理想,但是对于一些人脸特征比较明显的图片,识别率还是可以;还有就是对于大图片识别率为0,对于小图片识别率还算理想。