Segmentación de temas con ML Kit para Android

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

Función Detalles
Nombre del SDK play-services-mlkit-subject-segmentation
Implementación Sin agrupar: El modelo se descarga de forma dinámica mediante 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 tengan que 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 a 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 al 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 la 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 o solicitas una descarga explícita, el modelo se descarga la primera vez que ejecutas el segmento. 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 en una imagen, crea un objeto InputImage a partir de un Bitmap, media.Image, ByteBuffer, un array de bytes o un archivo ubicado en el dispositivo.

Puedes crear un objeto InputImage a partir de diferentes fuentes; cada una se explica 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 un objeto 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 se representa con un objeto Bitmap junto con los grados de rotación.

2. Crea una instancia de SubjectSegmenter

Define las opciones del segmento.

Para segmentar la 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 detalla 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 fondo.

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

Del mismo modo, también puedes obtener un mapa de bits del objeto 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 temas

Al igual que con las opciones en primer plano, puedes usar SubjectResultOptions para 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

De manera similar, 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()

Cómo crear el segmento de temas

Una vez que especifiques las opciones de SubjectSegmenterOptions, crea una instancia de SubjectSegmenter que llame a getClient() y pasa las opciones como un 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. Obtener el resultado de la segmentación de tema

Recupera máscaras y mapas de bits en primer plano

Una vez procesado, puedes recuperar la máscara en primer plano de tu 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();

Recupera máscaras y mapas de bits para cada tema

De manera similar, para recuperar la máscara de los sujetos segmentados, puedes llamar a getConfidenceMask() en cada sujeto 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 tema 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 crítica, considera llamar a una inferencia "de prueba" 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 × 512 píxeles.
  • Un enfoque de imagen deficiente también puede afectar la precisión. Si no obtienes resultados aceptables, solicita al usuario que vuelva a capturar la imagen.