Skip to content

Instantly share code, notes, and snippets.

@kitsook
Created January 1, 2017 06:32
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 kitsook/0e1820e3bc602663572398945ada2931 to your computer and use it in GitHub Desktop.
Save kitsook/0e1820e3bc602663572398945ada2931 to your computer and use it in GitHub Desktop.
Face detection with OpenCV
import cv2
import numpy as np
cv2.namedWindow("camera", 1)
capture = cv2.VideoCapture(0)
# Set to None to use default size
# To improve performance, can specify a lower resolution. e.g. 320x240
width = 320
height = 240
faceCascade = cv2.CascadeClassifier("/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml")
eyeCascade = cv2.CascadeClassifier("/usr/share/opencv/haarcascades/haarcascade_eye.xml")
if width is None:
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
else:
capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)
if height is None:
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
else:
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
result = np.zeros((height, width, 3), np.uint8)
def DetectRedEyes(image, faceCascade, eyeCascade):
cas_rejectLevel = 1.3
cas_levelWeight = 5
# Convert color input image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = faceCascade.detectMultiScale(gray, cas_rejectLevel, cas_levelWeight)
# If faces are found
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = image[y:y+h, x:x+w]
eyes = eyeCascade.detectMultiScale(roi_gray)
# For each eye found
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
return image
while True:
retval, img = capture.read()
image = DetectRedEyes(img, faceCascade, eyeCascade)
cv2.imshow("camera", image)
if cv2.waitKey(30) & 0xFF == ord('q'):
break
capture.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment