Android'de ML Kit ile Barkod Tarama

Barkodları tanımak ve kodunu çözmek için ML Kit'i kullanabilirsiniz.

Başlamadan önce

  1. Henüz yapmadıysanız Firebase'i Android projenize ekleyin.
  2. Modülünüze ML Kit Android kitaplıkları için bağımlılıkları ekleyin (uygulama düzeyinde) Gradle dosyası (genellikle 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'
    }
    

Giriş resmi kuralları

  • ML Kit'in barkodları doğru okuyabilmesi için giriş resimlerinde yeterli piksel verisiyle temsil edilen barkodlar.

    Belirli piksel verisi gereksinimleri hem ve kodlanan veri miktarıdır (çünkü çoğu barkod farklı uzunluklarda yükü desteklemeleri gerekir). Genellikle anlamlı olan en küçük barkodun birimi en az 2 piksel genişliğinde (ve 2 boyutlu kodlar, 2 piksel yüksekliğinde).

    Örneğin, EAN-13 barkodları çubuklar ile boşluklardan oluşur. Bu boşlukların sayısı 1, 2, 3 veya 4 birim genişliğinde olduğundan EAN-13 barkod görüntüsünde ideal olarak çubuklar ve en az 2, 4, 6 ve 8 piksel genişliğinde boşluklar. Çünkü EAN-13 barkod toplam 95 birim genişliğinde, barkod en az 190 olmalıdır piksel genişliğinde.

    PDF417 gibi daha yoğun biçimler için güvenli okumasını sağlayın. Örneğin, bir PDF417 kodunda en fazla 34 17 birim genişliğinde "kelimeler" bir satır olacak şekilde ekleyebilirsiniz. Bu, tercihen 1156 piksel genişliğinde.

  • Zayıf resim odağı, tarama doğruluğunu olumsuz etkileyebilir. Bu kabul edilebilir sonuçlar almak için kullanıcıdan resmi yeniden çekmesini istemeyi deneyin.

  • Tipik uygulamalarda, daha yüksek bir Barkod üreten çözünürlüklü resim (1280x720 veya 1920x1080 gibi) kameradan daha uzak bir mesafeden algılanabilir.

    Ancak gecikmenin kritik olduğu uygulamalarda daha iyi daha düşük çözünürlükte çekerek daha iyi performans giriş resminin büyük kısmını barkod oluşturur. Şunlara da bakabilirsiniz: Gerçek zamanlı performansı iyileştirmeye yönelik ipuçları.

1. Barkod dedektörünü yapılandırma

Hangi barkod biçimlerini okumayı beklediğinizi bilirseniz hızı artırabilirsiniz otomatik olarak devre dışı bırakabilirsiniz.

Örneğin, yalnızca Aztek kodunu ve QR kodlarını algılamak için bir FirebaseVisionBarcodeDetectorOptions nesnesini tanımlayın:

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

Aşağıdaki biçimler desteklenir:

  • Kod 128 (FORMAT_CODE_128)
  • Kod 39 (FORMAT_CODE_39)
  • Kod 93 (FORMAT_CODE_93)
  • Kodabar (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 Kodu (FORMAT_QR_CODE)
  • PDF417 (FORMAT_PDF417)
  • Aztek (FORMAT_AZTEC)
  • Veri Matrisi (FORMAT_DATA_MATRIX)

2. Barkod dedektörünü çalıştırın

Resimlerdeki barkodları tanımak için bir FirebaseVisionImage nesnesi oluşturun bir Bitmap, media.Image, ByteBuffer, bayt dizisi veya için geçerlidir. Ardından, FirebaseVisionImage nesnesini FirebaseVisionBarcodeDetector ürününün detectInImage yöntemi.

  1. Resminizden bir FirebaseVisionImage nesnesi oluşturun.

    • Bir FirebaseVisionImage nesnesi oluşturmak için media.Image nesnesi, örneğin bir media.Image nesnesini ve görüntünün FirebaseVisionImage.fromMediaImage() değerine döndürülüyor.

      URL'yi CameraX kitaplığı, OnImageCapturedListener ve ImageAnalysis.Analyzer sınıfları rotasyon değerini hesaplar gerekir, bu nedenle rotasyonu ML Kit'lerinden birine veya Çağrıdan önce ROTATION_ sabit değer FirebaseVisionImage.fromMediaImage():

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

      Resmin döndürmesini sağlayan bir kamera kitaplığı kullanmıyorsanız cihazın dönüşüne ve kameranın yönüne göre hesaplanabilir cihazdaki sensör:

      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
      }

      Ardından, media.Image nesnesini ve rotasyon değerini FirebaseVisionImage.fromMediaImage() değerine ayarlayın:

      Java

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

      Kotlin+KTX

      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
    • Dosya URI'sinden bir FirebaseVisionImage nesnesi oluşturmak için uygulama bağlamını ve dosya URI'sini FirebaseVisionImage.fromFilePath(). Bu özellik, kullanıcıdan seçim yapmasını istemek için bir ACTION_GET_CONTENT niyeti kullanın galeri uygulamasından bir resim.

      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()
      }
    • Bir FirebaseVisionImage nesnesi oluşturmak için ByteBuffer veya bir bayt dizisi, önce görüntüyü hesaplayın media.Image girişi için yukarıda açıklandığı gibi döndürülmesini sağlayın.

      Ardından, bir FirebaseVisionImageMetadata nesnesi oluşturun yüksekliğini, genişliğini, renk kodlaması biçimini ve ve rotasyon:

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

      Aşağıdakini oluşturmak için arabelleği veya diziyi ve meta veri nesnesini kullanın: FirebaseVisionImage nesne:

      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)
    • Bir FirebaseVisionImage nesnesi oluşturmak için Bitmap nesne:

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      Kotlin+KTX

      val image = FirebaseVisionImage.fromBitmap(bitmap)
      Bitmap nesnesi tarafından temsil edilen resim, dik olmalıdır, ek döndürme gerekmez.

  2. FirebaseVisionBarcodeDetector öğesinin bir örneğini alın:

    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)
  3. Son olarak, resmi detectInImage yöntemine iletin:

    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. Barkodlardan bilgi al

Barkod tanıma işlemi başarılı olursa, şunları içeren bir liste: FirebaseVisionBarcode nesne başarılı işleyiciye aktarılacak. Her biri FirebaseVisionBarcode nesnesi, görüntüsüdür. Her barkodun sınırlayıcı koordinatlarını barkodla kodlanan ham verilerin yer aldığı bir ekran görüntüsüdür. Barkod algılayıcı barkodla kodlanan veri türünü belirleyebildiğinden ayrıştırılmış veri içeren bir nesne alır.

Örneğin:

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

Gerçek zamanlı performansı iyileştirmeye yönelik ipuçları

Barkodları gerçek zamanlı bir uygulamada taramak istiyorsanız aşağıdaki talimatları uygulayın:

  • Girişleri kameranın orijinal çözünürlüğünde yakalamayın. Bazı cihazlarda yerel çözünürlükte giriş yakalamak çok büyük (10+ megapiksel) resimler, hiçbir yararı olmadan çok düşük gecikme emin olun. Bunun yerine, kameradan yalnızca gerekli boyutu isteyin izin verilen ses seviyesidir: Genellikle 2 megapikselden fazla değildir.

    Tarama hızı önemliyse yakalanan görüntüyü daha da düşürebilirsiniz belirler. Ancak barkodla ilgili minimum boyut gereksinimlerini de göz önünde bulundurun. kontrol edin.

  • Algılayıcıya yapılan çağrıları hızlandırın. Yeni bir video karesi kullanılabilir durumdaysa çerçeveyi bırakın.
  • Algılayıcının çıkışını üzerine grafik yerleştirmek için kullanıyorsanız giriş görüntüsünü kullanın, önce ML Kit'ten sonucu alın ve ardından görüntüyü oluşturun tek bir adımda yapabilirsiniz. Bu şekilde, oluşturduğunuz öğeleri ekran yüzeyinde her giriş karesi için yalnızca bir kez.
  • Camera2 API'sini kullanıyorsanız görüntüleri şurada yakalayın: ImageFormat.YUV_420_888 biçimindedir.

    Eski Kamera API'sini kullanıyorsanız görüntüleri şurada yakalayın: ImageFormat.NV21 biçimindedir.