您可以使用ML Kit來識別和解碼條碼。
在你開始之前
- 如果您尚未將 Firebase 新增至您的 Android 專案中,請將其新增至您的 Android 專案中。
- 將 ML Kit Android 函式庫的依賴項新增至模組(應用程式層級)Gradle 檔案(通常
app/build.gradle
):apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' dependencies { // ... implementation 'com.google.firebase:firebase-ml-vision:24.0.3' implementation 'com.google.firebase:firebase-ml-vision-barcode-model:16.0.1' }
輸入影像指南
為了讓 ML Kit 準確讀取條碼,輸入影像必須包含由足夠像素資料表示的條碼。
特定的像素資料要求取決於條碼的類型和其中編碼的資料量(因為大多數條碼支援可變長度有效負載)。一般來說,條碼的最小有意義單元應至少為 2 個像素寬(對於二維碼,為 2 個像素高)。
例如,EAN-13 條碼由 1、2、3 或 4 個單位寬的條和空格組成,因此 EAN-13 條碼影像理想情況下具有至少 2、4、6 和 4 個單位的條和空格。8 像素寬。由於 EAN-13 條碼的總寬度為 95 個單位,因此條碼的寬度應至少為 190 像素。
更密集的格式(例如 PDF417)需要更大的像素尺寸,ML Kit 才能可靠地讀取它們。例如,PDF417 程式碼在單行中最多可以有 34 個 17 單位寬的“字”,理想情況下寬度至少為 1156 像素。
影像聚焦不良會影響掃描精度。如果您沒有獲得可接受的結果,請嘗試要求使用者重新捕捉影像。
對於典型應用,建議提供更高解析度的影像(例如 1280x720 或 1920x1080),這樣可以從相機較遠的距離檢測條碼。
然而,在延遲至關重要的應用中,您可以透過以較低解析度擷取影像來提高效能,但要求條碼構成輸入影像的大部分。另請參閱提高即時效能的提示。
1. 設定條碼偵測器
如果您知道希望讀取哪些條碼格式,則可以透過將條碼偵測器配置為僅偵測這些格式來提高條碼偵測器的速度。例如,若要僅偵測 Aztec 程式碼和 QR 程式碼,請建立FirebaseVisionBarcodeDetectorOptions
對象,如下例所示:
Java
FirebaseVisionBarcodeDetectorOptions options = new FirebaseVisionBarcodeDetectorOptions.Builder() .setBarcodeFormats( FirebaseVisionBarcode.FORMAT_QR_CODE, FirebaseVisionBarcode.FORMAT_AZTEC) .build();
Kotlin+KTX
val options = FirebaseVisionBarcodeDetectorOptions.Builder() .setBarcodeFormats( FirebaseVisionBarcode.FORMAT_QR_CODE, FirebaseVisionBarcode.FORMAT_AZTEC) .build()
支援以下格式:
- 代碼 128 (
FORMAT_CODE_128
) - 代碼 39 (
FORMAT_CODE_39
) - 代碼 93 (
FORMAT_CODE_93
) - 庫達巴 (
FORMAT_CODABAR
) - EAN-13 (
FORMAT_EAN_13
) - EAN-8(
FORMAT_EAN_8
) - ITF(
FORMAT_ITF
) - UPC-A (
FORMAT_UPC_A
) - UPC-E (
FORMAT_UPC_E
) - 二維碼(
FORMAT_QR_CODE
) - PDF417(
FORMAT_PDF417
) - 阿茲特克 (
FORMAT_AZTEC
) - 資料矩陣(
FORMAT_DATA_MATRIX
)
2. 運行條碼檢測器
若要辨識影像中的條碼,請從Bitmap
、 media.Image
、 ByteBuffer
、位元組陣列或裝置上的檔案建立FirebaseVisionImage
物件。然後,將FirebaseVisionImage
物件傳遞給FirebaseVisionBarcodeDetector
的detectInImage
方法。從您的映像建立
FirebaseVisionImage
物件。若要從
media.Image
物件建立FirebaseVisionImage
物件(例如從裝置的相機擷取影像時),請將media.Image
物件和影像的旋轉傳遞給FirebaseVisionImage.fromMediaImage()
。如果您使用CameraX函式庫,則
OnImageCapturedListener
和ImageAnalysis.Analyzer
類別會為您計算旋轉值,因此您只需在呼叫FirebaseVisionImage.fromMediaImage()
之前將旋轉轉換為 ML Kit 的ROTATION_
常數之一:Java
private class YourAnalyzer implements ImageAnalysis.Analyzer { private int degreesToFirebaseRotation(int degrees) { switch (degrees) { case 0: return FirebaseVisionImageMetadata.ROTATION_0; case 90: return FirebaseVisionImageMetadata.ROTATION_90; case 180: return FirebaseVisionImageMetadata.ROTATION_180; case 270: return FirebaseVisionImageMetadata.ROTATION_270; default: throw new IllegalArgumentException( "Rotation must be 0, 90, 180, or 270."); } } @Override public void analyze(ImageProxy imageProxy, int degrees) { if (imageProxy == null || imageProxy.getImage() == null) { return; } Image mediaImage = imageProxy.getImage(); int rotation = degreesToFirebaseRotation(degrees); FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation); // Pass image to an ML Kit Vision API // ... } }
Kotlin+KTX
private class YourImageAnalyzer : ImageAnalysis.Analyzer { private fun degreesToFirebaseRotation(degrees: Int): Int = when(degrees) { 0 -> FirebaseVisionImageMetadata.ROTATION_0 90 -> FirebaseVisionImageMetadata.ROTATION_90 180 -> FirebaseVisionImageMetadata.ROTATION_180 270 -> FirebaseVisionImageMetadata.ROTATION_270 else -> throw Exception("Rotation must be 0, 90, 180, or 270.") } override fun analyze(imageProxy: ImageProxy?, degrees: Int) { val mediaImage = imageProxy?.image val imageRotation = degreesToFirebaseRotation(degrees) if (mediaImage != null) { val image = FirebaseVisionImage.fromMediaImage(mediaImage, imageRotation) // Pass image to an ML Kit Vision API // ... } } }
如果您不使用為您提供影像旋轉的相機庫,您可以根據裝置的旋轉和裝置中相機感測器的方向來計算它:
Java
private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } /** * 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, Context context) 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); // On most devices, the sensor orientation is 90 degrees, but for some // devices it is 270 degrees. For devices with a sensor orientation of // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees. CameraManager cameraManager = (CameraManager) context.getSystemService(CAMERA_SERVICE); int sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION); rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360; // Return the corresponding FirebaseVisionImageMetadata rotation value. int result; switch (rotationCompensation) { case 0: result = FirebaseVisionImageMetadata.ROTATION_0; break; case 90: result = FirebaseVisionImageMetadata.ROTATION_90; break; case 180: result = FirebaseVisionImageMetadata.ROTATION_180; break; case 270: result = FirebaseVisionImageMetadata.ROTATION_270; break; default: result = FirebaseVisionImageMetadata.ROTATION_0; Log.e(TAG, "Bad rotation value: " + rotationCompensation); } return result; }
Kotlin+KTX
private val ORIENTATIONS = SparseIntArray() init { ORIENTATIONS.append(Surface.ROTATION_0, 90) ORIENTATIONS.append(Surface.ROTATION_90, 0) ORIENTATIONS.append(Surface.ROTATION_180, 270) ORIENTATIONS.append(Surface.ROTATION_270, 180) } /** * 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, context: Context): 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) // On most devices, the sensor orientation is 90 degrees, but for some // devices it is 270 degrees. For devices with a sensor orientation of // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees. val cameraManager = context.getSystemService(CAMERA_SERVICE) as CameraManager val sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION)!! rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360 // Return the corresponding FirebaseVisionImageMetadata rotation value. val result: Int when (rotationCompensation) { 0 -> result = FirebaseVisionImageMetadata.ROTATION_0 90 -> result = FirebaseVisionImageMetadata.ROTATION_90 180 -> result = FirebaseVisionImageMetadata.ROTATION_180 270 -> result = FirebaseVisionImageMetadata.ROTATION_270 else -> { result = FirebaseVisionImageMetadata.ROTATION_0 Log.e(TAG, "Bad rotation value: $rotationCompensation") } } return result }
然後,將
media.Image
物件和旋轉值傳遞給FirebaseVisionImage.fromMediaImage()
:Java
FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation);
Kotlin+KTX
val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
- 若要從檔案 URI 建立
FirebaseVisionImage
對象,請將套用上下文和檔案 URI 傳遞給FirebaseVisionImage.fromFilePath()
。當您使用ACTION_GET_CONTENT
意圖提示使用者從其圖庫應用程式中選擇影像時,這非常有用。Java
FirebaseVisionImage image; try { image = FirebaseVisionImage.fromFilePath(context, uri); } catch (IOException e) { e.printStackTrace(); }
Kotlin+KTX
val image: FirebaseVisionImage try { image = FirebaseVisionImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
- 若要從
ByteBuffer
或位元組數組建立FirebaseVisionImage
對象,請先按照上面針對media.Image
輸入所述計算圖像旋轉。然後,建立一個
FirebaseVisionImageMetadata
對象,其中包含圖像的高度、寬度、顏色編碼格式和旋轉:Java
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder() .setWidth(480) // 480x360 is typically sufficient for .setHeight(360) // image recognition .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) .setRotation(rotation) .build();
Kotlin+KTX
val metadata = FirebaseVisionImageMetadata.Builder() .setWidth(480) // 480x360 is typically sufficient for .setHeight(360) // image recognition .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) .setRotation(rotation) .build()
使用緩衝區或陣列以及元資料物件來建立
FirebaseVisionImage
物件:Java
FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata); // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata);
Kotlin+KTX
val image = FirebaseVisionImage.fromByteBuffer(buffer, metadata) // Or: val image = FirebaseVisionImage.fromByteArray(byteArray, metadata)
- 要從
Bitmap
物件建立FirebaseVisionImage
物件:Java
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
Kotlin+KTX
val image = FirebaseVisionImage.fromBitmap(bitmap)
Bitmap
物件表示的影像必須是直立的,不需要額外旋轉。
取得
FirebaseVisionBarcodeDetector
的實例:Java
FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance() .getVisionBarcodeDetector(); // Or, to specify the formats to recognize: // FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance() // .getVisionBarcodeDetector(options);
Kotlin+KTX
val detector = FirebaseVision.getInstance() .visionBarcodeDetector // Or, to specify the formats to recognize: // val detector = FirebaseVision.getInstance() // .getVisionBarcodeDetector(options)
最後,將圖像傳遞給
detectInImage
方法:Java
Task<List<FirebaseVisionBarcode>> result = detector.detectInImage(image) .addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() { @Override public void onSuccess(List<FirebaseVisionBarcode> barcodes) { // Task completed successfully // ... } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Task failed with an exception // ... } });
Kotlin+KTX
val result = detector.detectInImage(image) .addOnSuccessListener { barcodes -> // Task completed successfully // ... } .addOnFailureListener { // Task failed with an exception // ... }
3. 從條碼中獲取訊息
如果條碼識別操作成功,FirebaseVisionBarcode
物件的清單將傳遞給成功偵聽器。每個FirebaseVisionBarcode
物件代表在影像中偵測到的條碼。對於每個條碼,您可以獲得其在輸入影像中的邊界座標,以及條碼編碼的原始資料。此外,如果條碼偵測器能夠確定條碼編碼的資料類型,您可以獲得包含解析資料的物件。例如:
Java
for (FirebaseVisionBarcode barcode: barcodes) { Rect bounds = barcode.getBoundingBox(); Point[] corners = barcode.getCornerPoints(); String rawValue = barcode.getRawValue(); int valueType = barcode.getValueType(); // See API reference for complete list of supported types switch (valueType) { case FirebaseVisionBarcode.TYPE_WIFI: String ssid = barcode.getWifi().getSsid(); String password = barcode.getWifi().getPassword(); int type = barcode.getWifi().getEncryptionType(); break; case FirebaseVisionBarcode.TYPE_URL: String title = barcode.getUrl().getTitle(); String url = barcode.getUrl().getUrl(); break; } }
Kotlin+KTX
for (barcode in barcodes) { val bounds = barcode.boundingBox val corners = barcode.cornerPoints val rawValue = barcode.rawValue val valueType = barcode.valueType // See API reference for complete list of supported types when (valueType) { FirebaseVisionBarcode.TYPE_WIFI -> { val ssid = barcode.wifi!!.ssid val password = barcode.wifi!!.password val type = barcode.wifi!!.encryptionType } FirebaseVisionBarcode.TYPE_URL -> { val title = barcode.url!!.title val url = barcode.url!!.url } } }
提升即時效能的技巧
如果您想在即時應用程式中掃描條碼,請遵循以下指南以獲得最佳幀速率:
不要以相機的原始解析度捕捉輸入。在某些裝置上,以原始解析度擷取輸入會產生非常大(10+ 百萬像素)的影像,這會導致非常低的延遲,並且對準確性沒有任何好處。相反,僅向相機請求條碼檢測所需的尺寸:通常不超過 200 萬像素。
如果掃描速度很重要,您可以進一步降低影像擷取解析度。但是,請記住上述最小條碼尺寸要求。
- 對檢測器的節流呼叫。如果偵測器運作時有新的視訊幀可用,則丟棄該幀。
- 如果您使用偵測器的輸出將圖形疊加在輸入影像上,請先從 ML Kit 取得結果,然後一步渲染影像並疊加。透過這樣做,每個輸入幀只需渲染到顯示表面一次。
如果您使用 Camera2 API,請以
ImageFormat.YUV_420_888
格式擷取影像。如果您使用較舊的相機 API,請以
ImageFormat.NV21
格式擷取影像。