Created
March 13, 2019 15:57
-
-
Save jamesbulpin/6ed4ddc15aadcf4cf75198ee55c76d36 to your computer and use it in GitHub Desktop.
Simple (and fairly crap) face tracker for Raspberry Pi with a pan-tilt hat.
This file contains 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
import numpy as np | |
import cv2 | |
import pantilthat | |
import picamera | |
pantilthat.pan(0) | |
pantilthat.tilt(0) | |
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') | |
camera = picamera.PiCamera() | |
camera.resolution = (640, 480) | |
while True: | |
output = np.empty((480, 640, 3), dtype=np.uint8) | |
camera.capture(output, 'bgr') | |
img = cv2.flip(output, -1) | |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
faces = faceCascade.detectMultiScale( | |
gray, | |
scaleFactor=1.2, | |
minNeighbors=5, | |
minSize=(20, 20) | |
) | |
for (x,y,w,h) in faces: | |
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) | |
roi_gray = gray[y:y+h, x:x+w] | |
roi_color = img[y:y+h, x:x+w] | |
if len(faces) == 1: | |
xx = x+w/2 | |
print(xx) | |
if xx < 300: | |
current_pan = pantilthat.get_pan() | |
delta = max(int((320 - xx)/10), 1) | |
pan = min(current_pan + delta, 70) | |
pantilthat.pan(pan) | |
elif xx > 340: | |
current_pan = pantilthat.get_pan() | |
delta = max(int((xx - 320)/10), 1) | |
pan = max(current_pan - delta, -70) | |
pantilthat.pan(pan) | |
yy = y+h/2 | |
print(yy) | |
if yy > 260: | |
current_tilt = pantilthat.get_tilt() | |
delta = max(int((yy-240)/8), 1) | |
tilt = min(current_tilt + delta, 70) | |
pantilthat.tilt(tilt) | |
elif yy < 220: | |
current_tilt = pantilthat.get_tilt() | |
delta = max(int((240-yy)/8), 1) | |
tilt = max(current_tilt - delta, -70) | |
pantilthat.tilt(tilt) | |
cv2.imshow('video',img) | |
k = cv2.waitKey(30) & 0xff | |
if k == 27: # press 'ESC' to quit | |
break | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment