이미지 라벨링을 맞춤 모델과 통합하는 방법에는 두 가지가 있습니다. 파이프라인을 앱의 일부로 번들링하거나 Google Play 서비스를 사용하는 번들링되지 않은 파이프라인을 사용하는 것입니다. 번들 해제된 파이프라인을 선택하면 앱이 더 작아집니다. 자세한 내용은 다음 표를 참조하세요.
| 번들 | 번들 해제됨 | |
|---|---|---|
| 라이브러리 이름 | com.google.mlkit:image-labeling-custom | com.google.android.gms:play-services-mlkit-image-labeling-custom |
구현 | 파이프라인은 빌드 시 앱에 정적으로 연결됩니다. | 파이프라인은 Google Play 서비스를 사용하여 동적으로 다운로드됩니다. |
| 앱 크기 | 크기가 약 3.8MB 증가합니다. | 크기가 약 200KB 증가합니다. |
| 초기화 시간 | 파이프라인을 즉시 사용할 수 있습니다. | 처음 사용하기 전에 파이프라인이 다운로드될 때까지 기다려야 할 수 있습니다. |
| API 수명 주기 단계 | 정식 버전(GA) | 베타 |
커스텀 모델을 통합하는 방법에는 두 가지가 있습니다. 앱의 애셋 폴더에 모델을 저장하여 번들로 묶거나 Firebase에서 동적으로 다운로드하는 것입니다. 다음 표에서는 두 옵션을 비교합니다.
| 번들 모델 | 호스팅된 모델 |
|---|---|
| 모델이 앱의 APK에 포함되어 크기가 증가합니다. | 모델이 APK에 포함되지 않습니다. Cloud Storage에 업로드하여 호스팅됩니다. Firebase용 Cloud Storage를 사용하는 것이 좋습니다. |
| Android 기기가 오프라인 상태일 때도 모델을 즉시 사용할 수 있음 | 앱에는 필요에 따라 모델을 다운로드하는 코드가 포함되어야 합니다. |
| Firebase 프로젝트가 필요 없음 | Firebase 프로젝트가 필요합니다 (Firebase용 Cloud Storage를 사용하는 경우). |
| 모델을 업데이트하려면 앱을 다시 게시해야 합니다. | 앱을 다시 게시하지 않고 모델 업데이트 푸시 |
| 기본 제공 A/B 테스트 없음 | Firebase 원격 구성을 사용한 A/B 테스트 |
사용해 보기
- 번들 모델의 사용 예는 비전 빠른 시작 앱을, 호스팅 모델의 사용 예는 AutoML 빠른 시작 앱을 참고하세요.
시작하기 전에
프로젝트 수준
build.gradle.kts파일의buildscript및allprojects섹션에 Google의 Maven 저장소가 포함되어야 합니다.모듈의 앱 수준 Gradle 파일(일반적으로
app/build.gradle.kts)에 ML Kit Android 라이브러리의 종속 항목을 추가합니다. 필요에 따라 다음 종속 항목 중 하나를 선택합니다.파이프라인을 앱과 함께 번들로 묶는 방법은 다음과 같습니다.
dependencies { // ... // Use this dependency to bundle the pipeline with your app implementation("com.google.mlkit:image-labeling-custom:17.0.3") }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") }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를 통해 파이프라인 가용성을 명시적으로 확인하고 다운로드를 요청할 수도 있습니다.
설치 시간 파이프라인 다운로드를 사용 설정하지 않거나 명시적 다운로드를 요청하지 않으면 라벨러를 처음 실행할 때 파이프라인이 다운로드됩니다. 다운로드가 완료되기 전에 요청하면 결과가 나오지 않습니다.
Firebase용 Cloud Storage를 사용하여 모델을 다운로드하려면 Android 프로젝트에 Firebase를 추가해야 합니다(아직 추가하지 않은 경우). 모델을 번들로 묶을 때는 이 작업이 필요하지 않습니다.
1. 모델 로드
로컬로 번들링된 소스 또는 원격으로 호스팅된 소스에서 모델을 로드할 수 있습니다.
로컬 모델 소스 구성
모델을 앱과 함께 번들로 묶으려면 다음 단계를 따르세요.
일반적으로
.tflite또는.lite로 끝나는 모델 파일을 앱의assets/폴더에 복사합니다.app/폴더를 마우스 오른쪽 버튼으로 클릭한 후 새로 만들기 > 폴더 > 애셋 폴더를 클릭하여 폴더부터 만들어야 할 수 있습니다.모델 파일의 경로를 지정하여
LocalModel객체를 만듭니다.Kotlin
val localModel = LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute path to model file) // or .setUri(URI to model file) .build()
자바
LocalModel localModel = new LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute path to model file) // or .setUri(URI to model file) .build();
원격으로 호스팅된 모델 소스 구성
원격으로 호스팅된 모델을 사용하려면 자체 앱 로직을 사용하여 모델 파일을 기기의 로컬 저장소에 다운로드한 다음 로컬 모델로 로드해야 합니다. Firebase용 Cloud Storage를 사용하여 모델을 호스팅하는 것이 좋습니다. 구현에 관한 자세한 내용은 Firebase ML에서 Cloud Storage로의 이전 가이드를 참고하세요.
이미지 라벨러 구성
모델 소스를 구성한 후 모델 소스 중 하나에서 ImageLabeler 객체를 만듭니다.
사용할 수 있는 옵션은 다음과 같습니다.
| 옵션 | |
|---|---|
confidenceThreshold
|
감지된 라벨의 최소 신뢰도 점수입니다. 설정하지 않으면 모델의 메타데이터에 지정된 분류기 기준이 사용됩니다. 모델에 메타데이터가 없거나 메타데이터에 분류자 임계값이 지정되어 있지 않으면 기본 임계값 0.0이 사용됩니다. |
maxResultCount
|
반환할 최대 라벨 수입니다. 설정하지 않으면 기본값 10이 사용됩니다. |
로컬로 번들된 모델만 있다면 LocalModel 객체에서 라벨러를 만듭니다.
Kotlin
val customImageLabelerOptions = CustomImageLabelerOptions.Builder(localModel) .setConfidenceThreshold(0.5f) .setMaxResultCount(5) .build() val labeler = ImageLabeling.getClient(customImageLabelerOptions)
자바
CustomImageLabelerOptions customImageLabelerOptions = new CustomImageLabelerOptions.Builder(localModel) .setConfidenceThreshold(0.5f) .setMaxResultCount(5) .build(); ImageLabeler labeler = ImageLabeling.getClient(customImageLabelerOptions);
원격 호스팅 모델이 있다면 실행 전에 모델이 다운로드되었는지 확인해야 합니다.
라벨러를 실행하기 전에만 확인하면 되지만 원격 호스팅 모델과 로컬 번들 모델이 모두 있는 경우 이미지 라벨러를 인스턴스화할 때 이 검사를 실행하는 것이 좋습니다. 원격 모델이 다운로드된 경우 원격 모델에서 라벨러를 만들고 그렇지 않은 경우 로컬 모델에서 라벨러를 만드세요.
Kotlin
val modelFile = File(context.cacheDir, "my_downloaded_model.tflite") val model = if (modelFile.exists()) { // Use the downloaded model if available LocalModel.Builder().setAbsoluteFilePath(modelFile.absolutePath).build() } else { // Fall back to the bundled model LocalModel.Builder().setAssetFilePath("model.tflite").build() } val options = CustomImageLabelerOptions.Builder(model) .setConfidenceThreshold(0.5f) .setMaxResultCount(5) .build() val labeler = ImageLabeling.getClient(options)
자바
File modelFile = new File(context.getCacheDir(), "my_downloaded_model.tflite"); LocalModel model; if (modelFile.exists()) { // Use the downloaded model if available model = new LocalModel.Builder().setAbsoluteFilePath(modelFile.getAbsolutePath()).build(); } else { // Fall back to the bundled model model = new LocalModel.Builder().setAssetFilePath("model.tflite").build(); } CustomImageLabelerOptions options = new CustomImageLabelerOptions.Builder(model) .setConfidenceThreshold(0.5f) .setMaxResultCount(5) .build(); ImageLabeler labeler = ImageLabeling.getClient(options);
원격 호스팅 모델만 있다면 모델 다운로드 여부가 확인될 때까지 모델 관련 기능 사용을 중지해야 합니다(예: UI 비활성화 또는 숨김).
Kotlin
val localFile = File(context.cacheDir, "my_remote_model.tflite") if (localFile.exists()) { initializeLabeler(localFile) } else { showLoadingUI() val storage = Firebase.storage val modelRef = storage.getReferenceFromUrl("gs://YOUR_BUCKET/path/to/model.tflite") modelRef.getFile(localFile) .addOnSuccessListener { hideLoadingUI() initializeLabeler(localFile) } .addOnFailureListener { showErrorUI() } } private fun initializeLabeler(modelFile: File) { val localModel = LocalModel.Builder().setAbsoluteFilePath(modelFile.absolutePath).build() val options = CustomImageLabelerOptions.Builder(localModel).build() val labeler = ImageLabeling.getClient(options) enableMLFeatures(labeler) }
Java
File localFile = new File(context.getCacheDir(), "my_remote_model.tflite"); if (localFile.exists()) { initializeLabeler(localFile); } else { showLoadingUI(); FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference modelRef = storage.getReferenceFromUrl("gs://YOUR_BUCKET/path/to/model.tflite"); modelRef.getFile(localFile) .addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { @Override public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { hideLoadingUI(); initializeLabeler(localFile); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { showErrorUI(); } }); } private void initializeLabeler(File modelFile) { LocalModel localModel = new LocalModel.Builder().setAbsoluteFilePath(modelFile.getAbsolutePath()).build(); CustomImageLabelerOptions options = new CustomImageLabelerOptions.Builder(localModel).build(); ImageLabeler labeler = ImageLabeling.getClient(options); enableMLFeatures(labeler); }
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 // ... } } }
자바
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 사용
파일 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 )
자바
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 객체를 ImageLabeler의 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 // ... } });
4. 라벨이 지정된 항목에 관한 정보 가져오기
이미지 라벨 지정 작업이 성공하면ImageLabel 객체의 목록이 성공 리스너에 전달됩니다. 각 ImageLabel 객체는 이미지에서 라벨이 지정된 항목을 나타냅니다. 각 라벨의 텍스트 설명 (LiteRT 모델 파일의 메타데이터에 표시되는 경우), 신뢰도 점수, 색인을 가져올 수 있습니다. 예를 들면 다음과 같습니다.
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또는camera2API를 사용하는 경우 이미지 라벨러에 대한 호출을 제한합니다. 이미지 라벨러가 실행 중일 때 새 동영상 프레임이 제공되는 경우 해당 프레임을 삭제합니다. 예는 빠른 시작 샘플 앱의VisionProcessorBase클래스를 참고하세요.CameraXAPI를 사용하는 경우 백프레셔 전략이 기본값인ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST으로 설정되어 있는지 확인하세요. 이렇게 하면 한 번에 하나의 이미지만 분석을 위해 전송됩니다. 분석기가 사용 중일 때 이미지가 더 많이 생성되면 자동으로 삭제되고 전송을 위해 대기열에 추가되지 않습니다. 분석 중인 이미지가 ImageProxy.close()를 호출하여 닫히면 다음 최신 이미지가 전송됩니다.- 이미지 레이블러 출력을 사용해 입력 이미지에서 그래픽을 오버레이하는 경우 먼저 ML Kit에서 인식 결과를 가져온 후 이미지를 렌더링하고 단일 단계로 오버레이합니다. 이렇게 하면 각 입력 프레임에 대해 디스플레이 표면에 한 번만 렌더링됩니다. 예를 보려면 빠른 시작 샘플 앱의
CameraSourcePreview및GraphicOverlay클래스를 참고하세요. - Camera2 API를 사용할 경우
ImageFormat.YUV_420_888형식으로 이미지를 캡처합니다. 이전 Camera API를 사용할 경우ImageFormat.NV21형식으로 이미지를 캡처합니다.