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

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

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

사용해 보기

  • 샘플 앱을 사용하여 이 API의 사용 예를 참조하세요.
  • Codelab을 참고하세요.

시작하기 전에

<ph type="x-smartling-placeholder">
  1. 프로젝트 수준 build.gradle 파일에 Google의 buildscriptallprojects 섹션에 있는 Maven 저장소

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

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

    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 <ph type="x-smartling-placeholder"></ph> PERFORMANCE_MODE_FAST (기본값) | PERFORMANCE_MODE_ACCURATE

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

setLandmarkMode <ph type="x-smartling-placeholder"></ph> LANDMARK_MODE_NONE (기본값) | LANDMARK_MODE_ALL

눈, 귀, 코, 얼굴의 '특징'을 식별할 것인지 여부 볼 수 있습니다.

setContourMode <ph type="x-smartling-placeholder"></ph> CONTOUR_MODE_NONE (기본값) | CONTOUR_MODE_ALL

얼굴 특징의 윤곽을 감지할지 여부입니다. 윤곽선은 자동으로 감지됩니다.

setClassificationMode <ph type="x-smartling-placeholder"></ph> 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. 입력 이미지 준비

이미지 속 얼굴을 인식하려면 InputImage 객체를 만듭니다. Bitmap, media.Image, ByteBuffer, 바이트 배열 또는 있습니다. 그런 다음 InputImage 객체를 FaceDetectorprocess 메서드

얼굴 인식의 경우 크기가 다음 이상인 이미지를 사용해야 합니다. 480x360 픽셀 실시간으로 얼굴을 인식하는 경우 프레임 캡처 지연 시간을 줄이는 데 도움이 됩니다.

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

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
            // ...
        }

자바

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
                                // ...
                            }
                        });
<ph type="x-smartling-placeholder">

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
    }
}

자바

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 감지기 호출을 제한합니다. 새 동영상 감지기가 실행되는 동안 frame 사용할 수 있게 되면 프레임을 삭제합니다. 자세한 내용은 <ph type="x-smartling-placeholder"></ph> VisionProcessorBase 클래스를 참조하세요.
  • CameraX API를 사용하는 경우 백프레셔 전략이 기본값으로 설정되어 있는지 확인 ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST 이렇게 하면 분석을 위해 한 번에 하나의 이미지만 전송됩니다. 더 많은 이미지가 분석기가 사용 중일 때 생성되지 않으면 자동으로 삭제되어 배달. 분석 중인 이미지가 ImageProxy.close()를 호출하면 다음 최신 이미지가 게재됩니다.
  • 감지기 출력을 사용하여 그래픽 이미지를 먼저 ML Kit에서 결과를 가져온 후 이미지를 하나의 단계로 오버레이할 수 있습니다. 이는 디스플레이 표면에 렌더링됩니다. 각 입력 프레임에 대해 한 번만 허용됩니다. 자세한 내용은 <ph type="x-smartling-placeholder"></ph> CameraSourcePreview GraphicOverlay 클래스를 참조하세요.
  • Camera2 API를 사용하는 경우 ImageFormat.YUV_420_888 형식으로 이미지를 캡처합니다. 이전 Camera API를 사용하는 경우 ImageFormat.NV21 형식으로 이미지를 캡처합니다.