使用 AutoML Vision Edge 訓練專屬模型後,即可在應用程式中使用該模型偵測圖片中的物件。
您可以透過兩種方式整合從 AutoML Vision Edge 訓練的模型:將模型放入應用程式的資產資料夾中進行套裝組合,或是從 Firebase 動態下載模型。
模型搭售方案 | |
---|---|
應用程式內建 |
|
託管於 Firebase |
|
事前準備
如要下載模型,請務必將 Firebase 新增至 Android 專案 (如果尚未新增)。如果是將模型與應用程式套件組合,則不需要這麼做。
將 TensorFlow Lite Task 程式庫的依附元件新增至模組的應用程式層級 gradle 檔案,通常為
app/build.gradle
:如要將模型與應用程式組合:
dependencies { // ... // Object detection with a bundled Auto ML model implementation 'org.tensorflow:tensorflow-lite-task-vision:0.0.0-nightly-SNAPSHOT' }
如要從 Firebase 動態下載模型,請一併新增 Firebase ML 依附元件:
dependencies { // ... // Object detection with an Auto ML model deployed to Firebase implementation platform('com.google.firebase:firebase-bom:26.1.1') implementation 'com.google.firebase:firebase-ml-model-interpreter' implementation 'org.tensorflow:tensorflow-lite-task-vision:0.0.0-nightly' }
1. 載入模型
設定本機模型來源
如要將模型與應用程式組合,請按照下列步驟操作:
- 從您從 Google Cloud 控制台下載的 ZIP 封存檔中解壓縮模型。
- 在應用程式套件中加入模型:
- 如果專案中沒有資產資料夾,請在
app/
資料夾上按一下滑鼠右鍵,然後依序點選「New」>「Folder」>「Assets Folder」,建立資產資料夾。 - 將內嵌中繼資料的
tflite
模型檔案複製到資產資料夾。
- 如果專案中沒有資產資料夾,請在
在應用程式的
build.gradle
檔案中新增下列程式碼,確保 Gradle 在建構應用程式時不會壓縮模型檔案:android { // ... aaptOptions { noCompress "tflite" } }
模型檔案會納入應用程式套件,並以原始資產的形式提供。
設定 Firebase 託管的模型來源
如要使用遠端代管模型,請建立 RemoteModel
物件,並指定您發布模型時指派的名稱:
Java
// Specify the name you assigned when you deployed the model.
FirebaseCustomRemoteModel remoteModel =
new FirebaseCustomRemoteModel.Builder("your_model").build();
Kotlin
// Specify the name you assigned when you deployed the model.
val remoteModel =
FirebaseCustomRemoteModel.Builder("your_model_name").build()
接著啟動模型下載工作,並指定允許下載的條件。如果裝置上沒有模型,或是有更新版本的模型可用,工作會從 Firebase 非同步下載模型:
Java
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.
}
});
Kotlin
val downloadConditions = DownloadConditions.Builder()
.requireWifi()
.build()
RemoteModelManager.getInstance().download(remoteModel, downloadConditions)
.addOnSuccessListener {
// Success.
}
許多應用程式會在初始化程式碼中啟動下載工作,但您可以在需要使用模型前的任何時間點執行這項操作。
從模型建立物件偵測工具
設定模型來源後,請從其中一個來源建立 ObjectDetector
物件。
如果只有本機綁定的模型,只要從模型檔案建立物件偵測器,並設定要要求的信賴分數門檻即可 (請參閱「評估模型」):
Java
// Initialization
ObjectDetectorOptions options = ObjectDetectorOptions.builder()
.setScoreThreshold(0) // Evaluate your model in the Google Cloud console
// to determine an appropriate value.
.build();
ObjectDetector objectDetector = ObjectDetector.createFromFileAndOptions(context, modelFile, options);
Kotlin
// Initialization
val options = ObjectDetectorOptions.builder()
.setScoreThreshold(0) // Evaluate your model in the Google Cloud console
// to determine an appropriate value.
.build()
val objectDetector = ObjectDetector.createFromFileAndOptions(context, modelFile, options)
如果您使用遠端代管模型,請務必先檢查模型是否已下載,再執行模型。您可以使用模型管理工具的 isModelDownloaded()
方法,檢查模型下載工作的狀態。
雖然您只需要在執行物件偵測器前確認這項設定,但如果您同時有遠端代管模型和本機隨附模型,在例項化物件偵測器時執行這項檢查可能會有意義:如果已下載遠端模型,請從遠端模型建立物件偵測器,否則請從本機模型建立。
Java
FirebaseModelManager.getInstance().isModelDownloaded(remoteModel)
.addOnSuccessListener(new OnSuccessListener<Boolean>() {
@Override
public void onSuccess(Boolean isDownloaded) {
}
});
Kotlin
FirebaseModelManager.getInstance().isModelDownloaded(remoteModel)
.addOnSuccessListener { success ->
}
如果只有遠端代管模型,您應停用模型相關功能 (例如將部分 UI 設為灰色或隱藏),直到確認模型已下載為止。方法是在模型管理工具的 download()
方法中附加監聽器。
確認模型已下載後,請從模型檔案建立物件偵測器:
Java
FirebaseModelManager.getInstance().getLatestModelFile(remoteModel)
.addOnCompleteListener(new OnCompleteListener<File>() {
@Override
public void onComplete(@NonNull Task<File> task) {
File modelFile = task.getResult();
if (modelFile != null) {
ObjectDetectorOptions options = ObjectDetectorOptions.builder()
.setScoreThreshold(0)
.build();
objectDetector = ObjectDetector.createFromFileAndOptions(
getApplicationContext(), modelFile.getPath(), options);
}
}
});
Kotlin
FirebaseModelManager.getInstance().getLatestModelFile(remoteModel)
.addOnSuccessListener { modelFile ->
val options = ObjectDetectorOptions.builder()
.setScoreThreshold(0f)
.build()
objectDetector = ObjectDetector.createFromFileAndOptions(
applicationContext, modelFile.path, options)
}
2. 準備輸入圖片
接著,針對要標記的每張圖片,從圖片建立 TensorImage
物件。您可以使用 fromBitmap
方法,從 Bitmap
建立 TensorImage
物件:
Java
TensorImage image = TensorImage.fromBitmap(bitmap);
Kotlin
val image = TensorImage.fromBitmap(bitmap)
如果圖片資料不是 Bitmap
格式,可以載入像素陣列,如 TensorFlow Lite 文件所示。
3. 執行物件偵測工具
如要偵測圖片中的物件,請將 TensorImage
物件傳遞至 ObjectDetector
的 detect()
方法。
Java
List<Detection> results = objectDetector.detect(image);
Kotlin
val results = objectDetector.detect(image)
4. 取得標示物件的相關資訊
如果物件偵測作業成功,會傳回 Detection
物件清單。每個 Detection
物件都代表圖片中偵測到的項目。您可以取得每個物件的周框和標籤。
例如:
Java
for (Detection result : results) {
RectF bounds = result.getBoundingBox();
List<Category> labels = result.getCategories();
}
Kotlin
for (result in results) {
val bounds = result.getBoundingBox()
val labels = result.getCategories()
}
提升即時成效的訣竅
如要在即時應用程式中標記圖片,請按照下列規範操作,以達到最佳影格速率:
- 節流對圖片標籤加註者的呼叫。如果圖片標籤器執行時有新的影片影格可用,請捨棄該影格。如需範例,請參閱快速入門範例應用程式中的
VisionProcessorBase
類別。 - 如果您要使用圖片標籤工具的輸出內容,在輸入圖片上疊加圖像,請先取得結果,然後在單一步驟中算繪圖片並疊加圖像。這樣做的話,每個輸入影格只會轉譯到顯示表面一次。如需範例,請參閱快速入門範例應用程式中的
CameraSourcePreview
和GraphicOverlay
類別。 -
如果您使用 Camera2 API,請以
ImageFormat.YUV_420_888
格式擷取圖片。如果使用舊版 Camera API,請以
ImageFormat.NV21
格式擷取圖片。