Created
November 15, 2013 21:23
-
-
Save tristanwietsma/7491869 to your computer and use it in GitHub Desktop.
Face tracking example in OpenCV
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
from __future__ import division | |
import cv, cv2, time | |
image_scale = 2 | |
HAAR_CASCADE_PATH = "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml" | |
def detect_faces(image): | |
gray = cv.CreateImage((image.width,image.height), 8, 1) | |
small_img = cv.CreateImage((cv.Round(image.width / image_scale), | |
cv.Round (image.height / image_scale)), 8, 1) | |
cv.CvtColor(image, gray, cv.CV_BGR2GRAY) | |
cv.Resize(gray, small_img, cv.CV_INTER_LINEAR) | |
cv.EqualizeHist(small_img, small_img) | |
faces = [] | |
detected = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100)) | |
if detected: | |
for (x,y,w,h),n in detected: | |
faces.append((x,y,w,h)) | |
return faces | |
cascade = cv.Load(HAAR_CASCADE_PATH) | |
F = [] | |
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE) | |
camera_index = 0 | |
capture = cv.CaptureFromCAM(camera_index) | |
storage = cv.CreateMemStorage() | |
def repeat(): | |
global capture #declare as globals since we are assigning to them now | |
global camera_index | |
frame = cv.QueryFrame(capture) | |
for (x,y,w,h) in detect_faces(frame): | |
cv.Rectangle(frame, (x,y), (x+w,y+h), 255) | |
print time.time(), 'target @ (%s,%s)' % (x + h/2, y + h/2) | |
cv.ShowImage("w1", frame) | |
c = cv.WaitKey(10) | |
if(c=="n"): #in "n" key is pressed while the popup window is in focus | |
camera_index += 1 #try the next camera index | |
capture = cv.CaptureFromCAM(camera_index) | |
if not capture: #if the next camera index didn't work, reset to 0. | |
camera_index = 0 | |
capture = cv.CaptureFromCAM(camera_index) | |
while True: | |
repeat() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment