使用 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 檔案中提取模型及其元資料。我們建議您直接使用下載的文件,不要進行修改(包括文件名稱)。
將您的模型及其元資料檔案包含在您的應用程式包中:
- 如果您的專案中沒有資產資料夾,請透過右鍵單擊
app/
資料夾,然後按一下新建 > 資料夾 > 資產資料夾來建立資料夾。 - 在 asset 資料夾下建立一個子資料夾來包含模型檔案。
- 將檔案
model.tflite
、dict.txt
和manifest.json
複製到子資料夾(所有三個檔案必須位於同一資料夾中)。
- 如果您的專案中沒有資產資料夾,請透過右鍵單擊
將以下內容新增至應用程式的
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
格式擷取影像。如果您使用較舊的相機 API,請以
ImageFormat.NV21
格式擷取影像。