使用 AutoML Vision Edge 训练您自己的模型后,您可以在您的应用程序中使用它来标记图像。
有两种方法可以集成从 AutoML Vision Edge 训练的模型:您可以通过将模型放入应用程序的资产文件夹来捆绑模型,或者您可以从 Firebase 动态下载它。
模型捆绑选项 | |
---|---|
捆绑在您的应用程序中 |
|
使用 Firebase 托管 |
|
在你开始之前
将 ML Kit Android 库的依赖项添加到模块的应用级 gradle 文件,通常是
app/build.gradle
:要将模型与您的应用程序捆绑在一起:
dependencies { // ... // Image labeling feature with bundled automl model implementation 'com.google.mlkit:image-labeling-custom:16.3.1' }
要从 Firebase 动态下载模型,请添加
linkFirebase
依赖项:dependencies { // ... // Image labeling feature with automl model downloaded // from firebase implementation 'com.google.mlkit:image-labeling-custom:16.3.1' implementation 'com.google.mlkit:linkfirebase:16.1.0' }
如果您想下载模型,请确保将 Firebase 添加到您的 Android 项目(如果您尚未这样做)。捆绑模型时不需要这样做。
1.加载模型
配置本地模型源
将模型与您的应用程序捆绑在一起:
从您从 Firebase 控制台下载的 zip 存档中提取模型及其元数据。我们建议您使用下载的文件,不要修改(包括文件名)。
在您的应用程序包中包含您的模型及其元数据文件:
- 如果您的项目中没有 assets 文件夹,请通过右键单击
app/
文件夹,然后单击New > Folder > Assets Folder来创建一个。 - 在资产文件夹下创建一个子文件夹以包含模型文件。
- 将文件
model.tflite
、dict.txt
和manifest.json
复制到子文件夹(所有三个文件必须位于同一文件夹中)。
- 如果您的项目中没有 assets 文件夹,请通过右键单击
将以下内容添加到应用程序的
build.gradle
文件中,以确保 Gradle 在构建应用程序时不会压缩模型文件:android { // ... aaptOptions { noCompress "tflite" } }
模型文件将包含在应用程序包中,并作为原始资产提供给 ML Kit。
创建
LocalModel
对象,指定模型清单文件的路径:爪哇
AutoMLImageLabelerLocalModel localModel = new AutoMLImageLabelerLocalModel.Builder() .setAssetFilePath("manifest.json") // or .setAbsoluteFilePath(absolute file path to manifest file) .build();
科特林
val localModel = LocalModel.Builder() .setAssetManifestFilePath("manifest.json") // or .setAbsoluteManifestFilePath(absolute file path to manifest file) .build()
配置 Firebase 托管的模型源
要使用远程托管模型,请创建一个CustomRemoteModel
对象,指定您在发布模型时为其分配的名称:
爪哇
// Specify the name you assigned in the Firebase console.
FirebaseModelSource firebaseModelSource =
new FirebaseModelSource.Builder("your_model_name").build();
CustomRemoteModel remoteModel =
new CustomRemoteModel.Builder(firebaseModelSource).build();
科特林
// Specify the name you assigned in the Firebase console.
val firebaseModelSource = FirebaseModelSource.Builder("your_model_name")
.build()
val remoteModel = CustomRemoteModel.Builder(firebaseModelSource).build()
然后,启动模型下载任务,指定允许下载的条件。如果模型不在设备上,或者有更新版本的模型可用,任务将从 Firebase 异步下载模型:
爪哇
DownloadConditions downloadConditions = new DownloadConditions.Builder()
.requireWifi()
.build();
RemoteModelManager.getInstance().download(remoteModel, downloadConditions)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(@NonNull Task<Void> task) {
// Success.
}
});
科特林
val downloadConditions = DownloadConditions.Builder()
.requireWifi()
.build()
RemoteModelManager.getInstance().download(remoteModel, downloadConditions)
.addOnSuccessListener {
// Success.
}
许多应用程序在其初始化代码中开始下载任务,但您可以在需要使用该模型之前的任何时候执行此操作。
从您的模型创建一个图像标签
配置模型源后,从其中一个创建一个ImageLabeler
对象。
如果您只有一个本地捆绑的模型,只需从您的CustomImageLabelerOptions
对象创建一个标签器并配置您想要的置信度分数阈值(请参阅评估您的模型):
爪哇
CustomImageLabelerOptions customImageLabelerOptions = new CustomImageLabelerOptions.Builder(localModel)
.setConfidenceThreshold(0.0f) // Evaluate your model in the Cloud console
// to determine an appropriate value.
.build();
ImageLabeler labeler = ImageLabeling.getClient(customImageLabelerOptions);
科特林
val customImageLabelerOptions = CustomImageLabelerOptions.Builder(localModel)
.setConfidenceThreshold(0.0f) // Evaluate your model in the Cloud console
// to determine an appropriate value.
.build()
val labeler = ImageLabeling.getClient(customImageLabelerOptions)
如果您有一个远程托管的模型,则必须在运行之前检查它是否已下载。您可以使用模型管理器的isModelDownloaded()
方法检查模型下载任务的状态。
尽管您只需在运行标签器之前确认这一点,但如果您同时拥有远程托管模型和本地捆绑模型,则在实例化图像标签器时执行此检查可能是有意义的:从远程模型创建标签器,如果它已被下载,否则来自本地模型。
爪哇
RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
.addOnSuccessListener(new OnSuccessListener<Boolean>() {
@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.0f) // Evaluate your model in the Cloud console
// to determine an appropriate threshold.
.build();
ImageLabeler labeler = ImageLabeling.getClient(options);
}
});
科特林
RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
.addOnSuccessListener { isDownloaded ->
val optionsBuilder =
if (isDownloaded) {
CustomImageLabelerOptions.Builder(remoteModel)
} else {
CustomImageLabelerOptions.Builder(localModel)
}
// Evaluate your model in the Cloud console to determine an appropriate threshold.
val options = optionsBuilder.setConfidenceThreshold(0.0f).build()
val labeler = ImageLabeling.getClient(options)
}
如果您只有一个远程托管的模型,您应该禁用与模型相关的功能——例如,灰显或隐藏部分 UI——直到您确认模型已下载。您可以通过将侦听器附加到模型管理器的download()
方法来实现:
爪哇
RemoteModelManager.getInstance().download(remoteModel, conditions)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@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.
}
});
科特林
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.
}
2.准备输入图像
然后,对于您要标记的每个图像,从您的图像创建一个InputImage
对象。当您使用Bitmap
或使用 camera2 API 时,图像标签器运行速度最快,如果可能,建议使用 YUV_420_888 media.Image
。
您可以从不同的来源创建一个InputImage
,每个来源都在下面进行了解释。
使用media.Image
要从media.Image
InputImage
,例如当您从设备的相机捕获图像时,请将media.Image
对象和图像的旋转传递给InputImage.fromMediaImage()
。
如果您使用CameraX库, OnImageCapturedListener
和ImageAnalysis.Analyzer
类会为您计算旋转值。
Kotlin+KTX
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) { if (imageProxy == null || imageProxy.getImage() == null) { return; } Image mediaImage = imageProxy.getImage(); InputImage image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees); // Pass image to an ML Kit Vision API // ... } }
如果您不使用提供图像旋转度数的相机库,则可以根据设备的旋转度数和设备中相机传感器的方向来计算它:
Kotlin+KTX
private val ORIENTATIONS = SparseIntArray() init { ORIENTATIONS.append(Surface.ROTATION_0, 90) ORIENTATIONS.append(Surface.ROTATION_90, 0) ORIENTATIONS.append(Surface.ROTATION_180, 270) ORIENTATIONS.append(Surface.ROTATION_270, 180) } /** * 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, context: Context): 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) // On most devices, the sensor orientation is 90 degrees, but for some // devices it is 270 degrees. For devices with a sensor orientation of // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees. val cameraManager = context.getSystemService(CAMERA_SERVICE) as CameraManager val sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION)!! rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360 // Return the corresponding FirebaseVisionImageMetadata rotation value. val result: Int when (rotationCompensation) { 0 -> result = FirebaseVisionImageMetadata.ROTATION_0 90 -> result = FirebaseVisionImageMetadata.ROTATION_90 180 -> result = FirebaseVisionImageMetadata.ROTATION_180 270 -> result = FirebaseVisionImageMetadata.ROTATION_270 else -> { result = FirebaseVisionImageMetadata.ROTATION_0 Log.e(TAG, "Bad rotation value: $rotationCompensation") } } return result }
Java
private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } /** * 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, Context context) 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); // On most devices, the sensor orientation is 90 degrees, but for some // devices it is 270 degrees. For devices with a sensor orientation of // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees. CameraManager cameraManager = (CameraManager) context.getSystemService(CAMERA_SERVICE); int sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION); rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360; // Return the corresponding FirebaseVisionImageMetadata rotation value. int result; switch (rotationCompensation) { case 0: result = FirebaseVisionImageMetadata.ROTATION_0; break; case 90: result = FirebaseVisionImageMetadata.ROTATION_90; break; case 180: result = FirebaseVisionImageMetadata.ROTATION_180; break; case 270: result = FirebaseVisionImageMetadata.ROTATION_270; break; default: result = FirebaseVisionImageMetadata.ROTATION_0; Log.e(TAG, "Bad rotation value: " + rotationCompensation); } return result; }
然后,将media.Image
对象和旋转度值传递给InputImage.fromMediaImage()
:
Kotlin+KTX
val image = InputImage.fromMediaImage(mediaImage, rotation)
Java
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
使用文件 URI
要从文件 URI 创建InputImage
对象,请将应用程序上下文和文件 URI 传递给InputImage.fromFilePath()
。当您使用ACTION_GET_CONTENT
意图提示用户从他们的图库应用程序中选择图像时,这很有用。
Kotlin+KTX
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+KTX
val image = InputImage.fromByteBuffer( byteBuffer, /* 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 );
使用Bitmap
要从Bitmap
对象创建InputImage
对象,请进行以下声明:
Kotlin+KTX
val image = InputImage.fromBitmap(bitmap, 0)
Java
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
图像由Bitmap
对象和旋转度数一起表示。
3.运行图像标签
要标记图像中的对象,请将image
对象传递给ImageLabeler
的process()
方法。
爪哇
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
// ...
}
});
科特林
labeler.process(image)
.addOnSuccessListener { labels ->
// Task completed successfully
// ...
}
.addOnFailureListener { e ->
// Task failed with an exception
// ...
}
4.获取有关标记对象的信息
如果图像标记操作成功,则会将ImageLabel
对象列表传递给成功侦听器。每个ImageLabel
对象代表图像中标记的内容。您可以获得每个标签的文本描述、匹配的置信度分数和匹配的索引。例如:
爪哇
for (ImageLabel label : labels) {
String text = label.getText();
float confidence = label.getConfidence();
int index = label.getIndex();
}
科特林
for (label in labels) {
val text = label.text
val confidence = label.confidence
val index = label.index
}
提高实时性能的技巧
如果您想在实时应用程序中标记图像,请遵循以下准则以获得最佳帧率:
- 限制对图像标签器的调用。如果在图像标签器运行时有新的视频帧可用,则丢弃该帧。有关示例,请参阅快速入门示例应用程序中的
VisionProcessorBase
类。 - 如果您使用图像标签器的输出在输入图像上叠加图形,请首先获取结果,然后渲染图像并在一个步骤中进行叠加。通过这样做,您只需为每个输入帧渲染到显示表面一次。有关示例,请参阅快速入门示例应用中的
CameraSourcePreview
和GraphicOverlay
类。 如果您使用 Camera2 API,请以
ImageFormat.YUV_420_888
格式捕获图像。如果您使用较旧的 Camera API,请以
ImageFormat.NV21
格式捕获图像。