在 Android 系统中使用机器学习套件进行自拍分割

机器学习套件针对自拍分割提供了经过优化的 SDK。

在构建时,自拍分割工具资源会静态关联到您的应用。 这会使应用下载大小增加约 4.5MB,并且 API 延迟时间 从 25 毫秒到 65 毫秒不等,具体取决于输入图片的大小(以 Pixel 上测得的值为准) 4.

试试看

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

准备工作

  1. 请务必在您的项目级 build.gradle 文件中的 buildscriptallprojects 部分添加 Google 的 Maven 制品库。
  2. 将 Android 版机器学习套件库的依赖项添加到模块的应用级 Gradle 文件(通常为 app/build.gradle):
dependencies {
  implementation 'com.google.mlkit:segmentation-selfie:16.0.0-beta5'
}

1. 创建 Segmenter 实例

细分器选项

如需对图片进行分割,请先通过指定以下选项创建 Segmenter 实例。

检测器模式

Segmenter 以两种模式运行。请务必选择与您的用例相符的选项。

STREAM_MODE (default)

此模式专为流式传输视频或相机中的帧而设计。在此模式下,分割器将利用之前帧的结果返回更平滑的分割结果。

SINGLE_IMAGE_MODE

此模式适用于不相关的单张图片。在此模式下,分割器将独立处理每张图像,不对帧进行平滑处理。

启用原始尺寸掩码

要求分割器返回与模型输出大小匹配的原始大小掩码。

原始遮罩大小(例如 256x256)通常小于输入图片大小。启用此选项时,请调用 SegmentationMask#getWidth()SegmentationMask#getHeight() 以获取掩码大小。

如果不指定此选项,分割器将重新缩放原始遮罩以匹配输入图像大小。如果您想应用自定义重新缩放逻辑,或者您的用例不需要重新缩放,请考虑使用此选项。

指定细分选项:

Kotlin

val options =
        SelfieSegmenterOptions.Builder()
            .setDetectorMode(SelfieSegmenterOptions.STREAM_MODE)
            .enableRawSizeMask()
            .build()

Java

SelfieSegmenterOptions options =
        new SelfieSegmenterOptions.Builder()
            .setDetectorMode(SelfieSegmenterOptions.STREAM_MODE)
            .enableRawSizeMask()
            .build();

创建 Segmenter 的实例。传递您指定的选项:

Kotlin

val segmenter = Segmentation.getClient(options)

Java

Segmenter segmenter = Segmentation.getClient(options);

2. 准备输入图片

如需对图片进行分割,请创建 InputImage 对象 从 Bitmapmedia.ImageByteBuffer、字节数组或 。

您可以创建 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 对象和旋转角度表示。

3. 处理图片

将准备好的 InputImage 对象传递给 Segmenterprocess 方法。

Kotlin

Task<SegmentationMask> result = segmenter.process(image)
       .addOnSuccessListener { results ->
           // Task completed successfully
           // ...
       }
       .addOnFailureListener { e ->
           // Task failed with an exception
           // ...
       }

Java

Task<SegmentationMask> result =
        segmenter.process(image)
                .addOnSuccessListener(
                        new OnSuccessListener<SegmentationMask>() {
                            @Override
                            public void onSuccess(SegmentationMask mask) {
                                // Task completed successfully
                                // ...
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                // Task failed with an exception
                                // ...
                            }
                        });

4. 获取细分结果

您可以得到如下细分结果:

Kotlin

val mask = segmentationMask.getBuffer()
val maskWidth = segmentationMask.getWidth()
val maskHeight = segmentationMask.getHeight()

for (val y = 0; y < maskHeight; y++) {
  for (val x = 0; x < maskWidth; x++) {
    // Gets the confidence of the (x,y) pixel in the mask being in the foreground.
    val foregroundConfidence = mask.getFloat()
  }
}

Java

ByteBuffer mask = segmentationMask.getBuffer();
int maskWidth = segmentationMask.getWidth();
int maskHeight = segmentationMask.getHeight();

for (int y = 0; y < maskHeight; y++) {
  for (int x = 0; x < maskWidth; x++) {
    // Gets the confidence of the (x,y) pixel in the mask being in the foreground.
    float foregroundConfidence = mask.getFloat();
  }
}

有关如何使用细分结果的完整示例,请参阅 机器学习套件快速入门示例

效果提升技巧

结果的质量取决于输入图片的质量:

  • 为了让机器学习套件获得准确的分割结果,图片应至少为 256x256 像素。
  • 图片聚焦不佳也会影响准确性。如果您没有获得可接受的结果,请让用户重新拍摄图片。

如果要在实时应用中使用分割,请遵循以下准则以实现最佳帧速率:

  • 使用 STREAM_MODE
  • 建议以较低的分辨率捕获图片。但是,您也要牢记此 API 的图片尺寸要求。
  • 请考虑启用原始尺寸掩码选项,并将所有重新缩放逻辑组合在一起。例如,不要让 API 先重新缩放蒙版以匹配您的输入图片尺寸,然后再重新缩放使其与要显示的视图尺寸一致,只需请求原始尺寸蒙版,然后将这两个步骤合二为一即可。
  • 如果您使用 Cameracamera2 API、 限制对检测器的调用。如果新视频 当检测器运行时有可用的帧时,请丢弃该帧。请参阅 VisionProcessorBase 类。
  • 如果您使用 CameraX API, 确保将 backpressure 策略设置为默认值 ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST。 这可保证一次只传送一张图片进行分析。如果有更多图片 在分析器繁忙时生成,它们会被自动丢弃,不会排队等待 。通过调用 ImageProxy.close(),将传递下一张图片。
  • 如果您使用检测器的输出在图像上叠加显示 输入图片,首先从机器学习套件获取结果, 和叠加层。这会渲染到 每个输入帧只执行一次。请参阅 CameraSourcePreview GraphicOverlay 类。
  • 如果您使用 Camera2 API,请以 ImageFormat.YUV_420_888 格式。如果您使用旧版 Camera API,请使用 ImageFormat.NV21 格式。