当前位置:   article > 正文

Android面部动态识别(眼睛+嘴巴+鼻子轮廓标记)_人脸识别画出眼睛鼻子轮廓

人脸识别画出眼睛鼻子轮廓

先上效果图(整个项目源码在gitee,如果有需要的同学可以私信我,仅限于学习)

准备工作

  1. 将 Firebase 添加到您的 Android 项目(如果尚未添加)。
  2. 将 Android 版机器学习套件库的依赖项添加到您的模块(应用级层)Gradle 文件(通常为 app/build.gradle):
    1. apply plugin: 'com.android.application'
    2. apply plugin: 'com.google.gms.google-services'
    3. dependencies {
    4.   // ...
    5.   implementation 'com.google.firebase:firebase-ml-vision:24.0.3'
    6.   // If you want to detect face contours (landmark detection and classification
    7.   // don't require this additional model):
    8.   implementation 'com.google.firebase:firebase-ml-vision-face-model:20.0.1'
    9. }
  3. 非强制但建议执行的操作:对您的应用进行配置,使之在从 Play 商店安装后自动将机器学习模式下载到设备上。

    为此,请将以下声明添加到您应用的 AndroidManifest.xml 文件:

    1. <application ...>
    2.   ...
    3.   <meta-data
    4.       android:name="com.google.firebase.ml.vision.DEPENDENCIES"
    5.       android:value="face" />
    6.   <!-- To use multiple models: android:value="face,model2,model3" -->
    7. </application>
    如果您未启用在安装时下载模型的选项,模型将在您首次运行检测器时下载。您在下载完毕之前提出的请求不会产生任何结果。

输入图片指南

为了使机器学习套件准确检测人脸,输入图片必须包含由足够像素数据表示的人脸。通常,要在图片中检测的每个人脸应至少为 100x100 像素。如果要检测人脸轮廓,机器学习套件需要更高的分辨率输入:每个人脸应至少为 200x200 像素。

如果您是在实时应用中检测人脸,则可能还需要考虑输入图片的整体尺寸。较小图片的处理速度相对较快,因此,为了减少延迟时间,请以较低的分辨率捕获图片(牢记上述准确性要求),并确保主体的面部在图片中占尽可能大的部分。另请参阅提高实时性能的相关提示

图片聚焦不良会影响准确性。如果您获得的结果不可接受,请尝试让用户重新捕获图片。

1. 配置人脸检测

在对图片应用人脸检测之前,如果要更改人脸检测器的任何默认设置,请使用 FirebaseVisionFaceDetectorOptions 对象指定这些设置。您可以更改以下设置:

设置
性能模式FAST(默认)| ACCURATE

在检测人脸时更注重速度还是准确性。

检测特征点NO_LANDMARKS(默认)| ALL_LANDMARKS

是否尝试识别面部“特征点”:眼睛、耳朵、鼻子、脸颊、嘴巴。

检测轮廓NO_CONTOURS(默认)| ALL_CONTOURS

是否检测面部特征的轮廓。仅检测图片中最突出的人脸的轮廓。

对人脸进行分类NO_CLASSIFICATIONS(默认)| ALL_CLASSIFICATIONS

是否将人脸分为不同类别(例如“微笑”和“睁眼”)。

人脸大小下限float(默认:0.1f

需要检测的人脸的大小下限(相对于图片)。

启用面部跟踪false(默认)| true

是否为人脸分配 ID,以用于跨图片跟踪人脸。

请注意,启用轮廓检测后,仅检测一个人脸,因此人脸跟踪不会产生有用的结果。为此,若要加快检测速度,请勿同时启用轮廓检测和人脸跟踪。

  1. public void initFaceSource() {
  2. FirebaseApp.initializeApp(activity);
  3. // High-accuracy landmark detection and face classification
  4. /*FirebaseVisionFaceDetectorOptions highAccuracyOpts =
  5. new FirebaseVisionFaceDetectorOptions.Builder()
  6. .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE) //性能模式
  7. .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS) //检测特征点
  8. .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATION
  9. .build();*/
  10. // Real-time contour detection of multiple faces
  11. FirebaseVisionFaceDetectorOptions realTimeOpts =
  12. new FirebaseVisionFaceDetectorOptions.Builder()
  13. .setPerformanceMode(FirebaseVisionFaceDetectorOptions.FAST)
  14. .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS) //检测轮廓
  15. .build();
  16. detector = FirebaseVision.getInstance().getVisionFaceDetector(realTimeOpts);
  17. }

2.运行人脸检测器

如需识别图片中的文本,请从设备上的以下资源创建一个 FirebaseVisionImage 对象:Bitmapmedia.ImageByteBuffer、字节数组或文件。然后,将 FirebaseVisionImage 对象传递给 FirebaseVisionFaceDetector 的 detectInImage 方法。

对于人脸识别,您使用的图片尺寸应至少为 480x360 像素。如果您要实时识别人脸,以此最低分辨率捕获帧有助于减少延迟时间。

  1. 基于图片创建 FirebaseVisionImage 对象。

    • 如需基于 media.Image 对象创建 FirebaseVisionImage 对象(例如从设备的相机捕获图片时),请将 media.Image 对象和图片的旋转角度传递给 FirebaseVisionImage.fromMediaImage()

      如果您使用了 CameraX 库,OnImageCapturedListener 和 ImageAnalysis.Analyzer 类会为您计算旋转角度值,因此您只需在调用 FirebaseVisionImage.fromMediaImage() 之前将旋转角度转换为机器学习套件的 ROTATION_ 常量之一(一般情况下前置摄像头需要旋转270,后置摄像头需要旋转90):

      1. imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(activity), imageProxy -> {
      2. if (task != null && !task.isComplete()) {
      3. imageProxy.close();
      4. return;
      5. }
      6. @SuppressLint("UnsafeExperimentalUsageError")
      7. //Bitmap bitmap = BitmapUtils.getBitmap(imageProxy);
      8. Image image = imageProxy.getImage();
      9. if (image == null) {
      10. imageProxy.close();
      11. return;
      12. }
      13. FirebaseVisionImage visionImage = FirebaseVisionImage.fromMediaImage(image, FirebaseVisionImageMetadata.ROTATION_90);
      14. //FirebaseVisionImage visionImage = FirebaseVisionImage.fromBitmap(bitmap);
      15. detect(visionImage);
      16. //detect(visionImage, bitmap);
      17. imageProxy.close();
      18. });

      如果您没有使用可提供图片旋转角度的相机库,可以根据设备的旋转角度和设备中相机传感器的朝向来计算旋转角度:

      1. private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
      2. static {
      3.     ORIENTATIONS.append(Surface.ROTATION_0, 90);
      4.     ORIENTATIONS.append(Surface.ROTATION_90, 0);
      5.     ORIENTATIONS.append(Surface.ROTATION_180, 270);
      6.     ORIENTATIONS.append(Surface.ROTATION_270, 180);
      7. }
      8. /**
      9.  * Get the angle by which an image must be rotated given the device's current
      10.  * orientation.
      11.  */
      12. @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
      13. private int getRotationCompensation(String cameraId, Activity activity, Context context)
      14.         throws CameraAccessException {
      15.     // Get the device's current rotation relative to its "native" orientation.
      16.     // Then, from the ORIENTATIONS table, look up the angle the image must be
      17.     // rotated to compensate for the device's rotation.
      18.     int deviceRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
      19.     int rotationCompensation = ORIENTATIONS.get(deviceRotation);
      20.     // On most devices, the sensor orientation is 90 degrees, but for some
      21.     // devices it is 270 degrees. For devices with a sensor orientation of
      22.     // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees.
      23.     CameraManager cameraManager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
      24.     int sensorOrientation = cameraManager
      25.             .getCameraCharacteristics(cameraId)
      26.             .get(CameraCharacteristics.SENSOR_ORIENTATION);
      27.     rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360;
      28.     // Return the corresponding FirebaseVisionImageMetadata rotation value.
      29.     int result;
      30.     switch (rotationCompensation) {
      31.         case 0:
      32.             result = FirebaseVisionImageMetadata.ROTATION_0;
      33.             break;
      34.         case 90:
      35.             result = FirebaseVisionImageMetadata.ROTATION_90;
      36.             break;
      37.         case 180:
      38.             result = FirebaseVisionImageMetadata.ROTATION_180;
      39.             break;
      40.         case 270:
      41.             result = FirebaseVisionImageMetadata.ROTATION_270;
      42.             break;
      43.         default:
      44.             result = FirebaseVisionImageMetadata.ROTATION_0;
      45.             Log.e(TAG, "Bad rotation value: " + rotationCompensation);
      46.     }
      47.     return result;
      48. }

      然后,将 media.Image 对象及旋转角度值传递给 FirebaseVisionImage.fromMediaImage()

      FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation);

    • 如需基于文件 URI 创建 FirebaseVisionImage 对象,请将应用上下文和文件 URI 传递给 FirebaseVisionImage.fromFilePath()。如果您使用 ACTION_GET_CONTENT Intent 提示用户从图库应用中选择图片,则这一操作非常有用。
      1. FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
      2.         .setWidth(480)   // 480x360 is typically sufficient for
      3.         .setHeight(360)  // image recognition
      4.         .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
      5.         .setRotation(rotation)
      6.         .build();

    • 如需基于 ByteBuffer 或字节数组创建 FirebaseVisionImage 对象,请先按上述 media.Image 输入的说明计算图片旋转角度。

      然后,创建一个包含图片的高度、宽度、颜色编码格式和旋转角度的 FirebaseVisionImageMetadata 对象:

      1. FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
      2.         .setWidth(480)   // 480x360 is typically sufficient for
      3.         .setHeight(360)  // image recognition
      4.         .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
      5.         .setRotation(rotation)
      6.         .build();

      使用缓冲区或数组以及元数据对象来创建 FirebaseVisionImage 对象:

      1. FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata);
      2. // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata);

    • 如需基于 Bitmap 对象创建 FirebaseVisionImage 对象,请执行以下操作

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      以 Bitmap 对象表示的图片必须保持竖直,不需要额外的旋转。
  2. 获取 FirebaseVisionFaceDetector 的一个实例:

    1. FirebaseVisionFaceDetector detector = FirebaseVision.getInstance()
    2.         .getVisionFaceDetector(options);

注意:检查控制台,看看是否存在构造函数生成的错误。

  1. 最后,将图片传递给 detectInImage 方法:

    1. Task<List<FirebaseVisionFace>> result =
    2.         detector.detectInImage(image)
    3.                 .addOnSuccessListener(
    4.                         new OnSuccessListener<List<FirebaseVisionFace>>() {
    5.                             @Override
    6.                             public void onSuccess(List<FirebaseVisionFace> faces) {
    7.                                 // Task completed successfully
    8.                                 // ...
    9.                             }
    10.                         })
    11.                 .addOnFailureListener(
    12.                         new OnFailureListener() {
    13.                             @Override
    14.                             public void onFailure(@NonNull Exception e) {
    15.                                 // Task failed with an exception
    16.                                 // ...
    17.                             }
    18.                         });

    注意:检查控制台,看看是否存在检测器生成的错误。

3. 获取检测到的人脸的相关信息

如果人脸识别操作成功,系统会向成功侦听器传递一组 FirebaseVisionFace 对象。每个 FirebaseVisionFace 对象都代表一张在图片中检测到的面孔。对于每张面孔,您可以获取它在输入图片中的边界坐标,以及您已配置面部检测器查找的任何其他信息。例如:

  1. for (FirebaseVisionFace face : faces) {
  2. Rect bounds = face.getBoundingBox();
  3. float rotY = face.getHeadEulerAngleY(); // Head is rotated to the right rotY degrees
  4. float rotZ = face.getHeadEulerAngleZ(); // Head is tilted sideways rotZ degrees
  5. // If landmark detection was enabled (mouth, ears, eyes, cheeks, and
  6. // nose available):
  7. FirebaseVisionFaceLandmark leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR);
  8. if (leftEar != null) {
  9. FirebaseVisionPoint leftEarPos = leftEar.getPosition();
  10. }
  11. // If contour detection was enabled:
  12. List<FirebaseVisionPoint> leftEyeContour =
  13. face.getContour(FirebaseVisionFaceContour.LEFT_EYE).getPoints();
  14. List<FirebaseVisionPoint> upperLipBottomContour =
  15. face.getContour(FirebaseVisionFaceContour.UPPER_LIP_BOTTOM).getPoints();
  16. // If classification was enabled:
  17. if (face.getSmilingProbability() != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
  18. float smileProb = face.getSmilingProbability();
  19. }
  20. if (face.getRightEyeOpenProbability() != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
  21. float rightEyeOpenProb = face.getRightEyeOpenProbability();
  22. }
  23. // If face tracking was enabled:
  24. if (face.getTrackingId() != FirebaseVisionFace.INVALID_ID) {
  25. int id = face.getTrackingId();
  26. }
  27. }

