Android에서 커스텀 모델을 사용하여 이미지 라벨 지정

ML Kit를 사용하면 이미지 속 항목을 인식하고 라벨을 지정할 수 있습니다. 이 API는 다양한 커스텀 이미지 분류 모델을 지원합니다. 모델 호환성 요구사항, 선행 학습된 모델을 찾을 수 있는 위치, 자체 모델을 학습시키는 방법에 대한 안내는 ML Kit를 사용한 커스텀 모델을 참조하세요.

이미지 라벨 지정을 커스텀 모델과 통합하는 방법에는 두 가지가 있습니다. 파이프라인을 앱의 일부로 번들로 묶거나 Google Play 서비스에 종속되는 번들 해제된 파이프라인을 사용하는 것입니다. 번들로 묶이지 않은 파이프라인을 선택하면 앱이 더 작아집니다. 자세한 내용은 아래 표를 참고하세요.

번들번들로 묶이지 않음
라이브러리 이름com.google.mlkit:image-labeling-customcom.google.android.gms:play-services-mlkit-image-labeling-custom
구현파이프라인은 빌드 시간에 앱에 정적으로 연결됩니다.파이프라인은 Google Play 서비스를 통해 동적으로 다운로드됩니다.
앱 크기크기가 약 3.8MB 증가합니다.크기가 약 200KB 증가했습니다.
초기화 시간파이프라인은 즉시 사용할 수 있습니다.처음 사용하기 전에 파이프라인이 다운로드될 때까지 기다려야 할 수 있습니다.
API 수명 주기 단계정식 버전(GA)베타

커스텀 모델을 통합하는 방법에는 두 가지가 있습니다. 앱의 애셋 폴더에 모델을 넣어 번들로 묶거나 Firebase에서 동적으로 다운로드하는 것입니다. 다음 표에서는 이 두 옵션을 비교합니다.

번들된 모델 호스팅된 모델
모델이 앱 APK의 일부이므로 모델 크기가 늘어납니다. 모델이 APK의 일부가 아닙니다. Firebase 머신러닝에 업로드하여 호스팅됩니다.
Android 기기가 오프라인 상태일 때도 모델을 즉시 사용할 수 있음 모델이 요청 시 다운로드됨
Firebase 프로젝트가 필요 없음 Firebase 프로젝트 필요
모델을 업데이트하려면 앱을 다시 게시해야 합니다. 앱을 다시 게시하지 않고 모델 업데이트 푸시
기본 제공되는 A/B 테스트 없음 Firebase 원격 구성으로 간편하게 A/B 테스트

사용해 보기

시작하기 전에

  1. 프로젝트 수준 build.gradle 파일의 buildscriptallprojects 섹션에 Google의 Maven 저장소가 포함되어야 합니다.

  2. 모듈의 앱 수준 Gradle 파일(일반적으로 app/build.gradle)에 ML Kit Android 라이브러리의 종속 항목을 추가합니다. 필요에 따라 다음 종속 항목 중 하나를 선택합니다.

    파이프라인을 앱과 번들로 묶는 방법:

    dependencies {
      // ...
      // Use this dependency to bundle the pipeline with your app
      implementation 'com.google.mlkit:image-labeling-custom:17.0.2'
    }
    

    Google Play 서비스에서 파이프라인을 사용하는 경우:

    dependencies {
      // ...
      // Use this dependency to use the dynamically downloaded pipeline in Google Play Services
      implementation 'com.google.android.gms:play-services-mlkit-image-labeling-custom:16.0.0-beta5'
    }
    
  3. Google Play 서비스에서 파이프라인을 사용하도록 선택한 경우 Play 스토어에서 앱이 설치된 후 기기에 파이프라인을 자동으로 다운로드하도록 앱을 구성할 수 있습니다. 이렇게 하려면 앱의 AndroidManifest.xml 파일에 다음 선언을 추가하세요.

    <application ...>
        ...
        <meta-data
            android:name="com.google.mlkit.vision.DEPENDENCIES"
            android:value="custom_ica" />
        <!-- To use multiple downloads: android:value="custom_ica,download2,download3" -->
    </application>
    

    Google Play 서비스 ModuleInstallClient API를 통해 파이프라인 가용성을 명시적으로 확인하고 다운로드를 요청할 수도 있습니다.

    설치 시 파이프라인 다운로드를 사용 설정하지 않거나 명시적 다운로드를 요청하지 않으면 라벨러를 처음 실행할 때 파이프라인이 다운로드됩니다. 다운로드가 완료되기 전에 요청하면 결과가 생성되지 않습니다.

  4. Firebase에서 모델을 동적으로 다운로드하려면 linkFirebase 종속 항목을 추가합니다.

    Firebase에서 모델을 동적으로 다운로드하려면 linkFirebase 종속 항목을 추가합니다.

    dependencies {
      // ...
      // Image labeling feature with model downloaded from Firebase
      implementation 'com.google.mlkit:image-labeling-custom:17.0.2'
      // Or use the dynamically downloaded pipeline in Google Play Services
      // implementation 'com.google.android.gms:play-services-mlkit-image-labeling-custom:16.0.0-beta5'
      implementation 'com.google.mlkit:linkfirebase:17.0.0'
    }
    
  5. 모델을 다운로드하려면 Android 프로젝트에 Firebase를 추가해야 합니다(아직 추가하지 않은 경우). 모델을 번들로 묶을 때는 이 작업이 필요하지 않습니다.

