Skip to content

Instantly share code, notes, and snippets.

@charlesreid1
Last active October 27, 2017 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlesreid1/381bb27eea325d24eeb3a11dbb113dbf to your computer and use it in GitHub Desktop.
Save charlesreid1/381bb27eea325d24eeb3a11dbb113dbf to your computer and use it in GitHub Desktop.
Simple Face Detection Algorithm with OpenCV 2.4, Python 2.7 on Mac OS X
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('bush.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
# If the 1.07 parameter becomes 1.08 we only detect right eye (???)
eyes = eye_cascade.detectMultiScale(roi_gray, 1.07, 1)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,0,255),2)
cv2.imwrite("detected_faces.jpg", img)
cv2.imshow('img',img)
cv2.waitKey(0)
#!/bin/bash
# Install Python2
brew install python
# Install OpenCV 2.4
brew install opencv@2
brew link --force opencv@2
# Make sure you have the latest Numpy
pip2 install -U numpy
pip2 install -U Pillow
#!/bin/bash
# Target face image
wget -O bush.jpeg https://upload.wikimedia.org/wikipedia/commons/thumb/d/d4/George-W-Bush.jpeg/580px-George-W-Bush.jpeg
# Haar face detection parameters
wget https://raw.githubusercontent.com/opencv/opencv/2.4/data/haarcascades/haarcascade_frontalface_default.xml
wget https://raw.githubusercontent.com/opencv/opencv/2.4/data/haarcascades/haarcascade_eye.xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment