הוספת תוויות למודלים עם אימון אוטומטי של Android ב-Android

אחרי שמאמנים מודל משלכם באמצעות AutoML Vision Edge, אפשר להשתמש בו באפליקציה כדי לתייג תמונות.

יש שתי דרכים לשלב מודלים שאומנו באמצעות AutoML Vision Edge: אפשר לארוז את המודל על ידי הוספתו לתיקיית הנכסים של האפליקציה, או להוריד אותו באופן דינמי מ-Firebase.

אפשרויות של חבילות מודלים
כלול באפליקציה
  • המודל הוא חלק מחבילת ה-APK של האפליקציה
  • המודל זמין באופן מיידי, גם כשמכשיר Android אופליין
  • אין צורך בפרויקט Firebase
באירוח של Firebase

לפני שמתחילים

  1. מוסיפים את התלויות של ספריות ML Kit Android לקובץ Gradle ברמת האפליקציה של המודול, שבדרך כלל נמצא בנתיב app/build.gradle:

    לצירוף מודל לאפליקציה:

    dependencies {
      // ...
      // Image labeling feature with bundled automl model
      implementation 'com.google.mlkit:image-labeling-custom:16.3.1'
    }
    

    כדי להוריד באופן דינמי מודל מ-Firebase, מוסיפים את linkFirebase התלות:

    dependencies {
      // ...
      // Image labeling feature with automl model downloaded
      // from firebase
      implementation 'com.google.mlkit:image-labeling-custom:16.3.1'
      implementation 'com.google.mlkit:linkfirebase:16.1.0'
    }
    
  2. אם רוצים להוריד מודל, צריך לוודא שהוספתם את Firebase לפרויקט Android, אם עדיין לא עשיתם זאת. זה לא נדרש כשמצרפים את המודל לחבילה.

1. טעינת המודל

הגדרת מקור מודל מקומי

כדי לארוז את המודל עם האפליקציה:

  1. מחלצים את המודל ואת המטא-נתונים שלו מארכיון ה-ZIP שהורדתם ממסוף Firebase. מומלץ להשתמש בקבצים כמו שהורדתם אותם, בלי לבצע בהם שינויים (כולל שמות הקבצים).

  2. כוללים את המודל ואת קובצי המטא-נתונים שלו בחבילת האפליקציה:

    1. אם אין לכם תיקיית נכסים בפרויקט, אתם יכולים ליצור אותה על ידי לחיצה ימנית על התיקייה app/ ואז לחיצה על New > Folder > Assets Folder (חדש > תיקייה > תיקיית נכסים).
    2. יוצרים תיקיית משנה בתיקיית הנכסים שתכיל את קובצי המודל.
    3. מעתיקים את הקבצים model.tflite, dict.txt ו-manifest.json לתיקיית המשנה (כל שלושת הקבצים צריכים להיות באותה תיקייה).
  3. כדי לוודא ש-Gradle לא יכווץ את קובץ המודל כשמבצעים build לאפליקציה, מוסיפים את השורות הבאות לקובץ build.gradle של האפליקציה:

    android {
        // ...
        aaptOptions {
            noCompress "tflite"
        }
    }
    

    קובץ המודל ייכלל בחבילת האפליקציה ויהיה זמין ל-ML Kit כנכס גולמי.

  4. יוצרים אובייקט LocalModel ומציינים את הנתיב לקובץ המניפסט של המודל:

    Java

    AutoMLImageLabelerLocalModel localModel =
        new AutoMLImageLabelerLocalModel.Builder()
            .setAssetFilePath("manifest.json")
            // or .setAbsoluteFilePath(absolute file path to manifest file)
            .build();
    

    Kotlin

    val localModel = LocalModel.Builder()
        .setAssetManifestFilePath("manifest.json")
        // or .setAbsoluteManifestFilePath(absolute file path to manifest file)
        .build()
    

הגדרה של מקור מודל שמתארח ב-Firebase

כדי להשתמש במודל שמתארח מרחוק, יוצרים אובייקט CustomRemoteModel ומציינים את השם שהקציתם למודל כשפרסמתם אותו:

Java

// Specify the name you assigned in the Firebase console.
FirebaseModelSource firebaseModelSource =
    new FirebaseModelSource.Builder("your_model_name").build();
CustomRemoteModel remoteModel =
    new CustomRemoteModel.Builder(firebaseModelSource).build();

Kotlin

// Specify the name you assigned in the Firebase console.
val firebaseModelSource = FirebaseModelSource.Builder("your_model_name")
    .build()
val remoteModel = CustomRemoteModel.Builder(firebaseModelSource).build()

לאחר מכן, מתחילים את משימת ההורדה של המודל ומציינים את התנאים שבהם רוצים לאפשר הורדה. אם המודל לא נמצא במכשיר, או אם יש גרסה חדשה יותר של המודל, המשימה תוריד את המודל מ-Firebase באופן אסינכרוני:

