Face detection is a computer vision technology.
It helps to locate and visualize human faces in digital images.
Pre-requisite
Knowledge of Numpy and Matplotlib is essential before working on the concepts of OpenCV.
Install following packages before installing OpenCV.
- Python
- Numpy
- Matplotlib
OpenCV already contains many pre-trained classifiers for face, eyes, smile etc.
These XML files are stored in /OpenTemp/opencv-3/data/haarcascades/ folder.
Now let’s create face detector with OpenCV.
First we need to load the required XML classifiers.
Then load our input image in grayscale mode.
Final Code is as follows :
import cv2
import numpy as np
from matplotlib import pyplot as plt
face_cascade=cv2.CascadeClassifier(“../OpenTemp/opencv-3/data/haarcascades/haarcascade_frontalface_default.xml”)
# load image to be identified
img=cv2.imread(“../Picturefolder/girl.jpeg”)
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMultiScale(gray_img,scaleFactor=1.05,minNeighbors=2)
for x,y,w,h in faces:
imag=cv2.rectangle(gray_img,(x,y),(x+w,y+h),(0,255,0),3)
resized=cv2.resize(imag,(int(imag.shape[1]),int(imag.shape[0])))
plt.imshow(resized)
plt.show
# waitKey(0) then the window shows the image until you press any key on
# keyboard
cv2.waitKey(0)
cv2.destroyAllWindows()
Conclusion:
It took almost 5 minutes to write the code.
Enjoy coding!!