4.实时人脸检测

相机获取到的图片对象imageProxy需要转换成

FirebaseVisionImage visionImage = FirebaseVisionImage.fromMediaImage(image, FirebaseVisionImageMetadata.ROTATION_90);

然后调用接口

detector.detectInImage(image)

添加

addOnSuccessListener
addOnFailureListener

识别成功和失败的接口(注意:如果图片角度不对,则识别失败也不会回调,相当于空跑,只有图片角度对了才可以)

识别成功回调到人脸信息List<FirebaseVisionFace>faces

遍历这个列表可以拿到人脸信息

  1. private final List<Float> points = new ArrayList<>();
  2. for (FirebaseVisionFace face : faces) {
  3. //Rect bounds = face.getBoundingBox();
  4. //float rotY = face.getHeadEulerAngleY(); // Head is rotated to the right rotY degrees
  5. //float rotZ = face.getHeadEulerAngleZ(); // Head is tilted sideways rotZ degrees
  6. //Log.e("Point", "top=" + bounds.top + " bottom=" + bounds.bottom + " left=" + bounds.left + " right=" + bounds.right);
  7. // If landmark detection was enabled (mouth, ears, eyes, cheeks, and nose available):
  8. //左眼
  9. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.LEFT_EYE).getPoints()) {
  10. points.add(point.getX());
  11. points.add(point.getY());
  12. }
  13. //右眼
  14. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.RIGHT_EYE).getPoints()) {
  15. points.add(point.getX());
  16. points.add(point.getY());
  17. }
  18. //左眉上
  19. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.LEFT_EYEBROW_TOP).getPoints()) {
  20. points.add(point.getX());
  21. points.add(point.getY());
  22. }
  23. //左眉下
  24. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.LEFT_EYEBROW_BOTTOM).getPoints()) {
  25. points.add(point.getX());
  26. points.add(point.getY());
  27. }
  28. //右眉上
  29. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.RIGHT_EYEBROW_TOP).getPoints()) {
  30. points.add(point.getX());
  31. points.add(point.getY());
  32. }
  33. //右眉下
  34. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.RIGHT_EYEBROW_BOTTOM).getPoints()) {
  35. points.add(point.getX());
  36. points.add(point.getY());
  37. }
  38. //鼻梁
  39. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.NOSE_BRIDGE).getPoints()) {
  40. points.add(point.getX());
  41. points.add(point.getY());
  42. }
  43. //鼻孔
  44. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.NOSE_BOTTOM).getPoints()) {
  45. points.add(point.getX());
  46. points.add(point.getY());
  47. }
  48. //上唇顶部
  49. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.UPPER_LIP_TOP).getPoints()) {
  50. points.add(point.getX());
  51. points.add(point.getY());
  52. }
  53. //上唇底部
  54. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.UPPER_LIP_BOTTOM).getPoints()) {
  55. points.add(point.getX());
  56. points.add(point.getY());
  57. }
  58. //下唇顶部
  59. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.LOWER_LIP_TOP).getPoints()) {
  60. points.add(point.getX());
  61. points.add(point.getY());
  62. }
  63. //下唇底部
  64. for (FirebaseVisionPoint point : face.getContour(FirebaseVisionFaceContour.LOWER_LIP_BOTTOM).getPoints()) {
  65. points.add(point.getX());
  66. points.add(point.getY());
  67. }
  68. }

识别出来的所有特征坐标,是依赖于

FirebaseVisionImage getBitmap()

所以在实时更新识别后的画面时,可以在原bitmap的基础上绘制轮廓坐标点

  1. Canvas canvas = new Canvas(bitmap);
  2. float[] points_f = new float[points.size()];
  3. for (int i = 0; i < points.size(); i++) {
  4. points_f[i] = points.get(i);
  5. }
  6. Paint paint = new Paint();
  7. paint.setColor(Color.BLUE);
  8. paint.setStrokeWidth(5);
  9. canvas.drawPoints(points_f, paint);
  10. imageView.setImageBitmap(bitmap);//imageView是个图片控件

5.获取google服务

在没有添加google-services.json的时候,会报错提示没有initializeApp

FirebaseApp.initializeApp(activity);

官网

https://console.firebase.google.com/https://console.firebase.google.com/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/101273
推荐阅读
相关标签
  

闽ICP备14008679号