סרוק ברקודים עם ערכת ML באנדרואיד

אתה יכול להשתמש ב-ML Kit כדי לזהות ולפענח ברקודים.

לפני שאתה מתחיל

  1. אם עדיין לא עשית זאת, הוסף את Firebase לפרויקט Android שלך .
  2. הוסף את התלות של ספריות אנדרואיד של ML Kit לקובץ 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 פיקסלים).

    לדוגמה, ברקודים של EAN-13 מורכבים מפס ורווחים ברוחב של 1, 2, 3 או 4 יחידות, כך שלתמונת ברקוד EAN-13 יש באופן אידיאלי פסים ורווחים שהם לפחות 2, 4, 6 ו רוחב 8 פיקסלים. מכיוון ברוחב של ברקוד EAN-13 הוא 95 יחידות בסך הכל, על הברקוד להיות ברוחב של 190 פיקסלים לפחות.

    פורמטים צפופים יותר, כגון PDF417, צריכים ממדי פיקסלים גדולים יותר כדי ש-ML Kit יקרא אותם בצורה מהימנה. לדוגמה, קוד PDF417 יכול לכלול עד 34 "מילים" ברוחב של 17 יחידות בשורה אחת, שבאופן אידיאלי יהיו ברוחב של לפחות 1156 פיקסלים.

  • מיקוד לקוי של התמונה עלול לפגוע בדיוק הסריקה. אם אינך מקבל תוצאות מקובלות, נסה לבקש מהמשתמש לצלם מחדש את התמונה.

  • עבור יישומים טיפוסיים, מומלץ לספק תמונה ברזולוציה גבוהה יותר (כגון 1280x720 או 1920x1080), מה שהופך ברקודים לזיהוי ממרחק גדול יותר מהמצלמה.

    עם זאת, ביישומים שבהם זמן האחזור הוא קריטי, אתה יכול לשפר את הביצועים על ידי לכידת תמונות ברזולוציה נמוכה יותר, אך דורש שהברקוד יהווה את רוב תמונת הקלט. ראה גם טיפים לשיפור הביצועים בזמן אמת .

1. הגדר את גלאי הברקוד

אם אתה יודע אילו פורמטים של ברקוד אתה מצפה לקרוא, אתה יכול לשפר את המהירות של גלאי הברקוד על ידי הגדרתו לזהות רק פורמטים אלה.

לדוגמה, כדי לזהות רק קוד אצטקי וקודי 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 )
  • 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 ( 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 תועבר למאזין ההצלחה. כל אובייקט 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, ולאחר מכן עבד את התמונה ואת שכבת העל בצעד אחד. על ידי כך, אתה מעבד למשטח התצוגה רק פעם אחת עבור כל מסגרת קלט.
  • אם אתה משתמש בממשק ה-API של Camera2, צלם תמונות בפורמט ImageFormat.YUV_420_888 .

    אם אתה משתמש ב-Camera API הישן יותר, צלם תמונות בפורמט ImageFormat.NV21 .