สแกนบาร์โค้ดด้วย ML Kit บน Android

คุณสามารถใช้ ML Kit เพื่อจดจำและถอดรหัสบาร์โค้ดได้

ก่อนที่คุณจะเริ่ม

  1. หากคุณยังไม่ได้ เพิ่ม Firebase ในโครงการ Android ของคุณ
  2. เพิ่มการพึ่งพาสำหรับไลบรารี ML Kit Android ให้กับไฟล์ Gradle ของโมดูล (ระดับแอป) (โดยปกติคือ 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'
    }
    

แนวทางการป้อนรูปภาพ

  • เพื่อให้ ML Kit อ่านบาร์โค้ดได้อย่างแม่นยำ รูปภาพที่ป้อนจะต้องมีบาร์โค้ดที่แสดงด้วยข้อมูลพิกเซลที่เพียงพอ

    ข้อกำหนดข้อมูลพิกเซลเฉพาะจะขึ้นอยู่กับประเภทของบาร์โค้ดและจำนวนข้อมูลที่เข้ารหัส (เนื่องจากบาร์โค้ดส่วนใหญ่รองรับเพย์โหลดความยาวผันแปรได้) โดยทั่วไป หน่วยที่มีความหมายน้อยที่สุดของบาร์โค้ดควรมีความกว้างอย่างน้อย 2 พิกเซล (และสำหรับโค้ด 2 มิติควรมีความสูง 2 พิกเซล)

    ตัวอย่างเช่น บาร์โค้ด EAN-13 ประกอบด้วยแท่งและช่องว่างที่มีความกว้าง 1, 2, 3 หรือ 4 หน่วย ดังนั้นรูปภาพบาร์โค้ด EAN-13 จึงควรมีแถบและช่องว่างอย่างน้อย 2, 4, 6 และ กว้าง 8 พิกเซล เนื่องจากบาร์โค้ด EAN-13 มีความกว้างทั้งหมด 95 หน่วย บาร์โค้ดจึงควรมีความกว้างอย่างน้อย 190 พิกเซล

    รูปแบบที่หนาแน่นมากขึ้น เช่น PDF417 จำเป็นต้องมีขนาดพิกเซลที่มากขึ้นเพื่อให้ ML Kit อ่านได้อย่างน่าเชื่อถือ ตัวอย่างเช่น โค้ด PDF417 สามารถมี "คำ" กว้าง 17 หน่วยได้สูงสุด 34 คำในแถวเดียว ซึ่งตามหลักการแล้วควรมีความกว้างอย่างน้อย 1156 พิกเซล

  • การโฟกัสภาพที่ไม่ดีอาจส่งผลเสียต่อความแม่นยำในการสแกน หากคุณไม่ได้รับผลลัพธ์ที่ยอมรับได้ ให้ลองขอให้ผู้ใช้จับภาพใหม่

  • สำหรับการใช้งานทั่วไป ขอแนะนำให้จัดเตรียมภาพที่มีความละเอียดสูงกว่า (เช่น 1280x720 หรือ 1920x1080) ซึ่งทำให้สามารถตรวจจับบาร์โค้ดได้จากระยะห่างที่มากขึ้นจากกล้อง

    อย่างไรก็ตาม ในแอปพลิเคชันที่เวลาแฝงเป็นสิ่งสำคัญ คุณสามารถปรับปรุงประสิทธิภาพได้โดยการถ่ายภาพด้วยความละเอียดที่ต่ำกว่า แต่กำหนดให้บาร์โค้ดเป็นส่วนใหญ่ของภาพที่ป้อนเข้า ดู เคล็ดลับในการปรับปรุงประสิทธิภาพแบบเรียลไทม์ ด้วย

1. กำหนดค่าตัวตรวจจับบาร์โค้ด

หากคุณทราบว่าคุณต้องการอ่านบาร์โค้ดรูปแบบใด คุณสามารถปรับปรุงความเร็วของตัวตรวจจับบาร์โค้ดได้โดยการกำหนดค่าให้ตรวจจับเฉพาะรูปแบบเหล่านั้นเท่านั้น

ตัวอย่างเช่น หากต้องการตรวจจับเฉพาะรหัส Aztec และรหัส QR ให้สร้างออบเจ็กต์ FirebaseVisionBarcodeDetectorOptions ดังตัวอย่างต่อไปนี้:

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

รองรับรูปแบบต่อไปนี้:

  • รหัส 128 ( FORMAT_CODE_128 )
  • รหัส 39 ( FORMAT_CODE_39 )
  • รหัส 93 ( FORMAT_CODE_93 )
  • โคดาบาร์ ( FORMAT_CODABAR )
  • EAN-13 ( FORMAT_EAN_13 )
  • EAN-8 ( FORMAT_EAN_8 )
  • ไอทีเอฟ ( FORMAT_ITF )
  • UPC-A ( FORMAT_UPC_A )
  • UPC-E ( FORMAT_UPC_E )
  • รหัส QR ( FORMAT_QR_CODE )
  • PDF417 ( FORMAT_PDF417 )
  • แอซเท็ก ( FORMAT_AZTEC )
  • ข้อมูลเมทริกซ์ ( FORMAT_DATA_MATRIX )

2. เรียกใช้ตัวตรวจจับบาร์โค้ด

หากต้องการจดจำบาร์โค้ดในรูปภาพ ให้สร้างออบเจ็กต์ FirebaseVisionImage จาก Bitmap , media.Image , ByteBuffer , อาร์เรย์ไบต์ หรือไฟล์บนอุปกรณ์ จากนั้น ส่งออบเจ็กต์ FirebaseVisionImage ไปยังเมธอด detectInImage ของ FirebaseVisionBarcodeDetector

  1. สร้างวัตถุ FirebaseVisionImage จากรูปภาพของคุณ

    • หากต้องการสร้างออบเจ็กต์ FirebaseVisionImage จากออบเจ็ media.Image เช่น เมื่อถ่ายภาพจากกล้องของอุปกรณ์ ให้ส่งอ media.Image และการหมุนของรูปภาพไปที่ FirebaseVisionImage.fromMediaImage()

      หากคุณใช้ไลบรารี CameraX คลาส OnImageCapturedListener และ ImageAnalysis.Analyzer จะคำนวณค่าการหมุนให้กับคุณ ดังนั้น คุณเพียงแค่ต้องแปลงการหมุนให้เป็นค่าคงที่ ROTATION_ ของ ML Kit ก่อนที่จะเรียกใช้ 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
                  // ...
              }
          }
      }
      

      หากคุณไม่ได้ใช้ไลบรารีกล้องที่ให้การหมุนภาพ คุณสามารถคำนวณได้จากการหมุนของอุปกรณ์และการวางแนวของเซ็นเซอร์กล้องในอุปกรณ์:

      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
      }

      จากนั้นส่งผ่านวัตถุ media.Image และค่าการหมุนไปที่ FirebaseVisionImage.fromMediaImage() :

      Java

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

      Kotlin+KTX

      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
    • หากต้องการสร้างออบเจ็กต์ FirebaseVisionImage จากไฟล์ URI ให้ส่งบริบทของแอปและ URI ไฟล์ไปที่ FirebaseVisionImage.fromFilePath() สิ่งนี้มีประโยชน์เมื่อคุณใช้เจตนา ACTION_GET_CONTENT เพื่อแจ้งให้ผู้ใช้เลือกรูปภาพจากแอปแกลเลอรีของตน

      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()
      }
    • หากต้องการสร้างออบเจ็กต์ FirebaseVisionImage จาก ByteBuffer หรืออาร์เรย์ไบต์ ขั้นแรกให้คำนวณการหมุนรูปภาพตามที่อธิบายไว้ข้างต้นสำหรับอินพุต media.Image

      จากนั้น สร้างออบเจ็กต์ FirebaseVisionImageMetadata ที่มีความสูง ความกว้าง รูปแบบการเข้ารหัสสี และการหมุนของรูปภาพ ดังนี้

      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 :

      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)
    • หากต้องการสร้างวัตถุ FirebaseVisionImage จากวัตถุ Bitmap :

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      Kotlin+KTX

      val image = FirebaseVisionImage.fromBitmap(bitmap)
      รูปภาพที่แสดงโดยวัตถุ Bitmap จะต้องตั้งตรง โดยไม่ต้องหมุนเพิ่มเติม

  2. รับอินสแตนซ์ของ FirebaseVisionBarcodeDetector :

    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. สุดท้าย ส่งภาพไปยังเมธอด detectInImage :

    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. รับข้อมูลจากบาร์โค้ด

