Segmentación de temas con ML Kit para Android

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

Función Detalles
Nombre del SDK play-services-mlkit-subject-segmentation
Implementación No agrupada: El modelo se descarga de forma dinámica con los Servicios de Google Play.
Impacto en el 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 se descargue el modelo 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 de Maven de Google en las secciones buildscript y allprojects.
  2. Agrega la dependencia de la biblioteca de segmentación de temas del Kit de AA 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, el modelo lo proporcionan los Servicios de Google Play. Puedes configurar tu app para que descargue automáticamente el modelo en el dispositivo después de que se instale 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 la descarga explícita, el modelo se descargará la primera vez que ejecutes el segmentador. Las solicitudes que realices antes de que se complete la descarga no producirán resultados.

1. Prepara la imagen de entrada

Para realizar la segmentación en 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 InputImage objeto a partir de diferentes fuentes, cada una de las cuales se explica a continuación.

Usa un media.Image

Para crear un InputImage objeto a partir de un objeto media.Image, como cuando capturas una imagen desde 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 de 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ámara que te proporcione el grado de rotación de la imagen, puedes calcularlo 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 del 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 InputImage objeto 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 ByteBuffer o ByteArray

Para crear un InputImage objeto a partir de un ByteBuffer o un 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 el 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, haz 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 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();

Aquí están 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 tema en primer plano del fondo.

Llamar a enableForegroundConfidenceMask() en las opciones te permite recuperar más tarde 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 tema 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 para las opciones en primer plano, puedes usar SubjectResultOptions para habilitar la máscara de confianza para cada tema 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 temas

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

Kotlin

val segmenter = SubjectSegmentation.getClient(options)

Java

SubjectSegmenter segmenter = SubjectSegmentation.getClient(options);

3. Procesa una imagen

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

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. Obtén el resultado de la segmentación de temas

Recupera máscaras y mapas de bits en primer plano

Una vez procesada, 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

Del mismo modo, puedes recuperar la máscara de los temas segmentados llamando 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 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 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 ML Kit 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 exactitud. Si no obtienes resultados aceptables, pídele al usuario que vuelva a capturar la imagen.