Android识别图片中脸部信息

在Android开发中,大部分应用都是以用户为第一位,用户都有自己的个人中心,用来展示自己的信息,头像无疑是展示自己最直观的方式,随着各种政策的出台,实名认证,真人头像变得尤为重要,如果要求上传真人头像,那就需要后台做校验,判断是不是真人,如果真人审核,那工作量是非人力所能为的,这时候就用到各种识别图片的算法,来做这些工作了,这里主要介绍Android里面谷歌开放的图片脸部识别的API。

上代码:

依赖:

dependencies {
    compile 'com.google.android.gms:play-services-vision:8.4.0'
}
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
  



  private Bitmap getFaceBitmap(Bitmap bmp, Context context) {

        FaceDetector faceDetector = new
                FaceDetector.Builder(context).setTrackingEnabled(false)
                .build();
        if (!faceDetector.isOperational()) {
            System.out.println("Face detector not working");
            return null;
        }
        Bitmap faceBitmap = null;

        Frame frame = new Frame.Builder().setBitmap(bmp).build();

        SparseArray<Face> faces = faceDetector.detect(frame);
        Log.e("RoungImage", "00100bmp.getWidth" + bmp.getWidth());
        Log.e("RoungImage", "00100bmp.getHeight" + bmp.getHeight());
        Log.e("RoungImage", "006faces:" + faces.size());
        for (int i = 0; i < faces.size(); i++) {
            Face thisFace = faces.valueAt(i);

            int faceWidth = (int) thisFace.getWidth();
            Log.e("RoungImage", "007faceWidth:" + faceWidth);
            int faceHeight = (int) thisFace.getHeight();
            Log.e("RoungImage", "008faceHeight:" + faceHeight);
            int x1 = (int) thisFace.getPosition().x;
            Log.e("RoungImage", "009x1:" + x1);
            int y1 = (int) thisFace.getPosition().y;
            Log.e("RoungImage", "0010y1" + y1);


            faceBitmap = Bitmap.createBitmap(bmp,
                    x1 > (faceWidth / 2) ? (x1 - faceWidth / 2) : 0,
                    y1 > (faceHeight / 2) ? (y1 - faceHeight / 2) : 0,
                    1.5 * faceWidth < bmp.getWidth() ? (int) (1.5 * faceWidth) : bmp.getWidth(),
                    1.5 * faceHeight < bmp.getWidth() ? (int) (1.5 * faceHeight) : bmp.getHeight());

        }
        if (faceBitmap != null) return faceBitmap;
        return bmp;
    }

  

这里测试两张图片,识别图片中的脸部信息,图片如下:

识别出各种坐标以后,大致是这样的:

精确度还是很不错的。

这里只是打印一下坐标,实际还有很多其他的API,eg:眼睛是否睁开,脸部是否微笑,微笑的概率,and so on...

原文地址:https://www.cnblogs.com/spring87/p/5530257.html