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

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

<ph type="x-smartling-placeholder">
기능번들로 묶이지 않음번들
구현모델은 Google Play 서비스를 통해 동적으로 다운로드됩니다.모델은 빌드 시간에 정적으로 연결됩니다.
앱 크기크기가 약 200KB 늘어났습니다.크기가 약 5.7MB 증가합니다.
초기화 시간처음 사용하기 전에 모델이 다운로드될 때까지 기다려야 할 수 있습니다.모델을 즉시 사용할 수 있습니다.

사용해 보기

  • 샘플 앱을 사용하여 이 API의 사용 예를 참조하세요.

시작하기 전에

<ph type="x-smartling-placeholder">
  1. 프로젝트 수준 build.gradle 파일에 Google의 buildscriptallprojects 섹션에 있는 Maven 저장소

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

    모델을 앱과 번들로 묶는 경우:

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

InputImage를 만들려면 다음 안내를 따르세요. (예: media.Image 객체에서 이미지를 캡처할 때) 기기의 카메라에서 이미지를 캡처하려면 media.Image 객체와 이미지의 InputImage.fromMediaImage()로 회전

<ph type="x-smartling-placeholder"></ph> 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
            // ...
        }
    }
}

자바

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
}

자바

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

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

InputImage를 만들려면 다음 안내를 따르세요. ByteBuffer 또는 ByteArray 이전에 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
)

자바

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

InputImage를 만들려면 다음 안내를 따르세요. 객체를 Bitmap 객체에서 삭제하려면 다음과 같이 선언합니다.

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)

자바

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

자바

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
                // ...
            }
        });
<ph type="x-smartling-placeholder">

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

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

Kotlin

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

자바

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

실시간 성능 개선을 위한 팁

실시간 애플리케이션에서 이미지에 라벨을 지정하려면 다음 가이드라인을 참조하세요.

  • Camera 또는 camera2 API 이미지 라벨러에 대한 호출을 제한합니다. 새 동영상 이미지 레이블러가 실행 중일 때 프레임이 사용 가능해지면 프레임을 낮춥니다. 자세한 내용은 <ph type="x-smartling-placeholder"></ph> VisionProcessorBase 클래스를 참조하세요.
  • CameraX API를 사용하는 경우 백프레셔 전략이 기본값으로 설정되어 있는지 확인 ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST 이렇게 하면 분석을 위해 한 번에 하나의 이미지만 전송됩니다. 더 많은 이미지가 분석기가 사용 중일 때 생성되지 않으면 자동으로 삭제되어 배달. 분석 중인 이미지가 ImageProxy.close()를 호출하면 다음 최신 이미지가 게재됩니다.
  • 이미지 라벨러의 출력을 사용하여 먼저 ML Kit에서 결과를 가져온 후 이미지를 하나의 단계로 오버레이할 수 있습니다. 이는 디스플레이 표면에 렌더링됩니다. 각 입력 프레임에 대해 한 번만 허용됩니다. 자세한 내용은 <ph type="x-smartling-placeholder"></ph> CameraSourcePreview GraphicOverlay 클래스를 참조하세요.
  • Camera2 API를 사용하는 경우 ImageFormat.YUV_420_888 형식으로 이미지를 캡처합니다. 이전 Camera API를 사용하는 경우 ImageFormat.NV21 형식으로 이미지를 캡처합니다.