Video karelerindeki nesneleri tespit edip takip etmek için ML Kit'i kullanabilirsiniz.
Makine Öğrenimi Kiti görüntülerini ilettiğinizde, Makine Öğrenimi Kiti her görüntü için algılanan en fazla beş nesne ve bunların görüntüdeki konumlarını içeren bir liste döndürür. Video akışlarında nesneleri algılarken her nesnenin, nesneyi resimler arasında izlemek için kullanabileceğiniz bir kimliği vardır. İsterseniz nesneleri geniş kategori açıklamalarıyla etiketleyen genel nesne sınıflandırmasını da etkinleştirebilirsiniz.
Başlamadan önce
- Henüz yapmadıysanız Firebase'i Android projenize ekleyin.
- Modül (uygulama düzeyinde) Gradle dosyanıza (genellikle
app/build.gradle
) ML Kit Android kitaplıkları için bağımlılıkları 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 tespit etmeye ve izlemeye başlamak için önce FirebaseVisionObjectDetector
örneği oluşturun. İsteğe bağlı olarak, varsayılandan değiştirmek istediğiniz algılayıcı ayarlarını belirtin.
Kullanım alanınıza uygun nesne algılayıcısını bir
FirebaseVisionObjectDetectorOptions
nesnesiyle 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) özelliğinde, nesne algılayıcı düşük gecikmeyle çalışır, ancak algılayıcının ilk birkaç çağrısında eksik sonuçlar (belirtilmemiş sınırlayıcı kutular veya kategori etiketleri gibi) üretebilir. Ayrıca,STREAM_MODE
ürününde algılayıcı nesnelere izleme kimlikleri atar. Bu kimlikleri, nesneleri çerçeveler arasında izlemek için kullanabilirsiniz. Nesneleri izlemek istediğinizde veya video akışlarını gerçek zamanlı olarak işleme gibi düşük gecikmenin önemli olduğu durumlarda bu modu kullanın.SINGLE_IMAGE_MODE
ürününde nesne algılayıcı, sonuç döndürmeden önce algılanan bir nesnenin sınırlayıcı kutusu ve (sınıflandırmayı etkinleştirdiyseniz) kategori etiketinin kullanılabilir olmasını bekler. Bunun sonucunda, algılama gecikmesi potansiyel olarak daha yüksek olur. Ayrıca,SINGLE_IMAGE_MODE
ürününde izleme kimlikleri atanmaz. Gecikme kritik değilse ve kısmi sonuçlarla uğraşmak istemiyorsanız bu modu kullanın.Birden çok nesneyi algılama ve izleme false
(varsayılan) |true
Beşe kadar nesnenin mi yoksa yalnızca en belirgin nesnenin mi algılanıp takip edileceği (varsayılan).
Nesneleri sınıflandırma false
(varsayılan) |true
Algılanan nesnelerin genel kategorilerde sınıflandırılıp sınıflandırılmayacağı. Etkinleştirildiğinde, nesne dedektörü nesneleri şu kategorilere ayırır: moda ürünleri, gıda, ev eşyaları, yerler, bitkiler ve bilinmiyor.
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 takip edilmesi
- Statik görüntüden birden fazla nesnenin algılanması
API'yi bu kullanım alanlarına göre yapılandırmak için:
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+KTX
// 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ği alın:Java
FirebaseVisionObjectDetector objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector(); // Or, to change the default settings: FirebaseVisionObjectDetector objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector(options);
Kotlin+KTX
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ğin processImage()
yöntemine iletin.
Bir dizideki her bir video veya resim karesi için aşağıdakileri yapın:
Resminizden bir
FirebaseVisionImage
nesnesi oluşturun.-
media.Image
nesnesinden birFirebaseVisionImage
nesnesi oluşturmak için (örneğin, bir cihazın kamerasından resim çekerken)media.Image
nesnesini ve resmin dönüşünüFirebaseVisionImage.fromMediaImage()
yönüne geçirin.KameraX kitaplığını kullanırsanız
OnImageCapturedListener
veImageAnalysis.Analyzer
sınıfları rotasyon değerini sizin için hesaplar. Bu nedenle,FirebaseVisionImage.fromMediaImage()
işlevini çağırmadan önce rotasyonu, ML Kit'inROTATION_
sabit değerlerinden 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 // ... } } }
Resmin dönüşünü gösteren bir kamera kitaplığı kullanmıyorsanız cihazın dönüşüne ve cihazdaki kamera sensörünün yönüne göre hesaplama yapabilirsiniz:
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 }
Daha sonra,
media.Image
nesnesini ve döndürme değeriniFirebaseVisionImage.fromMediaImage()
değerine iletin:Java
FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation);
Kotlin+KTX
val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
- Dosya URI'sinden bir
FirebaseVisionImage
nesnesi oluşturmak için uygulama bağlamını ve dosya URI'siniFirebaseVisionImage.fromFilePath()
öğesine iletin. Bu, kullanıcıdan galeri uygulamasından resim seçmesini istemek içinACTION_GET_CONTENT
niyeti kullandığınızda yararlı olur.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() }
- Bir
ByteBuffer
veya bayt dizisindenFirebaseVisionImage
nesnesi oluşturmak için önceliklemedia.Image
girişi için yukarıda açıklandığı gibi görüntü döndürmesini hesaplayın.Ardından resmin yüksekliği, genişliği, 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 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+KTX
val image = FirebaseVisionImage.fromByteBuffer(buffer, metadata) // Or: val image = FirebaseVisionImage.fromByteArray(byteArray, metadata)
Bitmap
nesnesindenFirebaseVisionImage
nesnesi oluşturmak için:Java
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
Kotlin+KTX
val image = FirebaseVisionImage.fromBitmap(bitmap)
Bitmap
nesnesinin temsil ettiği resim, ek döndürme gerekmeden dik olmalıdır.
-
Resmi
processImage()
yöntemine geçirin: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+KTX
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ılı işleyiciyeFirebaseVisionObject
saniyelik bir liste iletilir.Her
FirebaseVisionObject
aşağıdaki özellikleri içerir:Sınırlayıcı kutu Resimdeki nesnenin konumunu gösteren bir Rect
.İzleme Kimliği Nesneyi resimler arasında tanımlayan bir tam sayı. SINGLE_IMAGE_MODE içinde boş değer. Kategori Nesnenin genel kategorisi. Nesne algılayıcıda sınıflandırma etkinleştirilmediyse 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 etkinleştirilmediyse veya nesne bilinmeyen olarak sınıflandırılmışsa bu değer 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+KTX
// 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ılabilirliği ve performansı iyileştirme
En iyi kullanıcı deneyimi için uygulamanızda aşağıdaki yönergelere uyun:
- Nesne algılama işleminin başarılı olması, nesnenin görsel karmaşıklığına bağlıdır. Az sayıda görsel özelliğe sahip nesnelerin algılanması için resmin daha büyük bir kısmını kaplaması gerekebilir. Kullanıcılara, algılamak istediğiniz nesne türleri için iyi sonuç veren girişi yakalama konusunda yol göstermelisiniz.
- Sınıflandırma kullanırken, desteklenen kategorilere uygun olmayan nesneleri tespit etmek istiyorsanız bilinmeyen nesneler için özel işleme uygulayın.
Ayrıca [ML Kit Material Design vitrin uygulaması][showcase-link]{: .external } ve Materyal Tasarım Makine öğrenimi destekli özellikler için kalıplar koleksiyonuna da göz atın.
Akış modunu gerçek zamanlı bir uygulamada kullanırken en iyi kare hızlarına ulaşmak için şu yönergeleri uygulayın:
Çoğu cihaz yeterli kare hızı üretemediğinden akış modunda çoklu nesne algılamayı kullanmayın.
İhtiyacınız yoksa sınıflandırmayı devre dışı bırakın.
- Algılayıcıya yapılan çağrıları hızlandırın. Algılayıcı çalışırken yeni bir video karesi kullanılabilir hale gelirse kareyi bırakın.
- Algılayıcının çıkışını giriş görüntüsüne grafik yerleştirmek için kullanıyorsanız önce ML Kit'ten sonucu alın, ardından görüntüyü oluşturun ve tek bir adımda bindirme yapın. Böylece, her giriş karesi için görüntü yüzeyinde yalnızca bir kez oluşturma yaparsınız.
-
Camera2 API'yi kullanıyorsanız görüntüleri
ImageFormat.YUV_420_888
biçiminde çekin.Eski Kamera API'sini kullanıyorsanız görüntüleri
ImageFormat.NV21
biçiminde çekin.