1 분 소요

simple project

추가적인 공부 : https://opencv-python.readthedocs.io/en/latest/

프로젝트 : 얼굴 인식

mediapipe라이브러리를 활용한 Face Detection

패키지 설치 및 mediapipe에서 기본 코드 불러오기

pip install mediapipe

불러온 동영상에서 얼굴(눈,코,입)인식

import cv2
import mediapipe as mp

# 얼굴을 찾고, 찾은 얼굴에 표시를 해주기 위한 변수 정의
mp_face_detection = mp.solutions.face_detection # 얼굴 검출을 위한 face_detection 모듈을 사용
mp_drawing = mp.solutions.drawing_utils #얼굴의 특징을 그리기 위한 drawing_utils 모듈을 사용

# 동영상 파일 열기
cap = cv2.VideoCapture('Face_video.mp4')


with mp_face_detection.FaceDetection(
    model_selection=0, # 0(근거리 : 2m정도) or 1(원거리 :5m정도) 
    min_detection_confidence=0.7) as face_detection: # 70% confidence 이상이면 얼굴로 인식한다는 뜻(threshold)
    while cap.isOpened():
        success, image = cap.read()
        if not success:
            # 동영상 쓸 거면 'break' 웹캡이면 'continue'.
            break

        # To improve performance, optionally mark the image as not writeable to
        # pass by reference.
        image.flags.writeable = False
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #RGB로 변환
        results = face_detection.process(image) # 얼굴 인식

        # Draw the face detection annotations on the image.
        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        
        if results.detections: # 얼굴 인식 결과 정보 활용해서 image에 그리기
            # 6개의 특징 좌표 뽑아냄 (좌우 눈, 좌우 귀, 코, 입)
            for detection in results.detections:
                
                # 각 좌표에 점 찍기
                mp_drawing.draw_detection(image, detection)
                
                #특정 위치(좌표) 가져오기
                keypoints = detection.location_data.relative_keypoints
                right_eye = keypoints[0] #오른쪽 눈
                left_eye = keypoints[1] #왼쪽 눈
                nose_tip = keypoints[2] #코 끝부분
                
                #실제 이미지상에서의 좌표로 변환
                h, w, _ = image.shape #height, width, channel : 이미지로부터 행, 열 크기 가져옴
                right_eye = (int(right_eye.x * w), int(right_eye.y * h))
                left_eye = (int(left_eye.x * w), int(left_eye.y * h))
                nose_tip = (int(nose_tip.x * w), int(nose_tip.y * h))
                
                #눈에 동그라미 그리기
                cv2.circle(image, right_eye, 50, (255,0,0), 10, cv2.LINE_AA) 
                cv2.circle(image, left_eye, 50, (0,255,0), 10, cv2.LINE_AA) 
                
                #코에 동그라미 그리기
                cv2.circle(image, nose_tip, 50, (0,0,255), 10, cv2.LINE_AA)
                
                
                
        # Flip the image horizontally for a selfie-view display.
        cv2.imshow('MediaPipe Face Detection', cv2.resize(image, None, fx=0.5, fy=0.5))
        
        if cv2.waitKey(1) == ord('q'):
            break
cap.release()
cv2.destroyAllWindows()

카테고리:

업데이트: