Segmentación de temas con ML Kit para Android

Usa ML Kit para agregar fácilmente funciones de segmentación de temas a tu app.

Característica Detalles
Nombre del SDK play-services-mlkit-subject-segmentation
Implementación Sin empaquetar: El modelo se descarga de forma dinámica con los Servicios de Google Play.
Impacto del tamaño de la app Aumento de tamaño de ~200 KB.
Hora de inicialización Es posible que los usuarios deban esperar a que el modelo se descargue antes de usarlo por primera vez.

Probar

Antes de comenzar

  1. En tu archivo build.gradle de nivel de proyecto, asegúrate de incluir el repositorio Maven de Google en las secciones buildscript y allprojects.
  2. Agrega la dependencia para la biblioteca de segmentación de temas del ML Kit al archivo Gradle de nivel de la app de tu módulo, que suele ser app/build.gradle:
dependencies {
   implementation 'com.google.android.gms:play-services-mlkit-subject-segmentation:16.0.0-beta1'
}

Como se mencionó anteriormente, los Servicios de Google Play proporcionan el modelo. Puedes configurar tu app para que descargue automáticamente el modelo en el dispositivo después de instalar la app desde Play Store. Para ello, agrega la siguiente declaración al archivo AndroidManifest.xml de tu app:

<application ...>
      ...
      <meta-data
          android:name="com.google.mlkit.vision.DEPENDENCIES"
          android:value="subject_segment" >
      <!-- To use multiple models: android:value="subject_segment,model2,model3" -->
</application>

También puedes verificar explícitamente la disponibilidad del modelo y solicitar su descarga a través de los Servicios de Google Play con la API de ModuleInstallClient.

Si no habilitas las descargas de modelos en el momento de la instalación ni solicitas una descarga explícita, el modelo se descarga la primera vez que ejecutas el segmentador. Las solicitudes que realizas antes de que se complete la descarga no generan resultados.

1. Prepara la imagen de entrada

Para realizar la segmentación de una imagen, crea un objeto InputImage a partir de un Bitmap, una media.Image, un ByteBuffer, un array de bytes o un archivo ubicado en el dispositivo.

Puedes crear un objeto InputImage a partir de diferentes fuentes, que se explican a continuación.

Usa un media.Image

Para crear un objeto InputImage a partir de un objeto media.Image, como cuando capturas una imagen con la cámara de un dispositivo, pasa el objeto media.Image y la rotación de la imagen a InputImage.fromMediaImage().

Si usas la biblioteca CameraX, las clases OnImageCapturedListener y ImageAnalysis.Analyzer calculan el valor de rotación por ti.

Kotlin

private class YourImageAnalyzer : ImageAnalysis.Analyzer {

    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image
        if (mediaImage != null) {
            val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
            // Pass image to an ML Kit Vision API
            // ...
        }
    }
}

Java

private class YourAnalyzer implements ImageAnalysis.Analyzer {

    @Override
    public void analyze(ImageProxy imageProxy) {
        Image mediaImage = imageProxy.getImage();
        if (mediaImage != null) {
          InputImage image =
                InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees());
          // Pass image to an ML Kit Vision API
          // ...
        }
    }
}

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

Kotlin

private val ORIENTATIONS = SparseIntArray()

init {
    ORIENTATIONS.append(Surface.ROTATION_0, 0)
    ORIENTATIONS.append(Surface.ROTATION_90, 90)
    ORIENTATIONS.append(Surface.ROTATION_180, 180)
    ORIENTATIONS.append(Surface.ROTATION_270, 270)
}

/**
 * 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, isFrontFacing: Boolean): 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)

    // Get the device's sensor orientation.
    val cameraManager = activity.getSystemService(CAMERA_SERVICE) as CameraManager
    val sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION)!!

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360
    }
    return rotationCompensation
}

Java

private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
    ORIENTATIONS.append(Surface.ROTATION_0, 0);
    ORIENTATIONS.append(Surface.ROTATION_90, 90);
    ORIENTATIONS.append(Surface.ROTATION_180, 180);
    ORIENTATIONS.append(Surface.ROTATION_270, 270);
}

/**
 * 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, boolean isFrontFacing)
        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);

    // Get the device's sensor orientation.
    CameraManager cameraManager = (CameraManager) activity.getSystemService(CAMERA_SERVICE);
    int sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION);

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360;
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360;
    }
    return rotationCompensation;
}

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

Kotlin

val image = InputImage.fromMediaImage(mediaImage, rotation)

Java

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

Usa un URI de archivo

Para crear un objeto InputImage a partir de un URI de archivo, pasa el contexto de la app y el URI de archivo a InputImage.fromFilePath(). Esto es útil cuando usas un intent ACTION_GET_CONTENT para solicitarle al usuario que seleccione una imagen de su app de galería.

Kotlin

val image: InputImage
try {
    image = InputImage.fromFilePath(context, uri)
} catch (e: IOException) {
    e.printStackTrace()
}

Java

InputImage image;
try {
    image = InputImage.fromFilePath(context, uri);
} catch (IOException e) {
    e.printStackTrace();
}

Usa ByteBuffer o ByteArray

Para crear un objeto InputImage a partir de un objeto ByteBuffer o ByteArray, primero calcula el grado de rotación de la imagen como se describió anteriormente para la entrada media.Image. Luego, crea el objeto InputImage con el búfer o array, junto con la altura, el ancho, el formato de codificación de color y el grado de rotación de la imagen:

Kotlin

val image = InputImage.fromByteBuffer(
        byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
)
// Or:
val image = InputImage.fromByteArray(
        byteArray,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
)

Java

InputImage image = InputImage.fromByteBuffer(byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
);
// Or:
InputImage image = InputImage.fromByteArray(
        byteArray,
        /* image width */480,
        /* image height */360,
        rotation,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
);

Usa un Bitmap

Para crear un objeto InputImage a partir de un objeto Bitmap, realiza la siguiente declaración:

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);

La imagen está representada por un objeto Bitmap junto con los grados de rotación.

2. Crea una instancia de SubjectSegmenter

Define las opciones del segmentador

Para segmentar tu imagen, primero crea una instancia de SubjectSegmenterOptions de la siguiente manera:

Kotlin

val options = SubjectSegmenterOptions.Builder()
       // enable options
       .build()

Java

SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder()
        // enable options
        .build();

A continuación, se muestran los detalles de cada opción:

Máscara de confianza en primer plano

La máscara de confianza en primer plano te permite distinguir el sujeto en primer plano del segundo plano.

Llamar a enableForegroundConfidenceMask() en las opciones te permite recuperar la máscara en primer plano llamando a getForegroundMask() en el objeto SubjectSegmentationResult que se muestra después de procesar la imagen.

Kotlin

val options = SubjectSegmenterOptions.Builder()
        .enableForegroundConfidenceMask()
        .build()

Java

SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder()
        .enableForegroundConfidenceMask()
        .build();
Mapa de bits en primer plano

De manera similar, también puedes obtener un mapa de bits del sujeto en primer plano.

Llamar a enableForegroundBitmap() en las opciones te permite recuperar más tarde el mapa de bits en primer plano llamando a getForegroundBitmap() en el objeto SubjectSegmentationResult que se muestra después de procesar la imagen.

Kotlin

val options = SubjectSegmenterOptions.Builder()
        .enableForegroundBitmap()
        .build()

Java

SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder()
        .enableForegroundBitmap()
        .build();
Máscara de confianza de varios sujetos

Al igual que para las opciones en primer plano, puedes usar SubjectResultOptions a fin de habilitar la máscara de confianza para cada sujeto en primer plano de la siguiente manera:

Kotlin

val subjectResultOptions = SubjectSegmenterOptions.SubjectResultOptions.Builder()
    .enableConfidenceMask()
    .build()

val options = SubjectSegmenterOptions.Builder()
    .enableMultipleSubjects(subjectResultOptions)
    .build()

Java

SubjectResultOptions subjectResultOptions =
        new SubjectSegmenterOptions.SubjectResultOptions.Builder()
            .enableConfidenceMask()
            .build()

SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder()
      .enableMultipleSubjects(subjectResultOptions)
      .build()
Mapa de bits de varios temas

Del mismo modo, puedes habilitar el mapa de bits para cada tema:

Kotlin

val subjectResultOptions = SubjectSegmenterOptions.SubjectResultOptions.Builder()
    .enableSubjectBitmap()
    .build()

val options = SubjectSegmenterOptions.Builder()
    .enableMultipleSubjects(subjectResultOptions)
    .build()

Java

SubjectResultOptions subjectResultOptions =
      new SubjectSegmenterOptions.SubjectResultOptions.Builder()
        .enableSubjectBitmap()
        .build()

SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder()
      .enableMultipleSubjects(subjectResultOptions)
      .build()

Crea el segmentador de tema

Una vez que hayas especificado las opciones de SubjectSegmenterOptions, crea una instancia de SubjectSegmenter que llame a getClient() y pasa las opciones como parámetro:

Kotlin

val segmenter = SubjectSegmentation.getClient(options)

Java

SubjectSegmenter segmenter = SubjectSegmentation.getClient(options);

3. Procesa una imagen

Pasa el objeto InputImage preparado al método process de SubjectSegmenter:

Kotlin

segmenter.process(inputImage)
    .addOnSuccessListener { result ->
        // Task completed successfully
        // ...
    }
    .addOnFailureListener { e ->
        // Task failed with an exception
        // ...
    }

Java

segmenter.process(inputImage)
    .addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(SubjectSegmentationResult result) {
                // Task completed successfully
                // ...
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Task failed with an exception
                // ...
            }
        });

4. Cómo obtener el resultado de la segmentación del tema

Cómo recuperar máscaras y mapas de bits en primer plano

Una vez procesado, puedes recuperar la máscara en primer plano para la imagen llamando a getForegroundConfidenceMask() de la siguiente manera:

Kotlin

val colors = IntArray(image.width * image.height)

val foregroundMask = result.foregroundConfidenceMask
for (i in 0 until image.width * image.height) {
  if (foregroundMask[i] > 0.5f) {
    colors[i] = Color.argb(128, 255, 0, 255)
  }
}

val bitmapMask = Bitmap.createBitmap(
  colors, image.width, image.height, Bitmap.Config.ARGB_8888
)

Java

int[] colors = new int[image.getWidth() * image.getHeight()];

FloatBuffer foregroundMask = result.getForegroundConfidenceMask();
for (int i = 0; i < image.getWidth() * image.getHeight(); i++) {
  if (foregroundMask.get() > 0.5f) {
    colors[i] = Color.argb(128, 255, 0, 255);
  }
}

Bitmap bitmapMask = Bitmap.createBitmap(
      colors, image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888
);

También puedes recuperar un mapa de bits del primer plano de la imagen llamando a getForegroundBitmap():

Kotlin

val foregroundBitmap = result.foregroundBitmap

Java

Bitmap foregroundBitmap = result.getForegroundBitmap();

Recuperar máscaras y mapas de bits de cada tema

De manera similar, puedes recuperar la máscara para los sujetos segmentados si llamas a getConfidenceMask() en cada tema de la siguiente manera:

Kotlin

val subjects = result.subjects

val colors = IntArray(image.width * image.height)
for (subject in subjects) {
  val mask = subject.confidenceMask
  for (i in 0 until subject.width * subject.height) {
    val confidence = mask[i]
    if (confidence > 0.5f) {
      colors[image.width * (subject.startY - 1) + subject.startX] =
          Color.argb(128, 255, 0, 255)
    }
  }
}

val bitmapMask = Bitmap.createBitmap(
  colors, image.width, image.height, Bitmap.Config.ARGB_8888
)

Java

List subjects = result.getSubjects();

int[] colors = new int[image.getWidth() * image.getHeight()];
for (Subject subject : subjects) {
  FloatBuffer mask = subject.getConfidenceMask();
  for (int i = 0; i < subject.getWidth() * subject.getHeight(); i++) {
    float confidence = mask.get();
    if (confidence > 0.5f) {
      colors[width * (subject.getStartY() - 1) + subject.getStartX()]
          = Color.argb(128, 255, 0, 255);
    }
  }
}

Bitmap bitmapMask = Bitmap.createBitmap(
  colors, image.width, image.height, Bitmap.Config.ARGB_8888
);

También puedes acceder al mapa de bits de cada sujeto segmentado de la siguiente manera:

Kotlin

val bitmaps = mutableListOf()
for (subject in subjects) {
  bitmaps.add(subject.bitmap)
}

Java

List bitmaps = new ArrayList<>();
for (Subject subject : subjects) {
  bitmaps.add(subject.getBitmap());
}

Sugerencias para mejorar el rendimiento

Para cada sesión de la app, la primera inferencia suele ser más lenta que las inferencias posteriores debido a la inicialización del modelo. Si la latencia baja es fundamental, considera llamar a una inferencia “ficticia” con anticipación.

La calidad de los resultados depende de la calidad de la imagen de entrada:

  • Para que el Kit de AA obtenga un resultado de segmentación preciso, la imagen debe tener al menos 512 x 512 píxeles.
  • Un enfoque de imagen deficiente también puede afectar la precisión. Si no obtienes resultados aceptables, pídele al usuario que vuelva a capturar la imagen.