특징점 탐지
mediapipe
- 구글이 개발한 ML 라이브러리
- 얼굴 인식 등 다양한 종류의 과제를 간단히 수행할 수 있도록 제공
설치
pip install mediapipe
실습 준비
모듈 임포트
import cv2
import mediapipe as mp
import numpy as np
from PIL import Image
화면 캡처
cap = cv2.VideoCapture(0)
success, frame = cap.read()
보기
frame = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)
Image.fromarray(frame)
얼굴 탐지 준비
mp_face = mp.solutions.face_detection
face = mp_face.FaceDetection(
model_selection=1,
min_detection_confidence=0.5)
model_selection
:
- 0: 카메라와 사람의 거리가 2미터 이내인 경우에 적절한 모델(예: 셀카)
- 1: 카메라와 사람의 거리가 5미터 이내인 경우에 적절한 모델
min_detection_confidence
: 탐지하기에 필요한 최소 점수(0.0~1.0)
얼굴 탐지 처리
처리
results = face.process(frame)
결과 보기
results.detections
결과 출력
for문을 이용해서 탐지된 결과에서 코의 위치를 출력하고 이미지에 표시
draw = mp.solutions.drawing_utils
for d in results.detections:
print(mp_face.get_key_point(d, mp_face.FaceKeyPoint.NOSE_TIP))
draw.draw_detection(frame, d)
x: 0.5702608823776245 y: 0.5426509976387024
결과 보기
Image.fromarray(frame)
손가락 위치
mp_hands = mp.solutions.hands
hand = mp_hands.Hands(
max_num_hands=2, # 인식할 수 있는 손의 최대 개수
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
처리
hand_results = hand.process(frame)
결과 보기
hand_results.multi_hand_landmarks
시각화
if hand_results.multi_hand_landmarks:
for hand_landmarks in hand_results.multi_hand_landmarks:
draw.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
Image.fromarray(frame)
웹캠을 이용해서 얼굴 탐지
웹캠이 켜진 동안 반복
cap = cv2.VideoCapture(0)
while cap.isOpened():
success, frame = cap.read()
if not success:
break
# 캡처된 이미지 처리
frame.flags.writeable = False
frame = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)
face_results = face.process(frame)
hand_results = hand.process(frame)
# 출력을 위해 이미지를 BGR로 되돌림
frame.flags.writeable = True
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# 탐지된 얼굴 표시
if face_results.detections:
for detection in face_results.detections:
draw.draw_detection(frame, detection)
# 탐지된 손 표시
if hand_results.multi_hand_landmarks:
for hand_landmarks in hand_results.multi_hand_landmarks:
draw.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
cv2.imshow('Face', cv2.flip(frame, 1))
# 아무 키나 입력 받으면 멈춤
if cv2.waitKey(5) != -1:
break
cap.release() # 카메라 해제
cv2.destroyAllWindows() # 모든 창 닫기