Python/OpenCV
Face Tracking
DiabloH
2019. 8. 3. 12:36
opencv, numpy, dlib
import cv2
import dlib
import sys
import numpy as np
#영상 해상도 조정 비율
scaler = 1
# 정면을 바라보는 얼굴을 인식하며,
# 일부 학습이 완료된 shape_predictor_68_face_landmarks.dat 를 사용한다.
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
# load video
cap = cv2.VideoCapture('samples/man.mp4')
overlay_img = cv2.imread('samples/kakao.png', cv2.IMREAD_UNCHANGED)
while True:
ret, img = cap.read()
#다음 재생할 프레임이 없다면, While문 종료
if not ret:
break
# 영상의 회전각에 따라 얼굴 인식이 불가한 경우가 있으므로
# 영상이 -90 회전이 되어있는 경우 이미지를 90도 회전
#img = cv2.transpose(img)
#img = cv2.flip(img, 1)
#스케일 조정
img = cv2.resize(img, (int(img.shape[1] * scaler), int(img.shape[0] * scaler)))
ori = img.copy()
#detector 함수를 이용하여 img의 'frontal_face'를 찾는다.
faces = detector(img)
if len(faces) > 0:
for i in list(faces):
# 인식된 face에 box를 그린다
img = cv2.rectangle(img,
pt1=(i.left(), i.top()),
pt2=(i.right(), i.bottom()),
color=(255, 255, 255),
thickness=2,
lineType=cv2.LINE_AA)
# Head Shape
dlip_shape = predictor(img, i)
shape_2d = np.array([[p.x, p.y] for p in dlip_shape.parts()])
# Head Size
top_left = np.min(shape_2d, axis=0)
bottom_right = np.max(shape_2d, axis=0)
face_size = max(bottom_right - top_left)
shape_index = 0
for s in shape_2d:
cv2.circle(img,
center=tuple(s),
radius=1,
color=(255, 255, 255),
thickness=1,
lineType=cv2.LINE_AA)
shape_index += 1
cv2.putText(img,
'%d' %shape_index,
tuple(s),
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=0.5,
color=(255, 255, 255),
thickness=1, lineType=cv2.LINE_AA)
# face의 중심점에 overlay_img를 그림
center_x, center_y = np.mean(shape_2d, axis=0).astype(np.int)
result = overlay_transparent(ori,
overlay_img,
center_x, center_y,
overlay_size=(face_size, face_size))
cv2.imshow('imgOverlay', result)
cv2.imshow('img', img)
cv2.waitKey(20)
full source
github https://github.com/DevDiabloH/Facetracking_Python
DevDiabloH/Facetracking_Python
lib opencv, dlib, numpy. Contribute to DevDiabloH/Facetracking_Python development by creating an account on GitHub.
github.com