اسکن کردن بارکدها با ML Kit در Android

می‌توانید از ML Kit برای تشخیص و رمزگشایی رمزینه‌ها استفاده کنید.

ویژگیتفکیک‌شدهموجود در بسته‌بندی
پیاده‌سازیمدل به‌صورت پویا ازطریق «خدمات Google Play» بارگیری می‌شود.مدل در زمان ساخت به‌صورت ایستا به برنامه شما پیوند داده می‌شود.
حجم برنامهحدود ۲۰۰ کیلوبایت افزایش اندازه.حدود ۲٫۴ مگابایت افزایش اندازه.
زمان مقداردهی اولیهممکن است لازم باشد قبل‌از اولین استفاده، منتظر بمانید تا مدل بارگیری شود.مدل بلافاصله دردسترس است.

امتحان کنید

قبل‌از شروع

  1. در فایل build.gradle سطح پروژه، حتماً مخزن Maven مربوط به Google را در هر دو بخش buildscript و allprojects اضافه کنید.

  2. وابستگی‌های کتابخانه‌های ML Kit Android را به فایل 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»:

    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» استفاده کنید، می‌توانید برنامه‌تان را پیکربندی کنید تا پس‌از نصب برنامه از «فروشگاه 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 درخواست بارگیری کنید.

    اگر بارگیری مدل در زمان نصب را فعال نکنید یا درخواست بارگیری صریح نکنید، مدل اولین باری که اسکنر را اجرا می‌کنید بارگیری می‌شود. درخواست‌هایی که قبل‌از تکمیل بارگیری ارسال می‌کنید نتیجه‌ای دربر نخواهد داشت.

دستورالعمل‌های تصویر ورودی

  • برای اینکه ML Kit بارکدها را به‌دقت بخواند، تصاویر ورودی باید حاوی بارکدهایی باشند که با داده‌های پیکسل کافی نشان داده شده‌اند.

    الزامات خاص داده‌های پیکسل هم به نوع بارکد و هم به مقدار داده‌هایی که در آن کدگذاری شده است بستگی دارد، زیرا بسیاری از بارکدها از اندازه متغیر بار مفید پشتیبانی می‌کنند. به‌طورکلی، کوچک‌ترین واحد معنادار بارکد باید حداقل ۲ پیکسل عرض داشته باشد، و برای کدهای ۲ بعدی، ۲ پیکسل ارتفاع داشته باشد.

    برای مثال، بارکدهای EAN-13 از خطوط و فاصله‌هایی تشکیل شده‌اند که ۱، ۲، ۳، یا ۴ واحد پهنا دارند، بنابراین تصویر بارکد EAN-13 به‌طور ایده‌آل دارای خطوط و فاصله‌هایی است که حداقل ۲، ۴، ۶، و ۸ پیکسل پهنا دارند. چون رمزینه EAN-13 درمجموع ۹۵ واحد پهنا دارد، رمزینه باید حداقل ۱۹۰ پیکسل پهنا داشته باشد.

    قالب‌های متراکم‌تر، مانند PDF417، برای اینکه ML Kit بتواند آن‌ها را به‌طور قابل‌اعتمادی بخواند، به ابعاد پیکسلی بزرگ‌تری نیاز دارند. برای مثال، کد PDF417 می‌تواند تا ۳۴ «کلمه» ۱۷ واحدی در یک ردیف داشته باشد که در حالت ایده‌آل باید حداقل ۱۱۵۶ پیکسل عرض داشته باشد.

  • فوکوس ضعیف تصویر می‌تواند بر دقت اسکن تأثیر بگذارد. اگر برنامه‌تان نتایج قابل‌قبولی دریافت نمی‌کند، از کاربر بخواهید تصویر را دوباره ضبط کند.

  • برای برنامه‌های کاربردی معمولی، توصیه می‌شود تصویر با وضوح بالاتری مثل ۱۲۸۰x۷۲۰ یا ۱۹۲۰x۱۰۸۰ ارائه دهید که باعث می‌شود بارکدها از فاصله دورتری از دوربین قابل اسکن باشند.

    بااین‌حال، در برنامه‌هایی که تأخیر در آن‌ها حیاتی است، می‌توانید با گرفتن تصاویر با وضوح پایین‌تر، عملکرد را بهبود ببخشید، اما لازم است که رمزینه بخش عمده‌ای از تصویر ورودی را تشکیل دهد. همچنین نکاتی برای بهبود عملکرد هم‌زمان را ببینید.

۱. پیکربندی اسکنر بارکد

اگر می‌دانید که انتظار دارید کدام قالب‌های بارکد خوانده شود، می‌توانید با پیکربندی کردن آشکارساز بارکد برای تشخیص فقط آن قالب‌ها، سرعت آن را بهبود دهید.

برای مثال، برای شناسایی فقط کد Aztec و رمزینه‌های پاسخ‌سریع، BarcodeScannerOptions شیئی را مانند مثال زیر بسازید:

Kotlin

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

جاوا

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

قالب‌های زیر پشتیبانی می‌شوند:

  • کد ۱۲۸ (FORMAT_CODE_128)
  • کد ۳۹ (FORMAT_CODE_39)
  • کد ۹۳ (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)

از مدل دسته‌ای ۱۷.۱.۰ و مدل غیردسته‌ای ۱۸.۲.۰، می‌توانید 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
            // ...
        }
    }
}

جاوا

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
}

جاوا

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

استفاده از نشانی وب فایل

برای ایجاد شیء InputImage از نشانی وب فایل، بافت برنامه و نشانی وب فایل را به 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

برای ایجاد 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
)

جاوا

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 به‌همراه درجه‌های چرخش نشان داده می‌شود.

۳. دریافت نمونه‌ای از BarcodeScanner

Kotlin

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

جاوا

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

۴. پردازش تصویر

تصویر را به روش process ارسال کنید:

Kotlin

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

جاوا

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

۵. دریافت اطلاعات از رمزینه‌ها

اگر عملیات تشخیص بارکد موفقیت‌آمیز باشد، فهرستی از 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
        }
    }
}

جاوا

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

نکته‌هایی برای بهبود عملکرد هم‌زمان

اگر می‌خواهید بارکدها را در یک برنامه درلحظه اسکن کنید، این دستورالعمل‌ها را دنبال کنید تا به بهترین نرخ‌های فریم دست یابید:

  • ورودی را با وضوح اصلی دوربین ضبط نکنید. در برخی دستگاه‌ها، ضبط ورودی در وضوح اصلی تصاویر بسیار بزرگی (بیش‌از ۱۰ مگاپیکسل) تولید می‌کند که منجر به تأخیر بسیار زیاد می‌شود و هیچ مزیتی برای دقت ندارد. درعوض، فقط اندازه موردنیاز برای تشخیص بارکد را از دوربین درخواست کنید، که معمولاً بیشتر از ۲ مگاپیکسل نیست.

    اگر سرعت اسکن مهم است، می‌توانید وضوح ضبط تصویر را بیشتر کاهش دهید. بااین‌حال، حداقل الزامات اندازه بارکد را که در بالا ذکر شده است درنظر داشته باشید.

    اگر می‌خواهید بارکدها را از توالی قاب‌های ویدیو جاری‌سازی تشخیص دهید، ممکن است تشخیص‌دهنده نتایج متفاوتی از قاب به قاب تولید کند. باید صبر کنید تا مجموعه‌ای پیوسته از مقدار یکسان دریافت کنید تا مطمئن شوید نتیجه خوبی برمی‌گردانید.

    رقم «کنترل مجموع» برای ITF و CODE-39 پشتیبانی نمی‌شود.

  • اگر از 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 ضبط کنید.