Skip to content

Instantly share code, notes, and snippets.

@tonmoay
Created December 20, 2016 05:14
Show Gist options
  • Save tonmoay/f77a618502ecf4b97b7ff5536c4dd427 to your computer and use it in GitHub Desktop.
Save tonmoay/f77a618502ecf4b97b7ff5536c4dd427 to your computer and use it in GitHub Desktop.
Detect face & eyes with webcam & rectangle face with showing some text over rectangle real time. Save 30 faces into 'faceimg' directory & exit after face saving
import cv2
#import numpy as np
import time
#import finished
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
'''
References:
http://docs.opencv.org/trunk/d7/d8b/tutorial_py_face_detection.html
http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_objdetect/py_face_detection/py_face_detection.html
http://docs.opencv.org/3.1.0/dd/d43/tutorial_py_video_display.html
https://realpython.com/blog/python/face-recognition-with-python/
https://realpython.com/blog/python/face-detection-in-python-using-a-webcam/
'''
#Start of video record
cap = cv2.VideoCapture(0)
#time.sleep(5)
i=1
while(True):
#Capture frame-by frame
ret, frame = cap.read()
#if ret==0:
# continue
#Image Operation Starts here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#detects faces
face = face_cascade.detectMultiScale(gray,1.1,5)
#Draw the detected faces
for (x, y, w, h) in face:
cropped_face_colored=frame[y:(y+h),x:(x+w)]
cropped_face_gray=gray[y:(y+h),x:(x+w)]
eyes = eye_cascade.detectMultiScale(cropped_face_gray)
#smile= smile_cascade.detectMultiScale(cropped_face_gray)
cv2.imwrite('faceimg/face'+str(i)+'.jpg',cropped_face_colored)
i = i+1
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 96, 23), 1)
cv2.rectangle(cropped_face_colored,(ex,ey),(ex+ew,ey+eh),(255, 96, 23),1)
cv2.putText(frame, "Press q to Exit", (x, y-10),
cv2.FONT_HERSHEY_PLAIN, 1.0, (255,255,255))
#for(sx,sy,sw,sh) in smile:
# cv2.rectangle(cropped_face_colored,(sx,sy),(sx+sw,sy+sh),(255, 96, 23),1)
#Display the frame
cv2.imshow('Webcam',frame)
if (i==31):
break
#loop break control
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#Release the capture after finish
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment