Usa el Kit de AA para agregar fácilmente funciones de segmentación de sujetos a tu app.
Función | Detalles |
---|---|
Nombre del SDK | play-services-mlkit-subject-segmentation |
Implementación | Sin paquetes: 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 alrededor 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
- Prueba la app de ejemplo para ver un ejemplo de uso de esta API.
Antes de comenzar
- En tu archivo
build.gradle
a nivel de proyecto, asegúrate de incluir el repositorio Maven de Google en las seccionesbuildscript
yallprojects
. - Agrega la dependencia para la biblioteca de segmentación de sujetos de 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, el modelo es proporcionado por los Servicios de Google Play.
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 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 descargará la primera vez que ejecutes el segmentador. Las solicitudes que realices antes de que se complete la descarga no generarán ningún resultado.
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 se captura 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.
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 // ... } } }
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 de la rotación del dispositivo y la orientación del sensor de la cámara en el dispositivo:
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 }
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()
:
val image = InputImage.fromMediaImage(mediaImage, rotation)
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 del 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.
val image: InputImage try { image = InputImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
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 ByteBuffer
o un ByteArray
, primero calcula el grado de rotación de la imagen como se describió anteriormente en 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:
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 )
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:
val image = InputImage.fromBitmap(bitmap, 0)
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:
val options = SubjectSegmenterOptions.Builder() // enable options .build()
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 del primer plano te permite distinguir el sujeto del primer plano del fondo.
Llamar a enableForegroundConfidenceMask()
en las opciones te permite recuperar más adelante la máscara de primer plano llamando a getForegroundMask()
en el objeto SubjectSegmentationResult
que se muestra después de procesar la imagen.
val options = SubjectSegmenterOptions.Builder() .enableForegroundConfidenceMask() .build()
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 sujeto en primer plano.
Llamar a enableForegroundBitmap()
en las opciones te permite recuperar más adelante el mapa de bits en primer plano llamando a getForegroundBitmap()
en el objeto SubjectSegmentationResult
que se muestra después de procesar la imagen.
val options = SubjectSegmenterOptions.Builder() .enableForegroundBitmap() .build()
SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableForegroundBitmap() .build();
Máscara de confianza de varios sujetos
Al igual que con las opciones de primer plano, puedes usar SubjectResultOptions
para habilitar
la máscara de confianza para cada sujeto en primer plano de la siguiente manera:
val subjectResultOptions = SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableConfidenceMask() .build() val options = SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
SubjectResultOptions subjectResultOptions = new SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableConfidenceMask() .build() SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
Mapa de bits de varios sujetos
Del mismo modo, puedes habilitar el mapa de bits para cada sujeto:
val subjectResultOptions = SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableSubjectBitmap() .build() val options = SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
SubjectResultOptions subjectResultOptions = new SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableSubjectBitmap() .build() SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
Crea el segmentador de asuntos
Una vez que especifiques las opciones de SubjectSegmenterOptions
, crea una instancia de SubjectSegmenter
llamando a getClient()
y pasando las opciones como parámetro:
val segmenter = SubjectSegmentation.getClient(options)
SubjectSegmenter segmenter = SubjectSegmentation.getClient(options);
3. Procesa una imagen
Pasa el objeto InputImage
preparado al método process
de SubjectSegmenter
:
segmenter.process(inputImage) .addOnSuccessListener { result -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
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 sujetos
Cómo recuperar máscaras de primer plano y mapas de bits
Una vez que se procese, puedes recuperar la máscara de primer plano de tu imagen llamando a
getForegroundConfidenceMask()
de la siguiente manera:
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 )
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()
:
val foregroundBitmap = result.foregroundBitmap
Bitmap foregroundBitmap = result.getForegroundBitmap();
Cómo recuperar máscaras y mapas de bits para cada sujeto
De manera similar, puedes recuperar la máscara de los sujetos segmentados llamando a getConfidenceMask()
en cada sujeto de la siguiente manera:
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 )
Listsubjects = 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:
val bitmaps = mutableListOf() for (subject in subjects) { bitmaps.add(subject.bitmap) }
Listbitmaps = 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 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.