Human face detection and recognition is an important technology used in various applications such as students attendance in the classroom which is my graduation project.
The facial recognition process can be divided into two main stages: face detection which is the processing to know where object take place and face recognition to match and extract our object from database.
It is the pre-processing for face recognition. The main function of this step is to determine whether human faces appear in a given image and where these faces are located at. Besides serving as the pre-processing for face recognition, face detection could be used for region-of-interest detection and image classification.
After formalizing the representation of each face, the second step is to recognize the identities of these faces. In order to achieve automatic recognition, a face database is required to build. For each object/person, several images are taken and their features are extracted and stored in the database. Then when an input face image comes in, we perform face detection and feature extraction, and compare its feature to each face class stored in the database.
In this discussion, We are going to talk about face detection and apply this detection on any image or using camera
first thing we have to import our libraries, numpy and cv2
import cv2 import numpy as np
Then we have to download xml files that have some features to use it. We can get it from open cv file, sources, data and haarcascades that have all features
Here, We want to detect front face and eye so we will copy this xml files with our project
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
Download our image. Then convert it to gray image
img = cv2.imread('mm.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Then we have to detect all face in our image that matches all features in our xml file. So we will use detectMultiScale function that takes three parameters(Our image, scale factor, minNeighbors )
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
After detect any face in our image, It will return top left (x,y), height and width. Then we have to draw rectangle for each face.
cv2.rectangle takes our image, top left, top right, color and thickness
for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
We put our image in region-of-interest. In other word, We define the face.
roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w]
Because each face have two eyes, So we search about two eyes in our region of interest which is the face. Then for each eye, we draw our rectangle.
eyes = eye_cascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
Finally we show our image
cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows()
Finally, Watch this video.
If you want to detect your face through camera. It is the same idea here