Opencv Python facial recognition program

Here are the steps to download the requirements below.

steps :

  1. Download Python 2.7.x, numpy and Opencv 2.7. x. Check if your Windows 32-bit or 64-bit is compatible and install accordingly.
  2. Make sure numpy is running in your python, then try installing opencv.
  3. Put the files haarcascade_eye.xml & amp; haarcascade_frontalface_default.xml into one folder (see the code below for links)

Implementation

# OpenCV real-time face detection
# importing OpenCV Python libraries
# where is its functionality

import cv2 

 
# load the required trained XML classifiers
# https://github.com/Itseez/opencv/blob/master/
# data / haarcascades / haarcascade_frontalface_default.xml
# Trained XML classifiers describe some of the features of some
# the object we want to detect has been trained by the cascade function
# from the set positive (faces) and negative (not faces)
# pictures.

face_cascade = cv2.CascadeClassifier ( `haarcascade_frontalface_default.xml` )

 
# https://github.com/Itseez/opencv/blob/master
# /data/haarcascades/haarcascade_eye.xml
# Trained XML for eye detection

eye_cascade = cv2.CascadeClassifier ( `haarcascade_eye.xml`

  
# capture stills from the camera

cap = cv2.VideoCapture ( 0 )

 
# loop starts if capture was initiated.

while 1

  

# reads frames from the camera

ret, img = cap. read () 

 

# convert to grayscale every frame

  gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)

 

# Detects faces of different sizes in the input image

faces = face_cascade.detectMultiScale ( gray, 1.3 , 5 )

  

  for (x, y, w, h) in faces:

  # Draw rectangle on face

cv2.rectangle (img, (x, y), (x + w, y + h), ( 255 , 255 , 0 ), 2

roi_gray = gray [y: y + h, x: x + w]

roi_color = img [y: y + h, x: x + w]

 

# Defines eyes of different sizes in the input image

  eyes = eye_cascade.detectMultiScale (roi_gray) 

 

# Draw a rectangle in the eyes

for (ex, ey, ew, eh) in eyes:

cv2.rectangle (roi_color, (ex, ey), (ex + ew, ey + eh), ( 0 , 127 , 255 ), 2 )

 

# Show image in window

cv2.imshow ( `img` , img)

 

# Wait for the Esc key to stop

k = cv2.waitKey ( 30 ) & amp;  0xff

if k = = 27 :

break

 
# Close the window
cap .release ()

 
# Unallocate any associated memory usage
cv2.destroyAllWindows () 

Output:


Next article: