Android'de ML Kiti ile Barkodları Tarayın

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

Sen başlamadan önce

  1. Henüz yapmadıysanız Android projenize Firebase'i ekleyin .
  2. ML Kit Android kitaplıklarının bağımlılıklarını modülünüze (uygulama düzeyi) Gradle dosyasına ekleyin (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ş görseli yönergeleri

  • ML Kit'in barkodları doğru şekilde okuyabilmesi için giriş görüntülerinin yeterli piksel verileriyle temsil edilen barkodlar içermesi gerekir.

    Belirli piksel veri gereksinimleri hem barkodun türüne hem de içinde kodlanan veri miktarına bağlıdır (çünkü çoğu barkod değişken uzunluklu bir veri yükünü destekler). Genel olarak barkodun en küçük anlamlı birimi en az 2 piksel genişliğinde (ve 2 boyutlu kodlar için 2 piksel yüksekliğinde) olmalıdır.

    Örneğin, EAN-13 barkodları 1, 2, 3 veya 4 birim genişliğinde çubuklardan ve boşluklardan oluşur; dolayısıyla bir EAN-13 barkod görüntüsünde ideal olarak en az 2, 4, 6 ve 4 birim genişliğinde çubuklar ve boşluklar bulunur. 8 piksel genişliğinde. EAN-13 barkodu toplamda 95 birim genişliğinde olduğundan barkodun en az 190 piksel genişliğinde olması gerekir.

    PDF417 gibi daha yoğun formatların, ML Kit'in bunları güvenilir bir şekilde okuyabilmesi için daha büyük piksel boyutlarına ihtiyacı vardır. Örneğin, bir PDF417 kodu tek bir satırda en fazla 34 adet 17 birim genişliğinde "kelime" içerebilir; bu ideal olarak en az 1156 piksel genişliğinde olacaktır.

  • Zayıf görüntü odağı tarama doğruluğuna zarar verebilir. Kabul edilebilir sonuçlar alamıyorsanız kullanıcıdan görüntüyü yeniden yakalamasını istemeyi deneyin.

  • Tipik uygulamalar için, barkodların kameradan daha uzak bir mesafeden algılanabilmesini sağlayan daha yüksek çözünürlüklü bir görüntünün (1280x720 veya 1920x1080 gibi) sağlanması önerilir.

    Ancak gecikmenin kritik olduğu uygulamalarda, görüntüleri daha düşük çözünürlükte yakalayarak ancak barkodun giriş görüntüsünün çoğunluğunu oluşturmasını zorunlu kılarak performansı artırabilirsiniz. Ayrıca bkz . Gerçek zamanlı performansı artırmaya yönelik ipuçları .

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

Hangi barkod formatlarını okumayı beklediğinizi biliyorsanız, barkod dedektörünü yalnızca bu formatları algılayacak şekilde yapılandırarak hızını artırabilirsiniz.

Örneğin, yalnızca Aztek kodunu ve QR kodlarını algılamak için aşağıdaki örnekte olduğu gibi bir FirebaseVisionBarcodeDetectorOptions nesnesi oluşturun:

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 formatlar desteklenmektedir:

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

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

Bir görüntüdeki barkodları tanımak için Bitmap , media.Image , ByteBuffer , byte dizisinden veya cihazdaki bir dosyadan FirebaseVisionImage nesnesi oluşturun. Ardından FirebaseVisionImage nesnesini FirebaseVisionBarcodeDetector detectInImage yöntemine iletin.

  1. Görüntünüzden bir FirebaseVisionImage nesnesi oluşturun.

    • Bir media.Image nesnesinden bir FirebaseVisionImage nesnesi oluşturmak için (örneğin, bir cihazın kamerasından bir görüntü yakalarken), media.Image nesnesini ve görüntünün dönüşünü FirebaseVisionImage.fromMediaImage() öğesine iletin.

      CameraX kitaplığını kullanıyorsanız OnImageCapturedListener ve ImageAnalysis.Analyzer sınıfları sizin için dönüş değerini hesaplar; dolayısıyla FirebaseVisionImage.fromMediaImage() çağırmadan önce dönüşü ML Kit'in ROTATION_ sabitlerinden birine dönüştürmeniz yeterlidir:

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

      Görüntünün dönüşünü sağlayan bir kamera kitaplığı kullanmıyorsanız, bunu cihazın dönüşünden ve cihazdaki kamera sensörünün yönünden hesaplayabilirsiniz:

      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 döndürme değerini FirebaseVisionImage.fromMediaImage() öğesine iletin:

      Java

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

      Kotlin+KTX

      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
    • Bir dosya URI'sından FirebaseVisionImage nesnesi oluşturmak için uygulama içeriğini ve dosya URI'sini FirebaseVisionImage.fromFilePath() öğesine iletin. Kullanıcıdan galeri uygulamasından bir resim seçmesini istemek için ACTION_GET_CONTENT amacını kullandığınızda bu kullanışlıdır.

      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 veya bayt dizisinden bir FirebaseVisionImage nesnesi oluşturmak için, öncelikle media.Image girişi için yukarıda açıklandığı gibi görüntü döndürmeyi hesaplayın.

      Ardından görüntünün yüksekliğini, genişliğini, renk kodlama biçimini ve dönüşünü içeren bir FirebaseVisionImageMetadata nesnesi oluşturun:

      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 nesnesi oluşturmak için tamponu veya diziyi ve meta veri nesnesini kullanın:

      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 Bitmap nesnesinden FirebaseVisionImage nesnesi oluşturmak için:

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      Kotlin+KTX

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

  2. FirebaseVisionBarcodeDetector ö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 görüntüyü 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ın

Barkod tanıma işlemi başarılı olursa FirebaseVisionBarcode nesnelerinin bir listesi başarı dinleyicisine iletilecektir. Her FirebaseVisionBarcode nesnesi, görüntüde tespit edilen bir barkodu temsil eder. Her barkod için, giriş görüntüsündeki sınırlayıcı koordinatların yanı sıra barkod tarafından kodlanan ham verileri de alabilirsiniz. Ayrıca, barkod dedektörü barkod tarafından kodlanan verinin türünü belirleyebilirse ayrıştırılmış verileri içeren bir nesne elde edebilirsiniz.

Ö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ı artırmaya yönelik ipuçları

Barkodları gerçek zamanlı bir uygulamada taramak istiyorsanız en iyi kare hızlarına ulaşmak için şu yönergeleri izleyin:

  • Girişi kameranın doğal çözünürlüğünde yakalamayın. Bazı cihazlarda, girdiyi doğal çözünürlükte yakalamak son derece büyük (10+ megapiksel) görüntüler üretir; bu da gecikmenin çok düşük olmasına ve doğruluk açısından hiçbir fayda sağlamamasına neden olur. Bunun yerine, kameradan yalnızca barkod tespiti için gereken boyutu isteyin: genellikle 2 megapikselden fazla değil.

    Tarama hızı önemliyse görüntü yakalama çözünürlüğünü daha da düşürebilirsiniz. Ancak yukarıda özetlenen minimum barkod boyutu gerekliliklerini aklınızda bulundurun.

  • Gaz kelebeği dedektöre çağrı yapar. Dedektör çalışırken yeni bir video karesi kullanılabilir hale gelirse kareyi bırakın.
  • Giriş görüntüsü üzerine grafikleri yerleştirmek için dedektörün çıkışını kullanıyorsanız, önce ML Kit'ten sonucu alın, ardından tek adımda görüntüyü işleyin ve üst üste koyun. Bunu yaparak, her giriş karesi için ekran yüzeyini yalnızca bir kez görüntüleyebilirsiniz.
  • Camera2 API'sini kullanıyorsanız görüntüleri ImageFormat.YUV_420_888 formatında yakalayın.

    Eski Kamera API'sini kullanıyorsanız görüntüleri ImageFormat.NV21 formatında yakalayın.