Detectar y rastrear objetos con ML Kit en Android

Puede utilizar ML Kit para detectar y rastrear objetos en fotogramas de vídeo.

Cuando pasa imágenes de ML Kit, ML Kit devuelve, para cada imagen, una lista de hasta cinco objetos detectados y su posición en la imagen. Al detectar objetos en transmisiones de video, cada objeto tiene una identificación que puede usar para rastrear el objeto en las imágenes. Opcionalmente, también puede habilitar la clasificación aproximada de objetos, que etiqueta los objetos con descripciones de categorías amplias.

Antes de que empieces

  1. Si aún no lo has hecho, agrega Firebase a tu proyecto de Android .
  2. Agregue las dependencias de las bibliotecas de Android ML Kit al archivo Gradle de su módulo (nivel de aplicación) (generalmente 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. Configurar el detector de objetos.

Para comenzar a detectar y rastrear objetos, primero cree una instancia de FirebaseVisionObjectDetector y, opcionalmente, especifique cualquier configuración del detector que desee cambiar respecto a la configuración predeterminada.

  1. Configure el detector de objetos para su caso de uso con un objeto FirebaseVisionObjectDetectorOptions . Puede cambiar las siguientes configuraciones:

    Configuración del detector de objetos
    Modo de detección STREAM_MODE (predeterminado) | SINGLE_IMAGE_MODE

    En STREAM_MODE (predeterminado), el detector de objetos se ejecuta con baja latencia, pero puede producir resultados incompletos (como cuadros delimitadores o etiquetas de categoría no especificados) en las primeras invocaciones del detector. Además, en STREAM_MODE , el detector asigna ID de seguimiento a los objetos, que puedes usar para rastrear objetos a través de fotogramas. Utilice este modo cuando desee realizar un seguimiento de objetos o cuando sea importante una baja latencia, como al procesar secuencias de vídeo en tiempo real.

    En SINGLE_IMAGE_MODE , el detector de objetos espera hasta que el cuadro delimitador de un objeto detectado y (si habilitó la clasificación) la etiqueta de categoría estén disponibles antes de devolver un resultado. Como consecuencia, la latencia de detección es potencialmente mayor. Además, en SINGLE_IMAGE_MODE , los ID de seguimiento no se asignan. Utilice este modo si la latencia no es crítica y no desea lidiar con resultados parciales.

    Detectar y rastrear múltiples objetos false (predeterminado) | true

    Ya sea para detectar y rastrear hasta cinco objetos o solo el objeto más destacado (predeterminado).

    Clasificar objetos false (predeterminado) | true

    Si clasificar o no los objetos detectados en categorías generales. Cuando está habilitado, el detector de objetos clasifica los objetos en las siguientes categorías: artículos de moda, comida, artículos para el hogar, lugares, plantas y desconocidos.

    La API de seguimiento y detección de objetos está optimizada para estos dos casos de uso principales:

    • Detección en vivo y seguimiento del objeto más destacado en el visor de la cámara.
    • Detección de múltiples objetos a partir de una imagen estática.

    Para configurar la API para estos casos de uso:

    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. Obtenga una instancia de FirebaseVisionObjectDetector :

    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. Ejecute el detector de objetos.

Para detectar y rastrear objetos, pase imágenes al método processImage() de la instancia FirebaseVisionObjectDetector .

Para cada fotograma de vídeo o imagen de una secuencia, haga lo siguiente:

  1. Crea un objeto FirebaseVisionImage a partir de tu imagen.

    • Para crear un objeto FirebaseVisionImage a partir de un objeto media.Image , como al capturar una imagen desde la cámara de un dispositivo, pase el objeto media.Image y la rotación de la imagen a FirebaseVisionImage.fromMediaImage() .

      Si usa la biblioteca CameraX , las clases OnImageCapturedListener e ImageAnalysis.Analyzer calculan el valor de rotación por usted, por lo que solo necesita convertir la rotación a una de las constantes ROTATION_ del kit ML antes de llamar 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
                  // ...
              }
          }
      }
      

      Si no utiliza una biblioteca de cámaras que le proporcione la rotación de la imagen, puede calcularla a partir de la rotación del dispositivo y la orientación del sensor de la cámara en el dispositivo:

      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
      }

      Luego, pasa el objeto media.Image y el valor de rotación a FirebaseVisionImage.fromMediaImage() :

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation);

      Kotlin+KTX

      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
    • Para crear un objeto FirebaseVisionImage a partir de un URI de archivo, pase el contexto de la aplicación y el URI del archivo a FirebaseVisionImage.fromFilePath() . Esto es útil cuando usas un intent ACTION_GET_CONTENT para pedirle al usuario que seleccione una imagen de su aplicación de galería.

      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()
      }
    • Para crear un objeto FirebaseVisionImage a partir de un ByteBuffer o una matriz de bytes, primero calcule la rotación de la imagen como se describe anteriormente para la entrada media.Image .

      Luego, crea un objeto FirebaseVisionImageMetadata que contenga la altura, el ancho, el formato de codificación de color y la rotación de la imagen:

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

      Utilice el búfer o matriz y el objeto de metadatos para crear un objeto FirebaseVisionImage :

      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)
    • Para crear un objeto FirebaseVisionImage a partir de un objeto Bitmap :

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      Kotlin+KTX

      val image = FirebaseVisionImage.fromBitmap(bitmap)
      La imagen representada por el objeto Bitmap debe estar en posición vertical, sin necesidad de rotación adicional.
  2. Pase la imagen al método processImage() :

    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. Si la llamada a processImage() tiene éxito, se pasa una lista de FirebaseVisionObject al oyente exitoso.

    Cada FirebaseVisionObject contiene las siguientes propiedades:

    Cuadro delimitador Un Rect que indica la posición del objeto en la imagen.
    ID de rastreo Un número entero que identifica el objeto en las imágenes. Nulo en SINGLE_IMAGE_MODE.
    Categoría La categoría burda del objeto. Si el detector de objetos no tiene la clasificación habilitada, siempre es FirebaseVisionObject.CATEGORY_UNKNOWN .
    Confianza El valor de confianza de la clasificación de objetos. Si el detector de objetos no tiene habilitada la clasificación o el objeto está clasificado como desconocido, esto es 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
    }
    

Mejora de la usabilidad y el rendimiento

Para obtener la mejor experiencia de usuario, siga estas pautas en su aplicación:

  • La detección exitosa de objetos depende de la complejidad visual del objeto. Es posible que los objetos con una pequeña cantidad de características visuales necesiten ocupar una mayor parte de la imagen para ser detectados. Debe proporcionar a los usuarios orientación sobre cómo capturar entradas que funcionen bien con el tipo de objetos que desea detectar.
  • Al utilizar la clasificación, si desea detectar objetos que no encajan claramente en las categorías admitidas, implemente un manejo especial para objetos desconocidos.

Además, consulte la [aplicación de presentación de ML Kit Material Design][showcase-link]{: .external } y la colección de funciones basadas en aprendizaje automático Patrones de diseño de materiales.

Cuando utilice el modo de transmisión en tiempo real en una aplicación, siga estas pautas para lograr las mejores velocidades de fotogramas:

  • No utilices la detección de múltiples objetos en el modo de transmisión, ya que la mayoría de los dispositivos no podrán producir velocidades de fotogramas adecuadas.

  • Desactive la clasificación si no la necesita.

  • Llamadas del acelerador al detector. Si hay un nuevo cuadro de video disponible mientras el detector está en ejecución, suelte el cuadro.
  • Si está utilizando la salida del detector para superponer gráficos en la imagen de entrada, primero obtenga el resultado del ML Kit, luego renderice la imagen y superpóngala en un solo paso. Al hacerlo, renderiza en la superficie de visualización solo una vez por cada cuadro de entrada.
  • Si utiliza la API Camera2, capture imágenes en formato ImageFormat.YUV_420_888 .

    Si utiliza la API de cámara anterior, capture imágenes en formato ImageFormat.NV21 .