在 Android 上使用 AutoML 訓練的模型為圖片加上標籤
使用 AutoML Vision Edge 訓練專屬模型後,您就可以在應用程式中使用該模型為圖片加上標籤。 您可以透過兩種方式整合從 AutoML Vision Edge 訓練的模型:將模型打包至應用程式的素材資源資料夾,或是從 Firebase 動態下載模型。模型捆綁選項 | |
---|---|
已打包至應用程式 |
|
透過 Firebase 託管 |
|
立即試用
- 請試用範例應用程式,瞭解這個 API 的使用範例。
事前準備
1. 在專案層級的build.gradle
檔案中,請務必在 buildscript
和 allprojects
區段中納入 Google 的 Maven 存放區。2. 將 ML Kit Android 程式庫的依附元件新增至模組的應用程式層級 Gradle 檔案,通常為
app/build.gradle
:
如果要將模型與應用程式一起封裝:dependencies { // ... // Image labeling feature with bundled automl model implementation 'com.google.mlkit:image-labeling-automl:16.2.1' }
linkFirebase
依附元件:dependencies { // ... // Image labeling feature with automl model downloaded // from firebase implementation 'com.google.mlkit:image-labeling-automl:16.2.1' implementation 'com.google.mlkit:linkfirebase:16.0.1' }
1. 載入模型
設定本機模型來源
如要將模型與應用程式組合:1. 從 Firebase 主控台下載的 ZIP 封存檔中,擷取模型及其中繼資料。建議您使用下載的檔案,不做任何修改 (包括檔案名稱)。
2. 在應用程式套件中加入模型及其中繼資料檔案:
a. 如果專案中沒有 Assets 資料夾,請在
app/
資料夾上按一下滑鼠右鍵,然後依序點選「New」>「Folder」>「Assets Folder」建立資料夾。b. 在 assets 資料夾下建立子資料夾,用於容納模型檔案。
c. 將
model.tflite
、dict.txt
和 manifest.json
檔案複製到子資料夾 (三個檔案必須位於同一個資料夾)。3. 將以下內容加入應用程式的
build.gradle
檔案,確保 Gradle 在建構應用程式時不會壓縮模型檔案:android { // ... aaptOptions { noCompress "tflite" } }
注意:從 Android Gradle 外掛程式 4.1 版開始,.tflite 會預設加入 noCompress 清單,因此您不再需要上述設定。
4. 建立
LocalModel
物件,指定模型資訊清單檔案的路徑:val localModel = AutoMLImageLabelerLocalModel.Builder() .setAssetFilePath("manifest.json") // or .setAbsoluteFilePath(absolute file path to manifest file) .build()
AutoMLImageLabelerLocalModel localModel = new AutoMLImageLabelerLocalModel.Builder() .setAssetFilePath("manifest.json") // or .setAbsoluteFilePath(absolute file path to manifest file) .build();
設定由 Firebase 代管的模型來源
如要使用遠端代管的模型,請建立 RemoteModel
物件,並指定您在發布模型時指派的名稱:
// Specify the name you assigned in the Firebase console. val remoteModel = AutoMLImageLabelerRemoteModel.Builder("your_model_name").build()
// Specify the name you assigned in the Firebase console. AutoMLImageLabelerRemoteModel remoteModel = new AutoMLImageLabelerRemoteModel.Builder("your_model_name").build();
接著,啟動模型下載工作,並指定要允許下載的條件。如果裝置上沒有模型,或是有較新版本的模型可供使用,工作會從 Firebase 異步下載模型:
val downloadConditions = DownloadConditions.Builder() .requireWifi() .build() RemoteModelManager.getInstance().download(remoteModel, downloadConditions) .addOnSuccessListener { // Success. }
DownloadConditions downloadConditions = new DownloadConditions.Builder() .requireWifi() .build(); RemoteModelManager.getInstance().download(remoteModel, downloadConditions) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(@NonNull Task task) { // Success. } });
許多應用程式會在初始化程式碼中啟動下載工作,但您可以在需要使用模型之前的任何時間啟動下載工作。
根據模型建立圖片標註工具
設定模型來源後,請從其中一個來源建立 ImageLabeler
物件。
如果您只有在本地端封裝的模型,請從 AutoMLImageLabelerLocalModel
物件建立標記器,並設定所需的信心分數門檻 (請參閱「評估模型」):
val autoMLImageLabelerOptions = AutoMLImageLabelerOptions.Builder(localModel) .setConfidenceThreshold(0) // Evaluate your model in the Firebase console // to determine an appropriate value. .build() val labeler = ImageLabeling.getClient(autoMLImageLabelerOptions)
AutoMLImageLabelerOptions autoMLImageLabelerOptions = new AutoMLImageLabelerOptions.Builder(localModel) .setConfidenceThreshold(0.0f) // Evaluate your model in the Firebase console // to determine an appropriate value. .build(); ImageLabeler labeler = ImageLabeling.getClient(autoMLImageLabelerOptions)
如果您使用的是遠端代管模型,請務必先確認模型已下載,再執行模型。您可以使用模型管理員的 isModelDownloaded()
方法,查看模型下載作業的狀態。
雖然您只需要在執行標註器前確認這項資訊,但如果您同時擁有遠端代管模型和本機內建模型,在例項化圖片標註器時執行這項檢查可能會比較合理:如果已下載遠端模型,請從該模型建立標註器;如果未下載,請從本機模型建立標註器。
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener { isDownloaded -> val optionsBuilder = if (isDownloaded) { AutoMLImageLabelerOptions.Builder(remoteModel) } else { AutoMLImageLabelerOptions.Builder(localModel) } // Evaluate your model in the Firebase console to determine an appropriate threshold. val options = optionsBuilder.setConfidenceThreshold(0.0f).build() val labeler = ImageLabeling.getClient(options) }
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Boolean isDownloaded) { AutoMLImageLabelerOptions.Builder optionsBuilder; if (isDownloaded) { optionsBuilder = new AutoMLImageLabelerOptions.Builder(remoteModel); } else { optionsBuilder = new AutoMLImageLabelerOptions.Builder(localModel); } AutoMLImageLabelerOptions options = optionsBuilder .setConfidenceThreshold(0.0f) // Evaluate your model in the Firebase console // to determine an appropriate threshold. .build(); ImageLabeler labeler = ImageLabeling.getClient(options); } });
如果您只有遠端代管的模型,請在確認已下載模型前,停用模型相關功能 (例如將部分 UI 設為灰色或隱藏)。方法是將事件監聽器附加至模型管理員的 download()
方法:
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. }
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
或 (如果使用 camera2 API) YUV_420_888 media.Image
時,圖片標註器的執行速度最快,建議盡量使用這兩種格式。
您可以從不同來源建立 InputImage
物件,下文將說明每個來源。
使用 media.Image
如要從 media.Image
物件建立 InputImage
物件 (例如從裝置相機拍攝圖片時),請將 media.Image
物件和圖片的旋轉方向傳遞至 InputImage.fromMediaImage()
。
如果您使用
CameraX 程式庫,OnImageCapturedListener
和 ImageAnalysis.Analyzer
類別會為您計算旋轉值。
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 // ... } } }
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 // ... } } }
如果您未使用可提供圖片旋轉角度的相機程式庫,可以根據裝置的旋轉角度和裝置中相機感應器的方向來計算:
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 }
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()
:
val image = InputImage.fromMediaImage(mediaImage, rotation)
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
使用檔案 URI
如要從檔案 URI 建立 InputImage
物件,請將應用程式內容和檔案 URI 傳遞至 InputImage.fromFilePath()
。當您使用 ACTION_GET_CONTENT
意圖,提示使用者從相片庫應用程式中選取圖片時,這項功能就很實用。
val image: InputImage try { image = InputImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
InputImage image;
try {
image = InputImage.fromFilePath(context, uri);
} catch (IOException e) {
e.printStackTrace();
}
使用 ByteBuffer
或 ByteArray
如要從 ByteBuffer
或 ByteArray
建立 InputImage
物件,請先計算圖片旋轉角度,如前所述的 media.Image
輸入資料。接著,請使用緩衝區或陣列,搭配圖片的高度、寬度、顏色編碼格式和旋轉角度,建立 InputImage
物件:
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 )
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
物件,請進行下列宣告:
val image = InputImage.fromBitmap(bitmap, 0)
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
圖片由 Bitmap
物件和旋轉度數代表。
3. 執行圖片標註工具
如要為圖片中的物件加上標籤,請將image
物件傳遞至 ImageLabeler
的 process()
方法。labeler.process(image) .addOnSuccessListener { labels -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
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
物件都代表圖片中標示的項目。您可以取得每個標籤的文字說明、比對的信心分數和比對的索引。例如:
for (label in labels) { val text = label.text val confidence = label.confidence val index = label.index }
for (ImageLabel label : labels) { String text = label.getText(); float confidence = label.getConfidence(); int index = label.getIndex(); }
改善即時成效的訣竅
如要在即時應用程式中標示圖片,請遵循下列指南,以獲得最佳的幀率:
- 如果您使用
Camera
或camera2
API,請限制對圖像標註工具的呼叫。如果在圖片標註工具執行期間出現新的影片影格,請放棄該影格。如需範例,請參閱快速入門範例應用程式中的VisionProcessorBase
類別。 - 如果您使用
CameraX
API,請務必將回壓策略設為預設值ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
。這樣就能確保每次只會提交一張圖片進行分析。如果在分析器忙碌時產生更多圖片,系統會自動捨棄這些圖片,不會將圖片排入佇列以便傳送。呼叫 ImageProxy.close() 關閉要分析的圖片後,系統會傳送下一個最新的圖片。 - 如果您使用圖片標註器的輸出內容,在輸入圖片上重疊圖形,請先從 ML Kit 取得結果,然後在單一步驟中算繪圖片和重疊圖形。這項作業只會針對每個輸入影格轉譯至顯示介面。如需範例,請參閱快速入門範例應用程式中的
CameraSourcePreview
和GraphicOverlay
類別。 - 如果您使用 Camera2 API,請以
ImageFormat.YUV_420_888
格式擷取圖片。如果您使用舊版 Camera API,請以ImageFormat.NV21
格式擷取圖片。