หากการดำเนินการจดจำบาร์โค้ดสำเร็จ รายการของออบเจ็กต์ FirebaseVisionBarcode จะถูกส่งไปยัง Listener ที่สำเร็จ ออบเจ็กต์ FirebaseVisionBarcode แต่ละรายการแสดงถึงบาร์โค้ดที่ตรวจพบในรูปภาพ สำหรับบาร์โค้ดแต่ละอัน คุณสามารถรับพิกัดขอบเขตในรูปภาพอินพุต รวมถึงข้อมูลดิบที่เข้ารหัสด้วยบาร์โค้ด นอกจากนี้ หากตัวตรวจจับบาร์โค้ดสามารถระบุประเภทของข้อมูลที่เข้ารหัสด้วยบาร์โค้ดได้ คุณก็สามารถรับออบเจ็กต์ที่มีข้อมูลที่แยกวิเคราะห์ได้

ตัวอย่างเช่น:

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

เคล็ดลับในการปรับปรุงประสิทธิภาพแบบเรียลไทม์

หากคุณต้องการสแกนบาร์โค้ดในแอปพลิเคชันแบบเรียลไทม์ ให้ปฏิบัติตามคำแนะนำเหล่านี้เพื่อให้ได้เฟรมเรตที่ดีที่สุด:

  • อย่าจับภาพอินพุตที่ความละเอียดดั้งเดิมของกล้อง ในอุปกรณ์บางชนิด การจับอินพุตที่ความละเอียดมาตรฐานจะทำให้ได้ภาพที่มีขนาดใหญ่มาก (10+ ล้านพิกเซล) ซึ่งส่งผลให้มีเวลาแฝงต่ำมากและไม่มีประโยชน์ต่อความแม่นยำ แต่ให้ขอเฉพาะขนาดจากกล้องที่จำเป็นสำหรับการตรวจจับบาร์โค้ดเท่านั้น ซึ่งโดยปกติแล้วจะไม่เกิน 2 เมกะพิกเซล

    หากความเร็วในการสแกนเป็นสิ่งสำคัญ คุณสามารถลดความละเอียดในการจับภาพลงได้อีก อย่างไรก็ตาม โปรดคำนึงถึงข้อกำหนดขนาดบาร์โค้ดขั้นต่ำที่ระบุไว้ข้างต้น

  • คันเร่งเรียกไปที่เครื่องตรวจจับ หากมีเฟรมวิดีโอใหม่ในขณะที่ตัวตรวจจับกำลังทำงานอยู่ ให้ปล่อยเฟรมนั้น
  • หากคุณใช้เอาต์พุตของตัวตรวจจับเพื่อวางซ้อนกราฟิกบนรูปภาพอินพุต อันดับแรกรับผลลัพธ์จาก ML Kit จากนั้นเรนเดอร์รูปภาพและโอเวอร์เลย์ในขั้นตอนเดียว การทำเช่นนี้ คุณจะเรนเดอร์ไปยังพื้นผิวจอแสดงผลเพียงครั้งเดียวสำหรับแต่ละเฟรมอินพุต
  • หากคุณใช้ Camera2 API ให้จับภาพในรูปแบบ ImageFormat.YUV_420_888

    หากคุณใช้ Camera API รุ่นเก่า ให้จับภาพในรูปแบบ ImageFormat.NV21