Android에서 ML Kit를 사용하여 얼굴 인식

ML Kit를 사용하면 이미지 및 동영상에서 얼굴을 감지할 수 있습니다.

특성번들로 묶이지 않음번들
구현모델은 Google Play 서비스를 통해 동적으로 다운로드됩니다.모델은 빌드 시간에 앱에 정적으로 연결됩니다.
앱 크기크기가 약 800KB 증가했습니다.크기가 약 6.9MB 증가했습니다.
초기화 시간처음 사용하기 전에 모델이 다운로드될 때까지 기다려야 할 수 있습니다.모델을 즉시 사용할 수 있습니다.

사용해 보기

  • 샘플 앱을 살펴보고 이 API의 사용 예를 확인하세요.
  • Codelab을 통해 직접 코드를 사용해 보세요.

시작하기 전에

  1. 프로젝트 수준 build.gradle 파일의 buildscriptallprojects 섹션에 Google의 Maven 저장소가 포함되어야 합니다.

  2. 모듈의 앱 수준 Gradle 파일(일반적으로 app/build.gradle)에 ML Kit Android 라이브러리의 종속 항목을 추가합니다. 필요에 따라 다음 종속 항목 중 하나를 선택합니다.

    모델을 앱과 번들로 묶는 경우:

    dependencies {
      // ...
      // Use this dependency to bundle the model with your app
      implementation 'com.google.mlkit:face-detection:16.1.6'
    }
    

    Google Play 서비스에서 모델을 사용하는 경우:

    dependencies {
      // ...
      // Use this dependency to use the dynamically downloaded model in Google Play Services
      implementation 'com.google.android.gms:play-services-mlkit-face-detection:17.1.0'
    }
    
  3. Google Play 서비스에서 모델을 사용하도록 선택한 경우 Play 스토어에서 앱을 설치한 후 자동으로 모델을 기기에 다운로드하도록 앱을 구성할 수 있습니다. 이렇게 하려면 앱의 AndroidManifest.xml 파일에 다음 선언을 추가합니다.

    <application ...>
          ...
          <meta-data
              android:name="com.google.mlkit.vision.DEPENDENCIES"
              android:value="face" >
          <!-- To use multiple models: android:value="face,model2,model3" -->
    </application>
    

    모델 가용성을 명시적으로 확인하고 Google Play 서비스 ModuleInstallClient API를 통해 다운로드를 요청할 수도 있습니다.

    설치 시간 모델 다운로드를 사용 설정하거나 명시적 다운로드를 요청하지 않으면 감지기를 처음 실행할 때 모델이 다운로드됩니다. 다운로드가 완료되기 전에 요청하면 결과가 생성되지 않습니다.

입력 이미지 가이드라인

얼굴 인식에는 크기가 480x360픽셀 이상인 이미지를 사용해야 합니다. ML Kit가 얼굴을 정확하게 인식하려면 입력 이미지에 충분한 픽셀 데이터로 표시된 얼굴이 포함되어 있어야 합니다. 일반적으로 이미지에서 인식하려는 각 얼굴은 100x100픽셀 이상이어야 합니다. 얼굴 윤곽을 인식하려면 ML Kit에 더 높은 해상도의 입력이 필요합니다. 각 얼굴이 200x200픽셀 이상이어야 합니다.

실시간 애플리케이션에서 얼굴을 인식하는 경우 입력 이미지의 전체 크기도 고려해야 합니다. 이미지가 작을수록 더 빠르게 처리될 수 있으므로 지연 시간을 줄이려면 낮은 해상도에서 이미지를 캡처하세요. 단, 위의 정확도 요구사항에 유의하고 피사체의 얼굴이 최대한 많은 이미지를 차지하도록 해야 합니다. 또한 실시간 성능 향상을 위한 팁도 참조하세요.

이미지 초점이 잘 맞지 않으면 정확도에 영향을 줄 수도 있습니다. 허용 가능한 결과를 얻지 못하면 사용자에게 이미지를 다시 캡처하도록 요청합니다.

카메라를 기준으로 한 얼굴의 방향은 ML Kit가 감지하는 얼굴 특징에 영향을 줄 수도 있습니다. 얼굴 인식 개념을 참조하세요.

1. 얼굴 감지기 구성

이미지에 얼굴 인식 기능을 적용하기 전에 얼굴 인식기의 기본 설정을 변경하려면 FaceDetectorOptions 객체를 사용하여 설정을 지정하세요. 다음 설정을 변경할 수 있습니다.

설정
setPerformanceMode PERFORMANCE_MODE_FAST (기본값) | PERFORMANCE_MODE_ACCURATE

얼굴을 감지할 때 속도 또는 정확성을 우선시합니다.

setLandmarkMode LANDMARK_MODE_NONE (기본값) | LANDMARK_MODE_ALL

눈, 귀, 코, 뺨, 입과 같은 얼굴의 '특징'을 식별할 것인지 여부입니다.

setContourMode CONTOUR_MODE_NONE (기본값) | CONTOUR_MODE_ALL

얼굴 특징의 윤곽을 감지할지 여부입니다. 윤곽은 이미지 속 가장 뚜렷한 얼굴에 대해서만 인식됩니다.

setClassificationMode CLASSIFICATION_MODE_NONE (기본값) | CLASSIFICATION_MODE_ALL

얼굴을 '웃고 있음', '눈을 뜨고 있음' 등의 카테고리로 분류할 것인지 여부입니다.

setMinFaceSize float(기본값: 0.1f)

이미지 너비에 대한 머리 너비의 비율로 표현되며 원하는 가장 작은 얼굴 크기를 설정합니다.

enableTracking false (기본값) | true

얼굴에 ID를 할당할지 여부입니다. 이는 여러 이미지에서 얼굴을 추적하는 데 사용할 수 있습니다.

윤곽 인식이 사용 설정되면 얼굴 한 개만 인식되므로 얼굴 추적으로 유용한 결과가 생성되지 않습니다. 따라서 인식 속도를 높이려면 윤곽 인식과 얼굴 추적을 모두 사용 설정하지 마세요.

예를 들면 다음과 같습니다.

Kotlin

// High-accuracy landmark detection and face classification
val highAccuracyOpts = FaceDetectorOptions.Builder()
        .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
        .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
        .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL)
        .build()

// Real-time contour detection
val realTimeOpts = FaceDetectorOptions.Builder()
        .setContourMode(FaceDetectorOptions.CONTOUR_MODE_ALL)
        .build()

Java

// High-accuracy landmark detection and face classification
FaceDetectorOptions highAccuracyOpts =
        new FaceDetectorOptions.Builder()
                .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
                .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
                .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL)
                .build();

// Real-time contour detection
FaceDetectorOptions realTimeOpts =
        new FaceDetectorOptions.Builder()
                .setContourMode(FaceDetectorOptions.CONTOUR_MODE_ALL)
                .build();

2. 입력 이미지 준비

이미지 속 얼굴을 인식하려면 Bitmap, media.Image, ByteBuffer, 바이트 배열, 기기의 파일에서 InputImage 객체를 만듭니다. 그런 다음 InputImage 객체를 FaceDetectorprocess 메서드에 전달합니다.

얼굴 인식의 경우 크기가 480x360픽셀 이상인 이미지를 사용해야 합니다. 실시간으로 얼굴을 인식하는 경우 이 최소 해상도로 프레임을 캡처하면 지연 시간을 줄일 수 있습니다.

다양한 소스에서 InputImage 객체를 만들 수 있습니다. 각 소스는 아래에 설명되어 있습니다.

media.Image 사용

기기의 카메라에서 이미지를 캡처할 때와 같이 media.Image 객체에서 InputImage 객체를 만들려면 media.Image 객체 및 이미지 회전을 InputImage.fromMediaImage()에 전달합니다.

CameraX 라이브러리를 사용하는 경우 OnImageCapturedListenerImageAnalysis.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 객체 및 회전 각도 값을 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
)

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 객체로 표현됩니다.

3. FaceDetector 인스턴스 가져오기

Kotlin

val detector = FaceDetection.getClient(options)
// Or, to use the default option:
// val detector = FaceDetection.getClient();

Java

FaceDetector detector = FaceDetection.getClient(options);
// Or use the default options:
// FaceDetector detector = FaceDetection.getClient();

4. 이미지 처리

이미지를 process 메서드에 전달합니다.

Kotlin

val result = detector.process(image)
        .addOnSuccessListener { faces ->
            // Task completed successfully
            // ...
        }
        .addOnFailureListener { e ->
            // Task failed with an exception
            // ...
        }

Java

Task<List<Face>> result =
        detector.process(image)
                .addOnSuccessListener(
                        new OnSuccessListener<List<Face>>() {
                            @Override
                            public void onSuccess(List<Face> faces) {
                                // Task completed successfully
                                // ...
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                // Task failed with an exception
                                // ...
                            }
                        });

5. 감지된 얼굴에 관한 정보 얻기

얼굴 인식 작업이 성공하면 Face 객체의 목록이 성공 리스너에 전달됩니다. 각 Face 객체는 이미지에서 인식된 얼굴을 나타냅니다. 얼굴별로 입력 이미지의 경계 좌표 및 얼굴 인식기가 찾도록 구성한 다른 정보를 가져올 수 있습니다. 예를 들면 다음과 같습니다.

Kotlin

for (face in faces) {
    val bounds = face.boundingBox
    val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees
    val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees

    // If landmark detection was enabled (mouth, ears, eyes, cheeks, and
    // nose available):
    val leftEar = face.getLandmark(FaceLandmark.LEFT_EAR)
    leftEar?.let {
        val leftEarPos = leftEar.position
    }

    // If contour detection was enabled:
    val leftEyeContour = face.getContour(FaceContour.LEFT_EYE)?.points
    val upperLipBottomContour = face.getContour(FaceContour.UPPER_LIP_BOTTOM)?.points

    // If classification was enabled:
    if (face.smilingProbability != null) {
        val smileProb = face.smilingProbability
    }
    if (face.rightEyeOpenProbability != null) {
        val rightEyeOpenProb = face.rightEyeOpenProbability
    }

    // If face tracking was enabled:
    if (face.trackingId != null) {
        val id = face.trackingId
    }
}

Java

for (Face face : faces) {
    Rect bounds = face.getBoundingBox();
    float rotY = face.getHeadEulerAngleY();  // Head is rotated to the right rotY degrees
    float rotZ = face.getHeadEulerAngleZ();  // Head is tilted sideways rotZ degrees

    // If landmark detection was enabled (mouth, ears, eyes, cheeks, and
    // nose available):
    FaceLandmark leftEar = face.getLandmark(FaceLandmark.LEFT_EAR);
    if (leftEar != null) {
        PointF leftEarPos = leftEar.getPosition();
    }

    // If contour detection was enabled:
    List<PointF> leftEyeContour =
            face.getContour(FaceContour.LEFT_EYE).getPoints();
    List<PointF> upperLipBottomContour =
            face.getContour(FaceContour.UPPER_LIP_BOTTOM).getPoints();

    // If classification was enabled:
    if (face.getSmilingProbability() != null) {
        float smileProb = face.getSmilingProbability();
    }
    if (face.getRightEyeOpenProbability() != null) {
        float rightEyeOpenProb = face.getRightEyeOpenProbability();
    }

    // If face tracking was enabled:
    if (face.getTrackingId() != null) {
        int id = face.getTrackingId();
    }
}

얼굴 윤곽의 예

얼굴 윤곽 인식이 사용 설정되어 있으면 인식된 각 얼굴 특징에 대한 점 목록을 가져옵니다. 이러한 점들은 지형지물의 모양을 나타냅니다. 윤곽 표시 방법에 대한 자세한 내용은 얼굴 인식 개념을 참조하세요.

다음 이미지는 이러한 점들이 얼굴에 매핑되는 방식을 보여줍니다. 이미지를 클릭하여 확대합니다.

감지된 얼굴 윤곽 메시 예

실시간 얼굴 인식

실시간 애플리케이션에서 얼굴 인식을 사용하려는 경우 최상의 프레임 속도를 얻으려면 다음 가이드라인을 따르세요.

  • 얼굴 윤곽 인식 또는 분류와 특징 인식을 사용하도록 얼굴 인식기를 구성합니다. 단, 둘 다 사용할 수는 없습니다.

    윤곽 인식
    랜드마크 인식
    분류
    랜드마크 인식 및 분류
    윤곽 인식 및 랜드마크 인식
    윤곽 인식 및 분류
    윤곽 인식, 랜드마크 인식, 분류

  • FAST 모드를 사용 설정합니다 (기본적으로 사용 설정됨).

  • 낮은 해상도에서 이미지를 캡처하는 것이 좋습니다. 그러나 이 API의 이미지 크기 요구사항도 유의해야 합니다.

  • 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 형식으로 이미지를 캡처합니다.