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

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

ก่อนเริ่มต้น

  1. เพิ่ม Firebase ลงในโปรเจ็กต์ Android หากยังไม่ได้ทำ
  2. เพิ่มทรัพยากร Dependency สำหรับไลบรารี 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 และคิวอาร์โค้ด ให้สร้างออบเจ็กต์ 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)
  • ITF (FORMAT_ITF)
  • UPC-A (FORMAT_UPC_A)
  • UPC-E (FORMAT_UPC_E)
  • คิวอาร์โค้ด (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() ซึ่งจะเป็นประโยชน์เมื่อคุณใช้ Intent 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