סריקת ברקודים באמצעות ML Kit ב-Android

אתם יכולים להשתמש ב-ML Kit כדי לזהות ולפענח ברקודים.

תכונהלא מקובציםבחבילה
הטמעההמודל יורד באופן דינמי דרך Google Play Services.המודל מקושר באופן סטטי לאפליקציה בזמן ה-build.
גודל האפליקציההגודל גדל בכ-200KB.הגודל גדל בכ-2.4MB.
זמן האתחוליכול להיות שתצטרכו לחכות עד שהמודל יסיים לרדת לפני השימוש הראשון.המודל זמין באופן מיידי.

רוצה לנסות?

לפני שמתחילים

  1. בקובץ build.gradle ברמת הפרויקט, צריך לכלול את מאגר ה-Maven של Google בקטעים buildscript ו-allprojects.

  2. מוסיפים את התלויות של ספריות Android של ML Kit לקובץ Gradle ברמת האפליקציה של המודול, שבדרך כלל נמצא ב-app/build.gradle. בוחרים באחד מהיחסי התלות הבאים, בהתאם לצרכים שלכם:

    כדי לכלול את המודל באפליקציה:

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

    כדי להשתמש במודל ב-Google Play Services:

    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.1'
    }
    
  3. אם אתם בוחרים להשתמש במודל ב-Google Play Services, אתם יכולים להגדיר את האפליקציה כך שהמודל יורד אוטומטית למכשיר אחרי שהאפליקציה מותקנת מחנות Play. כדי לעשות את זה, מוסיפים את ההצהרה הבאה לקובץ AndroidManifest.xml של האפליקציה:

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

    אתם יכולים גם לבדוק באופן מפורש את זמינות המודל ולבקש להוריד אותו דרך ModuleInstallClient API של Google Play Services.

    אם לא תפעילו את הורדת המודלים בזמן ההתקנה או תבקשו הורדה מפורשת, המודל יורד בפעם הראשונה שתפעילו את הסורק. בקשות שתשלחו לפני שההורדה תסתיים לא יניבו תוצאות.

הנחיות לגבי תמונת הקלט

  • כדי ש-ML Kit יקרא ברקודים בצורה מדויקת, תמונות הקלט צריכות להכיל ברקודים שמיוצגים על ידי מספיק נתוני פיקסלים.

    הדרישות הספציפיות לגבי נתוני הפיקסלים תלויות בסוג הברקוד ובכמות הנתונים שמקודדים בו, כי הרבה ברקודים תומכים במטען ייעודי (payload) בגודל משתנה. באופן כללי, היחידה הקטנה ביותר בעלת המשמעות בברקוד צריכה להיות ברוחב של לפחות 2 פיקסלים, ובקודים דו-ממדיים, בגובה של 2 פיקסלים.

    לדוגמה, ברקודים מסוג EAN-13 מורכבים מקווים ומרווחים ברוחב של יחידה אחת, 2, 3 או 4 יחידות, ולכן בתמונה של ברקוד מסוג EAN-13 רצוי שיהיו קווים ומרווחים ברוחב של לפחות 2, 4, 6 ו-8 פיקסלים. מכיוון שברקוד EAN-13 הוא ברוחב של 95 יחידות בסך הכול, הברקוד צריך להיות ברוחב של 190 פיקסלים לפחות.

    פורמטים צפופים יותר, כמו PDF417, דורשים ממדי פיקסלים גדולים יותר כדי ש-ML Kit יוכל לקרוא אותם בצורה מהימנה. לדוגמה, קוד PDF417 יכול להכיל עד 34 "מילים" ברוחב 17 יחידות בשורה אחת, שבאופן אידיאלי יהיו ברוחב של לפחות 1,156 פיקסלים.

  • אם התמונה לא ממוקדת, יכול להיות שהסריקה לא תהיה מדויקת. אם האפליקציה לא מקבלת תוצאות קבילות, צריך לבקש מהמשתמש לצלם מחדש את התמונה.

  • באפליקציות רגילות, מומלץ לספק תמונה ברזולוציה גבוהה יותר, כמו 1280x720 או 1920x1080, שמאפשרת לסרוק ברקודים ממרחק גדול יותר מהמצלמה.

    עם זאת, באפליקציות שבהן זמן האחזור הוא קריטי, אפשר לשפר את הביצועים על ידי צילום תמונות ברזולוציה נמוכה יותר, אבל לדרוש שהברקוד יהיה רוב התמונה. כדאי גם לקרוא את הטיפים לשיפור הביצועים בזמן אמת.

1. הגדרת סורק הברקודים

אם אתם יודעים אילו פורמטים של ברקודים אתם צפויים לקרוא, אתם יכולים לשפר את המהירות של גלאי הברקודים על ידי הגדרה שלו לזיהוי הפורמטים האלה בלבד.

לדוגמה, כדי לזהות רק קוד Aztec וקודי QR, יוצרים אובייקט BarcodeScannerOptions כמו בדוגמה הבאה:

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

אפשר להשתמש בפורמטים הבאים:

  • Code 128 (FORMAT_CODE_128)
  • Code 39 (FORMAT_CODE_39)
  • קוד 93 (FORMAT_CODE_93)
  • 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)
  • קוד QR‏ (FORMAT_QR_CODE)
  • ‫PDF417‏ (FORMAT_PDF417)
  • אצטקית (FORMAT_AZTEC)
  • Data Matrix (FORMAT_DATA_MATRIX)

