您可以使用 ML Kit 為圖片中辨識出的物件加上標籤。ML Kit 提供的預設模型支援 400 多個不同的標籤。
功能 | 未組合 | 組合 |
---|---|---|
實作中 | 模型會透過 Google Play 服務動態下載。 | 模型會在建構時靜態連結至 。 |
應用程式大小 | 大約大小為 200 KB。 | 大小約為 5.7 MB。 |
初始化時間 | 可能必須先等待模型下載才能使用。 | 可立即使用型號 |
立即體驗
- 如要查看此 API 的範例,請搭配範例應用程式。
事前準備
在專案層級的
build.gradle
檔案中,請務必將 Google 的 Maven 存放區加進buildscript
和allprojects
區段。將 ML Kit Android 程式庫的依附元件新增至模組的應用程式層級 Gradle 檔案 (通常是
app/build.gradle
)。您可以根據需求選擇下列其中一種依附元件:綁定模型與應用程式的影響:
dependencies { // ... // Use this dependency to bundle the model with your app implementation 'com.google.mlkit:image-labeling:17.0.7' }
在 Google Play 服務中使用模型:
dependencies { // ... // Use this dependency to use the dynamically downloaded model in Google Play Services implementation 'com.google.android.gms:play-services-mlkit-image-labeling:16.0.8' }
如果您選擇在 Google Play 服務中使用該模型,您可以設定應用程式,讓應用程式從 Play 商店安裝後自動下載至裝置。如要這麼做,請在應用程式的
AndroidManifest.xml
檔案中新增以下宣告:<application ...> ... <meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="ica" > <!-- To use multiple models: android:value="ica,model2,model3" --> </application>
您也可以透過 Google Play 服務 ModuleInstallClient API 明確檢查模型可用性及要求下載。
如果不啟用安裝時模型下載或要求明確下載,系統會在您首次執行標籤人員時下載模型。在下載完成之前提出的要求不會產生任何結果。
您現在可以為圖片加上標籤。
1. 準備輸入圖片
使用圖片建立InputImage
物件。使用 Bitmap
時,圖片標籤器的執行速度最快;如果您使用 Camera2 API,則 YUV_420_888 media.Image
(建議盡可能使用)。
您可以從不同來源建立 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
物件搭配旋轉角度表示。
2. 設定並執行映像檔標籤工具
如要為圖片中的物件加上標籤,請將InputImage
物件傳遞至 ImageLabeler
的 process
方法。
首先,請取得
ImageLabeler
的執行個體。如要使用裝置端圖片標籤器,請進行以下宣告:
Kotlin
// To use default options: val labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS) // Or, to set the minimum confidence required: // val options = ImageLabelerOptions.Builder() // .setConfidenceThreshold(0.7f) // .build() // val labeler = ImageLabeling.getClient(options)
Java
// To use default options: ImageLabeler labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS); // Or, to set the minimum confidence required: // ImageLabelerOptions options = // new ImageLabelerOptions.Builder() // .setConfidenceThreshold(0.7f) // .build(); // ImageLabeler labeler = ImageLabeling.getClient(options);
- 接著,將圖片傳遞至
process()
方法:
Kotlin
labeler.process(image) .addOnSuccessListener { labels -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
Java
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 // ... } });
3. 取得已加上標籤物件的相關資訊
如果圖片標籤作業成功,系統會將ImageLabel
物件清單傳遞至成功的事件監聽器。每個 ImageLabel
物件都代表了圖片中加上標籤的內容。基本模型支援超過 400 種不同的標籤。
您可以取得每個標籤的文字說明、模型所有支援標籤的索引,以及相符項目的可信度分數。例如:
Kotlin
for (label in labels) { val text = label.text val confidence = label.confidence val index = label.index }
Java
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
格式的圖片。