Quét mã vạch bằng Bộ công cụ học máy trên Android

Bạn có thể dùng Bộ công cụ học máy để nhận dạng và giải mã mã vạch.

Tính năngKhông nhómGộp chung
Triển khaiMô hình được tải xuống một cách linh động thông qua Dịch vụ Google Play.Mô hình được liên kết tĩnh với ứng dụng của bạn tại thời điểm xây dựng.
Kích thước ứng dụngTăng kích thước khoảng 200 KB.Tăng kích thước khoảng 2,4 MB.
Thời gian khởi chạyCó thể phải đợi mô hình tải xuống trước khi sử dụng lần đầu.Mô hình có sẵn ngay lập tức.

Dùng thử

Trước khi bắt đầu

  1. Trong tệp build.gradle cấp dự án, hãy nhớ đưa kho lưu trữ Maven của Google vào cả hai mục buildscriptallprojects.

  2. Thêm các phần phụ thuộc của thư viện Android Bộ công cụ học máy vào tệp gradle cấp ứng dụng của mô-đun (thường là app/build.gradle). Chọn một trong các phần phụ thuộc sau đây tuỳ theo nhu cầu của bạn:

    Để nhóm mô hình với ứng dụng của bạn:

    dependencies {
      // ...
      // Use this dependency to bundle the model with your app
      implementation 'com.google.mlkit:barcode-scanning:17.2.0'
    }
    

    Cách sử dụng mô hình này trong Dịch vụ Google Play:

    dependencies {
      // ...
      // Use this dependency to use the dynamically downloaded model in Google Play Services
      implementation 'com.google.android.gms:play-services-mlkit-barcode-scanning:18.3.0'
    }
    
  3. Nếu chọn sử dụng mô hình này trong Dịch vụ Google Play, bạn có thể định cấu hình ứng dụng để tự động tải mô hình xuống thiết bị sau khi cài đặt ứng dụng qua Cửa hàng Play. Để làm như vậy, hãy thêm nội dung khai báo sau vào tệp AndroidManifest.xml của ứng dụng:

    <application ...>
          ...
          <meta-data
              android:name="com.google.mlkit.vision.DEPENDENCIES"
              android:value="barcode" >
          <!-- To use multiple models: android:value="barcode,model2,model3" -->
    </application>
    

    Bạn cũng có thể kiểm tra rõ ràng tình trạng cung cấp mô hình và yêu cầu tải xuống thông qua ModuleInstallClient API của Dịch vụ Google Play.

    Nếu bạn không cho phép tải mô hình tại thời điểm cài đặt xuống hoặc không yêu cầu tải xuống rõ ràng, thì mô hình sẽ được tải xuống trong lần đầu tiên bạn chạy trình quét. Các yêu cầu bạn đưa ra trước khi tải xuống hoàn tất sẽ không có kết quả.

Nguyên tắc nhập hình ảnh

  • Để Bộ công cụ học máy đọc được mã vạch chính xác, hình ảnh đầu vào phải chứa mã vạch được biểu thị bằng đủ dữ liệu pixel.

    Các yêu cầu cụ thể về dữ liệu pixel phụ thuộc vào cả loại mã vạch và lượng dữ liệu được mã hoá, vì nhiều mã vạch hỗ trợ tải trọng có kích thước thay đổi. Nhìn chung, đơn vị nhỏ nhất có nghĩa của mã vạch phải có chiều rộng tối thiểu là 2 pixel và đối với mã 2 chiều, chiều cao tối thiểu phải là 2 pixel.

    Ví dụ: mã vạch EAN-13 được tạo thành từ các thanh và dấu cách với chiều rộng là 1, 2, 3 hoặc 4 đơn vị. Vì vậy, hình ảnh mã vạch EAN-13 nên có các thanh và dấu cách rộng ít nhất 2, 4, 6 và 8 pixel. Vì mã vạch EAN-13 có tổng chiều rộng là 95 đơn vị, nên mã vạch phải có chiều rộng tối thiểu là 190 pixel.

    Các định dạng mật độ cao hơn (chẳng hạn như PDF417) cần kích thước pixel lớn hơn để Bộ công cụ học máy có thể đọc được các định dạng này một cách đáng tin cậy. Ví dụ: một mã PDF417 có thể có tối đa 34 "từ" rộng 17 đơn vị trong một hàng, lý tưởng nhất là rộng ít nhất là 1156 pixel.

  • Tiêu điểm ảnh kém có thể ảnh hưởng đến độ chính xác của quét. Nếu ứng dụng của bạn không nhận được kết quả chấp nhận được, hãy yêu cầu người dùng chụp lại hình ảnh.

  • Đối với các ứng dụng thông thường, bạn nên cung cấp hình ảnh có độ phân giải cao hơn, chẳng hạn như 1280x720 hoặc 1920x1080, giúp mã vạch có thể quét được từ một khoảng cách lớn hơn cách máy ảnh.

    Tuy nhiên, trong các ứng dụng có độ trễ rất quan trọng, bạn có thể cải thiện hiệu suất bằng cách chụp ảnh ở độ phân giải thấp hơn, nhưng yêu cầu mã vạch chiếm phần lớn hình ảnh đầu vào. Ngoài ra, hãy xem bài viết Mẹo cải thiện hiệu suất theo thời gian thực.

1. Định cấu hình trình quét mã vạch

Nếu biết định dạng mã vạch nào bạn muốn đọc, bạn có thể cải thiện tốc độ của trình phát hiện mã vạch bằng cách định cấu hình để chỉ phát hiện các định dạng đó.

Ví dụ: để chỉ phát hiện mã Aztec và mã QR, hãy tạo một đối tượng BarcodeScannerOptions như trong ví dụ sau:

Kotlin

val options = BarcodeScannerOptions.Builder()
        .setBarcodeFormats(
                Barcode.FORMAT_QR_CODE,
                Barcode.FORMAT_AZTEC)
        .build()

Java

BarcodeScannerOptions options =
        new BarcodeScannerOptions.Builder()
        .setBarcodeFormats(
                Barcode.FORMAT_QR_CODE,
                Barcode.FORMAT_AZTEC)
        .build();

Các định dạng sau được hỗ trợ:

  • Mã 128 (FORMAT_CODE_128)
  • Mã 39 (FORMAT_CODE_39)
  • Mã 93 (FORMAT_CODE_93)
  • Tiếng Codabar (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)
  • Mã QR (FORMAT_QR_CODE)
  • PDF417 (FORMAT_PDF417)
  • Tiếng Aztec (FORMAT_AZTEC)
  • Ma trận dữ liệu (FORMAT_DATA_MATRIX)

Kể từ mô hình đi kèm 17.1.0 và mô hình không theo gói 18.2.0, bạn cũng có thể gọi enableAllPotentialBarcodes() để trả về tất cả các mã vạch có thể có ngay cả khi không thể giải mã chúng. Bạn có thể dùng tính năng này để hỗ trợ việc phát hiện thêm, chẳng hạn như phóng to máy ảnh để thấy hình ảnh rõ ràng hơn về bất kỳ mã vạch nào trong hộp giới hạn được trả về.

Kotlin

val options = BarcodeScannerOptions.Builder()
        .setBarcodeFormats(...)
        .enableAllPotentialBarcodes() // Optional
        .build()

Java

BarcodeScannerOptions options =
        new BarcodeScannerOptions.Builder()
        .setBarcodeFormats(...)
        .enableAllPotentialBarcodes() // Optional
        .build();

Further on, starting from bundled library 17.2.0 and unbundled library 18.3.0, a new feature called auto-zoom has been introduced to further enhance the barcode scanning experience. With this feature enabled, the app is notified when all barcodes within the view are too distant for decoding. As a result, the app can effortlessly adjust the camera's zoom ratio to the recommended setting provided by the library, ensuring optimal focus and readability. This feature will significantly enhance the accuracy and success rate of barcode scanning, making it easier for apps to capture information precisely.

To enable auto-zooming and customize the experience, you can utilize the setZoomSuggestionOptions() method along with your own ZoomCallback handler and desired maximum zoom ratio, as demonstrated in the code below.

Kotlin

val options = BarcodeScannerOptions.Builder()
        .setBarcodeFormats(...)
        .setZoomSuggestionOptions(
            new ZoomSuggestionOptions.Builder(zoomCallback)
                .setMaxSupportedZoomRatio(maxSupportedZoomRatio)
                .build()) // Optional
        .build()

Java

BarcodeScannerOptions options =
        new BarcodeScannerOptions.Builder()
        .setBarcodeFormats(...)
        .setZoomSuggestionOptions(
            new ZoomSuggestionOptions.Builder(zoomCallback)
                .setMaxSupportedZoomRatio(maxSupportedZoomRatio)
                .build()) // Optional
        .build();

zoomCallback is required to be provided to handle whenever the library suggests a zoom should be performed and this callback will always be called on the main thread.

The following code snippet shows an example of defining a simple callback.

Kotlin

fun setZoom(ZoomRatio: Float): Boolean {
    if (camera.isClosed()) return false
    camera.getCameraControl().setZoomRatio(zoomRatio)
    return true
}

Java

boolean setZoom(float zoomRatio) {
    if (camera.isClosed()) {
        return false;
    }
    camera.getCameraControl().setZoomRatio(zoomRatio);
    return true;
}

maxSupportedZoomRatio is related to the camera hardware, and different camera libraries have different ways to fetch it (see the javadoc of the setter method). In case this is not provided, an unbounded zoom ratio might be produced by the library which might not be supported. Refer to the setMaxSupportedZoomRatio() method introduction to see how to get the max supported zoom ratio with different Camera libraries.

When auto-zooming is enabled and no barcodes are successfully decoded within the view, BarcodeScanner triggers your zoomCallback with the requested zoomRatio. If the callback correctly adjusts the camera to this zoomRatio, it is highly probable that the most centered potential barcode will be decoded and returned.

A barcode may remain undecodable even after a successful zoom-in. In such cases, BarcodeScanner may either invoke the callback for another round of zoom-in until the maxSupportedZoomRatio is reached, or provide an empty list (or a list containing potential barcodes that were not decoded, if enableAllPotentialBarcodes() was called) to the OnSuccessListener (which will be defined in step 4. Process the image).

2. Prepare the input image

To recognize barcodes in an image, create an InputImage object from either a Bitmap, media.Image, ByteBuffer, byte array, or a file on the device. Then, pass the InputImage object to the BarcodeScanner's process method.

You can create an InputImage object from different sources, each is explained below.

Using a media.Image

To create an InputImage object from a media.Image object, such as when you capture an image from a device's camera, pass the media.Image object and the image's rotation to InputImage.fromMediaImage().

If you use the CameraX library, the OnImageCapturedListener and ImageAnalysis.Analyzer classes calculate the rotation value for you.

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
          // ...
        }
    }
}

Nếu không sử dụng thư viện máy ảnh cho biết độ xoay của hình ảnh, bạn có thể tính độ xoay của hình ảnh dựa trên độ xoay của thiết bị và hướng của cảm biến máy ảnh trong thiết bị:

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;
}

Sau đó, hãy truyền đối tượng media.Image và giá trị độ xoay đến InputImage.fromMediaImage():

Kotlin

val image = InputImage.fromMediaImage(mediaImage, rotation)

Java

InputImage image = InputImage.fromMediaImage(mediaImage, rotation);

Sử dụng URI tệp

Để tạo đối tượng InputImage từ URI tệp, hãy chuyển ngữ cảnh ứng dụng và URI tệp đến InputImage.fromFilePath(). Điều này rất hữu ích khi bạn sử dụng ý định ACTION_GET_CONTENT để nhắc người dùng chọn một hình ảnh trong ứng dụng thư viện của họ.

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();
}

Sử dụng ByteBuffer hoặc ByteArray

Để tạo một đối tượng InputImage từ ByteBuffer hoặc ByteArray, trước tiên, hãy tính độ xoay hình ảnh như mô tả trước đó cho phương thức nhập media.Image. Sau đó, hãy tạo đối tượng InputImage bằng vùng đệm hoặc mảng, cùng với chiều cao, chiều rộng, định dạng mã hoá màu và độ xoay của hình ảnh:

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
);

Sử dụng Bitmap

Để tạo đối tượng InputImage qua đối tượng Bitmap, hãy khai báo sau:

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);

Hình ảnh được biểu thị bằng một đối tượng Bitmap cùng với độ xoay.

3. Tải một bản sao của BarcodeScanner

Kotlin

val scanner = BarcodeScanning.getClient()
// Or, to specify the formats to recognize:
// val scanner = BarcodeScanning.getClient(options)

Java

BarcodeScanner scanner = BarcodeScanning.getClient();
// Or, to specify the formats to recognize:
// BarcodeScanner scanner = BarcodeScanning.getClient(options);

4. Xử lý hình ảnh

Truyền hình ảnh vào phương thức process:

Kotlin

val result = scanner.process(image)
        .addOnSuccessListener { barcodes ->
            // Task completed successfully
            // ...
        }
        .addOnFailureListener {
            // Task failed with an exception
            // ...
        }

Java

Task<List<Barcode>> result = scanner.process(image)
        .addOnSuccessListener(new OnSuccessListener<List<Barcode>>() {
            @Override
            public void onSuccess(List<Barcode> barcodes) {
                // Task completed successfully
                // ...
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Task failed with an exception
                // ...
            }
        });

5. Lấy thông tin từ mã vạch

Nếu thao tác nhận dạng mã vạch thành công, danh sách các đối tượng Barcode sẽ được chuyển đến trình nghe thành công. Mỗi đối tượng Barcode đại diện cho một mã vạch đã được phát hiện trong hình ảnh. Đối với mỗi mã vạch, bạn có thể nhận được toạ độ giới hạn trong hình ảnh đầu vào cũng như dữ liệu thô được mã hoá bằng mã vạch. Ngoài ra, nếu trình quét mã vạch có thể xác định loại dữ liệu được mã hoá bằng mã vạch, thì bạn có thể nhận được một đối tượng chứa dữ liệu đã phân tích cú pháp.

Ví dụ:

Kotlin

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) {
        Barcode.TYPE_WIFI -> {
            val ssid = barcode.wifi!!.ssid
            val password = barcode.wifi!!.password
            val type = barcode.wifi!!.encryptionType
        }
        Barcode.TYPE_URL -> {
            val title = barcode.url!!.title
            val url = barcode.url!!.url
        }
    }
}

Java

for (Barcode 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 Barcode.TYPE_WIFI:
            String ssid = barcode.getWifi().getSsid();
            String password = barcode.getWifi().getPassword();
            int type = barcode.getWifi().getEncryptionType();
            break;
        case Barcode.TYPE_URL:
            String title = barcode.getUrl().getTitle();
            String url = barcode.getUrl().getUrl();
            break;
    }
}

Mẹo cải thiện hiệu suất theo thời gian thực

Nếu bạn muốn quét mã vạch trong một ứng dụng theo thời gian thực, hãy làm theo các nguyên tắc sau để đạt được tốc độ khung hình tốt nhất:

  • Đừng ghi lại dữ liệu đầu vào ở độ phân giải gốc của máy ảnh. Trên một số thiết bị, việc chụp ảnh đầu vào ở độ phân giải gốc sẽ tạo ra những hình ảnh cực lớn (10 megapixel trở lên), dẫn đến độ trễ rất thấp mà không mang lại lợi ích nào về độ chính xác. Thay vào đó, hãy chỉ yêu cầu kích thước từ máy ảnh (cần thiết cho tính năng phát hiện mã vạch) (thường không quá 2 megapixel).

    Nếu tốc độ quét là quan trọng, bạn có thể giảm độ phân giải chụp ảnh hơn nữa. Tuy nhiên, hãy lưu ý các yêu cầu tối thiểu về kích thước mã vạch nêu trên.

    Nếu bạn đang cố gắng nhận dạng mã vạch trong một chuỗi các khung hình video phát trực tuyến, thì trình nhận dạng có thể đưa ra các kết quả khác nhau giữa các khung hình. Bạn nên đợi cho đến khi nhận được một chuỗi liên tiếp có cùng giá trị để chắc chắn rằng mình đang trả về kết quả tốt.

    Chữ số tổng kiểm không được hỗ trợ cho ITF và CODE-39.

  • Nếu bạn sử dụng API Camera hoặc camera2, hãy điều tiết các lệnh gọi đến trình phát hiện. Nếu có khung hình video mới trong khi trình phát hiện đang chạy, hãy bỏ khung hình đó. Hãy xem lớp VisionProcessorBase trong ứng dụng mẫu khởi động nhanh để biết ví dụ.
  • Nếu bạn sử dụng API CameraX, hãy đảm bảo rằng chiến lược áp lực ngược được đặt về giá trị mặc định ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST. Việc này giúp đảm bảo mỗi lần hệ thống chỉ gửi một hình ảnh để phân tích. Nếu trình phân tích bận, nếu có nhiều hình ảnh khác được tạo, thì các hình ảnh đó sẽ tự động bị loại bỏ và không được đưa vào hàng đợi phân phối. Sau khi hình ảnh đang được phân tích được đóng bằng cách gọi ImageProxy.close(), hình ảnh mới nhất tiếp theo sẽ được phân phối.
  • Nếu bạn sử dụng đầu ra của trình phát hiện để phủ đồ hoạ lên hình ảnh đầu vào, trước tiên, hãy lấy kết quả từ Bộ công cụ học máy, sau đó kết xuất hình ảnh và lớp phủ trong một bước duy nhất. Thao tác này chỉ hiển thị trên bề mặt màn hình một lần cho mỗi khung đầu vào. Hãy xem các lớp CameraSourcePreview GraphicOverlay trong ứng dụng mẫu khởi động nhanh để tham khảo ví dụ.
  • Nếu bạn sử dụng API Camera2, hãy chụp ảnh ở định dạng ImageFormat.YUV_420_888. Nếu bạn sử dụng API Máy ảnh cũ, hãy chụp ảnh ở định dạng ImageFormat.NV21.