使用机器学习套件检测人脸网格信息 (Android)

您可以使用机器学习套件检测类似自拍的图片和视频中的人脸。

人脸网格检测 API
SDK 名称face-mesh-detection
实现在构建时,代码和资源会静态关联到您的应用。
应用大小影响约 6.4 MB
性能在大多数设备上实时生成。

试试看

  • 您可以试用示例应用, 请查看此 API 的用法示例。

准备工作

  1. 请务必在您的项目级 build.gradle 文件中添加 Google 的 buildscript 和所有项目部分中的 Maven 制品库。

  2. 将机器学习套件人脸网格检测库的依赖项添加到您的 模块的应用级 Gradle 文件,通常为 app/build.gradle

    dependencies {
     // ...
    
     implementation 'com.google.mlkit:face-mesh-detection:16.0.0-beta1'
    }
    

输入图片准则

  1. 图像应该在距离设备相机约 2 米(约 7 英尺)的范围内拍摄,因此 人脸足够大,能够实现最佳的人脸网格识别。在 一般来说,人脸越大,人脸网格识别的效果就越好。

  2. 人脸应朝向摄像头,且至少要有一半的面孔可见。 人脸和相机之间的任何大型物体都可能会降低 准确率。

如果要在实时应用中检测人脸,您还应该 考虑输入图片的整体尺寸。尺寸较小的图片 因此,以较低分辨率捕获图片可缩短延迟时间。 不过,请注意上述准确性要求,并确保 正文的脸会占据图像的尽可能多的空间。

配置人脸网格检测器

如果您想更改人脸网格检测器的任何默认设置,请指定 这类设置 FaceMeshDetectorOptions 对象。您可以更改以下设置:

  1. setUseCase

    • BOUNDING_BOX_ONLY:仅为检测到的人脸网格提供边界框。 这是最快的面部检测器,但有范围限制(人脸 必须在摄像头的 2 米或 7 英尺范围内)。

    • FACE_MESH(默认选项):提供边界框和额外的面孔 网格信息(468 个 3D 点和三角形信息)。与 BOUNDING_BOX_ONLY 个用例,延迟时间增加约 15%,测算时间为 Pixel 3。

例如:

Kotlin

val defaultDetector = FaceMeshDetection.getClient(
  FaceMeshDetectorOptions.DEFAULT_OPTIONS)

val boundingBoxDetector = FaceMeshDetection.getClient(
  FaceMeshDetectorOptions.Builder()
    .setUseCase(UseCase.BOUNDING_BOX_ONLY)
    .build()
)

Java

FaceMeshDetector defaultDetector =
        FaceMeshDetection.getClient(
                FaceMeshDetectorOptions.DEFAULT_OPTIONS);

FaceMeshDetector boundingBoxDetector = FaceMeshDetection.getClient(
        new FaceMeshDetectorOptions.Builder()
                .setUseCase(UseCase.BOUNDING_BOX_ONLY)
                .build()
        );

准备输入图片

如需检测图片中的人脸,请基于以下资源创建一个 InputImage 对象: 设备上的 Bitmapmedia.ImageByteBuffer、字节数组或文件。 然后,将 InputImage 对象传递给 FaceDetectorprocess 方法。

对于人脸网格检测,您应使用尺寸至少为 480x360 像素。如果您要实时检测人脸、捕获帧, 这样有助于减少延迟时间

您可以创建 InputImage 对象,下文对每种方法进行了说明。

使用 media.Image

如需创建 InputImage,请执行以下操作: 对象(例如从 media.Image 对象中捕获图片时) 请传递 media.Image 对象和图片的 旋转为 InputImage.fromMediaImage()

如果您使用 CameraX 库、OnImageCapturedListenerImageAnalysis.Analyzer 类计算旋转角度值 。

Kotlin

private class YourImageAnalyzer : ImageAnalysis.Analyzer {

    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image
        if (mediaImage != null) {
            val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
            // Pass image to an ML Kit Vision API
            // ...
        }
    }
}

Java

private class YourAnalyzer implements ImageAnalysis.Analyzer {

    @Override
    public void analyze(ImageProxy imageProxy) {
        Image mediaImage = imageProxy.getImage();
        if (mediaImage != null) {
          InputImage image =
                InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees());
          // Pass image to an ML Kit Vision API
          // ...
        }
    }
}

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

Kotlin

private val ORIENTATIONS = SparseIntArray()

init {
    ORIENTATIONS.append(Surface.ROTATION_0, 0)
    ORIENTATIONS.append(Surface.ROTATION_90, 90)
    ORIENTATIONS.append(Surface.ROTATION_180, 180)
    ORIENTATIONS.append(Surface.ROTATION_270, 270)
}

/**
 * Get the angle by which an image must be rotated given the device's current
 * orientation.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Throws(CameraAccessException::class)
private fun getRotationCompensation(cameraId: String, activity: Activity, isFrontFacing: Boolean): Int {
    // Get the device's current rotation relative to its "native" orientation.
    // Then, from the ORIENTATIONS table, look up the angle the image must be
    // rotated to compensate for the device's rotation.
    val deviceRotation = activity.windowManager.defaultDisplay.rotation
    var rotationCompensation = ORIENTATIONS.get(deviceRotation)

    // Get the device's sensor orientation.
    val cameraManager = activity.getSystemService(CAMERA_SERVICE) as CameraManager
    val sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION)!!

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360
    }
    return rotationCompensation
}

Java

private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
    ORIENTATIONS.append(Surface.ROTATION_0, 0);
    ORIENTATIONS.append(Surface.ROTATION_90, 90);
    ORIENTATIONS.append(Surface.ROTATION_180, 180);
    ORIENTATIONS.append(Surface.ROTATION_270, 270);
}

/**
 * Get the angle by which an image must be rotated given the device's current
 * orientation.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private int getRotationCompensation(String cameraId, Activity activity, boolean isFrontFacing)
        throws CameraAccessException {
    // Get the device's current rotation relative to its "native" orientation.
    // Then, from the ORIENTATIONS table, look up the angle the image must be
    // rotated to compensate for the device's rotation.
    int deviceRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    int rotationCompensation = ORIENTATIONS.get(deviceRotation);

    // Get the device's sensor orientation.
    CameraManager cameraManager = (CameraManager) activity.getSystemService(CAMERA_SERVICE);
    int sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION);

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360;
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360;
    }
    return rotationCompensation;
}

然后,传递 media.Image 对象和 将旋转角度值设为 InputImage.fromMediaImage()

Kotlin

val image = InputImage.fromMediaImage(mediaImage, rotation)

Java

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

使用文件 URI

如需创建 InputImage,请执行以下操作: 对象时,请将应用上下文和文件 URI 传递给 InputImage.fromFilePath()。在需要满足特定条件时 使用 ACTION_GET_CONTENT intent 提示用户进行选择 从图库应用中获取图片

Kotlin

val image: InputImage
try {
    image = InputImage.fromFilePath(context, uri)
} catch (e: IOException) {
    e.printStackTrace()
}

Java

InputImage image;
try {
    image = InputImage.fromFilePath(context, uri);
} catch (IOException e) {
    e.printStackTrace();
}

使用 ByteBufferByteArray

如需创建 InputImage,请执行以下操作: 对象ByteBufferByteArray时,首先计算图像 旋转角度。media.Image 然后,创建带有缓冲区或数组的 InputImage 对象以及图片的 高度、宽度、颜色编码格式和旋转角度:

Kotlin

val image = InputImage.fromByteBuffer(
        byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
)
// Or:
val image = InputImage.fromByteArray(
        byteArray,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
)

Java

InputImage image = InputImage.fromByteBuffer(byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
);
// Or:
InputImage image = InputImage.fromByteArray(
        byteArray,
        /* image width */480,
        /* image height */360,
        rotation,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
);

使用 Bitmap

如需创建 InputImage,请执行以下操作: 对象时,请进行以下声明:Bitmap

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);

图片由 Bitmap 对象和旋转角度表示。

处理图片

将图片传递给 process 方法:

Kotlin

val result = detector.process(image)
        .addOnSuccessListener { result ->
            // Task completed successfully
            // …
        }
        .addOnFailureListener { e ->
            // Task failed with an exception
            // …
        }

Java


Task<List<FaceMesh>> result = detector.process(image)
        .addOnSuccessListener(
                new OnSuccessListener<List<FaceMesh>>() {
                    @Override
                    public void onSuccess(List<FaceMesh> result) {
                        // Task completed successfully
                        // …
                    }
                })
        .addOnFailureListener(
                new OnFailureListener() {
                    @Override
                    Public void onFailure(Exception e) {
                        // Task failed with an exception
                        // …
                    }
                });

获取有关检测到的人脸网格的信息

如果在图片中检测到人脸,则系统会将 FaceMesh 对象列表传递给 成功监听器。每个 FaceMesh 代表一张在 图片。对于每个人脸网格,您可以在输入中获取其边界坐标 以及您配置人脸网格的任何其他信息 检测器查找。

Kotlin

for (faceMesh in faceMeshs) {
    val bounds: Rect = faceMesh.boundingBox()

    // Gets all points
    val faceMeshpoints = faceMesh.allPoints
    for (faceMeshpoint in faceMeshpoints) {
      val index: Int = faceMeshpoints.index()
      val position = faceMeshpoint.position
    }

    // Gets triangle info
    val triangles: List<Triangle<FaceMeshPoint>> = faceMesh.allTriangles
    for (triangle in triangles) {
      // 3 Points connecting to each other and representing a triangle area.
      val connectedPoints = triangle.allPoints()
    }
}

Java

for (FaceMesh faceMesh : faceMeshs) {
    Rect bounds = faceMesh.getBoundingBox();

    // Gets all points
    List<FaceMeshPoint> faceMeshpoints = faceMesh.getAllPoints();
    for (FaceMeshPoint faceMeshpoint : faceMeshpoints) {
        int index = faceMeshpoints.getIndex();
        PointF3D position = faceMeshpoint.getPosition();
    }

    // Gets triangle info
    List<Triangle<FaceMeshPoint>> triangles = faceMesh.getAllTriangles();
    for (Triangle<FaceMeshPoint> triangle : triangles) {
        // 3 Points connecting to each other and representing a triangle area.
        List<FaceMeshPoint> connectedPoints = triangle.getAllPoints();
    }
}