이미지를 ML Kit에 전달하면 이미지에서 최대 5개의 객체와 이미지 내 각 객체의 위치가 감지됩니다. 동영상 스트림에서 객체를 감지할 때 각 객체에는 프레임 간에 객체를 추적하는 데 사용할 수 있는 고유 ID가 있습니다.
커스텀 이미지 분류 모델을 사용하여 감지된 객체를 분류할 수 있습니다. 모델 호환성 요구사항, 사전 학습된 모델을 찾을 수 있는 위치, 자체 모델을 학습시키는 방법은 ML Kit를 사용한 커스텀 모델을 참고하세요.
커스텀 모델을 통합하는 방법에는 두 가지가 있습니다. 모델을 앱의 애셋 폴더에 넣어 번들로 묶거나 Cloud Storage에서 동적으로 다운로드할 수 있습니다. 다음 표에서는 두 가지 옵션을 비교합니다.
| 번들 모델 | 호스팅된 모델 |
|---|---|
| 모델이 앱 APK에 포함되어 크기가 커집니다. | 모델이 APK에 포함되지 않습니다. Cloud Storage에 업로드하여 호스팅됩니다. Firebase용 Cloud Storage를 사용하는 것이 좋습니다. |
| Android 기기가 오프라인 상태일 때도 모델을 즉시 사용할 수 있음 | 앱에 모델을 주문형으로 다운로드하는 코드가 포함되어야 합니다. |
| Firebase 프로젝트가 필요 없음 | Firebase 프로젝트가 필요합니다 (Firebase용 Cloud Storage를 사용하는 경우). |
| 모델을 업데이트하려면 앱을 다시 게시해야 합니다. | 앱을 다시 게시하지 않고 모델 업데이트 푸시 |
| 기본 제공 A/B 테스트 없음 | Firebase 원격 구성으로 A/B 테스트 |
사용해 보기
- 번들 모델의 사용 예는 Vision 빠른 시작 앱 을, 호스팅된 모델의 사용 예는 AutoML 빠른 시작 앱을 참고하세요.
- 이 API의 엔드 투 엔드 구현은 Material Design 쇼케이스 앱을 참고하세요.
시작하기 전에
1. 프로젝트 수준build.gradle.kts 파일의 buildscript 및 allprojects 섹션 모두에 Google의 Maven 저장소가 포함되어야 합니다.
모듈의 앱 수준 Gradle 파일(일반적으로
app/build.gradle.kts)에 ML Kit Android 라이브러리의 종속 항목을 추가합니다.모델을 앱과 함께 번들로 묶는 방법은 다음과 같습니다.
dependencies { // ... // Object detection & tracking feature with custom bundled model implementation("com.google.mlkit:object-detection-custom:17.0.2") }
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()
Java
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로의 마이그레이션 가이드를 참고하세요.
2. 객체 감지기 구성
모델 소스를 구성한 후 CustomObjectDetectorOptions 객체를 사용하여 사용 사례에 대한 객체 감지기를 구성합니다. 다음 설정을 변경할 수 있습니다.
| 객체 감지기 설정 | |
|---|---|
| 감지 모드 |
STREAM_MODE (기본값) | SINGLE_IMAGE_MODE
|
| 여러 객체 감지 및 추적 |
false (기본값) | true
감지 및 추적 대상을 최대 5개의 객체로 할지 아니면 가장 명백한 객체 (기본값)로 할지 여부입니다. |
| 객체 분류 |
false (기본값) | true
제공된 맞춤 분류 기준 모델을 사용하여 감지된 객체를 분류할지 여부입니다. 커스텀 분류
모델을 사용하려면 이 값을 |
| 분류 신뢰도 임곗값 |
감지된 라벨의 최소 신뢰도 점수입니다. 설정하지 않으면 모델의 메타데이터에 지정된 분류 임곗값이 사용됩니다. 모델에 메타데이터가 포함되어 있지 않거나 메타데이터에 분류 임곗값이 지정되어 있지 않으면 기본 임곗값인 0.0이 사용됩니다. |
| 객체당 최대 라벨 수 |
감지기가 반환할 객체당 최대 라벨 수입니다. 설정하지 않으면 기본값인 10이 사용됩니다. |
객체 감지 및 추적 API는 다음과 같은 2가지 주요 사용 사례에 최적화되어 있습니다.
- 카메라 뷰파인더에서 가장 뚜렷한 객체의 실시간 감지 및 추적
- 정적 이미지의 여러 객체 감지
로컬로 번들된 모델을 사용하여 이러한 사용 사례에 대한 API를 구성하려면 다음을 실행합니다.
Kotlin
// Live detection and tracking val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() // Multiple object detection in static images val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions)
Java
// Live detection and tracking CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); // Multiple object detection in static images CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions);
원격 호스팅 모델이 있다면 실행 전에 모델이 다운로드되었는지 확인해야 합니다.
이 상태는 감지기를 실행하기 전에만 확인하면 되지만, 원격 호스팅 모델과 로컬로 번들된 모델이 모두 있는 경우에는 이미지 감지기를 인스턴스화할 때 이 확인 작업을 수행하는 것이 합리적일 수 있으며 원격 모델이 다운로드되었으면 원격 모델에서, 그렇지 않으면 로컬 모델에서 감지기를 만듭니다.
Kotlin
val modelFile = File(context.cacheDir, "my_remote_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 customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(model) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions)
Java
File modelFile = new File(context.getCacheDir(), "my_remote_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(); } CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(model) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions);
원격 호스팅 모델만 있다면 모델 다운로드 여부가 확인될 때까지 모델 관련 기능 사용을 중지해야 합니다(예: UI 비활성화 또는 숨김).
Kotlin
val localFile = File(context.cacheDir, "my_remote_model.tflite") if (localFile.exists()) { // Model is already cached, initialize immediately initializeDetector(localFile) } else { // Model is not yet available, show loading UI and start download showLoadingUI() val storage = Firebase.storage val modelRef = storage.getReferenceFromUrl("gs://YOUR_BUCKET/path/to/model.tflite") modelRef.getFile(localFile) .addOnSuccessListener { // Download complete, initialize the detector hideLoadingUI() initializeDetector(localFile) } .addOnFailureListener { // Handle download error showErrorUI() } } private fun initializeDetector(modelFile: File) { val localModel = LocalModel.Builder().setAbsoluteFilePath(modelFile.absolutePath).build() val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions) // Enable ML-related UI features here enableMLFeatures(objectDetector) }
Java
File localFile = new File(context.getCacheDir(), "my_remote_model.tflite"); if (localFile.exists()) { // Model is already cached, initialize immediately initializeDetector(localFile); } else { // Model is not yet available, show loading UI and start download 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) { // Download complete, initialize the detector hideLoadingUI(); initializeDetector(localFile); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle download error showErrorUI(); } }); } private void initializeDetector(File modelFile) { LocalModel localModel = new LocalModel.Builder().setAbsoluteFilePath(modelFile.getAbsolutePath()).build(); CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions); // Enable ML-related UI features here enableMLFeatures(objectDetector); }
3. 입력 이미지 준비
이미지에서InputImage 객체를 만듭니다.
객체 감지기는 Bitmap, NV21 ByteBuffer 또는 YUV_420_888 media.Image에서 직접 실행됩니다. 이러한 소스 중 하나에 직접 액세스할 수 있는 경우 이러한 소스에서 InputImage를 구성하는 것이 좋습니다. 다른 소스에서 InputImage를 구성하면 Google에서 내부적으로 변환을 처리하며 효율성이 떨어질 수 있습니다.
다양한 소스로 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 객체 및 회101} 전 각도값을 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` 인텐트를 사용하여 사용자에게 갤러리 앱에서 이미지를 선택하라는 메시지를 표시할 때 유용한 방법입니다.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 )
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 객체로 표현됩니다.
4. 객체 감지기 실행
Kotlin
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (detectedObject in results) { // ... } });
Java
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (DetectedObject detectedObject : results) { // ... } });
5. 라벨이 지정된 객체 정보 가져오기
process()에 대한 호출이 성공하면 DetectedObject 목록이 성공 리스너에 전달됩니다.
각 DetectedObject에는 다음 속성이 포함됩니다.
| 경계 상자 | 이미지에서 객체의 위치를 나타내는 Rect입니다. |
||||||
| 추적 ID | 여러 이미지 간에 객체를 식별하는 정수입니다. SINGLE_IMAGE_MODE 에서는 Null입니다. | ||||||
| 라벨 |
|
Kotlin
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (detectedObject in results) { val boundingBox = detectedObject.boundingBox val trackingId = detectedObject.trackingId for (label in detectedObject.labels) { val text = label.text val index = label.index val confidence = label.confidence } }
Java
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (DetectedObject detectedObject : results) { Rect boundingBox = detectedObject.getBoundingBox(); Integer trackingId = detectedObject.getTrackingId(); for (Label label : detectedObject.getLabels()) { String text = label.getText(); int index = label.getIndex(); float confidence = label.getConfidence(); } }
우수한 사용자 환경 보장
최상의 사용자 환경을 위해 앱에서 다음 가이드라인을 따르세요.
- 객체 감지 성공 여부는 객체의 시각적 복잡성에 따라 달라집니다. 감지되려면 시각적 특징 수가 적은 객체가 이미지의 더 많은 부분을 차지해야 할 수 있습니다. 감지할 객체 종류에 효과적인 입력을 캡처할 수 있도록 돕는 안내를 사용자에게 제공해야 합니다.
- 분류를 사용할 때 지원되는 카테고리로 확실하게 분류되지 않는 객체를 감지하려면 알 수 없는 객체에 대한 특별한 처리를 구현합니다.
ML Kit 머티리얼 디자인 쇼케이스 앱 및 머티리얼 디자인의 머신러닝 기반의 기능 패턴 모음도 참조하세요.
성능 개선
실시간 애플리케이션에서 객체 감지를 사용하려는 경우 최상의 프레임 속도를 얻으려면 다음 안내를 따르세요.실시간 애플리케이션에서 스트리밍 모드를 사용하는 경우 여러 객체 감지를 사용하지 마세요. 대부분의 기기에서 적절한 프레임 속도를 생성할 수 없습니다.
- `Camera` 또는 `camera2` API를 사용하는 경우 감지기에 대한 호출을 제한합니다.
Cameracamera2감지기가 실행 중일 때 새 동영상 프레임이 제공되는 경우 해당 프레임을 드롭합니다. 관련 예시는 빠른 시작 샘플 앱에서VisionProcessorBase클래스를 참조하세요. CameraXAPI를 사용하는 경우 백프레셔 전략이 기본값인ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST로 설정되어 있는지 확인합니다. 이렇게 하면 한 번에 분석을 위해 하나의 이미지만 제공됩니다. 분석기가 사용 중일 때 이미지가 더 많이 생성되면 자동으로 삭제되고 전송을 위해 대기열에 추가되지 않습니다. ImageProxy.close()를 호출하여 분석 중인 이미지를 닫으면 다음 최신 이미지가 전송됩니다.- 인식기 출력을 사용해서 입력 이미지에서 그래픽을 오버레이하는 경우 먼저 ML Kit에서 결과를 가져온 후 이미지를 렌더링하고 단일 단계로 오버레이합니다. 이렇게 하면 입력 프레임별로 한 번만 디스플레이 표면에 렌더링됩니다. 관련 예시는 빠른 시작 샘플 앱에서
CameraSourcePreview및GraphicOverlay클래스를 참조하세요. - Camera2 API를 사용할 경우 이미지를
ImageFormat.YUV_420_888형식으로 캡처합니다. 이전 Camera API를 사용하는 경우ImageFormat.NV21형식으로 이미지를 캡처합니다.