Python OpenCV – Face Detection on a Image

import numpy as np
import cv2

img = cv2.imread(r'C:\Users\Linawati\Documents\ACCS\OpenCV\Liverpool.jpg', 1)

scale_percent = 130 # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
img2 = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) 

#change image colour space to gray
gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
path = 'GithubFrontalFace.xml'


face_cascade = cv2.CascadeClassifier(path)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=5, minSize=(40,40))
print(len(faces))

for(x,y,w,h) in faces:
    cv2.rectangle(img2,(x,y),(x+w, y+h), (0,255,0),2)
    
cv2.imshow('Image', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

The result of print(len(faces)) return 9. And the image result is as per below.

scaleFactor=1.05, minNeighbors=5, minSize=(40,40)

You can see that out of the 9 detection, 2 are false positives (7/9 = 78%). The confetti might be affecting the detection process as there are 3 to 4 more possible detection for the algorithm.

Now using another pretrained classifier call haarcascade_frontalface_alt2.xml from GitHub, all code is the same as above just that the xml file name has changed.

path = 'haarcascade_frontalface_alt2.xml'
Result is 10/11 = 91%