將圖片傳遞至 ML Kit 時,它會偵測圖片中最多五個物件,以及圖片中每個物件的位置。偵測影片串流中的物件時,每個物件都有專屬 ID,可用來追蹤影格之間的物件。
您可以使用自訂圖片分類模型,將偵測到的物件分類。如要瞭解模型相容性需求、如何尋找預先訓練模型,以及如何訓練自己的模型,請參閱「使用 ML Kit 自訂模型」一文。
整合自訂模型的方法有兩種。您可以將模型放到應用程式的資產資料夾中,也可以從 Firebase 動態下載。下表比較了這兩個選項。
組合模型 | 託管模型 |
---|---|
模型是應用程式的 APK 的一部分,因此會增加其大小。 | 模型不屬於您的 APK。託管於 Firebase 機器學習。 |
模型會立即可供使用,即使 Android 裝置處於離線狀態也沒問題 | 模型採隨選下載 |
不需要 Firebase 專案 | 需要 Firebase 專案 |
必須重新發布應用程式才能更新模型 | 不必重新發布應用程式就能推送模型更新 |
無內建 A/B 測試功能 | 透過 Firebase 遠端設定輕鬆進行 A/B 測試 |
立即體驗
- 請參閱視覺快速入門導覽課程應用程式,查看套裝組合模型的使用範例,以及 automl 快速入門導覽課程應用程式,查看託管模型的使用範例。
- 如需這個 API 的端對端實作,請參閱 Material Design 展示應用程式。
事前準備
在專案層級的
build.gradle
檔案中,請務必將 Google 的 Maven 存放區同時納入buildscript
和allprojects
區段。將 ML Kit Android 程式庫的依附元件新增至模組的應用程式層級 Gradle 檔案,通常為
app/build.gradle
:如需將模型與應用程式組合:
dependencies { // ... // Object detection & tracking feature with custom bundled model implementation 'com.google.mlkit:object-detection-custom:17.0.2' }
如要從 Firebase 動態下載模型,請新增
linkFirebase
依附元件:dependencies { // ... // Object detection & tracking feature with model downloaded // from firebase implementation 'com.google.mlkit:object-detection-custom:17.0.2' implementation 'com.google.mlkit:linkfirebase:17.0.0' }
如要下載模型,請先將 Firebase 新增至 Android 專案 (如果尚未新增)。建立模型組合時不需要這麼做。
1. 載入模型
設定本機模型來源
如要將模型與應用程式組合,請按照下列步驟操作:
將模型檔案 (通常以
.tflite
或.lite
結尾) 複製到應用程式的assets/
資料夾。(您可能需要先建立資料夾,方法是在app/
資料夾上按一下滑鼠右鍵,然後依序點選「New」>「Folder」>「Assets Folder」)。接著,將以下內容加入應用程式的
build.gradle
檔案,確保 Gradle 在建構應用程式時不會壓縮模型檔案:android { // ... aaptOptions { noCompress "tflite" // or noCompress "lite" } }
模型檔案會包含在應用程式套件中,做為原始資產提供給 ML Kit 使用。
建立
LocalModel
物件,指定模型檔案的路徑:Kotlin
val localModel = LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute file path to model file) // or .setUri(URI to model file) .build()
Java
LocalModel localModel = new LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute file path to model file) // or .setUri(URI to model file) .build();
設定 Firebase 託管的模型來源
如要使用遠端託管模型,請透過 FirebaseModelSource
建立 CustomRemoteModel
物件,並指定您在發布模型時指派的名稱:
Kotlin
// Specify the name you assigned in the Firebase console. val remoteModel = CustomRemoteModel .Builder(FirebaseModelSource.Builder("your_model_name").build()) .build()
Java
// Specify the name you assigned in the Firebase console. CustomRemoteModel remoteModel = new CustomRemoteModel .Builder(new FirebaseModelSource.Builder("your_model_name").build()) .build();
接著,啟動模型下載工作,指定您允許下載的條件。如果模型不在裝置上,或是有新版模型可用,工作將以非同步方式從 Firebase 下載模型:
Kotlin
val downloadConditions = DownloadConditions.Builder() .requireWifi() .build() RemoteModelManager.getInstance().download(remoteModel, downloadConditions) .addOnSuccessListener { // Success. }
Java
DownloadConditions downloadConditions = new DownloadConditions.Builder() .requireWifi() .build(); RemoteModelManager.getInstance().download(remoteModel, downloadConditions) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(@NonNull Task task) { // Success. } });
許多應用程式會在其初始化程式碼中啟動下載工作,但在需要使用模型之前,您隨時可以執行此操作。
2. 設定物件偵測工具
設定模型來源後,請使用 CustomObjectDetectorOptions
物件設定用途的物件偵測工具。您可以變更下列設定:
物件偵測器設定 | |
---|---|
偵測模式 |
STREAM_MODE (預設) | SINGLE_IMAGE_MODE 在 在 |
偵測並追蹤多個物件 |
false (預設) | true 偵測及追蹤最多五個物件,或是只追蹤最顯眼的物件 (預設)。 |
將物件分類 |
false (預設) | true 是否要使用所提供自訂分類器模型,將偵測到的物件分類。如要使用自訂分類模型,您必須將這個屬性設為 |
分類可信度門檻 |
偵測到標籤的最低可信度分數。如未設定,系統會使用模型中繼資料指定的任何分類器門檻。如果模型不含任何中繼資料,或是中繼資料未指定分類器門檻,系統就會使用預設的 0.0 門檻。 |
每個物件的標籤數量上限 |
偵測器要傳回的每個物件標籤數量上限。如未設定,系統會使用預設值 10。 |
物件偵測和追蹤 API 已針對以下兩項核心用途進行最佳化:
- 即時偵測及追蹤相機觀景窗中最顯眼的物件。
- 偵測靜態圖片中的多個物件。
如要為這些用途設定 API,請使用本機組合模型:
Kotlin
// Live detection and tracking val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() // Multiple object detection in static images val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions)
Java
// Live detection and tracking CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); // Multiple object detection in static images CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions);
如果您使用遠端託管的模型,必須在執行前檢查模型是否已下載。您可以使用模型管理員的 isModelDownloaded()
方法檢查模型下載工作的狀態。
雖然只有在執行偵測工具前才須確認,但如果您同時擁有遠端託管模型和本機組合模型,則在執行個體化圖片偵測工具時,可能還是執行這項檢查:如果您已下載遠端模型,並從本機模型建立偵測工具。
Kotlin
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener { isDownloaded -> val optionsBuilder = if (isDownloaded) { CustomObjectDetectorOptions.Builder(remoteModel) } else { CustomObjectDetectorOptions.Builder(localModel) } val customObjectDetectorOptions = optionsBuilder .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions) }
Java
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Boolean isDownloaded) { CustomObjectDetectorOptions.Builder optionsBuilder; if (isDownloaded) { optionsBuilder = new CustomObjectDetectorOptions.Builder(remoteModel); } else { optionsBuilder = new CustomObjectDetectorOptions.Builder(localModel); } CustomObjectDetectorOptions customObjectDetectorOptions = optionsBuilder .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions); } });
如果您只有遠端託管模型,建議停用模型相關功能 (例如顯示為灰色或隱藏部分 UI),直到確認模型已下載為止。您可以將事件監聽器附加至模型管理員的 download()
方法,藉此完成此操作:
Kotlin
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. }
Java
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. } });
3. 準備輸入圖片
使用圖片建立InputImage
物件。物件偵測工具會直接從 Bitmap
、NV21 ByteBuffer
或 YUV_420_888 media.Image
執行。如果您能直接存取其中一個來源,建議您從這些來源建構 InputImage
。如果您從其他來源建構 InputImage
,我們會在內部為您處理轉換作業,而這麼做的效率可能會降低。
您可以從不同來源建立 InputImage
物件,其說明如下。
使用 media.Image
如要從 media.Image
物件建立 InputImage
物件 (例如從裝置的相機擷取圖片),請將 media.Image
物件和圖片旋轉角度傳遞至 InputImage.fromMediaImage()
。
如果使用
CameraX 程式庫,OnImageCapturedListener
和 ImageAnalysis.Analyzer
類別會為您計算旋轉值。
Kotlin
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) { Image mediaImage = imageProxy.getImage(); if (mediaImage != null) { InputImage image = InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees()); // Pass image to an ML Kit Vision API // ... } } }
如果您使用的相機程式庫未提供圖片的旋轉角度,則可根據裝置的旋轉角度和相機感應器方向來計算圖像:
Kotlin
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 }
Java
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()
:
Kotlin
val image = InputImage.fromMediaImage(mediaImage, rotation)
Java
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
使用檔案 URI
如要從檔案 URI 中建立 InputImage
物件,請將應用程式結構定義和檔案 URI 傳遞至 InputImage.fromFilePath()
。當您使用 ACTION_GET_CONTENT
意圖提示使用者從圖片庫應用程式選取圖片時,這種做法就非常實用。
Kotlin
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
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 )
Java
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
物件,請做出下列宣告:
Kotlin
val image = InputImage.fromBitmap(bitmap, 0)
Java
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
圖片由 Bitmap
物件以旋轉度數表示。
4. 執行物件偵測工具
Kotlin
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (detectedObject in results) { // ... } });
Java
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (DetectedObject detectedObject : results) { // ... } });
5. 取得已加上標籤的物件相關資訊
如果呼叫 process()
成功,系統會將 DetectedObject
清單傳遞至成功事件監聽器。
每個 DetectedObject
都包含下列屬性:
定界框 | 表示物件在圖片中位置的 Rect 。 |
||||||
追蹤 ID | 用於識別圖片中物件的整數。SINGLE_IMAGE_MODE 中的空值。 | ||||||
標籤 |
|
Kotlin
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (detectedObject in results) { val boundingBox = detectedObject.boundingBox val trackingId = detectedObject.trackingId for (label in detectedObject.labels) { val text = label.text val index = label.index val confidence = label.confidence } }
Java
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (DetectedObject detectedObject : results) { Rect boundingBox = detectedObject.getBoundingBox(); Integer trackingId = detectedObject.getTrackingId(); for (Label label : detectedObject.getLabels()) { String text = label.getText(); int index = label.getIndex(); float confidence = label.getConfidence(); } }
確保良好的使用者體驗
為獲得最佳使用者體驗,請在應用程式中遵循下列規範:
- 物件偵測成功取決於物件的視覺複雜度。含有少量視覺特徵的物件可能需要較大的部分才能偵測出來。您應該為使用者提供相關指引,說明如何擷取適用於要偵測的物件種類的輸入內容。
- 使用分類時,如要偵測未完全符合支援類別的物件,請針對未知物件採用特殊處理方式。
此外,也請查看 ML Kit 質感設計展示應用程式及 Material Design「採用機器學習技術的功能的模式」集合。
提升效能
如果您想在即時應用程式中使用物件偵測功能,請按照下列指南操作,以達到最佳影格速率:在即時應用程式中使用串流模式時,請勿使用多個物件偵測功能,因為大多數裝置無法產生適當的影格速率。
- 如果您使用的是
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
格式擷取圖片。