Android에서 ML Kit를 사용하여 이미지 라벨 지정

ML Kit를 사용하면 이미지에서 인식된 객체에 라벨을 지정할 수 있습니다. ML Kit와 함께 제공되는 기본 모델은 400개 이상의 다양한 라벨을 지원합니다.

특성번들로 묶이지 않음번들
구현모델이 Google Play 서비스를 통해 동적으로 다운로드됩니다.모델이 빌드 시간에 정적으로 연결됩니다.
앱 크기크기가 약 200KB 증가합니다.크기가 약 5.7MB 증가합니다.
초기화 시간처음 사용하기 전에 모델이 다운로드될 때까지 기다려야 할 수도 있습니다.즉시 모델 사용 가능

사용해 보기

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

시작하기 전에

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

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

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

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

    Google Play 서비스에서 모델을 사용하는 경우:

    dependencies {
      // ...
      // Use this dependency to use the dynamically downloaded model in Google Play Services
      implementation 'com.google.android.gms:play-services-mlkit-image-labeling:16.0.8'
    }
    
  3. Google Play 서비스에서 모델을 사용하기로 선택한 경우 Play 스토어에서 앱이 설치된 후 기기에 모델을 자동으로 다운로드하도록 앱을 구성할 수 있습니다. 이를 위해 다음 선언을 앱의 AndroidManifest.xml 파일에 추가합니다.

    <application ...>
          ...
          <meta-data
              android:name="com.google.mlkit.vision.DEPENDENCIES"
              android:value="ica" >
          <!-- To use multiple models: android:value="ica,model2,model3" -->
    </application>
    

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

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

이제 이미지에 라벨을 지정할 수 있습니다.

1. 입력 이미지 준비

이미지에서 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 객체로 표현됩니다.

2. 이미지 라벨러 구성 및 실행

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

  1. 먼저 ImageLabeler의 인스턴스를 가져옵니다.

    기기 내 이미지 라벨러를 사용하려면 다음과 같이 선언합니다.

Kotlin

// To use default options:
val labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS)

// Or, to set the minimum confidence required:
// val options = ImageLabelerOptions.Builder()
//     .setConfidenceThreshold(0.7f)
//     .build()
// val labeler = ImageLabeling.getClient(options)

Java

// To use default options:
ImageLabeler labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS);

// Or, to set the minimum confidence required:
// ImageLabelerOptions options =
//     new ImageLabelerOptions.Builder()
//         .setConfidenceThreshold(0.7f)
//         .build();
// ImageLabeler labeler = ImageLabeling.getClient(options);
  1. 그런 다음 이미지를 process() 메서드에 전달합니다.

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

3. 라벨이 지정된 객체에 대한 정보 가져오기

이미지 라벨 지정 작업이 성공하면 ImageLabel 객체의 목록이 성공 리스너에 전달됩니다. 각 ImageLabel 객체는 이미지에서 라벨이 지정된 항목을 나타냅니다. 기본 모델은 400개 이상의 다양한 라벨을 지원합니다. 각 라벨의 텍스트 설명, 모델이 지원하는 모든 라벨 간의 색인, 일치 신뢰도 점수를 가져올 수 있습니다. 예를 들면 다음과 같습니다.

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