Face Detection From an Image in Python using OpenCV¶
You need to download the trained classifier XML file (haarcascade_frontalface_default.xml), which is available in OpenCv’s GitHub repository. Save it to your working location.
The detection works only on grayscale images. So it is important to convert the color image to grayscale.
Detect faces in the image¶
The detectMultiScale function is a general function that detects objects. Since we are calling it on the face cascade, that’s what it detects.
The first option is the grayscale image.
The second 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. minNeighbors defines how many objects are detected near the current one before it declares the face found.
import cv2 face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml') img = cv2.imread('family.jpg') gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray_img,scaleFactor=1.1,minNeighbors=5) print("Total Faces:",len(faces)) print("Face Coordinates:",faces)
Total Faces: 3 Face Coordinates: [[191 337 231 231] [399 446 201 201] [578 362 246 246]]
for x,y,w,h in faces: img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
cv2.imshow("Family",img) cv2.waitKey(0) cv2.destroyAllWindows()