Python용 얼굴 인식 가이드

MediaPipe 얼굴 인식기 작업을 사용하면 이미지 또는 동영상에서 얼굴을 감지할 수 있습니다. 이 작업을 사용하여 프레임 내에서 얼굴과 얼굴 특징을 찾을 수 있습니다. 이 작업은 단일 이미지 또는 연속 이미지 스트림으로 작동하는 머신러닝 (ML) 모델을 사용합니다. 작업은 왼쪽 눈, 오른쪽 눈, 코 끝, 입, 왼쪽 눈 이주, 오른쪽 눈 이주와 같은 얼굴의 핵심 포인트와 함께 얼굴 위치를 출력합니다.

이 안내에 설명된 코드 샘플은 GitHub에서 제공됩니다. 이 태스크의 기능, 모델, 구성 옵션에 대한 자세한 내용은 개요를 참조하세요.

코드 예시

얼굴 인식기의 예시 코드는 참조용으로 Python에서 이 작업을 완전히 구현합니다. 이 코드는 이 작업을 테스트하고 자체 얼굴 감지기 빌드를 시작하는 데 도움이 됩니다. 웹브라우저만 사용하여 얼굴 인식기 예시 코드를 보고 실행하고 수정할 수 있습니다.

Raspberry Pi용 얼굴 인식기를 구현하는 경우 Raspberry Pi 예시 앱을 참고하세요.

설정

이 섹션에서는 개발 환경을 설정하고 얼굴 감지기를 사용하도록 프로젝트를 코딩하는 주요 단계를 설명합니다. 플랫폼 버전 요구사항을 포함하여 MediaPipe 태스크를 사용하기 위한 개발 환경 설정에 관한 일반적인 정보는 Python 설정 가이드를 참조하세요.

패키지

MediaPipe 얼굴 인식기 작업에는 mediapipe PyPI 패키지가 필요합니다. 다음을 사용하여 이러한 종속 항목을 설치하고 가져올 수 있습니다.

$ python -m pip install mediapipe

가져오기

다음 클래스를 가져와 얼굴 인식기 작업 함수에 액세스합니다.

import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision

모델

MediaPipe 얼굴 감지기 작업에는 이 작업과 호환되는 학습된 모델이 필요합니다. 얼굴 인식기에 사용할 수 있는 학습된 모델에 대한 자세한 내용은 작업 개요 모델 섹션을 참조하세요.

모델을 선택 및 다운로드한 다음 로컬 디렉터리에 저장합니다.

model_path = '/absolute/path/to/face_detector.task'

BaseOptions 객체 model_asset_path 매개변수를 사용하여 사용할 모델의 경로를 지정합니다. 코드 예는 다음 섹션을 참고하세요.

할 일 만들기

MediaPipe 얼굴 인식기 작업은 create_from_options 함수를 사용하여 작업을 설정합니다. create_from_options 함수는 처리할 구성 옵션의 값을 허용합니다. 구성 옵션에 대한 자세한 내용은 구성 옵션을 참조하세요.

다음 코드는 이 작업을 빌드하고 구성하는 방법을 보여줍니다.

또한 이 샘플은 이미지, 동영상 파일, 라이브 스트림에 대한 작업 구성의 변형을 보여줍니다.

이미지

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face detector instance with the image mode:
options = FaceDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.IMAGE)
with FaceDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

동영상

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face detector instance with the video mode:
options = FaceDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.VIDEO)
with FaceDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

라이브 스트림

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
FaceDetectorResult = mp.tasks.vision.FaceDetectorResult
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face detector instance with the live stream mode:
def print_result(result: FaceDetectorResult, output_image: mp.Image, timestamp_ms: int):
    print('face detector result: {}'.format(result))

options = FaceDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.LIVE_STREAM,
    result_callback=print_result)
with FaceDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

이미지에 사용할 얼굴 인식기를 만드는 전체 예는 코드 예를 참고하세요.

구성 옵션

이 태스크에는 다음과 같은 Python 애플리케이션 구성 옵션이 있습니다.

옵션 이름 설명 값 범위 기본값
running_mode 작업의 실행 모드를 설정합니다. 모드는 세 가지가 있습니다.

IMAGE: 단일 이미지 입력 모드입니다.

VIDEO: 동영상의 디코딩된 프레임에 대한 모드입니다.

LIVE_STREAM: 카메라에서 전송하는 것과 같은 입력 데이터의 실시간 스트림 모드입니다. 이 모드에서는 resultListener를 호출하여 비동기식으로 결과를 수신하도록 리스너를 설정해야 합니다.
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
min_detection_confidence 얼굴 인식이 성공한 것으로 간주되는 최소 신뢰도 점수입니다. Float [0,1] 0.5
min_suppression_threshold 얼굴 인식이 겹치는 것으로 간주되기 위한 최소 비최대 비표시 기준점입니다. Float [0,1] 0.3
result_callback 얼굴 인식기가 라이브 스트림 모드일 때 감지 결과를 비동기식으로 수신하도록 결과 리스너를 설정합니다. 달리기 모드가 LIVE_STREAM로 설정된 경우에만 사용할 수 있습니다. N/A Not set

데이터 준비

입력을 이미지 파일 또는 Numpy 배열로 준비한 다음 mediapipe.Image 객체로 변환합니다. 입력이 동영상 파일이나 웹캠의 실시간 스트림인 경우 OpenCV와 같은 외부 라이브러리를 사용하여 입력 프레임을 Numpy 배열로 로드할 수 있습니다.

이미지

import mediapipe as mp

# Load the input image from an image file.
mp_image = mp.Image.create_from_file('/path/to/image')

# Load the input image from a numpy array.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_image)
    

동영상

import mediapipe as mp

# Use OpenCV’s VideoCapture to load the input video.

# Load the frame rate of the video using OpenCV’s CV_CAP_PROP_FPS
# You’ll need it to calculate the timestamp for each frame.

# Loop through each frame in the video using VideoCapture#read()

# Convert the frame received from OpenCV to a MediaPipe’s Image object.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
    

라이브 스트림

import mediapipe as mp

# Use OpenCV’s VideoCapture to start capturing from the webcam.

# Create a loop to read the latest frame from the camera using VideoCapture#read()

# Convert the frame received from OpenCV to a MediaPipe’s Image object.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
    

작업 실행

얼굴 인식기는 detect, detect_for_video, detect_async 함수를 사용하여 추론을 트리거합니다. 얼굴 인식의 경우 입력 데이터 사전 처리 및 이미지의 얼굴 인식이 포함됩니다.

다음 코드는 작업 모델을 사용하여 처리를 실행하는 방법을 보여줍니다.

이미지

# Perform face detection on the provided single image.
# The face detector must be created with the image mode.
face_detector_result = detector.detect(mp_image)
    

동영상

# Perform face detection on the provided single image.
# The face detector must be created with the video mode.
face_detector_result = detector.detect_for_video(mp_image, frame_timestamp_ms)
    

라이브 스트림

# Send live image data to perform face detection.
# The results are accessible via the `result_callback` provided in
# the `FaceDetectorOptions` object.
# The face detector must be created with the live stream mode.
detector.detect_async(mp_image, frame_timestamp_ms)
    

다음에 유의하세요.

  • 동영상 모드 또는 라이브 스트림 모드에서 실행하는 경우 얼굴 인식기 작업에 입력 프레임의 타임스탬프도 제공합니다.
  • 이미지 또는 동영상 모델에서 실행하는 경우 얼굴 인식기 작업은 입력 이미지 또는 프레임 처리가 완료될 때까지 현재 스레드를 차단합니다.
  • 라이브 스트림 모드에서 실행하면 얼굴 인식기 작업이 즉시 반환되며 현재 스레드를 차단하지 않습니다. 입력 프레임 처리가 완료될 때마다 감지 결과와 함께 결과 리스너를 호출합니다. 얼굴 인식기 작업이 다른 프레임을 처리 중일 때 감지 함수가 호출되면 새 입력 프레임을 무시합니다.

이미지에서 얼굴 인식기를 실행하는 전체 예는 코드 예를 참고하세요.

결과 처리 및 표시

얼굴 인식기는 인식을 실행할 때마다 FaceDetectorResult 객체를 반환합니다. 결과 객체에는 인식된 얼굴의 경계 상자와 인식된 각 얼굴의 신뢰도 점수가 포함됩니다.

다음은 이 작업의 출력 데이터 예를 보여줍니다.

FaceDetectionResult:
  Detections:
    Detection #0:
      BoundingBox:
        origin_x: 126
        origin_y: 100
        width: 463
        height: 463
      Categories:
        Category #0:
          index: 0
          score: 0.9729152917861938
      NormalizedKeypoints:
        NormalizedKeypoint #0:
          x: 0.18298381567001343
          y: 0.2961040139198303
        NormalizedKeypoint #1:
          x: 0.3302789330482483
          y: 0.29289937019348145
        ... (6 keypoints for each face)
    Detection #1:
      BoundingBox:
        origin_x: 616
        origin_y: 193
        width: 430
        height: 430
      Categories:
        Category #0:
          index: 0
          score: 0.9251380562782288
      NormalizedKeypoints:
        NormalizedKeypoint #0:
          x: 0.6151331663131714
          y: 0.3713381886482239
        NormalizedKeypoint #1:
          x: 0.7460576295852661
          y: 0.38825345039367676
        ... (6 keypoints for each face)

다음 이미지는 작업 출력을 시각화한 것입니다.

경계 상자가 없는 이미지의 경우 원본 이미지를 참조하세요.

얼굴 인식기 예시 코드는 작업에서 반환된 결과를 표시하는 방법을 보여줍니다. 자세한 내용은 코드 예시를 참고하세요.