Android için ML Kit ile konu segmentasyonu

Uygulamanıza konu segmentasyonu özelliklerini kolayca eklemek için ML Kit'i kullanın.

Özellik Ayrıntılar
SDK adı play-services-mlkit-subject-segmentation
Uygulama Grup halinde değil: Model, Google Play hizmetleri kullanılarak dinamik olarak indirilir.
Uygulama boyutu etkisi Dosya boyutunda yaklaşık 200 KB artış.
Başlatma süresi Kullanıcıların ilk kullanımdan önce modelin indirilmesini beklemesi gerekebilir.

Deneyin

Başlamadan önce

  1. Proje düzeyindeki build.gradle dosyanızda, Google'ın Maven deposunu hem buildscript hem de allprojects bölümlerinize eklediğinizden emin olun.
  2. ML Kit konu segmentasyonu kitaplığı için bağımlılığı, modülünüzün uygulama düzeyindeki Gradle dosyasına ekleyin. Bu dosya genellikle app/build.gradle şeklindedir:
dependencies {
   implementation 'com.google.android.gms:play-services-mlkit-subject-segmentation:16.0.0-beta1'
}

Yukarıda belirtildiği gibi bu model, Google Play Hizmetleri tarafından sağlanmaktadır. Uygulamanızı, Play Store'dan yüklendikten sonra modeli cihaza otomatik olarak indirecek şekilde yapılandırabilirsiniz. Bunu yapmak için aşağıdaki beyanı uygulamanızın AndroidManifest.xml dosyasına ekleyin:

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

Ayrıca, ModuleInstallClient API ile model kullanılabilirliğini açıkça kontrol edebilir ve Google Play hizmetleri üzerinden indirme isteğinde bulunabilirsiniz.

Yükleme zamanı modeli indirmelerini etkinleştirmezseniz veya açık bir şekilde indirme isteğinde bulunmazsanız model, segment oluşturucuyu ilk kez çalıştırdığınızda indirilir. İndirme tamamlanmadan önce yaptığınız istekler hiçbir sonuç vermez.

1. Giriş görüntüsünü hazırlama

Bir görüntü üzerinde segmentasyon yapmak için Bitmap, media.Image, ByteBuffer, bayt dizisi veya cihazdaki bir dosyadan InputImage nesnesi oluşturun.

Farklı kaynaklardan InputImage nesnesi oluşturabilirsiniz. Nesnelerin her biri aşağıda açıklanmıştır.

media.Image kullanılıyor

Bir media.Image nesnesinden InputImage nesnesi oluşturmak için (örneğin, bir cihazın kamerasından resim çekerken) media.Image nesnesini ve resmin dönüşünü InputImage.fromMediaImage() konumuna getirin.

KameraX kitaplığını kullanırsanız OnImageCapturedListener ve ImageAnalysis.Analyzer sınıfları, döndürme değerini sizin için hesaplar.

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
          // ...
        }
    }
}

Resmin dönüş derecesini belirten bir kamera kitaplığı kullanmıyorsanız bunu cihazın döndürme derecesinden ve cihazdaki kamera sensörünün yönüne göre hesaplayabilirsiniz:

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;
}

Daha sonra, media.Image nesnesini ve döndürme derecesi değerini InputImage.fromMediaImage() öğesine iletin:

Kotlin

val image = InputImage.fromMediaImage(mediaImage, rotation)

Java

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

Dosya URI'si kullanma

Dosya URI'sinden InputImage nesnesi oluşturmak için uygulama bağlamını ve dosya URI'sini InputImage.fromFilePath() adresine iletin. Bu, kullanıcıdan galeri uygulamasından bir resim seçmesini istemek için bir ACTION_GET_CONTENT amacı kullandığınızda faydalıdır.

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

ByteBuffer veya ByteArray kullanma

ByteBuffer veya ByteArray öğesinden InputImage nesnesi oluşturmak için önce daha önce media.Image girişi için açıklandığı gibi resim döndürme derecesini hesaplayın. Ardından, InputImage nesnesini resmin yüksekliği, genişliği, renk kodlama biçimi ve döndürme derecesiyle birlikte arabellek veya diziyle oluşturun:

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

Bitmap kullanılıyor

Bir Bitmap nesnesinden InputImage nesnesi oluşturmak için aşağıdaki bildirimi yapın:

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

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

Resim, döndürme dereceleriyle birlikte bir Bitmap nesnesiyle temsil edilir.

2. SubjectSegmenter örneği oluşturun

Segmenter seçeneklerini tanımlayın

Resminizi segmentlere ayırmak için önce aşağıdaki gibi bir SubjectSegmenterOptions örneği oluşturun:

Kotlin

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

Java

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

Aşağıda, her bir seçeneğin ayrıntılarını görebilirsiniz:

Ön plan güven maskesi

Ön plan güven maskesi, ön plandaki özneyi arka plandan ayırt etmenizi sağlar.

Seçeneklerdeki enableForegroundConfidenceMask() çağrısı, daha sonra görüntü işlendikten sonra döndürülen SubjectSegmentationResult nesnesinde getForegroundMask() yöntemini çağırarak ön plan maskesini alabilmenizi sağlar.

Kotlin

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

Java

SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder()
        .enableForegroundConfidenceMask()
        .build();
Ön plan bit eşlemi

Benzer şekilde, ön plan konusunun bit eşlemini de elde edebilirsiniz.

Seçeneklerdeki enableForegroundBitmap() çağrısı, görüntü işlendikten sonra döndürülen SubjectSegmentationResult nesnesinde getForegroundBitmap() yöntemini çağırarak daha sonra ön plan bit eşlemini alabilmenizi sağlar.

Kotlin

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

Java

SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder()
        .enableForegroundBitmap()
        .build();
Çok özneli güven maskesi

Ön plan seçeneklerinde olduğu gibi, her ön plan konusu için güven maskesini aşağıdaki şekilde etkinleştirmek üzere SubjectResultOptions kullanabilirsiniz:

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()
Çok konulu bit eşlem

Benzer şekilde, her bir konu için bit eşlemi etkinleştirebilirsiniz:

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

Konu segmentleyicisini oluşturma

SubjectSegmenterOptions seçeneklerini belirttikten sonra getClient() yöntemini çağıran ve seçenekleri parametre olarak ileten bir SubjectSegmenter örneği oluşturun:

Kotlin

val segmenter = SubjectSegmentation.getClient(options)

Java

SubjectSegmenter segmenter = SubjectSegmentation.getClient(options);

3. Resmi işleme

Hazırlanan InputImage nesnesini SubjectSegmenter process yöntemine geçirin:

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. Konu segmentasyonu sonucunu alma

Ön plan maskelerini ve bit eşlemlerini alma

İşlendikten sonra, getForegroundConfidenceMask() çağrısı yaptığınız resim için ön plan maskesini aşağıdaki şekilde alabilirsiniz:

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

getForegroundBitmap() işlevini çağıran resmin ön planının bit eşlemini de alabilirsiniz:

Kotlin

val foregroundBitmap = result.foregroundBitmap

Java

Bitmap foregroundBitmap = result.getForegroundBitmap();

Her konu için maskeleri ve bit eşlemleri alın

Benzer şekilde, her konu için aşağıdaki şekilde getConfidenceMask() yöntemini çağırarak segmentlere ayrılmış kişilerin maskesini alabilirsiniz:

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

Ayrıca, bölümlendirilmiş her bir konunun bit eşlemine aşağıdaki şekilde erişebilirsiniz:

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

Performansı artırmaya yönelik ipuçları

Her uygulama oturumunda ilk çıkarım, model başlatma nedeniyle sonraki çıkarımlardan genellikle daha yavaştır. Düşük gecikme çok önemliyse önceden "model" çıkarım çağırmayı düşünün.

Sonuçlarınızın kalitesi, giriş görüntüsünün kalitesine bağlıdır:

  • ML Kit'in doğru bir segmentasyon sonucu alabilmesi için görüntü en az 512x512 piksel olmalıdır.
  • Kötü resim odağı, doğruluğu da etkileyebilir. Kabul edilebilir sonuçlar alamazsanız kullanıcıdan resmi yeniden çekmesini isteyin.