Face Tracking using a Raspberry Pi with the Camera Module!

# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import sys

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32

rawCapture = PiRGBArray(camera, size=(640, 480))

# Create the haar cascade.  This should be a trained file for face (but can be anything really)
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)

# allow the camera to warmup
time.sleep(0.1)

# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    # grab the raw NumPy array representing the image
    image = frame.array

    # This is required when you do loops, otherwise the frame will be full on the next iteration
    frame.truncate(0)

    # Convert it to grayscale for the faceCascade
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Find all the faces using the Cascade Classifier
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE
    )

    print "Found {0} face(s)!".format(len(faces))
    for (x, y, w, h) in faces:
        print "Face at %d, %d" % (x + (w / 2), y + (h / 2))
 From the console:
stridera@raspberrypi ~ $ sudo python face_tracker.py haarcascade_frontalface_default.xml
Found 1 face(s)!
Face at 378, 127
Found 1 face(s)!
Face at 265, 190
Found 1 face(s)!
Face at 260, 215
Found 1 face(s)!
Face at 262, 232
Found 1 face(s)!
Face at 272, 225
Found 1 face(s)!
Face at 262, 205
Found 1 face(s)!
Face at 248, 175
Found 1 face(s)!
Face at 238, 164

About Matthew Jones

Writer, Programmer, Astronomer, Dreamer, Wisher, Fighter. Always striving to be better than I was.
This entry was posted in Electronics, Projects, Raspberry Pi, Robotics, Software. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *