当您将图片传递给机器学习套件时,它会检测图片中的最多 5 个对象以及图片中每个对象的位置。检测视频流中的对象时,每个对象都有一个唯一 ID,可用于逐帧跟踪对象。
您可以使用自定义图片分类模型对检测到的对象进行分类。请参阅使用机器学习套件的自定义模型,获取模型兼容性要求、在哪里可以找到预训练模型以及如何训练自己的模型。
集成自定义模型的方法有两种。您可以将模型捆绑在应用的资源文件夹中,也可以从 Firebase 动态下载该模型。下表对这两个选项进行了比较。
捆绑模型 | 托管模型 |
---|---|
模型是应用 APK 的一部分,因此会增加其大小。 | 此模型不是 APK 的一部分。该项目通过上传到 Firebase Machine Learning 进行托管。 |
即使 Android 设备处于离线状态,模型也可立即使用 | 模型可按需下载 |
不需要 Firebase 项目 | 需要 Firebase 项目 |
您必须重新发布应用才能更新模型 | 无需重新发布应用即可推送模型更新 |
无内置 A/B 测试 | 使用 Firebase Remote Config 轻松进行 A/B 测试 |
试试看
- 如需查看捆绑模型的示例,请参阅 Vision 快速入门应用;如需查看托管模型的示例,请参阅 automl 快速入门应用。
- 如需了解此 API 的端到端实现,请参阅 Material Design 展示应用。
准备工作
请务必在您的项目级
build.gradle
文件中的buildscript
和allprojects
部分添加 Google 的 Maven 代码库。将 Android 版机器学习套件库的依赖项添加到您的模块的应用级 Gradle 文件(通常为
app/build.gradle
):如需将模型与您的应用捆绑,请执行以下操作:
dependencies { // ... // Object detection & tracking feature with custom bundled model implementation 'com.google.mlkit:object-detection-custom:17.0.0' }
如需从 Firebase 动态下载模型,请添加
linkFirebase
依赖项:dependencies { // ... // Object detection & tracking feature with model downloaded // from firebase implementation 'com.google.mlkit:object-detection-custom:17.0.0' implementation 'com.google.mlkit:linkfirebase:17.0.0' }
如果您想下载模型,请务必将 Firebase 添加到您的 Android 项目(如果您尚未添加)。捆绑模型时不需要这样做。
1. 加载模型
配置本地模型来源
如需将模型与您的应用捆绑在一起,请执行以下操作:
将模型文件(通常以
.tflite
或.lite
结尾)复制到应用的assets/
文件夹。(您可能需要先创建此文件夹,方法是右键点击app/
文件夹,然后依次点击新建 > 文件夹 > Assets 文件夹 (New > Folder > Assets Folder)。)然后,将以下内容添加到应用的
build.gradle
文件中,以确保 Gradle 在构建应用时不会压缩模型文件:android { // ... aaptOptions { noCompress "tflite" // or noCompress "lite" } }
模型文件将包含在应用软件包中,并作为原始资源提供给机器学习套件使用。
创建
LocalModel
对象,指定模型文件的路径:Kotlin
val localModel = LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute file path to model file) // or .setUri(URI to model file) .build()
Java
LocalModel localModel = new LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute file path to model file) // or .setUri(URI to model file) .build();
配置 Firebase 托管的模型来源
如需使用远程托管的模型,请通过 FirebaseModelSource
创建一个 CustomRemoteModel
对象,指定您在发布该模型时分配给模型的名称:
Kotlin
// Specify the name you assigned in the Firebase console. val remoteModel = CustomRemoteModel .Builder(FirebaseModelSource.Builder("your_model_name").build()) .build()
Java
// Specify the name you assigned in the Firebase console. CustomRemoteModel remoteModel = new CustomRemoteModel .Builder(new FirebaseModelSource.Builder("your_model_name").build()) .build();
然后,启动模型下载任务,指定您希望在哪些条件下允许下载。如果模型不在设备上,或模型有较新的版本,则任务将从 Firebase 异步下载模型:
Kotlin
val downloadConditions = DownloadConditions.Builder() .requireWifi() .build() RemoteModelManager.getInstance().download(remoteModel, downloadConditions) .addOnSuccessListener { // Success. }
Java
DownloadConditions downloadConditions = new DownloadConditions.Builder() .requireWifi() .build(); RemoteModelManager.getInstance().download(remoteModel, downloadConditions) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(@NonNull Task task) { // Success. } });
许多应用会通过其初始化代码启动下载任务,但您可以在需要使用该模型之前随时启动下载任务。
2. 配置对象检测器
配置模型来源后,请使用 CustomObjectDetectorOptions
对象为您的用例配置对象检测器。您可以更改以下设置:
对象检测器设置 | |
---|---|
检测模式 |
STREAM_MODE (默认)| SINGLE_IMAGE_MODE
在 在 |
检测和跟踪多个对象 |
false (默认)| true
是检测和跟踪最多五个对象,还是仅检测和跟踪最突出的对象(默认)。 |
将对象分类 |
false (默认)| true
是否使用提供的自定义分类器模型对检测到的对象进行分类。如需使用您的自定义分类模型,您需要将其设置为 |
分类置信度阈值 |
检测到的标签的最小置信度分数。如果未设置,则将使用模型元数据指定的任何分类器阈值。如果模型不包含任何元数据,或者元数据未指定分类器阈值,则将使用默认阈值 0.0。 |
每个对象的标签数上限 |
检测器将返回的每个对象的标签数上限。如果未设置,则使用默认值 10。 |
对象检测和跟踪 API 针对以下两个核心用例进行了优化:
- 实时检测和跟踪相机取景器中最突出的对象。
- 检测静态图片中的多个对象。
如需使用本地捆绑的模型为这些用例配置 API,请执行以下操作:
Kotlin
// Live detection and tracking val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() // Multiple object detection in static images val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions)
Java
// Live detection and tracking CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); // Multiple object detection in static images CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions);
如果您有远程托管的模型,则在运行之前,必须检查模型是否已经下载。您可以使用模型管理器的 isModelDownloaded()
方法检查模型下载任务的状态。
虽然您只需在运行检测器之前确认这一点,但如果您同时拥有远程托管模型和本地捆绑模型,则可能需要在实例化图片检测器时执行此检查:如果已下载,则根据远程模型创建检测器,否则根据本地模型创建。
Kotlin
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener { isDownloaded -> val optionsBuilder = if (isDownloaded) { CustomObjectDetectorOptions.Builder(remoteModel) } else { CustomObjectDetectorOptions.Builder(localModel) } val customObjectDetectorOptions = optionsBuilder .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions) }
Java
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Boolean isDownloaded) { CustomObjectDetectorOptions.Builder optionsBuilder; if (isDownloaded) { optionsBuilder = new CustomObjectDetectorOptions.Builder(remoteModel); } else { optionsBuilder = new CustomObjectDetectorOptions.Builder(localModel); } CustomObjectDetectorOptions customObjectDetectorOptions = optionsBuilder .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions); } });
如果您只有远程托管的模型,则应停用与模型相关的功能(例如使界面的一部分变灰或将其隐藏),直到您确认模型已下载。为此,您可以将监听器附加到模型管理器的 download()
方法:
Kotlin
RemoteModelManager.getInstance().download(remoteModel, conditions) .addOnSuccessListener { // Download complete. Depending on your app, you could enable the ML // feature, or switch from the local model to the remote model, etc. }
Java
RemoteModelManager.getInstance().download(remoteModel, conditions) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void v) { // Download complete. Depending on your app, you could enable // the ML feature, or switch from the local model to the remote // model, etc. } });
3. 准备输入图片
基于图片创建InputImage
对象。对象检测器直接从 Bitmap
、NV21 ByteBuffer
或 YUV_420_888 media.Image
运行。如果您直接访问其中一个来源,建议您基于这些来源构建 InputImage
。如果您通过其他来源构建 InputImage
,我们会在内部为您处理转换,因此效率可能会降低。
您可以根据不同来源创建 InputImage
对象,下文逐一介绍了该对象。
使用 media.Image
如需基于 media.Image
对象创建 InputImage
对象(例如从设备的相机捕获图片时),请将 media.Image
对象和图片的旋转角度传递给 InputImage.fromMediaImage()
。
如果您使用 CameraX 库,OnImageCapturedListener
和 ImageAnalysis.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
如需基于文件 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(); }
使用 ByteBuffer
或 ByteArray
如需基于 ByteBuffer
或 ByteArray
创建 InputImage
对象,请首先按之前针对 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
如需基于 Bitmap
对象创建 InputImage
对象,请进行以下声明:
Kotlin
val image = InputImage.fromBitmap(bitmap, 0)
Java
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
图片由 Bitmap
对象以及旋转角度表示。
4. 运行对象检测器
Kotlin
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (detectedObject in results) { // ... } });
Java
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (DetectedObject detectedObject : results) { // ... } });
5. 获取有关已加标签的对象的信息
如果对 process()
的调用成功,系统会向成功监听器传递一组 DetectedObject
。
每个 DetectedObject
都包含以下属性:
边界框 | Rect ,用于指示对象在图片中的位置。 |
||||||
跟踪 ID | 一个整数,用于跨图片标识对象。在 SINGLE_IMAGE_MODE 下为 Null。 | ||||||
标签 |
|
Kotlin
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (detectedObject in results) { val boundingBox = detectedObject.boundingBox val trackingId = detectedObject.trackingId for (label in detectedObject.labels) { val text = label.text val index = label.index val confidence = label.confidence } }
Java
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (DetectedObject detectedObject : results) { Rect boundingBox = detectedObject.getBoundingBox(); Integer trackingId = detectedObject.getTrackingId(); for (Label label : detectedObject.getLabels()) { String text = label.getText(); int index = label.getIndex(); float confidence = label.getConfidence(); } }
确保出色的用户体验
为了提供最佳用户体验,请在您的应用中遵循以下准则:
- 对象检测成功与否取决于对象的视觉复杂性。为了被检测,具有少量视觉特征的对象可能需要占用图片的大部分空间。您应该为用户提供有关捕获与您要检测的对象种类非常相符的输入的指导。
- 使用分类时,如果您要检测不完全属于受支持类别的对象,请对未知对象实施特殊处理。
另外,请查看机器学习套件 Material Design 展示应用和适用于机器学习所支持功能集的 Material Design 模式集合。
提高性能
如果要在实时应用中使用对象检测,请遵循以下准则以实现最佳帧速率:在实时应用中使用流式传输模式时,请勿使用多个对象检测,因为大多数设备无法产生足够的帧速率。
- 如果您使用
Camera
或camera2
API,请限制对检测器的调用。如果在检测器运行时有新的视频帧可用,请丢弃该帧。如需查看示例,请参阅快速入门示例应用中的VisionProcessorBase
类。 - 如果您使用
CameraX
API,请确保将 Backpressure 策略设置为其默认值ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
。 这样可以确保一次只会投放一张图片进行分析。如果分析器在繁忙时生成更多图片,这些图片会自动丢弃,不会排队等待传送。通过调用 ImageProxy.close() 关闭要分析的图片后,系统会交付下一个最新图片。 - 如果要将检测器的输出作为图形叠加在输入图片上,请先从机器学习套件获取结果,然后在一个步骤中完成图片的呈现和叠加。对于每个输入帧,这仅会在显示表面呈现一次。如需查看示例,请参阅快速入门示例应用中的
CameraSourcePreview
和GraphicOverlay
类。 - 如果您使用 Camera2 API,请以
ImageFormat.YUV_420_888
格式捕获图片。如果您使用旧版 Camera API,请以ImageFormat.NV21
格式捕获图片。