ML Kit를 사용하여 여러 동영상 프레임에서 객체를 감지하고 추적할 수 있습니다.
ML Kit에 이미지를 전달하면 ML Kit는 각 이미지별로 최대 5개의 감지된 객체와 이미지 내 위치 목록을 반환합니다. 동영상 스트림에서 감지된 객체에 부여된 ID를 사용하면 여러 이미지 간에 객체를 추적할 수 있습니다. 대략적인 객체 분류를 사용 설정할 수도 있습니다. 이렇게 하면 객체에 대략적인 카테고리 설명이 라벨로 지정됩니다.
시작하기 전에
- 먼저 Android 프로젝트에 Firebase를 추가합니다.
- 모듈(앱 수준) Gradle 파일(일반적으로 app/build.gradle)에 ML Kit Android 라이브러리의 종속 항목을 추가합니다.apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' dependencies { // ... implementation 'com.google.firebase:firebase-ml-vision:24.0.3' implementation 'com.google.firebase:firebase-ml-vision-object-detection-model:19.0.6' } 
1. 객체 감지기 구성
객체 감지 및 추적을 시작하려면 우선 FirebaseVisionObjectDetector의 인스턴스를 만들고, 기본값과 다른 값으로 지정할 감지기 설정을 선택적으로 지정합니다.
- 사용 사례에 대한 객체 감지기를 - FirebaseVisionObjectDetectorOptions객체를 사용하여 구성합니다. 다음과 같은 설정을 변경할 수 있습니다.- 객체 감지기 설정 - 감지 모드 - STREAM_MODE(기본값) |- SINGLE_IMAGE_MODE- STREAM_MODE(기본값)에서는 객체 감지기가 짧은 지연 시간으로 실행되지만, 감지기를 처음 몇 번 호출할 때 경계 상자 또는 카테고리 라벨이 지정되지 않는 등 불완전한 결과가 나올 수 있습니다. 또한- STREAM_MODE에서는 감지기가 객체에 추적 ID를 할당하며, 이 ID를 사용하여 여러 프레임 간에 객체를 추적할 수 있습니다. 객체를 추적하려는 경우나 실시간 동영상 스트림 처리와 같이 짧은 지연 시간이 중요한 경우에 이 모드를 사용하세요.- SINGLE_IMAGE_MODE에서는 객체 감지기가 감지된 객체의 경계 상자 및 카테고리 라벨(분류를 사용 설정한 경우)이 확인될 때까지 기다린 후에 결과를 반환합니다. 따라서 감지 지연 시간이 길어질 가능성이 있습니다. 또한- SINGLE_IMAGE_MODE에서는 추적 ID가 할당되지 않습니다. 지연 시간이 중요하지 않으며 부분적인 결과를 처리하지 않으려는 경우에 이 모드를 사용하세요.- 여러 객체 감지 및 추적 - false(기본값) |- true- 감지 및 추적 대상을 최대 5개의 객체로 할지 아니면 가장 명백한 객체(기본값)로 할지 여부입니다. - 객체 분류 - false(기본값) |- true- 감지된 객체를 대략적인 카테고리로 분류할지 여부입니다. 이 기능을 사용 설정하면 객체 감지기가 객체를 의류, 식품, 가정용품, 장소, 식물, 알 수 없음 카테고리로 분류합니다. - 객체 감지 및 추적 API는 다음과 같은 2가지 주요 사용 사례에 최적화되어 있습니다. - 카메라 뷰파인더에서 가장 뚜렷한 객체의 실시간 감지 및 추적
- 정적 이미지의 여러 객체 감지
 - 이러한 사용 사례에 대한 API를 구성하려면 다음을 실행합니다. - Java- // Live detection and tracking FirebaseVisionObjectDetectorOptions options = new FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE) .enableClassification() // Optional .build(); // Multiple object detection in static images FirebaseVisionObjectDetectorOptions options = new FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() // Optional .build();- Kotlin- // Live detection and tracking val options = FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE) .enableClassification() // Optional .build() // Multiple object detection in static images val options = FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() // Optional .build()
- FirebaseVisionObjectDetector의 인스턴스를 가져옵니다.- Java- FirebaseVisionObjectDetector objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector(); // Or, to change the default settings: FirebaseVisionObjectDetector objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector(options);- Kotlin- val objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector() // Or, to change the default settings: val objectDetector = FirebaseVision.getInstance().getOnDeviceObjectDetector(options)
2. 객체 감지기 실행
객체를 감지하고 추적하려면 FirebaseVisionObjectDetector 인스턴스의 processImage() 메서드에 이미지를 전달합니다.
동영상의 각 프레임이나 연속된 이미지에 대해 다음을 수행합니다.
- 이미지에서 - FirebaseVisionImage객체를 만듭니다.- 
    기기의 카메라에서 이미지를 캡처할 때와 같이 media.Image객체에서FirebaseVisionImage객체를 만들려면media.Image객체 및 이미지 회전을FirebaseVisionImage.fromMediaImage()에 전달합니다.CameraX 라이브러리를 사용하는 경우 OnImageCapturedListener및ImageAnalysis.Analyzer클래스가 회전 값을 계산하므로FirebaseVisionImage.fromMediaImage()를 호출하기 전에 ML Kit의ROTATION_상수 중 하나로 회전을 변환하기만 하면 됩니다.Javaprivate class YourAnalyzer implements ImageAnalysis.Analyzer { private int degreesToFirebaseRotation(int degrees) { switch (degrees) { case 0: return FirebaseVisionImageMetadata.ROTATION_0; case 90: return FirebaseVisionImageMetadata.ROTATION_90; case 180: return FirebaseVisionImageMetadata.ROTATION_180; case 270: return FirebaseVisionImageMetadata.ROTATION_270; default: throw new IllegalArgumentException( "Rotation must be 0, 90, 180, or 270."); } } @Override public void analyze(ImageProxy imageProxy, int degrees) { if (imageProxy == null || imageProxy.getImage() == null) { return; } Image mediaImage = imageProxy.getImage(); int rotation = degreesToFirebaseRotation(degrees); FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation); // Pass image to an ML Kit Vision API // ... } } Kotlinprivate class YourImageAnalyzer : ImageAnalysis.Analyzer { private fun degreesToFirebaseRotation(degrees: Int): Int = when(degrees) { 0 -> FirebaseVisionImageMetadata.ROTATION_0 90 -> FirebaseVisionImageMetadata.ROTATION_90 180 -> FirebaseVisionImageMetadata.ROTATION_180 270 -> FirebaseVisionImageMetadata.ROTATION_270 else -> throw Exception("Rotation must be 0, 90, 180, or 270.") } override fun analyze(imageProxy: ImageProxy?, degrees: Int) { val mediaImage = imageProxy?.image val imageRotation = degreesToFirebaseRotation(degrees) if (mediaImage != null) { val image = FirebaseVisionImage.fromMediaImage(mediaImage, imageRotation) // Pass image to an ML Kit Vision API // ... } } } 이미지 회전을 제공하는 카메라 라이브러리를 사용하지 않는 경우 기기의 카메라 센서 방향 및 기기 회전에서 이미지 회전을 계산할 수 있습니다. Javaprivate static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } /** * 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, Context context) 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); // On most devices, the sensor orientation is 90 degrees, but for some // devices it is 270 degrees. For devices with a sensor orientation of // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees. CameraManager cameraManager = (CameraManager) context.getSystemService(CAMERA_SERVICE); int sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION); rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360; // Return the corresponding FirebaseVisionImageMetadata rotation value. int result; switch (rotationCompensation) { case 0: result = FirebaseVisionImageMetadata.ROTATION_0; break; case 90: result = FirebaseVisionImageMetadata.ROTATION_90; break; case 180: result = FirebaseVisionImageMetadata.ROTATION_180; break; case 270: result = FirebaseVisionImageMetadata.ROTATION_270; break; default: result = FirebaseVisionImageMetadata.ROTATION_0; Log.e(TAG, "Bad rotation value: " + rotationCompensation); } return result; } Kotlinprivate val ORIENTATIONS = SparseIntArray() init { ORIENTATIONS.append(Surface.ROTATION_0, 90) ORIENTATIONS.append(Surface.ROTATION_90, 0) ORIENTATIONS.append(Surface.ROTATION_180, 270) ORIENTATIONS.append(Surface.ROTATION_270, 180) } /** * 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, context: Context): 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) // On most devices, the sensor orientation is 90 degrees, but for some // devices it is 270 degrees. For devices with a sensor orientation of // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees. val cameraManager = context.getSystemService(CAMERA_SERVICE) as CameraManager val sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION)!! rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360 // Return the corresponding FirebaseVisionImageMetadata rotation value. val result: Int when (rotationCompensation) { 0 -> result = FirebaseVisionImageMetadata.ROTATION_0 90 -> result = FirebaseVisionImageMetadata.ROTATION_90 180 -> result = FirebaseVisionImageMetadata.ROTATION_180 270 -> result = FirebaseVisionImageMetadata.ROTATION_270 else -> { result = FirebaseVisionImageMetadata.ROTATION_0 Log.e(TAG, "Bad rotation value: $rotationCompensation") } } return result } 그런 다음 media.Image객체 및 회전 값을FirebaseVisionImage.fromMediaImage()에 전달합니다.JavaFirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation); Kotlinval image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation) 
- 파일 URI에서 FirebaseVisionImage객체를 만들려면 앱 컨텍스트 및 파일 URI를FirebaseVisionImage.fromFilePath()에 전달합니다.ACTION_GET_CONTENT인텐트를 사용하여 사용자에게 갤러리 앱에서 이미지를 선택하라는 메시지를 표시할 때 유용한 방법입니다.JavaFirebaseVisionImage image; try { image = FirebaseVisionImage.fromFilePath(context, uri); } catch (IOException e) { e.printStackTrace(); } Kotlinval image: FirebaseVisionImage try { image = FirebaseVisionImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() } 
- ByteBuffer또는 바이트 배열에서- FirebaseVisionImage객체를 만들려면 먼저 위에서 설명한 대로- media.Image입력의 이미지 회전을 계산합니다.- 그런 다음 이미지의 높이, 너비, 색상 인코딩 형식, 회전이 포함된 - FirebaseVisionImageMetadata객체를 만듭니다.- Java- FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder() .setWidth(480) // 480x360 is typically sufficient for .setHeight(360) // image recognition .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) .setRotation(rotation) .build(); - Kotlin- val metadata = FirebaseVisionImageMetadata.Builder() .setWidth(480) // 480x360 is typically sufficient for .setHeight(360) // image recognition .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) .setRotation(rotation) .build() - 버퍼나 배열, 메타데이터 객체를 사용하여 - FirebaseVisionImage객체를 만듭니다.- Java- FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata); // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata); - Kotlin- val image = FirebaseVisionImage.fromByteBuffer(buffer, metadata) // Or: val image = FirebaseVisionImage.fromByteArray(byteArray, metadata) 
- Bitmap객체에서- FirebaseVisionImage객체를 만들려면 다음 안내를 따르세요.- Java- FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap); - Kotlin- val image = FirebaseVisionImage.fromBitmap(bitmap) - Bitmap객체로 표현된 이미지가 추가 회전이 필요 없는 수직 상태여야 합니다.
 
- 
    
- processImage()메서드에 이미지를 전달합니다.- Java- objectDetector.processImage(image) .addOnSuccessListener( new OnSuccessListener<List<FirebaseVisionObject>>() { @Override public void onSuccess(List<FirebaseVisionObject> detectedObjects) { // Task completed successfully // ... } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Task failed with an exception // ... } });- Kotlin- objectDetector.processImage(image) .addOnSuccessListener { detectedObjects -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
- processImage()에 대한 호출이 성공하면- FirebaseVisionObject목록이 성공 리스너에 전달됩니다.- 각 - FirebaseVisionObject는 다음 속성을 포함합니다.- 경계 상자 - 이미지에서 객체의 위치를 나타내는 - Rect입니다.- 추적 ID - 여러 이미지 간에 객체를 식별하는 정수입니다. SINGLE_IMAGE_MODE에서는 Null입니다. - 카테고리 - 객체의 대략적인 카테고리입니다. 객체 감지기에 분류가 사용 설정되지 않은 경우에는 - FirebaseVisionObject.CATEGORY_UNKNOWN입니다.- 신뢰도 - 객체 분류의 신뢰값입니다. 객체 감지기에 분류가 사용 설정되지 않았거나 객체가 알 수 없음으로 분류된 경우에는 - null입니다.- Java- // The list of detected objects contains one item if multiple object detection wasn't enabled. for (FirebaseVisionObject obj : detectedObjects) { Integer id = obj.getTrackingId(); Rect bounds = obj.getBoundingBox(); // If classification was enabled: int category = obj.getClassificationCategory(); Float confidence = obj.getClassificationConfidence(); }- Kotlin- // The list of detected objects contains one item if multiple object detection wasn't enabled. for (obj in detectedObjects) { val id = obj.trackingId // A number that identifies the object across images val bounds = obj.boundingBox // The object's position in the image // If classification was enabled: val category = obj.classificationCategory val confidence = obj.classificationConfidence }
사용성 및 성능 향상
최상의 사용자 환경을 위해 앱에서 다음 가이드라인을 따르세요.
- 객체 감지 성공 여부는 객체의 시각적 복잡성에 따라 달라집니다. 객체의 시각적 특징 수가 적으면 감지할 이미지의 더 많은 부분을 사용해야 할 수도 있으므로 감지할 객체 종류에 효과적인 입력을 캡처할 수 있도록 돕는 안내를 사용자에게 제공해야 합니다.
- 분류를 사용할 때 지원되는 카테고리로 확실하게 분류되지 않는 객체를 감지하려면 알 수 없는 객체에 대한 특별한 처리를 구현합니다.
또한 [ML Kit Material Design 쇼케이스 앱][showcase-link]{: .external } 및 Material Design의 머신러닝 기반 기능 패턴 모음도 참조하세요.
실시간 애플리케이션에서 스트리밍 모드를 사용하는 경우 최상의 프레임 속도를 얻기 위해 다음 가이드라인을 따르세요.
- 스트리밍 모드에서 여러 객체 감지를 사용하지 마세요. 대부분의 기기에서 적절한 프레임 속도를 생성할 수 없습니다. 
- 분류가 필요하지 않으면 사용 중지합니다. 
- 감지기 호출을 제한합니다. 인식기가 실행 중일 때 새 동영상 프레임이 제공되는 경우 해당 프레임을 삭제합니다.
- 인식기 출력을 사용해서 입력 이미지에서 그래픽을 오버레이하는 경우 먼저 ML Kit에서 결과를 가져온 후 이미지를 렌더링하고 단일 단계로 오버레이합니다. 이렇게 하면 입력 프레임별로 한 번만 디스플레이 표면에 렌더링됩니다.
- 
  Camera2 API를 사용할 경우 ImageFormat.YUV_420_888형식으로 이미지를 캡처합니다.이전 Camera API를 사용하는 경우 ImageFormat.NV21형식으로 이미지를 캡처합니다.