1. 모델 로드

로컬 모델 소스 구성

모델을 앱과 함께 번들로 묶는 방법은 다음과 같습니다.

  1. 일반적으로 .tflite 또는 .lite로 끝나는 모델 파일을 앱의 assets/ 폴더에 복사합니다. app/ 폴더를 마우스 오른쪽 버튼으로 클릭한 후 새로 만들기 > 폴더 > 애셋 폴더를 클릭하여 폴더부터 만들어야 할 수도 있습니다.

  2. 그런 다음 Gradle이 앱을 빌드할 때 모델 파일을 압축하지 않도록 앱의 build.gradle 파일에 다음을 추가합니다.

    android {
        // ...
        aaptOptions {
            noCompress "tflite"
            // or noCompress "lite"
        }
    }
    

    모델 파일이 앱 패키지에 포함되며 ML Kit에서 원시 애셋으로 사용할 수 있습니다.

  3. 모델 파일의 경로를 지정하여 LocalModel 객체를 만듭니다.

    Kotlin

    val localModel = LocalModel.Builder()
            .setAssetFilePath("model.tflite")
            // or .setAbsoluteFilePath(absolute file path to model file)
            // or .setUri(URI to model file)
            .build()

    Java

    LocalModel localModel =
        new LocalModel.Builder()
            .setAssetFilePath("model.tflite")
            // or .setAbsoluteFilePath(absolute file path to model file)
            // or .setUri(URI to model file)
            .build();

Firebase 호스팅 모델 소스 구성

원격 호스팅 모델을 사용하려면 FirebaseModelSourceRemoteModel 객체를 만들고 모델을 게시할 때 모델에 할당한 이름을 지정합니다.

Kotlin

// Specify the name you assigned in the Firebase console.
val remoteModel =
    CustomRemoteModel
        .Builder(FirebaseModelSource.Builder("your_model_name").build())
        .build()

Java

// Specify the name you assigned in the Firebase console.
CustomRemoteModel remoteModel =
    new CustomRemoteModel
        .Builder(new FirebaseModelSource.Builder("your_model_name").build())
        .build();

이제 다운로드를 허용할 조건을 지정하여 모델 다운로드 작업을 시작합니다. 모델이 기기에 없거나 최신 버전의 모델을 사용할 수 있으면 모델이 Firebase에서 비동기식으로 다운로드됩니다.

Kotlin

val downloadConditions = DownloadConditions.Builder()
    .requireWifi()
    .build()
RemoteModelManager.getInstance().download(remoteModel, downloadConditions)
    .addOnSuccessListener {
        // Success.
    }

Java

DownloadConditions downloadConditions = new DownloadConditions.Builder()
        .requireWifi()
        .build();
RemoteModelManager.getInstance().download(remoteModel, downloadConditions)
        .addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(@NonNull Task task) {
                // Success.
            }
        });

대부분의 앱은 초기화 코드에서 다운로드 작업을 시작하지만 모델 사용이 필요한 시점 이전에 언제든지 다운로드할 수 있습니다.

이미지 라벨러 구성

모델 소스를 구성한 후 모델 소스 중 하나에서 ImageLabeler 객체를 만듭니다.

사용할 수 있는 옵션은 다음과 같습니다.

옵션
confidenceThreshold

감지된 라벨의 최소 신뢰도 점수입니다. 설정하지 않으면 모델의 메타데이터에서 지정한 분류 기준 임계값이 사용됩니다. 모델에 메타데이터가 포함되어 있지 않거나 메타데이터가 분류 기준 임곗값을 지정하지 않으면 기본 임곗값 0.0이 사용됩니다.

maxResultCount

반환할 최대 라벨 수입니다. 설정하지 않으면 기본값 10이 사용됩니다.

로컬로 번들된 모델만 있다면 LocalModel 객체에서 라벨러를 만듭니다.

Kotlin

val customImageLabelerOptions = CustomImageLabelerOptions.Builder(localModel)
    .setConfidenceThreshold(0.5f)
    .setMaxResultCount(5)
    .build()
val labeler = ImageLabeling.getClient(customImageLabelerOptions)

Java

CustomImageLabelerOptions customImageLabelerOptions =
        new CustomImageLabelerOptions.Builder(localModel)
            .setConfidenceThreshold(0.5f)
            .setMaxResultCount(5)
            .build();
ImageLabeler labeler = ImageLabeling.getClient(customImageLabelerOptions);

원격 호스팅 모델이 있다면 실행 전에 모델이 다운로드되었는지 확인해야 합니다. 모델 관리자의 isModelDownloaded() 메서드로 모델 다운로드 작업의 상태를 확인할 수 있습니다.

이 상태는 라벨러 실행 전에만 확인하면 되지만, 원격 호스팅 모델과 로컬로 번들된 모델이 모두 있는 경우에는 이미지 라벨러를 인스턴스화할 때 이 확인 작업을 수행하는 것이 합리적일 수 있습니다. 원격 모델이 다운로드되었으면 원격 모델에서, 그렇지 않으면 로컬 모델에서 라벨러를 만듭니다.

Kotlin

RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
    .addOnSuccessListener { isDownloaded ->
    val optionsBuilder =
        if (isDownloaded) {
            CustomImageLabelerOptions.Builder(remoteModel)
        } else {
            CustomImageLabelerOptions.Builder(localModel)
        }
    val options = optionsBuilder
                  .setConfidenceThreshold(0.5f)
                  .setMaxResultCount(5)
                  .build()
    val labeler = ImageLabeling.getClient(options)
}

Java

RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
        .addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(Boolean isDownloaded) {
                CustomImageLabelerOptions.Builder optionsBuilder;
                if (isDownloaded) {
                    optionsBuilder = new CustomImageLabelerOptions.Builder(remoteModel);
                } else {
                    optionsBuilder = new CustomImageLabelerOptions.Builder(localModel);
                }
                CustomImageLabelerOptions options = optionsBuilder
                    .setConfidenceThreshold(0.5f)
                    .setMaxResultCount(5)
                    .build();
                ImageLabeler labeler = ImageLabeling.getClient(options);
            }
        });

원격 호스팅 모델만 있다면 모델 다운로드 여부가 확인될 때까지 모델 관련 기능을 사용 중지해야 합니다(예: UI 비활성화 또는 숨김). 모델 관리자의 download() 메서드에 리스너를 연결하여 관련 기능을 사용 중지할 수 있습니다.

Kotlin

RemoteModelManager.getInstance().download(remoteModel, conditions)
    .addOnSuccessListener {
        // Download complete. Depending on your app, you could enable the ML
        // feature, or switch from the local model to the remote model, etc.
    }

Java

RemoteModelManager.getInstance().download(remoteModel, conditions)
        .addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(Void v) {
              // Download complete. Depending on your app, you could enable
              // the ML feature, or switch from the local model to the remote
              // model, etc.
            }
        });

2. 입력 이미지 준비

그런 다음 라벨을 지정할 각 이미지에서 InputImage 객체를 만듭니다. 이미지 라벨러는 Bitmap를 사용할 때 또는 camera2 API를 사용하는 경우에는 YUV_420_888 media.Image를 사용할 때 가장 빠르게 실행됩니다. 가능하면 권장되는 형식을 사용하시기 바랍니다.

다양한 소스에서 InputImage 객체를 만들 수 있습니다. 각 소스는 아래에 설명되어 있습니다.

media.Image 사용

기기의 카메라에서 이미지를 캡처할 때와 같이 media.Image 객체에서 InputImage 객체를 만들려면 media.Image 객체 및 이미지 회전을 InputImage.fromMediaImage()에 전달합니다.

CameraX 라이브러리를 사용하는 경우 OnImageCapturedListenerImageAnalysis.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 객체로 표현됩니다.

3. 이미지 라벨러 실행

이미지의 객체에 라벨을 지정하려면 image 객체를 ImageLabelerprocess() 메서드에 전달합니다.

Kotlin

labeler.process(image)
        .addOnSuccessListener { labels ->
            // Task completed successfully
            // ...
        }
        .addOnFailureListener { e ->
            // Task failed with an exception
            // ...
        }

Java

labeler.process(image)
        .addOnSuccessListener(new OnSuccessListener<List<ImageLabel>>() {
            @Override
            public void onSuccess(List<ImageLabel> labels) {
                // Task completed successfully
                // ...
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Task failed with an exception
                // ...
            }
        });

4. 라벨이 지정된 항목에 대한 정보 가져오기

이미지 라벨 지정 작업이 성공하면 ImageLabel 객체의 목록이 성공 리스너에 전달됩니다. 각 ImageLabel 객체는 이미지에서 라벨이 지정된 항목을 나타냅니다. 각 라벨의 텍스트 설명 (TensorFlow Lite 모델 파일의 메타데이터에서 제공되는 경우), 신뢰도 점수, 색인을 가져올 수 있습니다. 예를 들면 다음과 같습니다.

Kotlin

for (label in labels) {
    val text = label.text
    val confidence = label.confidence
    val index = label.index
}

Java

for (ImageLabel label : labels) {
    String text = label.getText();
    float confidence = label.getConfidence();
    int index = label.getIndex();
}

실시간 성능 개선을 위한 팁

실시간 애플리케이션에서 이미지 라벨을 지정하려는 경우 최상의 프레임 속도를 얻으려면 다음 가이드라인을 따르세요.

  • Camera 또는 camera2 API를 사용하는 경우 이미지 라벨러 호출을 제한합니다. 이미지 라벨러가 실행 중일 때 새 동영상 프레임이 제공되는 경우 해당 프레임을 삭제합니다. 관련 예시는 빠른 시작 샘플 앱에서 VisionProcessorBase 클래스를 참고하세요.
  • CameraX API를 사용하는 경우 백프레셔 전략이 기본값인 ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST로 설정되어 있는지 확인합니다. 이렇게 하면 분석을 위해 한 번에 하나의 이미지만 전송됩니다. 분석기 사용량이 많을 때 이미지가 추가로 생성되면 자동으로 삭제되어 전송 대기열에 추가되지 않습니다. ImageProxy.close()를 호출하여 분석 중인 이미지를 닫으면 다음 최신 이미지가 전송됩니다.
  • 이미지 라벨러 출력을 사용하여 입력 이미지에서 그래픽을 오버레이하는 경우 먼저 ML Kit에서 결과를 가져온 후 이미지를 렌더링하고 단일 단계로 오버레이합니다. 이는 입력 프레임별로 한 번만 디스플레이 표면에 렌더링됩니다. 관련 예시는 빠른 시작 샘플 앱에서 CameraSourcePreview GraphicOverlay 클래스를 참조하세요.
  • Camera2 API를 사용할 경우 ImageFormat.YUV_420_888 형식으로 이미지를 캡처합니다. 이전 Camera API를 사용할 경우 ImageFormat.NV21 형식으로 이미지를 캡처합니다.