Android에서 AutoML 학습 모델을 사용하여 이미지 라벨 지정

AutoML Vision Edge를 사용하여 자체 모델을 학습시킨 후 앱에서 모델을 사용하여 이미지에 라벨을 지정할 수 있습니다. AutoML Vision Edge에서 학습된 모델을 통합하는 방법에는 두 가지가 있습니다. 앱의 애셋 폴더에 모델을 저장하여 번들로 묶거나 Firebase에서 동적으로 다운로드하는 것입니다.
모델 번들 옵션
앱에 번들로 제공
  • 모델이 앱 APK의 일부입니다.
  • Android 기기가 오프라인 상태일 때도 모델을 즉시 사용할 수 있습니다.
  • Firebase 프로젝트가 필요 없음
Firebase로 호스팅
  • Firebase 머신러닝에 모델을 업로드하여 호스팅
  • APK 크기 축소
  • 모델이 요청 시 다운로드됨
  • 앱을 다시 게시하지 않고 모델 업데이트 푸시
  • Firebase 원격 구성으로 간편하게 A/B 테스트
  • Firebase 프로젝트가 필요합니다.

사용해 보기

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

시작하기 전에

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

2. 모듈의 앱 수준 Gradle 파일(일반적으로 app/build.gradle)에 ML Kit Android 라이브러리의 종속 항목을 추가합니다. 모델을 앱과 번들로 묶는 방법은 다음과 같습니다.
    dependencies {
      // ...
      // Image labeling feature with bundled automl model
      implementation 'com.google.mlkit:image-labeling-automl:16.2.1'
    }
    
Firebase에서 모델을 동적으로 다운로드하려면 linkFirebase 종속 항목을 추가합니다.
    dependencies {
      // ...
      // Image labeling feature with automl model downloaded
      // from firebase
      implementation 'com.google.mlkit:image-labeling-automl:16.2.1'
      implementation 'com.google.mlkit:linkfirebase:16.0.1'
    }
    
3. 모델을 다운로드하려면 Android 프로젝트에 Firebase를 추가해야 합니다(아직 추가하지 않은 경우). 모델을 번들로 묶을 때는 이 작업이 필요하지 않습니다.

1. 모델 로드

로컬 모델 소스 구성

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

1. Firebase Console에서 다운로드한 zip 보관 파일에서 모델과 모델의 메타데이터를 추출합니다. 다운로드한 파일을 수정하지 않고 (파일 이름 등) 그대로 사용하는 것이 좋습니다.

2. 모델 및 모델의 메타데이터 파일을 앱 패키지에 포함합니다.

a. 프로젝트에 애셋 폴더가 없으면 app/ 폴더를 마우스 오른쪽 버튼으로 클릭한 후 새로 만들기 > 폴더 > 애셋 폴더를 클릭하여 하나 만듭니다.

b. 애셋 폴더 아래에 모델 파일을 포함할 하위 폴더를 만듭니다.

c. model.tflite, dict.txt, manifest.json 파일을 하위 폴더에 복사합니다. 세 파일이 모두 같은 폴더에 있어야 합니다.

3. Gradle이 앱을 빌드할 때 모델 파일을 압축하지 않도록 앱의 build.gradle 파일에 다음을 추가합니다.
    android {
        // ...
        aaptOptions {
            noCompress "tflite"
        }
    }
    
모델 파일이 앱 패키지에 포함되며 ML Kit에서 원시 애셋으로 사용할 수 있습니다.

참고: Android Gradle 플러그인 버전 4.1부터는 .tflite가 no압축 목록에 기본으로 추가되며 위 항목은 더 이상 필요하지 않습니다.

4. 모델 매니페스트 파일의 경로를 지정하여 LocalModel 객체를 만듭니다.

Kotlin

val localModel = AutoMLImageLabelerLocalModel.Builder()
        .setAssetFilePath("manifest.json")
        // or .setAbsoluteFilePath(absolute file path to manifest file)
        .build()

Java

AutoMLImageLabelerLocalModel localModel =
    new AutoMLImageLabelerLocalModel.Builder()
        .setAssetFilePath("manifest.json")
        // or .setAbsoluteFilePath(absolute file path to manifest file)
        .build();

Firebase 호스팅 모델 소스 구성

원격 호스팅 모델을 사용하려면 모델을 게시할 때 할당한 이름을 지정하여 RemoteModel 객체를 만듭니다.

Kotlin

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

Java

// Specify the name you assigned in the Firebase console.
AutoMLImageLabelerRemoteModel remoteModel =
    new AutoMLImageLabelerRemoteModel.Builder("your_model_name").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 객체를 만듭니다.

로컬로 번들된 모델만 있다면 AutoMLImageLabelerLocalModel 객체에서 라벨러를 만들고 필요한 신뢰도 점수 임곗값을 구성합니다 (모델 평가 참조).

Kotlin

val autoMLImageLabelerOptions = AutoMLImageLabelerOptions.Builder(localModel)
    .setConfidenceThreshold(0)  // Evaluate your model in the Firebase console
                                // to determine an appropriate value.
    .build()
val labeler = ImageLabeling.getClient(autoMLImageLabelerOptions)

Java

AutoMLImageLabelerOptions autoMLImageLabelerOptions =
        new AutoMLImageLabelerOptions.Builder(localModel)
                .setConfidenceThreshold(0.0f)  // Evaluate your model in the Firebase console
                                               // to determine an appropriate value.
                .build();
ImageLabeler labeler = ImageLabeling.getClient(autoMLImageLabelerOptions)

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

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

Kotlin

RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
    .addOnSuccessListener { isDownloaded -> 
    val optionsBuilder =
        if (isDownloaded) {
            AutoMLImageLabelerOptions.Builder(remoteModel)
        } else {
            AutoMLImageLabelerOptions.Builder(localModel)
        }
    // Evaluate your model in the Firebase console to determine an appropriate threshold.
    val options = optionsBuilder.setConfidenceThreshold(0.0f).build()
    val labeler = ImageLabeling.getClient(options)
}

Java

RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
        .addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(Boolean isDownloaded) {
                AutoMLImageLabelerOptions.Builder optionsBuilder;
                if (isDownloaded) {
                    optionsBuilder = new AutoMLImageLabelerOptions.Builder(remoteModel);
                } else {
                    optionsBuilder = new AutoMLImageLabelerOptions.Builder(localModel);
                }
                AutoMLImageLabelerOptions options = optionsBuilder
                        .setConfidenceThreshold(0.0f)  // Evaluate your model in the Firebase console
                                                       // to determine an appropriate threshold.
                        .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 라이브러리를 사용하는 경우 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 객체로 표현됩니다.

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 객체는 이미지에서 라벨이 지정된 항목을 나타냅니다. 각 라벨의 텍스트 설명, 일치 신뢰도 점수, 일치 색인을 가져올 수 있습니다. 예를 들면 다음과 같습니다.

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 형식으로 이미지를 캡처합니다.