ติดป้ายกำกับอิมเมจด้วยโมเดลที่ฝึก AutoML ใน Android

หลังจากที่ฝึกโมเดลของคุณเองโดยใช้ AutoML Vision Edge แล้ว คุณจะใช้โมเดลดังกล่าวในแอปเพื่อติดป้ายกำกับรูปภาพได้ การผสานรวมโมเดลที่ฝึกจาก AutoML Vision Edge มี 2 วิธีด้วยกัน ได้แก่ คุณสามารถรวมโมเดลโดยใส่ไว้ในโฟลเดอร์เนื้อหาของแอป หรือจะดาวน์โหลดแบบไดนามิกจาก Firebase ก็ได้
ตัวเลือกการจัดแพ็กเกจโมเดล
รวมกลุ่มไว้ในแอป
  • โมเดลนี้เป็นส่วนหนึ่งของ APK ของแอป
  • โมเดลนี้จะพร้อมใช้งานทันทีแม้อุปกรณ์ Android จะออฟไลน์
  • ไม่จำเป็นต้องมีโปรเจ็กต์ Firebase
โฮสต์ด้วย Firebase
  • โฮสต์โมเดลโดยอัปโหลดไปยัง Firebase Machine Learning
  • ลดขนาด APK
  • โมเดลนี้ดาวน์โหลดแบบออนดีมานด์
  • พุชการอัปเดตโมเดลโดยไม่ต้องเผยแพร่แอปอีกครั้ง
  • การทดสอบ A/B ง่ายๆ ด้วยการกำหนดค่าระยะไกลของ Firebase
  • ต้องมีโปรเจ็กต์ Firebase

ลองเลย

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

1. ในไฟล์ build.gradle ระดับโปรเจ็กต์ ให้ตรวจสอบว่ามีที่เก็บ Maven ของ Google ทั้งในส่วน buildscript และ allprojects

2. เพิ่มทรัพยากร Dependency สำหรับไลบรารี Android ของ ML Kit ลงในไฟล์ Gradle ระดับแอปของโมดูล ซึ่งปกติแล้วจะอยู่ที่ app/build.gradle สำหรับการรวมโมเดลกับแอป:
    dependencies {
      // ...
      // Image labeling feature with bundled automl model
      implementation 'com.google.mlkit:image-labeling-automl:16.2.1'
    }
    
หากต้องการดาวน์โหลดโมเดลแบบไดนามิกจาก Firebase ให้เพิ่มทรัพยากร Dependency linkFirebase ดังนี้
    dependencies {
      // ...
      // Image labeling feature with automl model downloaded
      // from firebase
      implementation 'com.google.mlkit:image-labeling-automl:16.2.1'
      implementation 'com.google.mlkit:linkfirebase:16.0.1'
    }
    
3. หากต้องการดาวน์โหลดโมเดล ให้เพิ่ม Firebase ลงในโปรเจ็กต์ Android หากยังไม่ได้ทำ เนื่องจากจะได้รวมโมเดลนี้เข้าด้วยกันโดยไม่จำเป็นต้องดำเนินการดังกล่าว

1. โหลดโมเดล

กำหนดค่าแหล่งที่มาของโมเดลในเครื่อง

หากต้องการรวมโมเดลเข้ากับแอป ให้ทำดังนี้

1. ดึงโมเดลและข้อมูลเมตาจากไฟล์ ZIP ที่คุณดาวน์โหลดจากคอนโซล Firebase เราขอแนะนำให้คุณใช้ไฟล์ขณะที่คุณดาวน์โหลด โดยไม่มีการแก้ไข (รวมถึงชื่อไฟล์)

2. ใส่โมเดลและไฟล์ข้อมูลเมตาของโมเดลในแพ็กเกจแอป

ก. หากไม่มีโฟลเดอร์ชิ้นงานในโปรเจ็กต์ ให้สร้างโฟลเดอร์โดยการคลิกขวาที่โฟลเดอร์ app/ แล้วคลิกใหม่ > โฟลเดอร์ > โฟลเดอร์ชิ้นงาน

ข. สร้างโฟลเดอร์ย่อยภายในโฟลเดอร์เนื้อหาเพื่อเก็บไฟล์โมเดล

ค. คัดลอกไฟล์ model.tflite, dict.txt และ manifest.json ไปยังโฟลเดอร์ย่อย (ทั้ง 3 ไฟล์ต้องอยู่ในโฟลเดอร์เดียวกัน)