Java

DownloadConditions downloadConditions = new DownloadConditions.Builder()
        .requireWifi()
        .build();
RemoteModelManager.getInstance().download(remoteModel, downloadConditions)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(@NonNull Task<Void> task) {
                // Success.
            }
        });

Kotlin

val downloadConditions = DownloadConditions.Builder()
    .requireWifi()
    .build()
RemoteModelManager.getInstance().download(remoteModel, downloadConditions)
    .addOnSuccessListener {
        // Success.
    }

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

יצירת כלי לתוויות תמונות מהמודל

אחרי שמגדירים את מקורות המודלים, יוצרים אובייקט ImageLabeler מאחד מהם.

אם יש לכם רק מודל שצורף באופן מקומי, פשוט יוצרים תווית מCustomImageLabelerOptions האובייקט ומגדירים את סף ציון מהימנות שרוצים לדרוש (ראו הערכת המודל):

Java

CustomImageLabelerOptions customImageLabelerOptions = new CustomImageLabelerOptions.Builder(localModel)
    .setConfidenceThreshold(0.0f)  // Evaluate your model in the Cloud console
                                   // to determine an appropriate value.
    .build();
ImageLabeler labeler = ImageLabeling.getClient(customImageLabelerOptions);

Kotlin

val customImageLabelerOptions = CustomImageLabelerOptions.Builder(localModel)
    .setConfidenceThreshold(0.0f)  // Evaluate your model in the Cloud console
                                   // to determine an appropriate value.
    .build()
val labeler = ImageLabeling.getClient(customImageLabelerOptions)

אם יש לכם מודל שמתארח מרחוק, תצטרכו לוודא שהוא הורד לפני שתפעילו אותו. אפשר לבדוק את סטטוס ההורדה של המודל באמצעות השיטה isModelDownloaded() של הכלי לניהול מודלים.

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

Java

RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
        .addOnSuccessListener(new OnSuccessListener<Boolean>() {
            @Override
            public void onSuccess(Boolean isDownloaded) {
                CustomImageLabelerOptions.Builder optionsBuilder;
                if (isDownloaded) {
                    optionsBuilder = new CustomImageLabelerOptions.Builder(remoteModel);
                } else {
                    optionsBuilder = new CustomImageLabelerOptions.Builder(localModel);
                }
                CustomImageLabelerOptions options = optionsBuilder
                        .setConfidenceThreshold(0.0f)  // Evaluate your model in the Cloud console
                                                       // to determine an appropriate threshold.
                        .build();

                ImageLabeler labeler = ImageLabeling.getClient(options);
            }
        });

Kotlin

RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
    .addOnSuccessListener { isDownloaded ->
        val optionsBuilder =
            if (isDownloaded) {
                CustomImageLabelerOptions.Builder(remoteModel)
            } else {
                CustomImageLabelerOptions.Builder(localModel)
            }
        // Evaluate your model in the Cloud console to determine an appropriate threshold.
        val options = optionsBuilder.setConfidenceThreshold(0.0f).build()
        val labeler = ImageLabeling.getClient(options)
}

אם יש לכם רק מודל שמתארח מרחוק, אתם צריכים להשבית את הפונקציונליות שקשורה למודל – למשל, להאפיר או להסתיר חלק מהממשק – עד שתאשרו שהמודל הורד. כדי לעשות את זה, צריך לצרף מאזין לשיטה download() של מנהל המודלים:

Java

RemoteModelManager.getInstance().download(remoteModel, conditions)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void v) {
              // Download complete. Depending on your app, you could enable
              // the ML feature, or switch from the local model to the remote
              // model, etc.
            }
        });

Kotlin

RemoteModelManager.getInstance().download(remoteModel, conditions)
    .addOnSuccessListener {
        // Download complete. Depending on your app, you could enable the ML
        // feature, or switch from the local model to the remote model, etc.
    }

2. הכנת תמונת הקלט

לאחר מכן, לכל תמונה שרוצים לתייג, יוצרים אובייקט InputImage מהתמונה. התוויתן של התמונות פועל הכי מהר כשמשתמשים ב-Bitmap או, אם משתמשים ב-camera2 API, ב-YUV_420_888 media.Image, שהם מומלצים כשזה אפשרי.

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

שימוש ב-media.Image

כדי ליצור אובייקט InputImage מאובייקט media.Image, למשל כשמצלמים תמונה ממצלמת המכשיר, מעבירים את אובייקט media.Image ואת סיבוב התמונה אל InputImage.fromMediaImage().

אם משתמשים בספריית CameraX, המחלקות OnImageCapturedListener ו-ImageAnalysis.Analyzer מחשבות את ערך הסיבוב בשבילכם.

Kotlin

private class YourImageAnalyzer : ImageAnalysis.Analyzer {
    override fun analyze(imageProxy: ImageProxy?) {
        val mediaImage = imageProxy?.image
        if (mediaImage != null) {
            val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
            // Pass image to an ML Kit Vision API
            // ...
        }
    }
}

Java

private class YourAnalyzer implements ImageAnalysis.Analyzer {

    @Override
    public void analyze(ImageProxy imageProxy) {
        if (imageProxy == null || imageProxy.getImage() == null) {
            return;
        }
        Image mediaImage = imageProxy.getImage();
        InputImage image =
                InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees);
        // Pass image to an ML Kit Vision API
        // ...
    }
}

אם אתם לא משתמשים בספריית מצלמה שמספקת את זווית הסיבוב של התמונה, אתם יכולים לחשב אותה לפי זווית הסיבוב של המכשיר והכיוון של חיישן המצלמה במכשיר:

Kotlin

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
}

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

לאחר מכן מעבירים את האובייקט media.Image ואת ערך מעלות הסיבוב אל InputImage.fromMediaImage():

Kotlin

val image = InputImage.fromMediaImage(mediaImage, rotation)

Java

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

שימוש ב-URI של קובץ

כדי ליצור אובייקט InputImage מ-URI של קובץ, מעבירים את הקשר של האפליקציה ואת ה-URI של הקובץ אל InputImage.fromFilePath(). האפשרות הזו שימושית כשמשתמשים ב-ACTION_GET_CONTENT intent כדי להנחות את המשתמש לבחור תמונה מאפליקציית הגלריה שלו.

Kotlin

val image: InputImage
try {
    image = InputImage.fromFilePath(context, uri)
} catch (e: IOException) {
    e.printStackTrace()
}

Java

InputImage image;
try {
    image = InputImage.fromFilePath(context, uri);
} catch (IOException e) {
    e.printStackTrace();
}

שימוש ב-ByteBuffer או ב-ByteArray

כדי ליצור אובייקט InputImage מ-ByteBuffer או מ-ByteArray, קודם צריך לחשב את זווית הסיבוב של התמונה כמו שמתואר למעלה לגבי קלט media.Image. לאחר מכן, יוצרים את האובייקט InputImage עם המאגר או המערך, יחד עם הגובה, הרוחב, פורמט קידוד הצבע וזווית הסיבוב של התמונה:

Kotlin

val image = InputImage.fromByteBuffer(
        byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
)

Java

InputImage image = InputImage.fromByteBuffer(byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
);

שימוש ב-Bitmap

כדי ליצור אובייקט InputImage מאובייקט Bitmap, צריך להצהיר על כך באופן הבא:

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);

התמונה מיוצגת על ידי אובייקט Bitmap יחד עם מעלות הסיבוב.

3. הפעלת הכלי להוספת תוויות לתמונות

כדי להוסיף תוויות לאובייקטים בתמונה, מעבירים את האובייקט image לשיטה ImageLabeler של process().

Java

labeler.process(image)
        .addOnSuccessListener(new OnSuccessListener<List<ImageLabel>>() {
            @Override
            public void onSuccess(List<ImageLabel> labels) {
                // Task completed successfully
                // ...
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Task failed with an exception
                // ...
            }
        });

Kotlin

labeler.process(image)
        .addOnSuccessListener { labels ->
            // Task completed successfully
            // ...
        }
        .addOnFailureListener { e ->
            // Task failed with an exception
            // ...
        }

4. קבלת מידע על אובייקטים עם תוויות

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

Java

for (ImageLabel label : labels) {
    String text = label.getText();
    float confidence = label.getConfidence();
    int index = label.getIndex();
}

Kotlin

for (label in labels) {
    val text = label.text
    val confidence = label.confidence
    val index = label.index
}

טיפים לשיפור הביצועים בזמן אמת

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

  • הגבלת מספר הפעמים שאפשר להשתמש ב-API לתווית תמונה. אם פריים חדש של סרטון הופך לזמין בזמן שהכלי לתוויות תמונות פועל, צריך להשליך את הפריים. דוגמה אפשר לראות במחלקה VisionProcessorBase באפליקציית הדוגמה למתחילים.
  • אם אתם משתמשים בפלט של הכלי לתוויות תמונות כדי להוסיף שכבת גרפיקה על תמונת הקלט, קודם צריך לקבל את התוצאה, ואז לעבד את התמונה ואת שכבת הגרפיקה בשלב אחד. כך, הרינדור מתבצע רק פעם אחת לכל מסגרת קלט. אפשר לראות דוגמה במחלקות CameraSourcePreview ו- GraphicOverlay באפליקציה לדוגמה למתחילים.
  • אם אתם משתמשים ב-Camera2 API, צלמו תמונות בפורמט ImageFormat.YUV_420_888.

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