Android'de Makine Öğrenimi Kiti ile Nesneleri Tespit Etme ve İzleme

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 en fazla beş algılanan nesne ve bunların resimdeki konumları. Algılarken her nesnenin bir kimliği vardır. Bunları izlemek için nesnelere takılmayın. İsterseniz genel nesneyi de etkinleştirebilirsiniz. geniş kategori tanımlarına sahip nesneleri etiketleyen bir modeldir.

Başlamadan önce

  1. Henüz yapmadıysanız Firebase'i Android projenize ekleyin.
  2. Modülünüze ML Kit Android kitaplıkları için bağımlılıkları ekleyin (uygulama düzeyinde) Gradle dosyası (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-object-detection-model:19.0.6'
    }
    

1. Nesne algılayıcıyı yapılandırma

Nesneleri tespit edip izlemeye başlamak için önce FirebaseVisionObjectDetector (isteğe bağlı olarak, belirlediğiniz tüm algılayıcı ayarlarını) varsayılan değeri değiştirmek istersiniz.

  1. Kullanım alanınıza göre nesne algılayıcıyı FirebaseVisionObjectDetectorOptions nesne algılandı. Şunları değiştirebilirsiniz: Ayarlar:

    Nesne Algılayıcı Ayarları
    Algılama modu STREAM_MODE (varsayılan) | SINGLE_IMAGE_MODE

    STREAM_MODE ürününde (varsayılan) nesne algılayıcısı çalışır düşük gecikme süresi vardır, ancak eksik sonuçlar oluşturabilir (ör. (belirtilmemiş sınırlayıcı kutular veya kategori etiketleri) yer alır. çağrılarına karşılık gelir. Ayrıca STREAM_MODE içinde, algılayıcı, nesnelere izleme kimlikleri atar. Bu kimlikleri çerçevelerde nesneleri izler. YouTube TV'yi izlemek istediğinizde veya veri işleme sırasında olduğu gibi düşük gecikmenin gerçek zamanlı video akışı sağlar.

    SINGLE_IMAGE_MODE konumunda, nesne algılayıcısı bekliyor gelene kadar (etkin değilse) ve sınıflandırma) kategori etiketinin mevcut bir yardımcı olur. Bunun sonucunda, algılama gecikmesi potansiyel olarak daha yüksek olur. Ayrıca, SINGLE_IMAGE_MODE ürününde izleme kimlikleri atanır. Gecikme önemli değilse ve kritik düzeyde değilse bu modu kullanın kısmi sonuçlarla uğraşmanız gerekir.

    Birden çok nesneyi algılama ve izleme false (varsayılan) | true

    Beş adede kadar veya yalnızca en fazla nesne algılayıp takip etme belirgin nesne (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 algılayıcı, nesneleri şu kategoriler: moda ürünleri, gıda, ev eşyaları, yerler, bitkiler ve bilinmeyenler.

    Nesne algılama ve izleme API'si, bu iki temel kullanım için optimize edilmiştir vakalar:

    • Kameradaki en belirgin nesnenin canlı algılanması ve takip edilmesi vizör
    • 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()
    
  2. 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 resimleri FirebaseVisionObjectDetector cihazına iletin örneğin processImage() yöntemini kullanabilirsiniz.

Bir dizideki her bir video veya resim karesi için aşağıdakileri yapın:

  1. Resminizden bir FirebaseVisionImage nesnesi oluşturun.

    • BirFirebaseVisionImage media.Image nesnesi, örneğin bir media.Image nesnesini ve görüntünün FirebaseVisionImage.fromMediaImage() değerine döndürülüyor.

      URL'yi CameraX kitaplığı, OnImageCapturedListener ve ImageAnalysis.Analyzer sınıfları rotasyon değerini hesaplar gerekir, dolayısıyla rotasyonu Makine Öğrenimi Kiti'nin birine dönüştürmeniz Çağrıdan önce ROTATION_ sabit değer FirebaseVisionImage.fromMediaImage():

      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öndürmesini sağlayan bir kamera kitaplığı kullanmıyorsanız cihazın dönüşüne ve kameranın yönüne göre hesaplanabilir cihazdaki sensör:

      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 rotasyon değerini FirebaseVisionImage.fromMediaImage() değerine ayarlayın:

      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'sini FirebaseVisionImage.fromFilePath(). Bu özellik, kullanıcıdan seçim yapmasını istemek için bir ACTION_GET_CONTENT niyeti kullanın galeri uygulamasından bir resim.

      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()
      }
    • BirFirebaseVisionImage ByteBuffer veya bir bayt dizisi, önce görüntüyü hesaplayın media.Image girişi için yukarıda açıklandığı gibi döndürülmesini sağlayın.

      Ardından, bir FirebaseVisionImageMetadata nesnesi oluşturun yüksekliğini, genişliğini, renk kodlaması biçimini ve ve rotasyon:

      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()

      Aşağıdakini oluşturmak için arabelleği veya diziyi ve meta veri nesnesini kullanın: FirebaseVisionImage nesne:

      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)
    • BirFirebaseVisionImage Bitmap nesne:

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      Kotlin+KTX

      val image = FirebaseVisionImage.fromBitmap(bitmap)
      Bitmap nesnesi tarafından temsil edilen resim, dik olmalıdır, ek döndürme gerekmez.
  2. 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
                // ...
            }
    
  3. processImage() çağrısı başarılı olursa FirebaseVisionObject içeren bir liste başarıyla dinleyiciye aktarılır.

    Her FirebaseVisionObject aşağıdaki özellikleri içerir:

    Sınırlayıcı kutu NesneninRect görüntüsüdür.
    İzleme Kimliği Nesneyi resimler arasında tanımlayan bir tam sayı. Boş değer: TEK_IMAGE_MODE.
    Kategori Nesnenin genel kategorisi. Nesne algılayıcı sınıflandırmayı etkinleştirdiyseniz, bu her zaman FirebaseVisionObject.CATEGORY_UNKNOWN
    Güven Nesne sınıflandırmasının güven değeri. Nesne algılayıcının sınıflandırması etkinleştirilmemiş veya nesne bilinmeyen olarak sınıflandırıldı, bu null

    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. Nesneler az sayıda görsel özellikle birlikte kullanılması, resim olarak algılanır. Kullanıcılara, içeriklerinizin yakalanması için iyi çalışan bir girişe sahip olması gerekir.
  • Sınıflandırma kullanırken, düşmeyen nesneleri tespit etmek isterseniz desteklenen kategorilere ayırarak, bilinmeyen kullanıcılar için nesneler'i tıklayın.

Ayrıca, [ML Kit Material Design vitrin uygulaması][showcase-link]{: .external } ve Materyal Tasarım Makine öğrenimi destekli özellikleri içeren kalıplar koleksiyonu.

Gerçek zamanlı bir uygulamada akış modunu kullanırken şu yönergeleri izleyin: en iyi kare hızlarına ulaşın:

  • Çoğu cihaz çalışmayacağından akış modunda çoklu nesne algılamayı kullanmayın. üretebilmesidir.

  • İ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. Yeni bir video karesi kullanılabilir durumdaysa çerçeveyi bırakın.
  • Algılayıcının çıkışını üzerine grafik yerleştirmek için kullanıyorsanız giriş görüntüsünü kullanın, önce ML Kit'ten sonucu alın ve ardından görüntüyü oluşturun tek bir adımda yapabilirsiniz. Bu şekilde, oluşturduğunuz öğeleri ekran yüzeyinde her giriş karesi için yalnızca bir kez.
  • Camera2 API'sini kullanıyorsanız görüntüleri şurada yakalayın: ImageFormat.YUV_420_888 biçimindedir.

    Eski Kamera API'sini kullanıyorsanız görüntüleri şurada yakalayın: ImageFormat.NV21 biçimindedir.