이미지를 ML Kit에 전달하면 이미지에서 최대 5개의 객체를 감지합니다. 이미지의 각 객체의 위치와 함께 표시됩니다. Kubernetes에서 객체를 감지할 때는 각 객체에는 객체를 추적하는 데 사용할 수 있는 고유 ID가 있습니다. 확인할 수 있습니다
커스텀 이미지 분류 모델을 사용하여 있습니다. 자세한 내용은 ML Kit를 사용한 커스텀 모델을 참조하세요. 모델 호환성 요구사항, 선행 학습된 모델을 찾을 수 있는 위치, 자체 모델을 학습시키는 방법을 알아봅니다.
커스텀 모델을 통합하는 방법에는 두 가지가 있습니다. 다음을 기준으로 모델을 번들로 묶을 수 있습니다. 앱의 애셋 폴더에 넣거나 동적으로 다운로드할 수 있습니다. 있습니다. 다음 표에서는 두 가지 옵션을 비교합니다.
| 번들 모델 | 호스팅된 모델 |
|---|---|
| 모델이 앱 APK에 포함되어 크기가 커집니다. | 모델이 APK의 일부가 아닙니다. 에 업로드되어 호스팅됩니다. Firebase 머신러닝. |
| Android 기기가 오프라인 상태일 때도 모델을 즉시 사용할 수 있습니다. | 모델이 요청 시 다운로드됩니다. |
| Firebase 프로젝트가 필요하지 않음 | Firebase 프로젝트 필요 |
| 모델을 업데이트하려면 앱을 다시 게시해야 합니다. | 앱을 다시 게시할 필요 없이 모델 업데이트 푸시 |
| A/B 테스트 기본 제공 없음 | Firebase 원격 구성으로 간편하게 A/B 테스트 진행 |
사용해 보기
- Vision 빠른 시작 앱 보기 를 참조하세요. automl 빠른 시작 앱을 호스팅된 모델의 사용 예시입니다.
- 머티리얼 디자인 쇼케이스 앱을 참조하세요.
시작하기 전에
프로젝트 수준
build.gradle파일에 다음 코드를 포함해야 합니다.buildscript및allprojects섹션ML Kit Android 라이브러리의 종속 항목을 모듈의 앱 수준 gradle 파일(일반적으로
app/build.gradle임)을 빌드합니다.모델을 앱과 번들로 묶는 방법은 다음과 같습니다.
dependencies { // ... // Object detection & tracking feature with custom bundled model implementation 'com.google.mlkit:object-detection-custom:17.0.2' }Firebase에서 모델을 동적으로 다운로드하려면
linkFirebase를 추가합니다. 종속됩니다.dependencies { // ... // Object detection & tracking feature with model downloaded // from firebase implementation 'com.google.mlkit:object-detection-custom:17.0.2' implementation 'com.google.mlkit:linkfirebase:17.0.0' }모델을 다운로드하려면 Android 프로젝트에 Firebase 추가 확인하세요. 모델을 번들로 묶는 경우에는 이 작업이 필요하지 않습니다.
1. 모델 로드
로컬 모델 소스 구성
모델을 앱과 번들로 묶으려면 다음 안내를 따르세요.
일반적으로
.tflite또는.lite로 끝나는 모델 파일을 앱의assets/폴더 (먼저app/폴더를 마우스 오른쪽 버튼으로 클릭한 다음 신규 > 폴더 > 애셋 폴더를 클릭합니다.)그런 다음 앱의
build.gradle파일에 다음을 추가하여 다음을 확인합니다. Gradle은 앱을 빌드할 때 모델 파일을 압축하지 않습니다.android { // ... aaptOptions { noCompress "tflite" // or noCompress "lite" } }모델 파일이 앱 패키지에 포함되며 ML Kit에서 사용할 수 있습니다. 원시 애셋으로 저장하는 것입니다
모델 파일의 경로를 지정하여
LocalModel객체를 만듭니다.Kotlin
val localModel = LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute file path to model file) // or .setUri(URI to model file) .build()
자바
LocalModel localModel = new LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute file path to model file) // or .setUri(URI to model file) .build();
Firebase 호스팅 모델 소스 구성
원격 호스팅 모델을 사용하려면 다음을 수행하여 CustomRemoteModel 객체를 만듭니다.
FirebaseModelSource: 학습 시 모델에 할당한 이름 지정
다음 항목을 게시:
Kotlin
// Specify the name you assigned in the Firebase console. val remoteModel = CustomRemoteModel .Builder(FirebaseModelSource.Builder("your_model_name").build()) .build()
자바
// Specify the name you assigned in the Firebase console. CustomRemoteModel remoteModel = new CustomRemoteModel .Builder(new FirebaseModelSource.Builder("your_model_name").build()) .build();
그런 다음 모델을 다운로드할 조건을 지정하여 모델 다운로드 작업을 선택합니다. 모델이 기기에 없거나 최신 사용 가능해지면 태스크는 DAG를 비동기식으로 있습니다.
Kotlin
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. } });
대부분의 앱은 초기화 코드에서 다운로드 작업을 시작하지만 모델을 사용하기 전에 언제든지 이 작업을 할 수 있습니다.
2. 객체 감지기 구성
모델 소스를 구성한 후
사용 사례를 CustomObjectDetectorOptions 객체로 전달합니다. 언제든지
설정할 수 있습니다.
| 객체 감지기 설정 | |
|---|---|
| 감지 모드 |
STREAM_MODE (기본값) | SINGLE_IMAGE_MODE
|
| 여러 객체 감지 및 추적 |
false (기본값) | true
최대 5개의 객체를 감지하고 추적할지, 아니면 가장 많은 객체만 감지하고 추적할지 여부 가시도 높은 객체 (기본값). |
| 객체 분류 |
false (기본값) | true
제공된
커스텀 분류 기준 모델을 사용합니다. 맞춤 분류를 사용하려면 다음 단계를 따르세요.
|
| 분류 신뢰도 임곗값 |
감지된 라벨의 최소 신뢰도 점수입니다. 설정하지 않으면 모델의 메타데이터에 지정된 분류 기준 임곗값이 사용됩니다. 모델에 메타데이터가 없거나 메타데이터가 포함되지 않은 경우 분류 기준 임곗값을 지정하면 기본 임곗값인 0.0이 있습니다. |
| 객체당 최대 라벨 수 |
인식기가 실행하는 객체당 최대 라벨 수 반환합니다. 설정하지 않으면 기본값 10이 사용됩니다. |
객체 감지 및 추적 API는 이 두 가지 핵심 용도에 최적화되어 있습니다. 사례:
- 카메라에서 가장 눈에 띄는 물체를 실시간으로 감지하고 추적합니다. 뷰파인더를 사용할 수 있습니다.
- 정적 이미지에서 여러 객체를 감지합니다.
로컬로 번들된 모델을 사용하여 이러한 사용 사례에 맞게 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)
자바
// 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);
원격 호스팅 모델이 있는 경우에는 모델이
다운로드할 수 있습니다. 모델 다운로드 상태를 확인할 수 있습니다.
모델 관리자의 isModelDownloaded() 메서드를 사용하여 태스크를 수행합니다.
감지기를 실행하기 전에만 이를 확인하면 되지만, 원격 호스팅 모델과 로컬로 번들된 모델이 모두 있는 경우 이미지 감지기를 인스턴스화할 때 이 확인 작업을 수행하는 것이 좋습니다. 다운로드한 경우 원격 모델에서 감지기를 가져오고, 로컬 저장소에서 그렇지 않은 경우에는 모델이 필요합니다
Kotlin
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener { isDownloaded -> val optionsBuilder = if (isDownloaded) { CustomObjectDetectorOptions.Builder(remoteModel) } else { CustomObjectDetectorOptions.Builder(localModel) } val customObjectDetectorOptions = optionsBuilder .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions) }
자바
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Boolean isDownloaded) { CustomObjectDetectorOptions.Builder optionsBuilder; if (isDownloaded) { optionsBuilder = new CustomObjectDetectorOptions.Builder(remoteModel); } else { optionsBuilder = new CustomObjectDetectorOptions.Builder(localModel); } CustomObjectDetectorOptions customObjectDetectorOptions = optionsBuilder .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions); } });
원격 호스팅 모델만 있는 경우 모델 관련 사용을 중지해야 합니다.
UI의 일부분을 회색으로 표시하거나 숨기는 등
모델이 다운로드되었음을 확인합니다. 그러려면 리스너를
모델 관리자의 download() 메서드에 추가합니다.
Kotlin
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. }
Java
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. } });
3. 입력 이미지 준비
이미지에서InputImage 객체를 만듭니다.
객체 감지기는 Bitmap, NV21 ByteBuffer 또는
YUV_420_888 media.Image를 반환합니다. 이러한 소스에서 InputImage를 구성하는 것은
그 중 하나에 직접 액세스할 수 있는 경우
권장됩니다. YAML 파일을
다른 소스에서 InputImage인 경우 Google에서 내부적으로 전환을 처리합니다.
효율성이 떨어질 수 있습니다
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 객체로 표현됩니다.
4. 객체 감지기 실행
Kotlin
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (detectedObject in results) { // ... } });
자바
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (DetectedObject detectedObject : results) { // ... } });
5. 라벨이 지정된 객체 정보 가져오기
process() 호출이 성공하면 DetectedObject 목록이 다음에 전달됩니다.
성공 리스너입니다.
각 DetectedObject에는 다음 속성이 포함됩니다.
| 경계 상자 | 다음에서 객체의 위치를 나타내는 Rect:
이미지 |
||||||
| 추적 ID | 여러 이미지에서 객체를 식별하는 정수입니다. Null in SINGLE_IMAGE_MODE여야 합니다. | ||||||
| 라벨 |
|
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 } }
자바
// 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또는camera2API 감지기 호출을 제한합니다. 새 동영상 감지기가 실행되는 동안 frame 사용할 수 있게 되면 프레임을 삭제합니다. 자세한 내용은 <ph type="x-smartling-placeholder"></ph>VisionProcessorBase클래스를 참조하세요. CameraXAPI를 사용하는 경우 백프레셔 전략이 기본값으로 설정되어 있는지 확인 <ph type="x-smartling-placeholder"></ph>ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST이렇게 하면 분석을 위해 한 번에 하나의 이미지만 전송됩니다. 더 많은 이미지가 분석기가 사용 중일 때 생성되지 않으면 자동으로 삭제되어 배달. 분석 중인 이미지가 ImageProxy.close()를 호출하면 다음 최신 이미지가 게재됩니다.- 감지기 출력을 사용하여 그래픽 이미지를
먼저 ML Kit에서 결과를 가져온 후 이미지를
하나의 단계로 오버레이할 수 있습니다. 이는 디스플레이 표면에 렌더링됩니다.
각 입력 프레임에 대해 한 번만 허용됩니다. 자세한 내용은
<ph type="x-smartling-placeholder"></ph>
CameraSourcePreview및 <ph type="x-smartling-placeholder"></ph>GraphicOverlay클래스를 참조하세요. - Camera2 API를 사용하는 경우
ImageFormat.YUV_420_888형식으로 이미지를 캡처합니다. 이전 Camera API를 사용하는 경우ImageFormat.NV21형식으로 이미지를 캡처합니다.