ML Kit'i kullanarak videonun karelerindeki nesneleri algılayıp takip edebilirsiniz.
ML Kit'e görüntü ilettiğinizde ML Kit, her görüntü için en fazla beş algılanan nesnenin listesini ve görüntüdeki konumlarını döndürür. Video akışlarındaki nesneler algılanırken her nesnenin, nesneyi resimler arasında izlemek için kullanabileceğiniz bir kimliği olur. İsteğe bağlı olarak, nesneleri geniş kategori açıklamalarıyla etiketleyen kaba nesne sınıflandırmasını da etkinleştirebilirsiniz.
Başlamadan önce
- Henüz yapmadıysanız Firebase'i Android projenize ekleyin.
- ML Kit Android kitaplıklarına ait bağımlılıkları modülünüzün (uygulama düzeyinde) Gradle dosyasına (genellikle
app/build.gradle
) ekleyin: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-object-detection-model:19.0.6' }
1. Nesne algılayıcıyı yapılandırma
Nesneleri algılamaya ve izlemeye başlamak için önce FirebaseVisionObjectDetector
örneğini oluşturun. İsteğe bağlı olarak, varsayılandan değiştirmek istediğiniz algılayıcı ayarlarını belirtin.
Nesne algılayıcıyı,
FirebaseVisionObjectDetectorOptions
nesnesiyle kullanım alanınıza göre yapılandırın. Aşağıdaki ayarları değiştirebilirsiniz:Nesne Algılayıcı Ayarları Algılama modu STREAM_MODE
(varsayılan) |SINGLE_IMAGE_MODE
STREAM_MODE
(varsayılan) modunda, nesne algılayıcı düşük gecikmeyle çalışır ancak algılayıcının ilk birkaç çağrısında eksik sonuçlar (ör. belirtilmemiş sınırlayıcı kutular veya kategori etiketleri) üretebilir. Ayrıca,STREAM_MODE
içinde dedektör, nesnelere izleme kimlikleri atar. Bu kimlikleri, nesneleri kareler arasında izlemek için kullanabilirsiniz. Nesneleri izlemek istediğinizde veya düşük gecikmenin önemli olduğu durumlarda (ör. video akışlarını gerçek zamanlı olarak işlerken) bu modu kullanın.SINGLE_IMAGE_MODE
içinde, nesne algılayıcı, algılanan bir nesnenin sınırlayıcı kutusu ve (sınıflandırmayı etkinleştirdiyseniz) kategori etiketi kullanılabilir hale gelene kadar bekler ve ardından bir sonuç döndürür. Bu nedenle, algılama gecikmesi daha yüksek olabilir. AyrıcaSINGLE_IMAGE_MODE
içinde izleme kimlikleri atanmaz. Gecikme kritik değilse ve kısmi sonuçlarla uğraşmak istemiyorsanız bu modu kullanın.Birden fazla nesneyi algılama ve izleme false
(varsayılan) |true
Beş nesneye kadar algılama ve izleme veya yalnızca en belirgin nesneyi algılama ve izleme (varsayılan).
Nesneleri sınıflandırma false
(varsayılan) |true
Algılanan nesnelerin kaba kategorilere sınıflandırılıp sınıflandırılmayacağı. Etkinleştirildiğinde nesne algılayıcı, nesneleri şu kategorilere ayırır: moda ürünleri, yiyecek, ev eşyaları, yerler, bitkiler ve bilinmeyen.
Nesne algılama ve izleme API'si, aşağıdaki iki temel kullanım alanı için optimize edilmiştir:
- Kamera vizöründeki en belirgin nesnenin canlı olarak algılanması ve izlenmesi
- Statik bir görüntüden birden fazla nesne algılama
API'yi bu kullanım alanları için yapılandırmak üzere:
Java
// Live detection and tracking FirebaseVisionObjectDetectorOptions options = new FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE) .enableClassification() // Optional .build(); // Multiple object detection in static images FirebaseVisionObjectDetectorOptions options = new FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() // Optional .build();
Kotlin
// Live detection and tracking val options = FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE) .enableClassification() // Optional .build() // Multiple object detection in static images val options = FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() // Optional .build()
FirebaseVisionObjectDetector
örneğini alma:Java
FirebaseVisionObjectDetector objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector(); // Or, to change the default settings: FirebaseVisionObjectDetector objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector(options);
Kotlin
val objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector() // Or, to change the default settings: val objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector(options)
2. Nesne algılayıcıyı çalıştırma
Nesneleri algılamak ve izlemek için görüntüleri FirebaseVisionObjectDetector
örneğinin processImage()
yöntemine iletin.
Bir dizideki her video veya resim karesi için aşağıdakileri yapın:
Resminizden
FirebaseVisionImage
nesnesi oluşturun.-
Bir
media.Image
nesnesindenFirebaseVisionImage
nesnesi oluşturmak için (ör. bir cihazın kamerasından görüntü yakalarken)media.Image
nesnesini ve görüntünün dönüşünüFirebaseVisionImage.fromMediaImage()
'ye iletin.CameraX kitaplığını kullanıyorsanız
OnImageCapturedListener
veImageAnalysis.Analyzer
sınıfları sizin için döndürme değerini hesaplar. Bu nedenle,FirebaseVisionImage.fromMediaImage()
işlevini çağırmadan önce döndürmeyi 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
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 // ... } } }
Resmin dönüşünü sağlayan bir kamera kitaplığı kullanmıyorsanız, 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
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önüş değeriniFirebaseVisionImage.fromMediaImage()
'ye iletin:Java
FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation);
Kotlin
val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
- Dosya URI'sinden
FirebaseVisionImage
nesnesi oluşturmak için uygulama bağlamını ve dosya URI'siniFirebaseVisionImage.fromFilePath()
'ye iletin. Bu, kullanıcıdan galeri uygulamasından bir resim seçmesini istemek içinACTION_GET_CONTENT
amacını kullandığınızda yararlıdır.Java
FirebaseVisionImage image; try { image = FirebaseVisionImage.fromFilePath(context, uri); } catch (IOException e) { e.printStackTrace(); }
Kotlin
val image: FirebaseVisionImage try { image = FirebaseVisionImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
ByteBuffer
veya bayt dizisindenFirebaseVisionImage
nesnesi oluşturmak için öncemedia.Image
girişi için yukarıda açıklandığı şekilde görüntü döndürme işlemini hesaplayın.Ardından, resmin 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
val metadata = FirebaseVisionImageMetadata.Builder() .setWidth(480) // 480x360 is typically sufficient for .setHeight(360) // image recognition .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) .setRotation(rotation) .build()
Bir
FirebaseVisionImage
nesnesi oluşturmak için arabelleği veya diziyi ve meta veri nesnesini kullanın:Java
FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata); // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata);
Kotlin
val image = FirebaseVisionImage.fromByteBuffer(buffer, metadata) // Or: val image = FirebaseVisionImage.fromByteArray(byteArray, metadata)
FirebaseVisionImage
nesnesindenBitmap
nesnesi oluşturmak için:Java
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
Kotlin
val image = FirebaseVisionImage.fromBitmap(bitmap)
Bitmap
nesnesiyle gösterilen resim dik olmalı ve ek döndürme işlemi gerektirmemelidir.
-
Resmi
processImage()
yöntemine iletin:Java
objectDetector.processImage(image) .addOnSuccessListener( new OnSuccessListener<List<FirebaseVisionObject>>() { @Override public void onSuccess(List<FirebaseVisionObject> detectedObjects) { // Task completed successfully // ... } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Task failed with an exception // ... } });
Kotlin
objectDetector.processImage(image) .addOnSuccessListener { detectedObjects -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
processImage()
çağrısı başarılı olursa başarı dinleyicisineFirebaseVisionObject
listesi iletilir.Her
FirebaseVisionObject
aşağıdaki özellikleri içerir:Sınırlayıcı kutu Nesnenin resimdeki konumunu gösteren bir Rect
.İzleme Kimliği Nesneyi resimler arasında tanımlayan bir tam sayı. Null in SINGLE_IMAGE_MODE. Kategori Nesnenin genel kategorisi. Nesne algılayıcıda sınıflandırma etkin değilse bu değer her zaman FirebaseVisionObject.CATEGORY_UNKNOWN
olur.Güven Nesne sınıflandırmasının güven değeri. Nesne algılayıcıda sınıflandırma etkin değilse veya nesne bilinmeyen olarak sınıflandırılmışsa bu null
olur.Java
// The list of detected objects contains one item if multiple object detection wasn't enabled. for (FirebaseVisionObject obj : detectedObjects) { Integer id = obj.getTrackingId(); Rect bounds = obj.getBoundingBox(); // If classification was enabled: int category = obj.getClassificationCategory(); Float confidence = obj.getClassificationConfidence(); }
Kotlin
// The list of detected objects contains one item if multiple object detection wasn't enabled. for (obj in detectedObjects) { val id = obj.trackingId // A number that identifies the object across images val bounds = obj.boundingBox // The object's position in the image // If classification was enabled: val category = obj.classificationCategory val confidence = obj.classificationConfidence }
Kullanılabilirlik ve performansı iyileştirme
En iyi kullanıcı deneyimi için uygulamanızda aşağıdaki kurallara uyun:
- Başarılı nesne algılama, nesnenin görsel karmaşıklığına bağlıdır. Az sayıda görsel özelliğe sahip nesnelerin algılanması için görüntünün daha büyük bir bölümünü kaplaması gerekebilir. Kullanıcılara, algılamak istediğiniz nesne türleriyle iyi çalışan girişleri yakalama konusunda rehberlik etmelisiniz.
- Sınıflandırma kullanırken desteklenen kategorilere net bir şekilde girmeyen nesneleri algılamak istiyorsanız bilinmeyen nesneler için özel işlem uygulayın.
Ayrıca, [ML Kit Material Design showcase app][showcase-link]{: .external } ve Material Design Patterns for machine learning-powered features koleksiyonuna da göz atın.
Gerçek zamanlı bir uygulamada akış modunu kullanırken en iyi kare hızlarını elde etmek için aşağıdaki yönergeleri uygulayın:
Çoğu cihaz yeterli kare hızını sağlayamayacağından, akış modunda çoklu nesne algılama özelliğini kullanmayın.
İhtiyacınız yoksa sınıflandırmayı devre dışı bırakın.
- Dedektöre yapılan çağrıları sınırlayın. Algılayıcı çalışırken yeni bir video karesi kullanılabilir hale gelirse kareyi bırakın.
- Dedektörün çıkışını giriş resmine grafik yerleştirmek için kullanıyorsanız önce ML Kit'ten sonucu alın, ardından resmi tek adımda oluşturup yerleştirin. Bunu yaptığınızda, her giriş çerçevesi için yalnızca bir kez görüntüleme yüzeyine işleme yaparsınız.
-
Camera2 API'yi kullanıyorsanız
ImageFormat.YUV_420_888
biçiminde resim çekin.Eski Camera API'yi kullanıyorsanız görüntüleri
ImageFormat.NV21
biçiminde çekin.