| 10번째 줄: |
10번째 줄: |
| | detector = dlib.get_frontal_face_detector() # 얼굴탐지모델 | | detector = dlib.get_frontal_face_detector() # 얼굴탐지모델 |
| | predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') # 얼굴 랜드마크 탐지 모델. 학습된 모델을 가져온다. | | predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') # 얼굴 랜드마크 탐지 모델. 학습된 모델을 가져온다. |
| | + | facerec = dlib.face_recognition_model_v1('models/dlib_face_recognition_resnet_model_v1.dat') # 인식모델. 랜드마크에서 shape를 받아 구분한다. |
| | + | # 위 모델로 특정인을 인식할 수 있다. |
| | + | |
| | + | descs = np.load('img/descs.npy', allow_pickle=True)[()] |
| | cap = cv2.VideoCapture(0) # 영상 캡쳐. 경로 대신 0을 넣으면 웹캠이 켜진다. | | cap = cv2.VideoCapture(0) # 영상 캡쳐. 경로 대신 0을 넣으면 웹캠이 켜진다. |
| | + | </syntaxhighlight>dlib_face_recognition_reset_model 은 다음 링크를 통해 받자. 링크 |
| | + | |
| | + | 위 과정에서 에러가 난다면 [[얼굴추적]] 문서를 참고하자. |
| | + | |
| | + | === 함수정의 === |
| | + | {| class="wikitable" |
| | + | !의도 |
| | + | !설명 |
| | + | !방법 |
| | + | |- |
| | + | |특징점을 배열로 반환하기 |
| | + | |얼굴의 특징점을 찾아 배열로 반환한다. |
| | + | |<syntaxhighlight lang="python"> |
| | + | def detect_faces(img): |
| | + | faces = detector(img, 1) |
| | + | if len(faces) == 0: |
| | + | return np.empty(0) |
| | + | |
| | + | for k, face in enumerate(faces): |
| | + | shape = predictor(img, face) # 주어진 얼굴의 특징점을 찾는다. |
| | + | face_descriptor = facerec.compute_face_descriptor(img, shape) |
| | + | |
| | + | result = {'name':'unkown', 'dist':0.6, 'color':(0,0,255)} # 못찾았을 때의 기본값. |
| | + | for name, saved_desc in descs.items(): # 교육된 아이템에서 순회한다.... |
| | + | dist = np.linalg.norm([face_descriptor] - saved_desc, axis=1) # 인식된 데이터와 학습된 데이터를 비교. |
| | + | if dist < result['dist']: # 일치값이 0.6보다 낮다면..(일반적으로 0.6이 잘 된다고 알려져 있음) |
| | + | result = {'name': name, 'dist': dist, 'color': (255, 255, 255)} |
| | | | |
| − | faces = detector(img) # 디텍터에 이미지를 넣어주어 얼굴을 찾는다.
| + | cv2.putText(img, result['name'], org=(face.left(), face.top()), fontFace=cv2.FONT_HERSHEY_SIMPLEX, |
| − | for face in faces:
| + | fontScale=1, color=result['color'], thickness=2) |
| − | # 인식이 잘 되었는지 확인. 네모 그리기. 기존 이미지에 덧씌워 보여준다. | + | </syntaxhighlight> |
| − | img = cv2.rectangle(img, pt1=(face.left(), face.top()), pt2=(face.right(), face.bottom()),
| + | |} |
| − | color=(255, 255, 255), # 색 지정이 가능하다.
| |
| − | thickness=2, # 두께지정
| |
| − | lineType=cv2.LINE_AA # 선의 타입 지정
| |
| − | )
| |
| | | | |
| − | cv2.imshow('window', img) # 창에 해당하는 이미지를 띄운다. | + | === 실행 === |
| − | cv2.waitKey(1) # 1ms만큼 대기 해야 창이 제대로 열린다. | + | <syntaxhighlight lang="python"> |
| − | </syntaxhighlight>위 과정에서 에러가 난다면 [[얼굴추적]] 문서를 참고하자. | + | while True: # 기본적으로 계속 진행 |
| | + | ret, img = cap.read() # 캡처한 영상을 프레임 단위로 읽는다. |
| | + | if not ret: # 잘 찍히면 ret은 True를 반환한다. |
| | + | break # 프레임이 없다면 종료. |
| | + | detect_faces(img) |
| | + | cv2.imshow('window', img) # 창에 해당하는 이미지를 띄운다. |
| | + | cv2.waitKey(1) # 이게 있어야 창이 제대로 열린다. |
| | + | </syntaxhighlight> |
| | [[분류:딥러닝 트레킹]] | | [[분류:딥러닝 트레킹]] |