ML Kit 提供經過最佳化的 SDK,可用於自拍區隔。
Selfie Segmenter 素材資源會在建構期間與應用程式建立靜態連結。這會使應用程式下載大小增加約 4.5 MB,而 API 延遲時間則視輸入圖片大小而定,在 Pixel 4 上測量為 25 毫秒至 65 毫秒。
立即試用
- 請試用範例應用程式,瞭解這個 API 的使用範例。
事前準備
- 在專案層級的
build.gradle
檔案中,請務必在buildscript
和allprojects
區段中納入 Google 的 Maven 存放區。 - 將 ML Kit Android 程式庫的依附元件新增至模組的應用程式層級 Gradle 檔案,通常為
app/build.gradle
:
dependencies {
implementation 'com.google.mlkit:segmentation-selfie:16.0.0-beta6'
}
1. 建立 Segmenter 例項
區隔器選項
如要對圖片進行區隔,請先指定下列選項,建立 Segmenter
的例項。
偵測器模式
Segmenter
有兩種運作模式。請務必選擇符合用途的選項。
STREAM_MODE (default)
這個模式專門用於從影片或相機串流影格。在這個模式中,分割器會利用先前影格中的結果,傳回更流暢的分割結果。
SINGLE_IMAGE_MODE
這個模式專為不相關的單張圖片而設計。在這個模式下,分割器會分別處理每張圖片,不會在影格上進行平滑處理。
啟用原始大小遮罩
要求分割器傳回與模型輸出大小相符的原始大小遮罩。
原始遮罩大小 (例如 256x256) 通常會小於輸入圖片大小。啟用這個選項時,請呼叫 SegmentationMask#getWidth()
和 SegmentationMask#getHeight()
取得遮罩大小。
如果未指定這個選項,分割器會重新調整原始遮罩的比例,以符合輸入圖片的大小。如果您想套用自訂的重新調整大小邏輯,或是您的用途不需要重新調整大小,建議您使用這個選項。
指定分割器選項:
val options = SelfieSegmenterOptions.Builder() .setDetectorMode(SelfieSegmenterOptions.STREAM_MODE) .enableRawSizeMask() .build()
SelfieSegmenterOptions options = new SelfieSegmenterOptions.Builder() .setDetectorMode(SelfieSegmenterOptions.STREAM_MODE) .enableRawSizeMask() .build();
建立 Segmenter
的例項。傳遞您指定的選項:
val segmenter = Segmentation.getClient(options)
Segmenter segmenter = Segmentation.getClient(options);
2. 準備輸入圖片
如要對圖片執行分割作業,請使用 Bitmap
、media.Image
、ByteBuffer
、位元組陣列或裝置上的檔案,建立 InputImage
物件。
您可以從不同來源建立 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. 處理圖片
將準備好的 InputImage
物件傳遞至 Segmenter
的 process
方法。
Task<SegmentationMask> result = segmenter.process(image) .addOnSuccessListener { results -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
Task<SegmentationMask> result = segmenter.process(image) .addOnSuccessListener( new OnSuccessListener<SegmentationMask>() { @Override public void onSuccess(SegmentationMask mask) { // Task completed successfully // ... } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Task failed with an exception // ... } });
4. 取得區隔結果
您可以透過下列方式取得區隔結果:
val mask = segmentationMask.getBuffer() val maskWidth = segmentationMask.getWidth() val maskHeight = segmentationMask.getHeight() for (val y = 0; y < maskHeight; y++) { for (val x = 0; x < maskWidth; x++) { // Gets the confidence of the (x,y) pixel in the mask being in the foreground. val foregroundConfidence = mask.getFloat() } }
ByteBuffer mask = segmentationMask.getBuffer(); int maskWidth = segmentationMask.getWidth(); int maskHeight = segmentationMask.getHeight(); for (int y = 0; y < maskHeight; y++) { for (int x = 0; x < maskWidth; x++) { // Gets the confidence of the (x,y) pixel in the mask being in the foreground. float foregroundConfidence = mask.getFloat(); } }
如需使用區隔結果的完整範例,請參閱 ML Kit 快速入門範例。
提升效能的訣竅
結果的品質取決於輸入圖片的品質:
- 為了讓 ML Kit 取得準確的分割結果,圖片至少應為 256 x 256 像素。
- 圖片對焦不佳也會影響準確度。如果您無法取得可接受的結果,請要求使用者重新拍攝圖片。
如果您想在即時應用程式中使用區隔功能,請按照下列指南操作,以獲得最佳的幀率:
- 使用
STREAM_MODE
。 - 建議您以較低解析度拍攝相片。不過,請注意這個 API 的圖片尺寸規定。
- 建議您啟用原始大小遮罩選項,並將所有重新調整大小的邏輯結合在一起。舉例來說,您可以先要求原始大小遮罩,然後再將其重新調整為符合輸入圖片大小,而非先讓 API 重新調整遮罩大小以符合輸入圖片大小,然後再重新調整以符合檢視畫面大小,這樣一來,您就能將這兩個步驟合併為一個步驟。
- 如果您使用
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
格式擷取圖片。