Android के लिए ML किट की मदद से, चीज़ों को अलग-अलग ग्रुप में बांटना

अपने ऐप्लिकेशन में सब्जेक्ट सेगमेंटेशन की सुविधाएं आसानी से जोड़ने के लिए, ML Kit का इस्तेमाल करें.

सुविधा जानकारी
एसडीके का नाम play-services-mlkit-subject-segmentation
लागू करना अनबंडल: Google Play services का इस्तेमाल करके, मॉडल को डाइनैमिक तरीके से डाउनलोड किया जाता है.
ऐप्लिकेशन के साइज़ का असर साइज़ में करीब 200 केबी की बढ़ोतरी.
शुरू होने में लगने वाला समय पहली बार इस्तेमाल करने से पहले, उपयोगकर्ताओं को मॉडल डाउनलोड होने का इंतज़ार करना पड़ सकता है.

इसे आज़माएं

शुरू करने से पहले

  1. प्रोजेक्ट-लेवल की build.gradle फ़ाइल में, buildscript और allprojects, दोनों सेक्शन में Google की Maven रिपॉज़िटरी को शामिल करना न भूलें.
  2. अपने मॉड्यूल की ऐप्लिकेशन-लेवल की gradle फ़ाइल में, ML Kit की सब्जेक्ट सेगमेंटेशन लाइब्रेरी के लिए डिपेंडेंसी जोड़ें. यह फ़ाइल आम तौर पर app/build.gradle होती है:
dependencies {
   implementation 'com.google.android.gms:play-services-mlkit-subject-segmentation:16.0.0-beta1'
}

जैसा कि ऊपर बताया गया है, यह मॉडल Google Play services उपलब्ध कराता है. अपने ऐप्लिकेशन को इस तरह कॉन्फ़िगर किया जा सकता है कि Play Store से ऐप्लिकेशन इंस्टॉल होने के बाद, मॉडल डिवाइस पर अपने-आप डाउनलोड हो जाए. इसके लिए, अपने ऐप्लिकेशन की AndroidManifest.xml फ़ाइल में यह एलान जोड़ें:

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

ModuleInstallClient API की मदद से, Google Play services के ज़रिए मॉडल की उपलब्धता की जांच की जा सकती है और उसे डाउनलोड करने का अनुरोध किया जा सकता है.

अगर आपने इंस्टॉल के समय मॉडल डाउनलोड करने की सुविधा चालू नहीं की है या साफ़ तौर पर डाउनलोड करने का अनुरोध नहीं किया है, तो सेगमेंटर को पहली बार चलाने पर मॉडल डाउनलोड हो जाता है. डाउनलोड पूरा होने से पहले किए गए अनुरोधों के नतीजे नहीं मिलते.

1. इनपुट इमेज तैयार करना

किसी इमेज को सेगमेंट में बांटने के लिए, InputImage ऑब्जेक्ट बनाएं. इसके लिए, Bitmap, media.Image, ByteBuffer, बाइट कलेक्शन या डिवाइस पर मौजूद किसी फ़ाइल का इस्तेमाल करें.

InputImage ऑब्जेक्ट को अलग-अलग सोर्स से बनाया जा सकता है. हर सोर्स के बारे में यहां बताया गया है.

media.Image का इस्तेमाल करके

media.Image ऑब्जेक्ट से InputImage ऑब्जेक्ट बनाने के लिए, media.Image ऑब्जेक्ट और इमेज के रोटेशन को InputImage.fromMediaImage() में पास करें. जैसे, किसी डिवाइस के कैमरे से इमेज कैप्चर करते समय.

अगर CameraX लाइब्रेरी का इस्तेमाल किया जाता है, तो OnImageCapturedListener और ImageAnalysis.Analyzer क्लास, आपके लिए रोटेशन वैल्यू का हिसाब लगाती हैं.

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

अगर ऐसी कैमरा लाइब्रेरी का इस्तेमाल नहीं किया जाता है जो आपको इमेज के रोटेशन की डिग्री देती है, तो डिवाइस के रोटेशन की डिग्री और डिवाइस में कैमरा सेंसर के ओरिएंटेशन से इसका हिसाब लगाया जा सकता है:

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

इसके बाद, media.Image ऑब्जेक्ट और रोटेशन डिग्री की वैल्यू को InputImage.fromMediaImage() में पास करें:

Kotlin

val image = InputImage.fromMediaImage(mediaImage, rotation)

Java

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

फ़ाइल यूआरआई का इस्तेमाल करना

फ़ाइल यूआरआई से InputImage ऑब्जेक्ट बनाने के लिए, ऐप्लिकेशन कॉन्टेक्स्ट और फ़ाइल यूआरआई को InputImage.fromFilePath() में पास करें. यह तब काम आता है, जब ACTION_GET_CONTENT इंटेंट का इस्तेमाल करके, उपयोगकर्ता को उसके गैलरी ऐप्लिकेशन से कोई इमेज चुनने के लिए कहा जाता है.

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 या ByteArray का इस्तेमाल करना

ByteBuffer या ByteArray से InputImage ऑब्जेक्ट बनाने के लिए, पहले इमेज के रोटेशन की डिग्री का हिसाब लगाएं. इसके बारे में, media.Image इनपुट के लिए पहले बताया गया है. इसके बाद, बफ़र या कलेक्शन के साथ InputImage ऑब्जेक्ट बनाएं. साथ ही, इमेज की ऊंचाई, चौड़ाई, कलर एन्कोडिंग फ़ॉर्मैट, और रोटेशन डिग्री भी जोड़ें:

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 का इस्तेमाल करके

Bitmap ऑब्जेक्ट से InputImage ऑब्जेक्ट बनाने के लिए, यह एलान करें:

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

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

इमेज को Bitmap ऑब्जेक्ट और रोटेशन डिग्री के साथ दिखाया जाता है.

2. SubjectSegmenter का इंस्टेंस बनाना

सेगमेंट करने के विकल्प तय करना

अपनी इमेज को सेगमेंट में बांटने के लिए, सबसे पहले SubjectSegmenterOptions का एक इंस्टेंस बनाएं. इसके लिए, यह तरीका अपनाएं:

Kotlin

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

Java

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

यहां हर विकल्प के बारे में जानकारी दी गई है:

फ़ोरग्राउंड कॉन्फ़िडेंस मास्क

फ़ोरग्राउंड कॉन्फ़िडेंस मास्क की मदद से, फ़ोरग्राउंड में मौजूद सब्जेक्ट को बैकग्राउंड से अलग किया जा सकता है.

विकल्पों में enableForegroundConfidenceMask() को कॉल करने से, इमेज को प्रोसेस करने के बाद मिले SubjectSegmentationResult ऑब्जेक्ट पर getForegroundMask() को कॉल करके, फ़ोरग्राउंड मास्क को बाद में वापस लाया जा सकता है.

Kotlin

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

Java

SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder()
        .enableForegroundConfidenceMask()
        .build();
फ़ोरग्राउंड बिट मैप

इसी तरह, फ़ोरग्राउंड सब्जेक्ट का बिटमैप भी पाया जा सकता है.

विकल्पों में enableForegroundBitmap() को कॉल करने से, इमेज को प्रोसेस करने के बाद दिखाए गए SubjectSegmentationResult ऑब्जेक्ट पर getForegroundBitmap() को कॉल करके, फ़ोरग्राउंड बिट मैप को बाद में वापस लाया जा सकता है.

Kotlin

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

Java

SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder()
        .enableForegroundBitmap()
        .build();
एक से ज़्यादा सब्जेक्ट के लिए कॉन्फ़िडेंस मास्क

फ़ोरग्राउंड के विकल्पों की तरह ही, हर फ़ोरग्राउंड सब्जेक्ट के लिए कॉन्फ़िडेंस मास्क को चालू करने के लिए, SubjectResultOptions का इस्तेमाल किया जा सकता है. इसके लिए, यह तरीका अपनाएं:

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()
एक से ज़्यादा सब्जेक्ट वाला बिट मैप

इसी तरह, हर विषय के लिए बिट मैप को चालू किया जा सकता है:

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

सब्जेक्ट सेगमेंटर बनाएं

SubjectSegmenterOptions विकल्प तय करने के बाद, getClient() को कॉल करने वाला SubjectSegmenter इंस्टेंस बनाएं और विकल्पों को पैरामीटर के तौर पर पास करें:

Kotlin

val segmenter = SubjectSegmentation.getClient(options)

Java

SubjectSegmenter segmenter = SubjectSegmentation.getClient(options);

3. किसी इमेज को प्रोसेस करना

तैयार किए गए InputImage ऑब्जेक्ट को SubjectSegmenter के 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. सब्जेक्ट सेगमेंटेशन का नतीजा पाना

फ़ोरग्राउंड मास्क और बिटमैप वापस पाना

प्रोसेस होने के बाद, getForegroundConfidenceMask() को कॉल करके अपनी इमेज के लिए फ़ोरग्राउंड मास्क को वापस पाया जा सकता है. इसके लिए, यह तरीका अपनाएं:

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() को कॉल करके, इमेज के फ़ोरग्राउंड का बिटमैप भी वापस पाया जा सकता है:

Kotlin

val foregroundBitmap = result.foregroundBitmap

Java

Bitmap foregroundBitmap = result.getForegroundBitmap();

हर सब्जेक्ट के लिए मास्क और बिटमैप वापस पाना

इसी तरह, सेगमेंट किए गए सब्जेक्ट के लिए मास्क को वापस लाया जा सकता है. इसके लिए, हर सब्जेक्ट पर getConfidenceMask() को इस तरह कॉल करें:

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

अलग-अलग सेगमेंट में बांटे गए हर सब्जेक्ट का बिटमैप भी ऐक्सेस किया जा सकता है. इसके लिए, यह तरीका अपनाएं:

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

परफ़ॉर्मेंस को बेहतर बनाने के लिए सलाह

हर ऐप्लिकेशन सेशन के लिए, पहला अनुमान अक्सर बाद के अनुमानों की तुलना में धीमा होता है. ऐसा मॉडल के शुरू होने की वजह से होता है. अगर कम इंतज़ार का समय ज़रूरी है, तो समय से पहले "डमी" अनुमान को कॉल करें.

नतीजों की क्वालिटी, इनपुट इमेज की क्वालिटी पर निर्भर करती है:

  • ML Kit को सटीक सेगमेंटेशन नतीजे पाने के लिए, इमेज कम से कम 512x512 पिक्सल की होनी चाहिए.
  • इमेज का फ़ोकस खराब होने से भी, सटीक नतीजे मिलने पर असर पड़ सकता है. अगर आपको सही नतीजे नहीं मिलते हैं, तो उपयोगकर्ता से इमेज को फिर से कैप्चर करने के लिए कहें.