Skip to content

Instantly share code, notes, and snippets.

@dividuum
Created December 6, 2010 10:31
Show Gist options
  • Save dividuum/730105 to your computer and use it in GitHub Desktop.
Save dividuum/730105 to your computer and use it in GitHub Desktop.
Detecting faces and adding santa claus hats for fun and profit
# Based on
# http://japskua.wordpress.com/2010/08/04/detecting-eyes-with-python-opencv/
# http://stackoverflow.com/questions/1650568/how-do-i-create-an-opencv-image-from-a-pil-image
import os
import sys
import logging
from cStringIO import StringIO
import cv
from PIL import Image, ImageFile
log = logging.getLogger(__name__)
RESOURCE_PATH = os.path.join(os.path.dirname(__file__), 'res')
FACE_CASCADE = cv.Load(os.path.join(RESOURCE_PATH, "model.xml")) # haarcascade_frontalface_alt_tree.xml
MUETZE = Image.open(StringIO(file(os.path.join(RESOURCE_PATH, "muetze.png"), "rb").read()))
def add_muetze(pil_image):
rgb = pil_image.convert("RGB")
image = cv.CreateImageHeader(rgb.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(image, rgb.rotate(180).tostring()[::-1])
min_size = (20,20)
image_scale = 2
haar_scale = 1.1
min_neighbors = 7
haar_flags = 0
# Allocate the temporary images
gray = cv.CreateImage((image.width, image.height), 8, 1)
smallImage = cv.CreateImage((cv.Round(image.width / image_scale), cv.Round(image.height / image_scale)), 8 ,1)
# Convert color input image to grayscale
cv.CvtColor(image, gray, cv.CV_RGB2GRAY)
# Scale input image for faster processing
cv.Resize(gray, smallImage, cv.CV_INTER_LINEAR)
# Equalize the histogram
cv.EqualizeHist(smallImage, smallImage)
faces = cv.HaarDetectObjects(smallImage, FACE_CASCADE,
cv.CreateMemStorage(0), haar_scale,
min_neighbors, haar_flags, min_size)
for ((x, y, w, h), n) in faces:
x = int(x * image_scale)
y = int(y * image_scale)
w = int(w * image_scale)
h = int(h * image_scale)
x = int(x - w/2)
w = int(w * 1.6)
h = int(h * 1.6)
scaled_muetze = MUETZE.copy()
scaled_muetze.thumbnail((w, h), Image.ADAPTIVE)
box = (x, y - int(h*0.5))
pil_image.paste(scaled_muetze, box, scaled_muetze)
return pil_image
if __name__ == "__main__":
image = Image.open(StringIO(file(sys.argv[1]).read()))
image.load()
image = add_muetze(image)
image.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment