Android에서 AutoML 학습 모델을 사용하여 이미지 라벨 지정
AutoML Vision Edge를 사용하여 자체 모델을 학습시킨 후 앱에서 이 모델을 사용하여 이미지에 라벨을 지정할 수 있습니다. AutoML Vision Edge에서 학습된 모델을 통합하는 방법에는 두 가지가 있습니다. 앱의 애셋 폴더에 모델을 저장하여 번들로 묶거나 Firebase에서 동적으로 다운로드하는 것입니다.모델 번들 옵션 | |
---|---|
앱에 번들로 제공 |
|
Firebase로 호스팅 |
|
사용해 보기
- 샘플 앱을 사용해 이 API의 사용 예를 살펴보세요.
시작하기 전에
1. 프로젝트 수준build.gradle
파일의 buildscript
및 allprojects
섹션 모두에 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' }
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' }
1. 모델 로드
로컬 모델 소스 구성
모델을 앱과 함께 번들로 묶으려면 다음 단계를 따르세요.1. Firebase Console에서 다운로드한 zip 파일에서 모델과 모델의 메타데이터를 추출합니다. 다운로드한 파일을 수정하지 않고 (파일 이름 등) 그대로 사용하는 것이 좋습니다.
2. 모델과 모델의 메타데이터 파일을 앱 패키지에 포함합니다.
a. 프로젝트에 애셋 폴더가 없으면
app/
폴더를 마우스 오른쪽 버튼으로 클릭한 다음 새로 만들기 > 폴더 > 애셋 폴더를 클릭하여 하나 만듭니다.b. 애셋 폴더 아래에 모델 파일을 포함할 하위 폴더를 만듭니다.
c.
model.tflite
, dict.txt
, manifest.json
파일을 하위 폴더에 복사합니다. 세 파일이 모두 같은 폴더에 있어야 합니다.3. Gradle이 앱을 빌드할 때 모델 파일을 압축하지 않도록 앱의
build.gradle
파일에 다음을 추가합니다.
android { // ... aaptOptions { noCompress "tflite" } }
참고: Android Gradle 플러그인 4.1 버전부터는 .tflite가 noCompress 목록에 기본적으로 추가되므로 위의 작업이 더 이상 필요하지 않습니다.
4. 모델 매니페스트 파일의 경로를 지정하여
LocalModel
객체를 만듭니다.
val localModel = AutoMLImageLabelerLocalModel.Builder() .setAssetFilePath("manifest.json") // or .setAbsoluteFilePath(absolute file path to manifest file) .build()
AutoMLImageLabelerLocalModel localModel = new AutoMLImageLabelerLocalModel.Builder() .setAssetFilePath("manifest.json") // or .setAbsoluteFilePath(absolute file path to manifest file) .build();
Firebase 호스팅 모델 소스 구성
원격 호스팅 모델을 사용하려면 모델을 게시할 때 할당한 이름을 지정하여 RemoteModel
객체를 만듭니다.
// Specify the name you assigned in the Firebase console. val remoteModel = AutoMLImageLabelerRemoteModel.Builder("your_model_name").build()
// Specify the name you assigned in the Firebase console. AutoMLImageLabelerRemoteModel remoteModel = new AutoMLImageLabelerRemoteModel.Builder("your_model_name").build();
이제 다운로드를 허용할 조건을 지정하여 모델 다운로드 작업을 시작합니다. 모델이 기기에 없거나 최신 버전의 모델을 사용할 수 있으면 모델이 Firebase에서 비동기식으로 다운로드됩니다.
val downloadConditions = DownloadConditions.Builder() .requireWifi() .build() RemoteModelManager.getInstance().download(remoteModel, downloadConditions) .addOnSuccessListener { // Success. }
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
객체에서 라벨러를 만들고 필요한 신뢰도 점수 임곗값을 구성합니다 (모델 평가 참조).
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)
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()
메서드로 모델 다운로드 작업의 상태를 확인할 수 있습니다.
레이블러를 실행하기 전에만 확인하면 되지만 원격 호스팅 모델과 로컬로 번들된 모델이 모두 있는 경우 이미지 레이블러를 인스턴스화할 때 이 검사를 실행하는 것이 좋습니다. 다운로드된 경우 원격 모델에서 레이블러를 만들고 그렇지 않은 경우 로컬 모델에서 레이블러를 만듭니다.
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) }
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()
메서드에 리스너를 연결하여 관련 기능을 사용 중지할 수 있습니다.
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. }
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
클래스가 회전 값을 자동으로 계산합니다.
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 // ... } } }
이미지 회전 각도를 제공하는 카메라 라이브러리를 사용하지 않는 경우 기기의 카메라 센서 방향 및 기기 회전 각도에서 이미지 회전 각도를 계산할 수 있습니다.
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()
에 전달합니다.
val image = InputImage.fromMediaImage(mediaImage, rotation)
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
파일 URI 사용
파일 URI에서 InputImage
객체를 만들려면 앱 컨텍스트 및 파일 URI를 InputImage.fromFilePath()
에 전달합니다. ACTION_GET_CONTENT
인텐트를 사용하여 사용자에게 갤러리 앱에서 이미지를 선택하라는 메시지를 표시할 때 유용한 방법입니다.
val image: InputImage try { image = InputImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
InputImage image;
try {
image = InputImage.fromFilePath(context, uri);
} catch (IOException e) {
e.printStackTrace();
}
ByteBuffer
또는 ByteArray
사용
ByteBuffer
또는 ByteArray
에서 InputImage
객체를 만들려면 먼저 앞서 media.Image
입력에서 설명한 대로 이미지 회전 각도를 계산합니다.
그런 다음 이미지의 높이, 너비, 색상 인코딩 형식, 회전 각도와 함께 버퍼 또는 배열을 사용하여 InputImage
객체를 만듭니다.
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
객체를 만들려면 다음과 같이 선언합니다.
val image = InputImage.fromBitmap(bitmap, 0)
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
이미지는 회전 각도와 함께 Bitmap
객체로 표현됩니다.
3. 이미지 라벨러 실행
이미지의 객체에 라벨을 지정하려면image
객체를 ImageLabeler
의 process()
메서드에 전달합니다.
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
객체는 이미지에서 라벨이 지정된 항목을 나타냅니다. 각 라벨의 텍스트 설명, 일치 신뢰도 점수, 일치 색인을 가져올 수 있습니다.
예를 들면 다음과 같습니다.
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를 사용하는 경우 이미지 라벨러 호출을 제한합니다. 이미지 라벨러가 실행 중일 때 새 동영상 프레임을 사용할 수 있게 되면 프레임을 삭제합니다. 관련 예시는 빠른 시작 샘플 앱에서VisionProcessorBase
클래스를 참고하세요.CameraX
API를 사용하는 경우 백프레셔 전략이 기본값인ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
로 설정되어 있는지 확인합니다. 이렇게 하면 한 번에 하나의 이미지만 분석을 위해 전송됩니다. 분석 도구가 사용 중이면 더 많은 이미지가 생성되더라도 자동으로 삭제되고 전송 대기열에 추가되지 않습니다. ImageProxy.close()를 호출하여 분석 중인 이미지가 닫히면 다음 최신 이미지가 전송됩니다.- 이미지 레이블러 출력을 사용하여 입력 이미지에 그래픽을 오버레이하는 경우 먼저 ML Kit에서 결과를 가져온 후 이미지를 렌더링하고 단일 단계로 오버레이합니다. 이렇게 하면 입력 프레임별로 한 번만 디스플레이 표면에 렌더링됩니다. 관련 예시는 빠른 시작 샘플 앱에서
CameraSourcePreview
및GraphicOverlay
클래스를 참고하세요. - Camera2 API를 사용할 경우
ImageFormat.YUV_420_888
형식으로 이미지를 캡처합니다. 이전 Camera API를 사용하는 경우ImageFormat.NV21
형식으로 이미지를 캡처합니다.