ติดป้ายกำกับรูปภาพด้วยโมเดลที่ AutoML ฝึกใน Android
หลังจากฝึกโมเดลของคุณเองโดยใช้ AutoML Vision Edge แล้ว คุณจะใช้โมเดลดังกล่าวในแอปเพื่อติดป้ายกำกับรูปภาพได้ การผสานรวมโมเดลที่ฝึกจาก AutoML Vision Edge ทำได้ 2 วิธี ได้แก่ คุณสามารถรวมโมเดลโดยวางไว้ในโฟลเดอร์เนื้อหาของแอป หรือจะดาวน์โหลดแบบไดนามิกจาก Firebase ก็ได้ตัวเลือกการรวมโมเดล | |
---|---|
รวมอยู่ในแอป |
|
โฮสต์ด้วย Firebase |
|
ลองเลย
- ลองใช้แอปตัวอย่างเพื่อดูตัวอย่างการใช้งาน API นี้
ก่อนเริ่มต้น
1. ในไฟล์build.gradle
ระดับโปรเจ็กต์ ให้ตรวจสอบว่าได้ใส่ที่เก็บ Maven ของ Google ไว้ทั้งในส่วน buildscript
และ allprojects
2. เพิ่มทรัพยากร Dependency สำหรับไลบรารี ML Kit สำหรับ Android ลงในไฟล์ Gradle ระดับแอปของโมดูล ซึ่งโดยปกติจะเป็น
app/build.gradle
ดังนี้
สำหรับการรวมโมเดลกับแอป ให้ทำดังนี้
dependencies { // ... // Image labeling feature with bundled automl model implementation 'com.google.mlkit:image-labeling-automl:16.2.1' }
linkFirebase
ต่อไปนี้เป็น Dependency
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' }
1. โหลดโมเดล
กำหนดค่าแหล่งข้อมูลโมเดลในเครื่อง
วิธีรวมโมเดลกับแอป1. แตกไฟล์โมเดลและข้อมูลเมตาของโมเดลออกจากไฟล์ ZIP ที่คุณดาวน์โหลดจากคอนโซล Firebase เราขอแนะนำให้คุณใช้ไฟล์ตามที่ดาวน์โหลดมาโดยไม่มีการแก้ไข (รวมถึงชื่อไฟล์)
2. รวมโมเดลและไฟล์ข้อมูลเมตาของโมเดลไว้ในแพ็กเกจแอป
ก. หากไม่มีโฟลเดอร์ชิ้นงานในโปรเจ็กต์ ให้สร้างโฟลเดอร์โดยคลิกขวาที่โฟลเดอร์
app/
แล้วคลิกใหม่ > โฟลเดอร์ > โฟลเดอร์ชิ้นงานข. สร้างโฟลเดอร์ย่อยในโฟลเดอร์ชิ้นงานเพื่อเก็บไฟล์โมเดล
ค. คัดลอกไฟล์
model.tflite
, dict.txt
และ manifest.json
ไปยังโฟลเดอร์ย่อย (ไฟล์ทั้ง 3 ไฟล์ต้องอยู่ในโฟลเดอร์เดียวกัน)3. เพิ่มข้อมูลต่อไปนี้ลงในไฟล์
build.gradle
ของแอปเพื่อให้แน่ใจว่า Gradle จะไม่บีบอัดไฟล์โมเดลเมื่อสร้างแอป
android { // ... aaptOptions { noCompress "tflite" } }
หมายเหตุ: ตั้งแต่ปลั๊กอิน Android Gradle เวอร์ชัน 4.1 เป็นต้นไป ระบบจะเพิ่ม .tflite ลงในรายการ noCompress โดยค่าเริ่มต้น และคุณไม่จําเป็นต้องใช้คำสั่งข้างต้นอีกต่อไป
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 บางส่วน จนกว่าคุณจะยืนยันว่าดาวน์โหลดโมเดลแล้ว โดยแนบโปรแกรมรับฟังกับเมธอด 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
ไปยังเมธอด ImageLabeler
's
process()
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
ในแอปตัวอย่างการเริ่มต้นใช้งาน - หากคุณใช้
CameraX
API ให้ตรวจสอบว่าได้ตั้งค่ากลยุทธ์การลดแรงดันเป็นค่าเริ่มต้นแล้วImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
วิธีนี้ช่วยให้มั่นใจว่าจะมีการส่งรูปภาพเพียงรูปเดียวเพื่อการวิเคราะห์ในแต่ละครั้ง หากมีการสร้างรูปภาพเพิ่มเติมเมื่อเครื่องมือวิเคราะห์ไม่ว่าง ระบบจะทิ้งรูปภาพเหล่านั้นโดยอัตโนมัติและจะไม่จัดคิวเพื่อนำส่ง เมื่อปิดรูปภาพที่กำลังวิเคราะห์โดยการเรียกใช้ ImageProxy.close() ระบบจะส่งรูปภาพล่าสุดถัดไป - หากคุณใช้เอาต์พุตของเครื่องติดป้ายกำกับรูปภาพเพื่อวางกราฟิกซ้อนทับบนรูปภาพอินพุต ให้รับผลลัพธ์จาก ML Kit ก่อน จากนั้นจึงแสดงผลรูปภาพและวางซ้อนในขั้นตอนเดียว ซึ่งจะแสดงผลบนพื้นผิวการแสดงผลเพียงครั้งเดียวสำหรับเฟรมอินพุตแต่ละเฟรม ดูตัวอย่างได้จากคลาส
CameraSourcePreview
และGraphicOverlay
ในแอปตัวอย่างการเริ่มต้นใช้งาน - หากคุณใช้ Camera2 API ให้จับภาพในรูปแบบ
ImageFormat.YUV_420_888
หากคุณใช้ Camera API เวอร์ชันเก่า ให้ถ่ายภาพในรูปแบบImageFormat.NV21