Python용 얼굴 특징 감지 가이드

MediaPipe Face Landmarker 태스크를 사용하면 이미지와 동영상에서 얼굴 특징과 표정을 감지할 수 있습니다. 이 태스크를 사용하여 사람의 얼굴 표정을 식별하고 얼굴 필터와 효과를 적용하여 가상 아바타를 만들 수 있습니다. 이 작업에서는 단일 이미지 또는 연속적인 이미지 스트림으로 작동할 수 있는 머신러닝 (ML) 모델을 사용합니다. 이 태스크는 3차원 얼굴 랜드마크, 실시간으로 세부적인 얼굴 표면을 추론하는 블렌드셰이프 점수 (얼굴 표정을 나타내는 계수), 효과 렌더링에 필요한 변환을 실행하는 변환 행렬을 출력합니다.

이 안내에 설명된 코드 샘플은 GitHub에서 확인할 수 있습니다. 이 태스크의 기능, 모델, 구성 옵션에 관한 자세한 내용은 개요를 참고하세요.

코드 예

얼굴 랜드마커의 예시 코드는 참고용으로 Python에서 이 작업을 완전히 구현한 코드를 제공합니다. 이 코드를 사용하면 이 작업을 테스트하고 자체 얼굴 랜드마커 빌드를 시작할 수 있습니다. 웹브라우저만 사용하여 얼굴 지형지물표시기 예시 코드를 보고, 실행하고, 수정할 수 있습니다.

Raspberry Pi용 Face Landmarker를 구현하는 경우 Raspberry Pi 예시 앱을 참고하세요.

설정

이 섹션에서는 특히 Face Landmarker를 사용하기 위해 개발 환경과 코드 프로젝트를 설정하는 주요 단계를 설명합니다. 플랫폼 버전 요구사항을 비롯하여 MediaPipe 작업을 사용하기 위한 개발 환경 설정에 관한 일반적인 정보는 Python 설정 가이드를 참고하세요.

패키지

MediaPipe Face Landmarker 태스크에는 mediapipe PyPI 패키지가 필요합니다. 다음을 사용하여 이러한 종속 항목을 설치하고 가져올 수 있습니다.

$ python -m pip install mediapipe

가져오기

Face Landmarker 태스크 함수에 액세스하려면 다음 클래스를 가져옵니다.

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

모델

MediaPipe Face Landmarker 태스크를 사용하려면 이 태스크와 호환되는 학습된 모델이 필요합니다. Face Landmarker에 사용할 수 있는 학습된 모델에 관한 자세한 내용은 작업 개요 모델 섹션을 참고하세요.

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

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

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

할 일 만들기

MediaPipe Face Landmarker 작업은 create_from_options 함수를 사용하여 작업을 설정합니다. create_from_options 함수는 처리할 구성 옵션의 값을 허용합니다. 구성 옵션에 관한 자세한 내용은 구성 옵션을 참고하세요.

다음 코드는 이 태스크를 빌드하고 구성하는 방법을 보여줍니다.

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

이미지

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceLandmarker = mp.tasks.vision.FaceLandmarker
FaceLandmarkerOptions = mp.tasks.vision.FaceLandmarkerOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = FaceLandmarkerOptions(
    base_options=BaseOptions(model_asset_path=model_path),
    running_mode=VisionRunningMode.IMAGE)

with FaceLandmarker.create_from_options(options) as landmarker:
  # The landmarker is initialized. Use it here.
  # ...
    

동영상

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceLandmarker = mp.tasks.vision.FaceLandmarker
FaceLandmarkerOptions = mp.tasks.vision.FaceLandmarkerOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face landmarker instance with the video mode:
options = FaceLandmarkerOptions(
    base_options=BaseOptions(model_asset_path=model_path),
    running_mode=VisionRunningMode.VIDEO)

with FaceLandmarker.create_from_options(options) as landmarker:
  # The landmarker is initialized. Use it here.
  # ...
    

실시간 스트림

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceLandmarker = mp.tasks.vision.FaceLandmarker
FaceLandmarkerOptions = mp.tasks.vision.FaceLandmarkerOptions
FaceLandmarkerResult = mp.tasks.vision.FaceLandmarkerResult
VisionRunningMode = mp.tasks.vision.RunningMode

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

options = FaceLandmarkerOptions(
    base_options=BaseOptions(model_asset_path=model_path),
    running_mode=VisionRunningMode.LIVE_STREAM,
    result_callback=print_result)

with FaceLandmarker.create_from_options(options) as landmarker:
  # The landmarker is initialized. Use it here.
  # ...
    

이미지와 함께 사용할 얼굴 랜드마커를 만드는 전체 예시는 코드 예시를 참고하세요.

구성 옵션

이 작업에는 Python 애플리케이션의 다음 구성 옵션이 있습니다.

옵션 이름 설명 값 범위 기본값
running_mode 태스크의 실행 모드를 설정합니다. 모드는 세 가지입니다.

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

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

LIVE_STREAM: 카메라와 같은 입력 데이터의 라이브 스트림 모드입니다. 이 모드에서는 결과를 비동기식으로 수신할 리스너를 설정하려면 resultListener를 호출해야 합니다.
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
num_faces FaceLandmarker에서 감지할 수 있는 최대 얼굴 수입니다. 보간은 num_faces가 1로 설정된 경우에만 적용됩니다. Integer > 0 1
min_face_detection_confidence 얼굴 감지가 성공으로 간주되는 최소 신뢰도 점수입니다. Float [0.0,1.0] 0.5
min_face_presence_confidence 얼굴 특징 감지에서 얼굴 존재 점수의 최소 신뢰도 점수입니다. Float [0.0,1.0] 0.5
min_tracking_confidence 얼굴 추적이 성공으로 간주되는 최소 신뢰도 점수입니다. Float [0.0,1.0] 0.5
output_face_blendshapes 얼굴 랜드마커가 얼굴 블렌드셰이프를 출력하는지 여부입니다. 얼굴 블렌드셰이프는 3D 얼굴 모델을 렌더링하는 데 사용됩니다. Boolean False
output_facial_transformation_matrixes FaceLandmarker가 얼굴 변환 행렬을 출력하는지 여부입니다. FaceLandmarker는 행렬을 사용하여 얼굴 특징을 표준 얼굴 모델에서 감지된 얼굴로 변환하므로 사용자가 감지된 특징에 효과를 적용할 수 있습니다. Boolean False
result_callback FaceLandmarker가 라이브 스트림 모드일 때 랜드마커 결과를 비동기식으로 수신하도록 결과 리스너를 설정합니다. 실행 모드가 LIVE_STREAM로 설정된 경우에만 사용할 수 있습니다. ResultListener N/A

데이터 준비

입력을 이미지 파일 또는 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 landmarking on the provided single image.
# The face landmarker must be created with the image mode.
face_landmarker_result = landmarker.detect(mp_image)
    

동영상

# Perform face landmarking on the provided single image.
# The face landmarker must be created with the video mode.
face_landmarker_result = landmarker.detect_for_video(mp_image, frame_timestamp_ms)
    

실시간 스트림

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

다음에 유의하세요.

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

이미지에서 얼굴 위치 지정 도구를 실행하는 전체 예는 코드 예를 참고하세요.

결과 처리 및 표시

얼굴 랜드마커는 감지 실행마다 FaceLandmarkerResult 객체를 반환합니다. 결과 객체에는 각 얼굴 랜드마크의 좌표와 함께 감지된 각 얼굴의 얼굴 메시가 포함됩니다. 원하는 경우 결과 객체에 얼굴 표정을 나타내는 블렌드셰이프와 감지된 특징에 얼굴 효과를 적용하는 얼굴 변환 매트릭스도 포함될 수 있습니다.

다음은 이 태스크의 출력 데이터 예시입니다.

FaceLandmarkerResult:
  face_landmarks:
    NormalizedLandmark #0:
      x: 0.5971359014511108
      y: 0.485361784696579
      z: -0.038440968841314316
    NormalizedLandmark #1:
      x: 0.3302789330482483
      y: 0.29289937019348145
      z: -0.09489090740680695
    ... (478 landmarks for each face)
  face_blendshapes:
    browDownLeft: 0.8296722769737244
    browDownRight: 0.8096957206726074
    browInnerUp: 0.00035583582939580083
    browOuterUpLeft: 0.00035752105759456754
    ... (52 blendshapes for each face)
  facial_transformation_matrixes:
    [9.99158978e-01, -1.23036895e-02, 3.91213447e-02, -3.70770246e-01]
    [1.66496094e-02,  9.93480563e-01, -1.12779640e-01, 2.27719707e+01]
    ...

다음 이미지는 태스크 출력의 시각화를 보여줍니다.

얼굴의 도형과 크기를 나타내기 위해 얼굴 영역이 기하학적으로 매핑된 남성

얼굴 위치 지정자 예시 코드는 태스크에서 반환된 결과를 표시하는 방법을 보여줍니다. 자세한 내용은 코드 예시를 참고하세요.