החל מגרסה 17.1.0 של המודל המצורף ומגרסה 18.2.0 של המודל הלא מצורף, אפשר גם להפעיל את enableAllPotentialBarcodes() כדי להחזיר את כל הברקודים הפוטנציאליים, גם אם לא ניתן לפענח אותם. אפשר להשתמש בזה כדי לשפר את הזיהוי, למשל על ידי הגדלת התצוגה במצלמה כדי לקבל תמונה ברורה יותר של כל ברקוד בתיבה התוחמת שמוחזרת.

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

אם אתם לא משתמשים בספריית מצלמה שמספקת את זווית הסיבוב של התמונה, אתם יכולים לחשב אותה לפי זווית הסיבוב של המכשיר והכיוון של חיישן המצלמה במכשיר:

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 של קובץ

כדי ליצור אובייקט InputImage מ-URI של קובץ, מעבירים את הקשר האפליקציה ואת ה-URI של הקובץ אל InputImage.fromFilePath(). זה שימושי כשמשתמשים ב-Intent מסוג 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

כדי ליצור אובייקט InputImage מ-ByteBuffer או מ-ByteArray, קודם מחשבים את זווית הסיבוב של התמונה כמו שמתואר למעלה לגבי קלט 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

כדי ליצור אובייקט InputImage מאובייקט Bitmap, צריך להצהיר על הדברים הבאים:

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

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

התמונה מיוצגת על ידי אובייקט Bitmap יחד עם מעלות הסיבוב.

3. מקבלים מופע של 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. מעבדים את התמונה

מעבירים את התמונה ל-method‏ 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. קבלת מידע מברקודים

אם פעולת הזיהוי של הברקוד מצליחה, רשימה של אובייקטים מסוג Barcode מועברת למאזין להצלחה. כל אובייקט Barcode מייצג ברקוד שזוהה בתמונה. לכל ברקוד, אתם יכולים לקבל את הקואורדינטות של התיבה התוחמת בתמונת הקלט, וגם את הנתונים הגולמיים שמקודדים בברקוד. בנוסף, אם סורק הברקודים הצליח לקבוע את סוג הנתונים שמקודדים בברקוד, אתם יכולים לקבל אובייקט שמכיל נתונים מנותחים.

לדוגמה:

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

טיפים לשיפור הביצועים בזמן אמת

אם אתם רוצים לסרוק ברקודים באפליקציה בזמן אמת, כדאי לפעול לפי ההנחיות הבאות כדי להשיג את קצב הפריימים הטוב ביותר:

  • לא לצלם קלט ברזולוציה המקורית של המצלמה. בחלק מהמכשירים, צילום קלט ברזולוציה המקורית יוצר תמונות גדולות מאוד (יותר מ-10 מגה-פיקסל), וכתוצאה מכך זמן האחזור ארוך מאוד בלי שום יתרון מבחינת הדיוק. במקום זאת, בקשו מהמצלמה רק את הגודל שנדרש לזיהוי ברקוד, שבדרך כלל לא עולה על 2 מגה-פיקסל.

    אם מהירות הסריקה חשובה, אפשר להוריד עוד יותר את הרזולוציה של צילום התמונות. עם זאת, חשוב לזכור את דרישות הגודל המינימלי של הברקוד שמתוארות למעלה.

    אם אתם מנסים לזהות ברקודים מרצף של פריימים של וידאו בסטרימינג, יכול להיות שהמזהה יפיק תוצאות שונות מפריים לפריים. כדאי להמתין עד שתקבלו סדרה רציפה של אותו ערך כדי להיות בטוחים שאתם מחזירים תוצאה טובה.

    ספרת סיכום הביקורת (checksum) לא נתמכת ב-ITF וב-CODE-39.

  • אם אתם משתמשים ב-API של Camera או של camera2, כדאי להגביל את הקריאות לגלאי. אם פריים חדש של סרטון הופך לזמין בזמן שהגלאי פועל, צריך להשמיט את הפריים. אפשר לראות דוגמה לכך במחלקה VisionProcessorBase באפליקציה לדוגמה למתחילים.
  • אם אתם משתמשים ב-API של CameraX, ודאו שאסטרטגיית הלחץ הנגדי מוגדרת לערך ברירת המחדל שלה ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST. כך אפשר להבטיח שרק תמונה אחת תישלח לניתוח בכל פעם. אם נוצרות תמונות נוספות בזמן שהמנתח עסוק, הן יוסרו באופן אוטומטי ולא יועברו לתור. אחרי שהתמונה שמנותחת נסגרת באמצעות קריאה ל-ImageProxy.close()‎, התמונה הבאה תועבר.
  • אם אתם משתמשים בפלט של הגלאי כדי להוסיף שכבת-על של גרפיקה לתמונת הקלט, קודם צריך לקבל את התוצאה מ-ML Kit, ואז לעבד את התמונה ולהוסיף את שכבת-העל בשלב אחד. העיבוד הזה מתבצע במשטח התצוגה רק פעם אחת לכל פריים של קלט. אפשר לראות דוגמה במחלקות CameraSourcePreview ו- GraphicOverlay באפליקציה לדוגמה למתחילים.
  • אם משתמשים ב-Camera2 API, צריך לצלם תמונות בפורמט ImageFormat.YUV_420_888. אם משתמשים ב-Camera API הישן, צריך לצלם תמונות בפורמט ImageFormat.NV21.