Android용 ML Kit를 사용한 주제 세분화

ML Kit를 사용하여 주제 세분화 기능을 앱에 쉽게 추가할 수 있습니다.

기능 세부정보
SDK 이름 play-services-mlkit-subject-segmentation
구현 번들로 묶이지 않음: 모델이 Google Play 서비스를 사용하여 동적으로 다운로드됩니다.
앱 크기의 영향 크기가 최대 200KB 증가합니다.
초기화 시간 사용자가 처음 사용하기 전에 모델이 다운로드될 때까지 기다려야 할 수도 있습니다.

사용해 보기

  • 샘플 앱을 살펴보고 이 API의 사용 예를 확인합니다.

시작하기 전에

  1. 프로젝트 수준 build.gradle 파일의 buildscriptallprojects 섹션에 Google의 Maven 저장소가 포함되어야 합니다.
  2. 모듈의 앱 수준 Gradle 파일(일반적으로 app/build.gradle)에 ML Kit 주제 세분화 라이브러리의 종속 항목을 추가합니다.
dependencies {
   implementation 'com.google.android.gms:play-services-mlkit-subject-segmentation:16.0.0-beta1'
}

위에서 언급한 것처럼 이 모델은 Google Play 서비스를 통해 제공됩니다. Play 스토어에서 앱을 설치한 후 기기에 모델을 자동으로 다운로드하도록 앱을 구성할 수 있습니다. 이를 위해 앱의 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 서비스를 통해 모델 가용성을 명시적으로 확인하고 다운로드를 요청할 수도 있습니다.

설치 시 모델 다운로드를 사용 설정하지 않거나 명시적 다운로드를 요청하지 않으면 세그멘터를 처음 실행할 때 모델이 다운로드됩니다. 다운로드가 완료되기 전에 요청하면 결과가 생성되지 않습니다.

1. 입력 이미지 준비

이미지를 분할하려면 Bitmap, media.Image, ByteBuffer, 바이트 배열, 기기의 파일에서 InputImage 객체를 만듭니다.

다양한 소스에서 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);

파일 URI 사용

파일 URI에서 InputImage 객체를 만들려면 앱 컨텍스트 및 파일 URI를 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 객체를 SubjectSegmenterprocess 메서드에 전달합니다.

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픽셀 이상이어야 합니다.
  • 이미지 초점이 잘 맞지 않으면 정확도에 영향을 줄 수 있습니다. 허용 가능한 수준의 결과를 얻지 못하면 사용자에게 이미지를 다시 캡처하도록 요청합니다.