使用 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
格式捕獲圖像。