Created
June 27, 2019 09:30
-
-
Save addam/76b9a7746df32b60bd5e8a7c33e3e012 to your computer and use it in GitHub Desktop.
Quick face tracker using dlib + opencv. Face detector is slow, shape predictor is quick -- therefore they execute in separate threads.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import cv2 as cv | |
import dlib | |
from threading import Thread | |
import time | |
pose_model = dlib.shape_predictor("/usr/share/dlib/shape_predictor_68_face_landmarks.dat") | |
detector = dlib.get_frontal_face_detector() | |
def camera(source): | |
cam = cv.VideoCapture(0) | |
while 1: | |
status, img = cam.read() | |
if not status: | |
return | |
yield img | |
def points(r): | |
return (r.left(), r.top()), (r.right(), r.bottom()) | |
for img in camera(0): | |
faces = detector(img) | |
if not faces: | |
continue | |
face = faces[0] | |
break | |
def print_fps(img): | |
now = time.clock() | |
if print_fps.last: | |
cv.putText(img, f"fps: {1/(now - print_fps.last):.1f}", (10, 20), 0, 0.5, (0, 255, 255)) | |
print_fps.last = now | |
print_fps.last = None | |
def detect_forever(): | |
while detect_forever.img is None: | |
# wait for initialization | |
time.sleep(1) | |
# the thread is shut down by setting img to None | |
while detect_forever.img is not None: | |
detect_forever.faces = detector(detect_forever.img) | |
time.sleep(1) | |
detect_forever.img = None | |
detect_forever.faces = list() | |
t = Thread(target=detect_forever) | |
t.start() | |
for img in camera(0): | |
detect_forever.img = img | |
if not detect_forever.faces: | |
# wait for initialization | |
continue | |
shape = pose_model(img, detect_forever.faces[0]) | |
horz = shape.part(13).x - shape.part(3).x | |
vert = shape.part(8).y - shape.part(27).y | |
face = dlib.rectangle(int(shape.part(3).x - 0.1*horz), int(shape.part(27).y - 0.4*vert), int(shape.part(13).x + 0.1 * horz), int(shape.part(8).y - 0.1*vert)) | |
cv.rectangle(img, *points(face), (0, 0, 255), 1) | |
detect_forever.faces[0] = face | |
print_fps(img) | |
cv.imshow("face", img) | |
if cv.waitKey(1) == 27: | |
break | |
detect_forever.img = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment