Face Detection VS Face Recognition
Face detection only detects the presence of a face in an image while fact recognition involves identifying whose face it is. Face detection is performed using a classifier, it is essentially an algorithm that decides whether a given image is positive or negative meaning whether a face is present or not. The classifier needs to be trained with millions of images with and without faces, fortunately, OpenCV has a lot of pre-trained classifiers that we can use.
Haarcascade Classifier
This website is the OpenCV Github page where they store their haarcascade classifiers.

The one that I used is the “haarcascade_frontalface_defult.xml”. It includes about thirty-three thousand lines of code.

Click on the raw button and it will display the raw code for this classifier, then copy everything in this raw code into an xml file in the computer.

Main Code
Read an image of a person and turn it into a gray-scale image.
import cv2 as cv
img = cv.imread('Image/Woman')
cv.imshow('Person', img)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray Person', gray)

Create a haarcascade variable, and pass in the path to the xml file for the trained classifier. It will read in the thirty-three thousand lines of code and store it in the haarcascade variable.
haar_cascade = cv.CascadeClassifier('haar_face.xml')
OpenCV will use the variables inputted to detect a face and return the rectangular coordinates of that face as a list under the “face_rect” variable
face_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=6)

Since the OpenCV would return the rectangular coordinates of the face, we can loop through this list of coordinates and draw an rectangle over the detected faces.
print(f’Number of faces found = {len(face_rect)}’)
for (x,y,w,h) in face_rect:
cv.rectangle(img, (x,y), (x+w,y+h), (0,255,0), thickness=2)
cv.imshow(‘Detected Faces’, img)
cv.waitKey(0)

Complete Code
import cv2 as cv
img = cv.imread('Image/Woman')
cv.imshow('Person', img)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray Person', gray)
haar_cascade = cv.CascadeClassifier('haar_face.xml')
face_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=6)
print(f'Number of faces found = {len(face_rect)}')
for (x,y,w,h) in face_rect:
cv.rectangle(img, (x,y), (x+w,y+h), (0,255,0), thickness=2)
cv.imshow('Detected Faces', img)
cv.waitKey(0)