AutoML Vision Edge'i kullanarak kendi modelinizi eğittikten sonra, bunu uygulamanızda görüntüleri etiketlemek için kullanabilirsiniz.
Sen başlamadan önce
- Henüz yapmadıysanız Android projenize Firebase'i ekleyin .
- ML Kit Android kitaplıklarının bağımlılıklarını modülünüze (uygulama düzeyinde) Gradle dosyasına ekleyin (genellikle
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-automl:18.0.5' }
1. Modeli yükleyin
ML Kit, AutoML tarafından oluşturulan modellerinizi cihazda çalıştırır. Ancak ML Kit'i modelinizi uzaktan Firebase'den, yerel depolamadan veya her ikisinden yükleyecek şekilde yapılandırabilirsiniz.
Modeli Firebase'de barındırarak, yeni bir uygulama sürümü yayınlamadan modeli güncelleyebilir ve farklı modelleri farklı kullanıcı gruplarına dinamik olarak sunmak için Uzaktan Yapılandırma ve A/B Testini kullanabilirsiniz.
Modeli yalnızca Firebase'de barındırarak sağlamayı ve uygulamanızla birlikte paketlememeyi seçerseniz uygulamanızın ilk indirme boyutunu azaltabilirsiniz. Ancak, model uygulamanızla birlikte paketlenmemişse, uygulamanız modeli ilk kez indirene kadar modelle ilgili herhangi bir işlevin kullanılamayacağını unutmayın.
Modelinizi uygulamanızla birlikte paketleyerek, Firebase tarafından barındırılan model mevcut olmadığında uygulamanızın makine öğrenimi özelliklerinin çalışmaya devam etmesini sağlayabilirsiniz.
Firebase tarafından barındırılan bir model kaynağı yapılandırma
Uzaktan barındırılan modeli kullanmak için, modeli yayınlarken atadığınız adı belirterek bir FirebaseAutoMLRemoteModel
nesnesi oluşturun:
Java
// Specify the name you assigned in the Firebase console.
FirebaseAutoMLRemoteModel remoteModel =
new FirebaseAutoMLRemoteModel.Builder("your_remote_model").build();
Kotlin+KTX
// Specify the name you assigned in the Firebase console.
val remoteModel = FirebaseAutoMLRemoteModel.Builder("your_remote_model").build()
Ardından, indirmeye izin vermek istediğiniz koşulları belirterek model indirme görevini başlatın. Model cihazda yoksa veya modelin daha yeni bir sürümü mevcutsa görev, modeli Firebase'den eşzamansız olarak indirir:
Java
FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder()
.requireWifi()
.build();
FirebaseModelManager.getInstance().download(remoteModel, conditions)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// Success.
}
});
Kotlin+KTX
val conditions = FirebaseModelDownloadConditions.Builder()
.requireWifi()
.build()
FirebaseModelManager.getInstance().download(remoteModel, conditions)
.addOnCompleteListener {
// Success.
}
Çoğu uygulama, indirme görevini kendi başlatma kodunda başlatır, ancak bunu, modeli kullanmanız gerekmeden önce herhangi bir noktada yapabilirsiniz.
Yerel bir model kaynağı yapılandırma
Modeli uygulamanızla paketlemek için:
- Modeli ve meta verilerini Firebase konsolundan indirdiğiniz zip arşivinden çıkarın. Dosyaları indirdiğiniz gibi, değişiklik yapmadan (dosya adları dahil) kullanmanızı öneririz.
Modelinizi ve meta veri dosyalarını uygulama paketinize ekleyin:
- Projenizde varlıklar klasörünüz yoksa,
app/
klasöre sağ tıklayıp ardından Yeni > Klasör > Varlıklar Klasörü seçeneğine tıklayarak bir tane oluşturun. - Model dosyalarını içerecek varlıklar klasörünün altında bir alt klasör oluşturun.
-
model.tflite
,dict.txt
vemanifest.json
dosyalarını alt klasöre kopyalayın (üç dosyanın tümü aynı klasörde olmalıdır).
- Projenizde varlıklar klasörünüz yoksa,
- Gradle'ın uygulamayı oluştururken model dosyasını sıkıştırmadığından emin olmak için uygulamanızın
build.gradle
dosyasına aşağıdakini ekleyin:android { // ... aaptOptions { noCompress "tflite" } }
Model dosyası, uygulama paketine dahil edilecek ve ham varlık olarak ML Kit'e sunulacak. - Model bildirim dosyasının yolunu belirterek bir
FirebaseAutoMLLocalModel
nesnesi oluşturun:Java
FirebaseAutoMLLocalModel localModel = new FirebaseAutoMLLocalModel.Builder() .setAssetFilePath("manifest.json") .build();
Kotlin+KTX
val localModel = FirebaseAutoMLLocalModel.Builder() .setAssetFilePath("manifest.json") .build()
Modelinizden bir görüntü etiketleyici oluşturun
Model kaynaklarınızı yapılandırdıktan sonra bunlardan birinden FirebaseVisionImageLabeler
nesnesi oluşturun.
Yalnızca yerel olarak paketlenmiş bir modeliniz varsa FirebaseAutoMLLocalModel
nesnenizden bir etiketleyici oluşturmanız ve gerek duymak istediğiniz güven puanı eşiğini yapılandırmanız yeterlidir (bkz . Modelinizi değerlendirin ):
Java
FirebaseVisionImageLabeler labeler;
try {
FirebaseVisionOnDeviceAutoMLImageLabelerOptions options =
new FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(localModel)
.setConfidenceThreshold(0.0f) // Evaluate your model in the Firebase console
// to determine an appropriate value.
.build();
labeler = FirebaseVision.getInstance().getOnDeviceAutoMLImageLabeler(options);
} catch (FirebaseMLException e) {
// ...
}
Kotlin+KTX
val options = FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(localModel)
.setConfidenceThreshold(0) // Evaluate your model in the Firebase console
// to determine an appropriate value.
.build()
val labeler = FirebaseVision.getInstance().getOnDeviceAutoMLImageLabeler(options)
Uzaktan barındırılan bir modeliniz varsa, çalıştırmadan önce indirilip indirilmediğini kontrol etmeniz gerekecektir. Model yöneticisinin isModelDownloaded()
yöntemini kullanarak model indirme görevinin durumunu kontrol edebilirsiniz.
Etiketleyiciyi çalıştırmadan önce bunu yalnızca onaylamanız gerekse de, hem uzaktan barındırılan bir modeliniz hem de yerel olarak paketlenmiş bir modeliniz varsa, görüntü etiketleyiciyi başlatırken bu kontrolü gerçekleştirmek mantıklı olabilir: eğer uzak modelden bir etiketleyici oluşturun indirilmiştir ve aksi takdirde yerel modelden indirilmiştir.
Java
FirebaseModelManager.getInstance().isModelDownloaded(remoteModel)
.addOnSuccessListener(new OnSuccessListener<Boolean>() {
@Override
public void onSuccess(Boolean isDownloaded) {
FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder optionsBuilder;
if (isDownloaded) {
optionsBuilder = new FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(remoteModel);
} else {
optionsBuilder = new FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(localModel);
}
FirebaseVisionOnDeviceAutoMLImageLabelerOptions options = optionsBuilder
.setConfidenceThreshold(0.0f) // Evaluate your model in the Firebase console
// to determine an appropriate threshold.
.build();
FirebaseVisionImageLabeler labeler;
try {
labeler = FirebaseVision.getInstance().getOnDeviceAutoMLImageLabeler(options);
} catch (FirebaseMLException e) {
// Error.
}
}
});
Kotlin+KTX
FirebaseModelManager.getInstance().isModelDownloaded(remoteModel)
.addOnSuccessListener { isDownloaded ->
val optionsBuilder =
if (isDownloaded) {
FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(remoteModel)
} else {
FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(localModel)
}
// Evaluate your model in the Firebase console to determine an appropriate threshold.
val options = optionsBuilder.setConfidenceThreshold(0.0f).build()
val labeler = FirebaseVision.getInstance().getOnDeviceAutoMLImageLabeler(options)
}
Yalnızca uzaktan barındırılan bir modeliniz varsa, modelin indirildiğini onaylayana kadar modelle ilgili işlevleri (örneğin, kullanıcı arayüzünüzün grileştirilmesi veya bir kısmının gizlenmesi) devre dışı bırakmalısınız. Bunu, model yöneticisinin download()
yöntemine bir dinleyici ekleyerek yapabilirsiniz:
Java
FirebaseModelManager.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+KTX
FirebaseModelManager.getInstance().download(remoteModel, conditions)
.addOnCompleteListener {
// Download complete. Depending on your app, you could enable the ML
// feature, or switch from the local model to the remote model, etc.
}
2. Giriş görüntüsünü hazırlayın
Ardından, etiketlemek istediğiniz her görüntü için bu bölümde açıklanan seçeneklerden birini kullanarak bir FirebaseVisionImage
nesnesi oluşturun ve bunu bir FirebaseVisionImageLabeler
örneğine (sonraki bölümde anlatılacaktır) aktarın.
Bir media.Image
nesnesinden, cihazdaki bir dosyadan, bir bayt dizisinden veya bir Bitmap
nesnesinden FirebaseVisionImage
nesnesi oluşturabilirsiniz:
Bir
media.Image
nesnesinden birFirebaseVisionImage
nesnesi oluşturmak için (örneğin, bir cihazın kamerasından bir görüntü yakalarken),media.Image
nesnesini ve görüntünün dönüşünüFirebaseVisionImage.fromMediaImage()
öğesine iletin.CameraX kitaplığını kullanıyorsanız
OnImageCapturedListener
veImageAnalysis.Analyzer
sınıfları sizin için dönüş değerini hesaplar; dolayısıylaFirebaseVisionImage.fromMediaImage()
çağırmadan önce dönüşü ML Kit'inROTATION_
sabitlerinden birine dönüştürmeniz yeterlidir: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 // ... } } }
Görüntünün dönüşünü sağlayan bir kamera kitaplığı kullanmıyorsanız, bunu cihazın dönüşünden ve cihazdaki kamera sensörünün yönünden hesaplayabilirsiniz:
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 }
Ardından
media.Image
nesnesini ve döndürme değeriniFirebaseVisionImage.fromMediaImage()
öğesine iletin:Java
FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation);
Kotlin+KTX
val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
- Bir dosya URI'sından
FirebaseVisionImage
nesnesi oluşturmak için uygulama içeriğini ve dosya URI'siniFirebaseVisionImage.fromFilePath()
öğesine iletin. Kullanıcıdan galeri uygulamasından bir resim seçmesini istemek içinACTION_GET_CONTENT
amacını kullandığınızda bu kullanışlıdır.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() }
-
ByteBuffer
veya bayt dizisinden birFirebaseVisionImage
nesnesi oluşturmak için, önceliklemedia.Image
girişi için yukarıda açıklandığı gibi görüntü döndürmeyi hesaplayın.Ardından görüntünün yüksekliğini, genişliğini, renk kodlama biçimini ve dönüşünü içeren bir
FirebaseVisionImageMetadata
nesnesi oluşturun: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
nesnesi oluşturmak için tamponu veya diziyi ve meta veri nesnesini kullanın: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)
- Bir
Bitmap
nesnesindenFirebaseVisionImage
nesnesi oluşturmak için:Java
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
Kotlin+KTX
val image = FirebaseVisionImage.fromBitmap(bitmap)
Bitmap
nesnesi tarafından temsil edilen görüntü, ek bir döndürme gerekmeden dik olmalıdır.
3. Görüntü etiketleyiciyi çalıştırın
Bir görüntüdeki nesneleri etiketlemek için FirebaseVisionImage
nesnesini FirebaseVisionImageLabeler
processImage()
yöntemine iletin.
Java
labeler.processImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionImageLabel>>() {
@Override
public void onSuccess(List<FirebaseVisionImageLabel> labels) {
// Task completed successfully
// ...
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
}
});
Kotlin+KTX
labeler.processImage(image)
.addOnSuccessListener { labels ->
// Task completed successfully
// ...
}
.addOnFailureListener { e ->
// Task failed with an exception
// ...
}
Görüntü etiketleme başarılı olursa, başarı dinleyicisine bir dizi FirebaseVisionImageLabel
nesnesi iletilecektir. Her nesneden görüntüde tanınan bir özellik hakkında bilgi alabilirsiniz.
Örneğin:
Java
for (FirebaseVisionImageLabel label: labels) {
String text = label.getText();
float confidence = label.getConfidence();
}
Kotlin+KTX
for (label in labels) {
val text = label.text
val confidence = label.confidence
}
Gerçek zamanlı performansı artırmaya yönelik ipuçları
- Gaz kelebeği dedektöre çağrı yapar. Dedektör çalışırken yeni bir video karesi kullanılabilir hale gelirse kareyi bırakın.
- Giriş görüntüsü üzerine grafikleri yerleştirmek için dedektörün çıkışını kullanıyorsanız, önce ML Kit'ten sonucu alın, ardından tek adımda görüntüyü işleyin ve üst üste koyun. Bunu yaparak, her giriş karesi için ekran yüzeyini yalnızca bir kez görüntüleyebilirsiniz.
Camera2 API'sini kullanıyorsanız görüntüleri
ImageFormat.YUV_420_888
formatında yakalayın.Eski Kamera API'sini kullanıyorsanız görüntüleri
ImageFormat.NV21
formatında yakalayın.