Working with Scale Factor

Learn how to use the scale factor when detecting faces in Python.

We'll cover the following...

Face detection

In this lesson, we’ll use the image below to detect faces.

Let’s detect faces in this picture.

Press + to interact
#!/usr/bin/python
import sys
import cv2
import matplotlib.pyplot as plt
def face_detect(imgpath, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
image = cv2.imread(imgpath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(cascasdepath)
faces = face_cascade.detectMultiScale(
gray,
scaleFactor = 1.1,
minNeighbors = 5,
minSize = (30,30)
)
print("The number of faces found = ", len(faces))
for (x,y,w,h) in faces:
cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
if nogui:
cv2.imwrite('test_face.png', image)
return len(faces)
else:
cv2.imwrite("output/Faces_found.png", image)
if __name__ == "__main__":
face_detect(sys.argv[1])

We can see that our program detected objects that were not faces at all.

Why did this happen?

The picture seems to have been taken from afar and possibly from a mobile phone. ...