Có hai cách để tích hợp các mô hình được đào tạo từ AutoML Vision Edge: Bạn có thể nhóm mô hình bằng cách đặt nó vào bên trong thư mục nội dung của ứng dụng hoặc bạn có thể tải xuống động từ Firebase.
Các tùy chọn gói mô hình | |
---|---|
Có trong ứng dụng của bạn |
|
Được lưu trữ bằng Firebase |
|
Trước khi bắt đầu
Thêm phần phụ thuộc cho các thư viện ML Kit Android vào tệp gradle cấp ứng dụng của mô-đun của bạn, thường là
app/build.gradle
:Để kết hợp một mô hình với ứng dụng của bạn:
dependencies { // ... // Image labeling feature with bundled automl model implementation 'com.google.mlkit:image-labeling-custom:16.3.1' }
Để tải xuống động một mô hình từ Firebase, hãy thêm phần phụ thuộc
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' }
Nếu bạn muốn tải xuống một mô hình , hãy đảm bảo bạn thêm Firebase vào dự án Android của mình , nếu bạn chưa làm như vậy. Điều này không bắt buộc khi bạn đóng gói mô hình.
1. Tải mô hình
Định cấu hình nguồn mô hình cục bộ
Để kết hợp mô hình với ứng dụng của bạn:
Giải nén mô hình và siêu dữ liệu của nó từ kho lưu trữ zip mà bạn đã tải xuống từ bảng điều khiển Firebase. Chúng tôi khuyên bạn nên sử dụng các tệp khi tải xuống mà không cần sửa đổi (bao gồm cả tên tệp).
Bao gồm mô hình của bạn và các tệp siêu dữ liệu của nó trong gói ứng dụng của bạn:
- Nếu bạn không có thư mục nội dung trong dự án của mình, hãy tạo một thư mục bằng cách nhấp chuột phải vào
app/
thư mục, sau đó nhấp vào Mới> Thư mục> Thư mục tài sản . - Tạo một thư mục con trong thư mục nội dung để chứa các tệp mô hình.
- Sao chép các tệp
model.tflite
,dict.txt
, vàmanifest.json
vào thư mục con (cả ba tệp phải nằm trong cùng một thư mục).
- Nếu bạn không có thư mục nội dung trong dự án của mình, hãy tạo một thư mục bằng cách nhấp chuột phải vào
Thêm phần sau vào tệp
build.gradle
của ứng dụng để đảm bảo Gradle không nén tệp mô hình khi xây dựng ứng dụng:android { // ... aaptOptions { noCompress "tflite" } }
Tệp mô hình sẽ được bao gồm trong gói ứng dụng và có sẵn cho ML Kit dưới dạng nội dung thô.
Tạo đối tượng
LocalModel
, chỉ định đường dẫn đến tệp kê khai mô hình: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()
Định cấu hình nguồn mô hình được lưu trữ trên Firebase
Để sử dụng mô hình được lưu trữ từ xa, hãy tạo một đối tượng CustomRemoteModel
, chỉ định tên bạn đã gán cho mô hình khi xuất bản:
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()
Sau đó, bắt đầu tác vụ tải xuống mô hình, chỉ định các điều kiện mà bạn muốn cho phép tải xuống. Nếu mô hình không có trên thiết bị hoặc nếu có phiên bản mới hơn của mô hình, tác vụ sẽ tải xuống mô hình từ Firebase một cách không đồng bộ:
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.
}
Nhiều ứng dụng bắt đầu tác vụ tải xuống trong mã khởi tạo của chúng, nhưng bạn có thể làm như vậy bất kỳ lúc nào trước khi cần sử dụng mô hình.
Tạo một trình gắn nhãn hình ảnh từ mô hình của bạn
Sau khi bạn định cấu hình các nguồn mô hình của mình, hãy tạo một đối tượng ImageLabeler
từ một trong số chúng.
Nếu bạn chỉ có một mô hình gói cục bộ, chỉ cần tạo một trình gắn nhãn từ đối tượng CustomImageLabelerOptions
của bạn và định cấu hình ngưỡng điểm tin cậy mà bạn muốn yêu cầu (xem Đánh giá mô hình của bạn ):
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)
Nếu bạn có một mô hình được lưu trữ từ xa, bạn sẽ phải kiểm tra xem nó đã được tải xuống chưa trước khi chạy. Bạn có thể kiểm tra trạng thái của tác vụ tải xuống mô hình bằng phương thức isModelDownloaded()
của trình quản lý mô hình.
Mặc dù bạn chỉ phải xác nhận điều này trước khi chạy trình gắn nhãn, nhưng nếu bạn có cả mô hình được lưu trữ từ xa và mô hình được gói cục bộ, bạn có thể thực hiện kiểm tra này khi khởi tạo trình gắn nhãn hình ảnh: tạo trình gắn nhãn từ mô hình từ xa nếu nó đã được tải xuống và từ mô hình cục bộ nếu không.
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)
}
Nếu bạn chỉ có một mô hình được lưu trữ từ xa, bạn nên tắt chức năng liên quan đến mô hình — ví dụ: chuyển sang màu xám hoặc ẩn một phần của giao diện người dùng — cho đến khi bạn xác nhận rằng mô hình đã được tải xuống. Bạn có thể làm như vậy bằng cách đính kèm một trình lắng nghe vào phương thức download()
của trình quản lý mô hình:
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. Chuẩn bị hình ảnh đầu vào
Sau đó, đối với mỗi hình ảnh bạn muốn gắn nhãn, hãy tạo một đối tượngInputImage
từ hình ảnh của bạn. Trình gắn nhãn hình ảnh chạy nhanh nhất khi bạn sử dụng Bitmap
hoặc, nếu bạn sử dụng API camera2, một YUV_420_888 media.Image
, được khuyến nghị khi có thể. Bạn có thể tạo một InputImage
đầu vào từ các nguồn khác nhau, mỗi nguồn được giải thích bên dưới.
Sử dụng phương media.Image
Để tạo một đối tượng InputImage
từ một đối tượng media.Image
, chẳng hạn như khi bạn chụp ảnh từ camera của thiết bị, hãy chuyển đối tượng media.Image
và vòng quay của ảnh tới InputImage.fromMediaImage()
.
Nếu bạn sử dụng thư viện CameraX , các lớp OnImageCapturedListener
và ImageAnalysis.Analyzer
tính toán giá trị xoay vòng cho bạn.
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+KTX
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 // ... } } }
Nếu bạn không sử dụng thư viện máy ảnh cung cấp cho bạn mức độ xoay của hình ảnh, bạn có thể tính toán nó từ mức độ xoay của thiết bị và hướng của cảm biến máy ảnh trong thiết bị:
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 }
Sau đó, chuyển đối tượng media.Image
và giá trị độ xoay vào InputImage.fromMediaImage()
:
Java
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
Kotlin+KTX
val image = InputImage.fromMediaImage(mediaImage, rotation)
Sử dụng URI tệp
Để tạo đối tượng InputImage
từ URI tệp, hãy chuyển ngữ cảnh ứng dụng và URI tệp vào InputImage.fromFilePath()
. Điều này hữu ích khi bạn sử dụng ý định ACTION_GET_CONTENT
để nhắc người dùng chọn hình ảnh từ ứng dụng thư viện của họ.
Java
InputImage image; try { image = InputImage.fromFilePath(context, uri); } catch (IOException e) { e.printStackTrace(); }
Kotlin+KTX
val image: InputImage try { image = InputImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
Sử dụng ByteBuffer
hoặc ByteArray
Để tạo một đối tượng InputImage
từ một ByteBuffer
hoặc một ByteArray
, trước tiên hãy tính toán mức độ xoay hình ảnh như đã mô tả trước đó cho đầu vào media.Image
. Sau đó, tạo đối tượng InputImage
bằng bộ đệm hoặc mảng, cùng với chiều cao, chiều rộng, định dạng mã hóa màu và độ xoay của hình ảnh:
Java
InputImage image = InputImage.fromByteBuffer(byteBuffer, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 );
Kotlin+KTX
val image = InputImage.fromByteBuffer( byteBuffer, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 )
Sử dụng một Bitmap
Để tạo một đối tượng InputImage
từ một đối tượng Bitmap
, hãy khai báo sau:
Java
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
Kotlin+KTX
val image = InputImage.fromBitmap(bitmap, 0)
Hình ảnh được thể hiện bằng một đối tượng Bitmap
cùng với các độ quay.
3. Chạy trình gắn nhãn hình ảnh
Để gắn nhãn các đối tượng trong một hình ảnh, hãy chuyển đối tượng image
vào phương thức process()
của ImageLabeler
.
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. Nhận thông tin về các đối tượng được gắn nhãn
Nếu thao tác gắn nhãn hình ảnh thành công, danh sách các đối tượngImageLabel
sẽ được chuyển đến trình nghe thành công. Mỗi đối tượng ImageLabel
đại diện cho một cái gì đó đã được gắn nhãn trong hình ảnh. Bạn có thể lấy mô tả văn bản của từng nhãn, điểm tin cậy của đối sánh và chỉ số của đối sánh. Ví dụ: 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
}
Mẹo để cải thiện hiệu suất thời gian thực
Nếu bạn muốn gắn nhãn hình ảnh trong ứng dụng thời gian thực, hãy làm theo các nguyên tắc sau để đạt được tốc độ khung hình tốt nhất:- Throttle gọi đến trình gắn nhãn hình ảnh. Nếu khung video mới khả dụng trong khi trình gắn nhãn hình ảnh đang chạy, hãy thả khung hình đó xuống. Hãy xem lớp
VisionProcessorBase
trong ứng dụng mẫu khởi động nhanh để làm ví dụ. - Nếu bạn đang sử dụng đầu ra của trình dán nhãn hình ảnh để phủ đồ họa lên hình ảnh đầu vào, trước tiên hãy lấy kết quả, sau đó hiển thị hình ảnh và lớp phủ trong một bước duy nhất. Bằng cách đó, bạn chỉ hiển thị trên bề mặt hiển thị một lần cho mỗi khung hình đầu vào. Hãy xem các lớp
CameraSourcePreview
vàGraphicOverlay
trong ứng dụng mẫu khởi động nhanh để làm ví dụ. Nếu bạn sử dụng API Camera2, hãy chụp ảnh ở định dạng
ImageFormat.YUV_420_888
.Nếu bạn sử dụng API Camera cũ hơn, hãy chụp ảnh ở định dạng
ImageFormat.NV21
.