3. เพิ่มข้อมูลต่อไปนี้ลงในไฟล์ build.gradle ของแอปเพื่อให้ Gradle ไม่บีบอัดไฟล์โมเดลเมื่อสร้างแอป
    android {
        // ...
        aaptOptions {
            noCompress "tflite"
        }
    }
    
ไฟล์โมเดลจะรวมอยู่ในแพ็กเกจแอปและพร้อมให้ ML Kit เป็นเนื้อหาดิบ

หมายเหตุ: ตั้งแต่ปลั๊กอิน Android Gradle เวอร์ชัน 4.1 ระบบจะเพิ่ม .tflite ลงในรายการ noCompress โดยค่าเริ่มต้น และคุณไม่จำเป็นต้องใช้ .tflite ด้านบนอีกต่อไป

4. สร้างออบเจ็กต์ LocalModel โดยระบุเส้นทางไปยังไฟล์ Manifest ของโมเดล

Kotlin

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

Java

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

กำหนดค่าแหล่งที่มาของรูปแบบที่โฮสต์ใน Firebase

หากต้องการใช้โมเดลที่โฮสต์จากระยะไกล ให้สร้างออบเจ็กต์ RemoteModel โดยระบุชื่อที่คุณกำหนดโมเดลเมื่อเผยแพร่

Kotlin

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

Java

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

จากนั้น เริ่มงานดาวน์โหลดโมเดล โดยระบุเงื่อนไขที่คุณต้องการอนุญาตให้ดาวน์โหลด หากโมเดลไม่ได้อยู่ในอุปกรณ์ หรือหากมีโมเดลเวอร์ชันใหม่กว่า งานจะดาวน์โหลดโมเดลแบบไม่พร้อมกันจาก Firebase ดังนี้

Kotlin

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

Java

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

แอปจำนวนมากเริ่มงานดาวน์โหลดในโค้ดการเริ่มต้น แต่ก่อนจะใช้โมเดลได้ทุกเมื่อ

สร้างผู้ติดป้ายกำกับรูปภาพจากโมเดล

หลังจากกำหนดค่าแหล่งที่มาของโมเดลแล้ว ให้สร้างออบเจ็กต์ ImageLabeler จากแหล่งที่มาเหล่านั้น

หากคุณมีเฉพาะโมเดลที่จัดกลุ่มในเครื่อง เพียงสร้างผู้ติดป้ายกำกับจากออบเจ็กต์ AutoMLImageLabelerLocalModel และกำหนดค่าเกณฑ์คะแนนความเชื่อมั่นที่ต้องการ (ดูประเมินโมเดล)

Kotlin

val autoMLImageLabelerOptions = AutoMLImageLabelerOptions.Builder(localModel)
    .setConfidenceThreshold(0)  // Evaluate your model in the Firebase console
                                // to determine an appropriate value.
    .build()
val labeler = ImageLabeling.getClient(autoMLImageLabelerOptions)

Java

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

หากมีโมเดลที่โฮสต์จากระยะไกล คุณจะต้องตรวจสอบว่าได้ดาวน์โหลดโมเดลแล้วก่อนที่จะเรียกใช้ คุณจะตรวจสอบสถานะของงานดาวน์โหลดโมเดลได้โดยใช้เมธอด isModelDownloaded() ของผู้จัดการโมเดล

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

Kotlin

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

Java

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

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

หากมีเฉพาะโมเดลที่โฮสต์จากระยะไกล คุณควรปิดใช้ฟังก์ชันการทำงานที่เกี่ยวข้องกับโมเดล เช่น ทำให้ UI เป็นสีเทาหรือซ่อนบางส่วน จนกว่าคุณจะยืนยันว่าได้ดาวน์โหลดโมเดลแล้ว ซึ่งทำได้โดยแนบ Listener เข้ากับเมธอด download() ของตัวจัดการโมเดล ดังนี้

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

Java

RemoteModelManager.getInstance().download(remoteModel, conditions)
        .addOnSuccessListener(new OnSuccessListener() {
            @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.
            }
        });

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) {
        Image mediaImage = imageProxy.getImage();
        if (mediaImage != null) {
          InputImage image =
                InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees());
          // Pass image to an ML Kit Vision API
          // ...
        }
    }
}

หากคุณไม่ได้ใช้คลังภาพกล้องที่ให้องศาการหมุนของรูปภาพ คุณจะคํานวณจากองศาการหมุนของอุปกรณ์และการวางแนวของเซ็นเซอร์กล้องในอุปกรณ์ได้ ดังนี้

Kotlin

private val ORIENTATIONS = SparseIntArray()

init {
    ORIENTATIONS.append(Surface.ROTATION_0, 0)
    ORIENTATIONS.append(Surface.ROTATION_90, 90)
    ORIENTATIONS.append(Surface.ROTATION_180, 180)
    ORIENTATIONS.append(Surface.ROTATION_270, 270)
}

/**
 * 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, isFrontFacing: Boolean): 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)

    // Get the device's sensor orientation.
    val cameraManager = activity.getSystemService(CAMERA_SERVICE) as CameraManager
    val sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION)!!

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360
    }
    return rotationCompensation
}

Java

private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
    ORIENTATIONS.append(Surface.ROTATION_0, 0);
    ORIENTATIONS.append(Surface.ROTATION_90, 90);
    ORIENTATIONS.append(Surface.ROTATION_180, 180);
    ORIENTATIONS.append(Surface.ROTATION_270, 270);
}

/**
 * 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, boolean isFrontFacing)
        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);

    // Get the device's sensor orientation.
    CameraManager cameraManager = (CameraManager) activity.getSystemService(CAMERA_SERVICE);
    int sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION);

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360;
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360;
    }
    return rotationCompensation;
}

จากนั้นส่งออบเจ็กต์ media.Image และค่าองศาการหมุนไปยัง InputImage.fromMediaImage()

Kotlin

val image = InputImage.fromMediaImage(mediaImage, rotation)

Java

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

การใช้ URI ของไฟล์

หากต้องการสร้างออบเจ็กต์ InputImage จาก URI ไฟล์ ให้ส่งบริบทของแอปและ URI ของไฟล์ไปยัง InputImage.fromFilePath() ซึ่งจะเป็นประโยชน์เมื่อคุณใช้ Intent ACTION_GET_CONTENT เพื่อแจ้งให้ผู้ใช้เลือกรูปภาพจากแอปแกลเลอรี

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
)
// Or:
val image = InputImage.fromByteArray(
        byteArray,
        /* 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
);
// Or:
InputImage image = InputImage.fromByteArray(
        byteArray,
        /* image width */480,
        /* image height */360,
        rotation,
        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 ไปยังเมธอด process() ของ ImageLabeler

Kotlin

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

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

4. รับข้อมูลเกี่ยวกับออบเจ็กต์ที่ติดป้ายกำกับ

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

Kotlin

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

Java

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

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

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

  • หากคุณใช้ Camera หรือ camera2 API ให้ควบคุมการเรียกใช้ไปยังผู้ติดป้ายกำกับอิมเมจ หากเฟรมวิดีโอใหม่พร้อมใช้งานขณะที่ผู้ติดป้ายกำกับรูปภาพกำลังทำงาน ให้วางเฟรมนั้นลง ดูตัวอย่างคลาส VisionProcessorBase ในแอปตัวอย่าง Quickstart
  • หากคุณใช้ CameraX API โปรดตรวจสอบว่าได้ตั้งค่ากลยุทธ์ Backpressure เป็นค่าเริ่มต้น ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST แล้ว ซึ่งจะช่วยรับประกันว่าระบบจะส่งรูปภาพเพื่อทำการวิเคราะห์ได้ทีละ 1 ภาพเท่านั้น หากมีการสร้างรูปภาพเพิ่มเติมเมื่อตัววิเคราะห์ไม่ว่าง ระบบจะปล่อยรูปภาพเหล่านั้นโดยอัตโนมัติและไม่เข้าคิวเพื่อนำส่ง เมื่อปิดรูปภาพที่วิเคราะห์แล้วโดยการเรียกใช้ ImageProxy.close() ระบบจะส่งรูปภาพล่าสุดถัดไป
  • หากใช้เอาต์พุตของผู้ติดป้ายกำกับรูปภาพเพื่อวางซ้อนกราฟิกบนรูปภาพอินพุต ให้แสดงผลลัพธ์จาก ML Kit ก่อน จากนั้นจึงแสดงผลรูปภาพและการวางซ้อนในขั้นตอนเดียว ซึ่งจะแสดงบนพื้นผิวจอแสดงผลเพียงครั้งเดียวต่อเฟรมอินพุตแต่ละเฟรม ดูตัวอย่างคลาส CameraSourcePreview และ GraphicOverlay ในแอปตัวอย่าง Quickstart
  • หากคุณใช้ Camera2 API ให้จับภาพในรูปแบบ ImageFormat.YUV_420_888 หากคุณใช้ Camera API เวอร์ชันเก่า ให้จับภาพในรูปแบบ ImageFormat.NV21