您可以使用机器学习套件识别图片中的实体并为其添加标签。此 API 支持各种自定义图片分类模型。请参阅使用机器学习套件的自定义模型,获取模型兼容性要求、在哪里可以找到预训练模型以及如何训练自己的模型。
您可以通过以下两种方式将图片标签与自定义模型集成:将流水线作为应用的一部分捆绑,或使用依赖于 Google Play 服务的未捆绑流水线。如果您选择未捆绑流水线,您的应用将更小。请参阅下表了解详情。
捆绑 | 未捆绑 | |
---|---|---|
库名称 | com.google.mlkit:image-labeling-custom | com.google.android.gms:play-services-mlkit-image-labeling-custom |
实现 | 流水线在构建时静态关联到您的应用。 | 流水线是通过 Google Play 服务动态下载的。 |
应用大小 | 大小增加约 3.8 MB。 | 大小增加约 200 KB。 |
初始化时间 | 流水线立即可用。 | 首次使用前可能需要等待流水线下载完毕。 |
API 生命周期阶段 | 正式版 (GA) | 测试版 |
集成自定义模型的方法有两种:将模型放在应用的资源文件夹中进行捆绑,或者从 Firebase 动态下载模型。下表对这两个选项进行了比较。
捆绑模型 | 托管模型 |
---|---|
模型是应用 APK 的一部分,因此会增加其大小。 | 此模型不是 APK 的一部分。该项目通过上传到 Firebase Machine Learning 进行托管。 |
即使 Android 设备处于离线状态,模型也可立即使用 | 模型可按需下载 |
不需要 Firebase 项目 | 需要 Firebase 项目 |
您必须重新发布应用才能更新模型 | 无需重新发布应用即可推送模型更新 |
无内置 A/B 测试 | 使用 Firebase Remote Config 轻松进行 A/B 测试 |
试试看
- 如需查看捆绑模型的示例,请参阅 Vision 快速入门应用;如需查看托管模型的示例,请参阅 automl 快速入门应用。
准备工作
请务必在您的项目级
build.gradle
文件中的buildscript
和allprojects
部分添加 Google 的 Maven 代码库。将 Android 版机器学习套件库的依赖项添加到您的模块的应用级 Gradle 文件(通常为
app/build.gradle
)。根据您的需求选择以下依赖项之一:要将流水线与您的应用捆绑在一起,请执行以下操作:
dependencies { // ... // Use this dependency to bundle the pipeline with your app implementation 'com.google.mlkit:image-labeling-custom:17.0.1' }
对于在 Google Play 服务中使用流水线:
dependencies { // ... // Use this dependency to use the dynamically downloaded pipeline in Google Play Services implementation 'com.google.android.gms:play-services-mlkit-image-labeling-custom:16.0.0-beta4' }
如果您选择在 Google Play 服务中使用流水线,可以对应用进行配置,使其从 Play 商店安装后自动将流水线下载到设备上。为此,请将以下声明添加到应用的
AndroidManifest.xml
文件中:<application ...> ... <meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="custom_ica" /> <!-- To use multiple downloads: android:value="custom_ica,download2,download3" --> </application>
您还可以通过 Google Play 服务 ModuleInstallClient API 明确检查流水线可用性并请求下载。
如果您未启用在安装时下载流水线的功能,也未请求明确下载流水线,那么系统会在您首次运行标记器时下载流水线。您在下载完毕之前提出的请求不会产生任何结果。
如果要从 Firebase 动态下载模型,请添加
linkFirebase
依赖项:要从 Firebase 动态下载模型,请添加
linkFirebase
依赖项:dependencies { // ... // Image labeling feature with model downloaded from Firebase implementation 'com.google.mlkit:image-labeling-custom:17.0.1' // Or use the dynamically downloaded pipeline in Google Play Services // implementation 'com.google.android.gms:play-services-mlkit-image-labeling-custom:16.0.0-beta4' 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
创建一个 RemoteModel
对象,指定您在发布该模型时分配给模型的名称:
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. } });
许多应用会通过其初始化代码启动下载任务,但您可以在需要使用该模型之前随时启动下载任务。
配置图片标记器
配置模型来源后,根据其中一个模型创建 ImageLabeler
对象。
提供的选项如下:
选项 | |
---|---|
confidenceThreshold
|
检测到的标签的最小置信度分数。如果未设置,则将使用模型元数据指定的任何分类器阈值。如果模型不包含任何元数据,或者元数据未指定分类器阈值,则将使用默认阈值 0.0。 |
maxResultCount
|
要返回的标签数上限。如果未设置,则使用默认值 10。 |
如果您只有本地捆绑的模型,只需根据您的 LocalModel
对象创建一个标记器即可:
Kotlin
val customImageLabelerOptions = CustomImageLabelerOptions.Builder(localModel) .setConfidenceThreshold(0.5f) .setMaxResultCount(5) .build() val labeler = ImageLabeling.getClient(customImageLabelerOptions)
Java
CustomImageLabelerOptions customImageLabelerOptions = new CustomImageLabelerOptions.Builder(localModel) .setConfidenceThreshold(0.5f) .setMaxResultCount(5) .build(); ImageLabeler labeler = ImageLabeling.getClient(customImageLabelerOptions);
如果您有远程托管的模型,则在运行之前,必须检查模型是否已经下载。您可以使用模型管理器的 isModelDownloaded()
方法检查模型下载任务的状态。
虽然您只需在运行标记器之前确认这一点,但如果您同时拥有远程托管模型和本地捆绑模型,则可能需要在实例化图片标记器时执行此检查:如果已下载,则根据远程模型创建标记器,否则根据本地模型进行创建。
Kotlin
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener { isDownloaded -> val optionsBuilder = if (isDownloaded) { CustomImageLabelerOptions.Builder(remoteModel) } else { CustomImageLabelerOptions.Builder(localModel) } val options = optionsBuilder .setConfidenceThreshold(0.5f) .setMaxResultCount(5) .build() val labeler = ImageLabeling.getClient(options) }
Java
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Boolean isDownloaded) { CustomImageLabelerOptions.Builder optionsBuilder; if (isDownloaded) { optionsBuilder = new CustomImageLabelerOptions.Builder(remoteModel); } else { optionsBuilder = new CustomImageLabelerOptions.Builder(localModel); } CustomImageLabelerOptions options = optionsBuilder .setConfidenceThreshold(0.5f) .setMaxResultCount(5) .build(); ImageLabeler labeler = ImageLabeling.getClient(options); } });
如果您只有远程托管的模型,则应停用与模型相关的功能(例如使界面的一部分变灰或将其隐藏),直到您确认模型已下载。为此,您可以将监听器附加到模型管理器的 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. } });
2. 准备输入图片
然后,对于每个您想要加标签的图片,基于图片创建一个InputImage
对象。使用 Bitmap
或 YUV_420_888 media.Image
(如果您使用 Camera2 API)时,图片标记器的运行速度最快;建议您尽量使用这两种格式的图片。
您可以根据不同来源创建 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
对象以及旋转角度表示。
3. 运行图片标记器
如需给图片中的对象加标签,请将 image
对象传递给 ImageLabeler
的 process()
方法。
Kotlin
labeler.process(image) .addOnSuccessListener { labels -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
Java
labeler.process(image) .addOnSuccessListener(new OnSuccessListener<List<ImageLabel>>() { @Override public void onSuccess(List<ImageLabel> labels) { // Task completed successfully // ... } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Task failed with an exception // ... } });
4. 获取有关已加标签的实体的信息
如果给图片加标签操作成功,系统会向成功监听器传递一组ImageLabel
对象。每个 ImageLabel
对象代表图片中加了标签的某个事物。您可以获取每个标签的文本说明(如果 TensorFlow Lite 模型文件的元数据中提供了该说明)、置信度分数和索引。例如:
Kotlin
for (label in labels) { val text = label.text val confidence = label.confidence val index = label.index }
Java
for (ImageLabel label : labels) { String text = label.getText(); float confidence = label.getConfidence(); int index = label.getIndex(); }
实时性能提升技巧
如果要在实时应用中给图片加标签,请遵循以下准则以实现最佳帧速率:
- 如果您使用
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
格式捕获图片。