Detect Number of Faces in an Image Using OpenCV in Python

In this tutorial, we will introduce the way to detect the number of faces in an image, we will use python opencv to implement it.

1. Import library

import cv2

2. Read an image

im2=cv2.imread(r"member.jpg",0)
im=cv2.imread(r"member.jpg")

3. Create a face detector

facedetector=cv2.CascadeClassifier(r"haarcascade_frontalface_default.xml")

4. Detect faces in an image

face=facedetector.detectMultiScale(im2,1.1,5)

5. Ouput the number of faces

print('number of faces:')
print(len(face))

6. Show faces in an image

for x,y,z,h in face:
    cv2.rectangle(im,(x,y),(x+z,y+h),(0,0,225),3)
cv2.imshow("facedetective",im)
cv2.waitKey(0)
cv2.destroyallWindows()