机器学习套件提供了经过优化的 SDK,用于自拍分割。
自拍分割器素材资源会在构建时静态链接到您的应用。这会使应用下载大小增加约 4.5MB,并且 API 延迟时间可能会因输入图片大小而异,在 25 毫秒到 65 毫秒之间(在 Pixel 4 上测得)。
试试看
- 试用示例应用,了解此 API 的使用示例。
准备工作
- 请务必在项目级
build.gradle
文件中的buildscript
和allprojects
部分添加 Google 的 Maven 代码库。 - 将 Android 版机器学习套件库的依赖项添加到模块的应用级 Gradle 文件(通常为
app/build.gradle
):
dependencies {
implementation 'com.google.mlkit:segmentation-selfie:16.0.0-beta6'
}
1. 创建 Segmenter 实例
细分器选项
如需对图片进行分割,请先通过指定以下选项创建 Segmenter
实例。
检测器模式
Segmenter
可在两种模式下运行。请务必选择与您的应用场景匹配的模型。
STREAM_MODE (default)
此模式适用于从视频或摄像头流式传输帧。在此模式下,分割器将利用之前帧的结果返回更平滑的分割结果。
SINGLE_IMAGE_MODE
此模式适用于不相关的单张图片。在此模式下,分割器会独立处理每张图片,不会跨帧进行平滑处理。
启用原始尺寸遮罩
请求分割器返回与模型输出大小匹配的原始大小掩码。
原始掩码大小(例如 256x256)通常小于输入图片大小。启用此选项时,请调用 SegmentationMask#getWidth()
和 SegmentationMask#getHeight()
以获取掩码大小。
如果未指定此选项,分割器将重新调整原始蒙版,使其与输入图片大小相匹配。如果您想应用自定义的放大缩小逻辑,或者您的用例不需要放大缩小,请考虑使用此选项。
指定分段器选项:
val options = SelfieSegmenterOptions.Builder() .setDetectorMode(SelfieSegmenterOptions.STREAM_MODE) .enableRawSizeMask() .build()
SelfieSegmenterOptions options = new SelfieSegmenterOptions.Builder() .setDetectorMode(SelfieSegmenterOptions.STREAM_MODE) .enableRawSizeMask() .build();
创建 Segmenter
的实例。传递您指定的选项:
val segmenter = Segmentation.getClient(options)
Segmenter segmenter = Segmentation.getClient(options);
2. 准备输入图片
如需对图片执行分割,请基于设备上的以下资源创建一个 InputImage
对象:Bitmap
、media.Image
、ByteBuffer
、字节数组或文件。
您可以基于不同来源创建 InputImage
对象,下文分别介绍了具体方法。
使用 media.Image
如需基于 media.Image
对象创建 InputImage
对象(例如从设备的相机捕获图片时),请将 media.Image
对象和图片的旋转角度传递给 InputImage.fromMediaImage()
。
如果您使用
CameraX 库,OnImageCapturedListener
和 ImageAnalysis.Analyzer
类会为您计算旋转角度值。
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 // ... } } }
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 // ... } } }
如果您不使用可提供图片旋转角度的相机库,则可以根据设备的旋转角度和设备中相机传感器的朝向来计算旋转角度:
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 }
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()
:
val image = InputImage.fromMediaImage(mediaImage, rotation)
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
使用文件 URI
如需基于文件 URI 创建 InputImage
对象,请将应用上下文和文件 URI 传递给 InputImage.fromFilePath()
。如果您使用 ACTION_GET_CONTENT
intent 提示用户从图库应用中选择图片,则这一操作非常有用。
val image: InputImage try { image = InputImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
InputImage image;
try {
image = InputImage.fromFilePath(context, uri);
} catch (IOException e) {
e.printStackTrace();
}
使用 ByteBuffer
或 ByteArray
如需基于 ByteBuffer
或 ByteArray
创建 InputImage
对象,请先按先前 media.Image
输入的说明计算图片旋转角度。然后,使用缓冲区或数组以及图片的高度、宽度、颜色编码格式和旋转角度创建 InputImage
对象:
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 )
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
如需基于 Bitmap
对象创建 InputImage
对象,请进行以下声明:
val image = InputImage.fromBitmap(bitmap, 0)
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
图片由 Bitmap
对象以及旋转角度表示。
3. 处理图片
将准备好的 InputImage
对象传递给 Segmenter
的 process
方法。
Task<SegmentationMask> result = segmenter.process(image) .addOnSuccessListener { results -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
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. 获取细分结果
您可以按如下方式获取细分结果:
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() } }
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(); } }
如需查看有关如何使用分割结果的完整示例,请参阅 ML Kit 快速入门示例。
提升效果的提示
结果的质量取决于输入图片的质量:
- 为了让机器学习套件获得准确的分割结果,图片应至少为 256x256 像素。
- 图片聚焦不佳也会影响准确性。如果您无法获得满意的结果,请让用户重新拍摄图片。
如果要在实时应用中使用分割功能,请遵循以下准则以实现最佳帧速率:
- 使用
STREAM_MODE
。 - 建议以较低分辨率捕获图片,但是,您也要牢记此 API 的图片尺寸要求。
- 不妨考虑启用原始尺寸掩码选项,并将所有放大缩小逻辑组合在一起。例如,您不必先让 API 将遮罩重新调整为与输入图片大小相匹配,然后再将其重新调整为与要显示的 View 大小相匹配,只需请求原始大小的遮罩,并将这两步合二为一。
- 如果您使用
Camera
或camera2
API,请限制对检测器的调用次数。如果在检测器运行时有新的视频帧可用,请丢弃该帧。如需查看示例,请参阅快速入门示例应用中的VisionProcessorBase
类。 - 如果您使用
CameraX
API,请务必将回压策略设置为默认值ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
。 这样可以保证一次只传送一张图片进行分析。如果在分析器繁忙时生成了更多图片,系统会自动舍弃这些图片,而不会将其加入队列以供传送。通过调用 ImageProxy.close() 关闭要分析的图片后,系统会传送下一个最新图片。 - 如果要将检测器的输出作为图形叠加在输入图片上,请先从机器学习套件获取结果,然后在一个步骤中完成图片的呈现和叠加。这样,每个输入帧只需在显示表面呈现一次。如需查看示例,请参阅快速入门示例应用中的
CameraSourcePreview
和GraphicOverlay
类。 - 如果您使用 Camera2 API,请以
ImageFormat.YUV_420_888
格式捕获图片。如果您使用旧版 Camera API,请以ImageFormat.NV21
格式捕获图片。