Face Detection
Can’t have dog pictures here, sadly 🙁

import cv2
image_path = "./Path/To/Photo.extension"
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(
gray,
scaleFactor= 1.1,
minNeighbors= 5,
minSize=(10, 10)
)
faces_detected = format(len(faces)) + " faces detected!"
print(faces_detected)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 255, 0), 2)
viewImage(image,faces_detected)
The detectMultiScale function is a general function that detects objects. Since we’re calling it on the face cascade, that’s what it detects.
The detectMultiScale function takes 4 parameters
- The first parameter is the grayscale image.
- The second parameter is the
scaleFactor. Since some faces may be closer to the camera, they would appear bigger than the faces in the back. The scale factor compensates for this. - The detection algorithm uses a moving window to detect objects.
minNeighborsdefines how many objects are detected near the current one before it declares the face found. -
minSize, meanwhile, gives the size of each window.

