Face Detection with OpenCV pretrained data

OpenCV : OpenCV is the most popular library for computer vision. Originally written in C/C++, it now provides bindings for Python.

Shashank Lipate
2 min readFeb 27, 2021

For face detection, OpenCV uses cascades. (You can learn about it in opencv documentation)

It is simple to use download xml file from github and load it in your code by the following command.

Cascade = cv2.CascadeClassifier(<Path of the xml file>)

use this object by passing your image or frame into it.

faces = Cascade.detectMultiScale(
image,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)

This function detects the actual face and is the key part of our code, so let’s go over the options:

  1. The detectMultiScale function is a general function that detects objects. Since we are calling it on the face cascade, that’s what it detects.
  2. The first option is the image.
  3. 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.
  4. 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. minSize, meanwhile, gives the size of each window.

Note: I took commonly used values for these fields. In real life, you would experiment with different values for the window size, scale factor, and so on until you found one that works best for you.

The function returns a list of rectangles in which it believes it found a face. Next, we will loop over where it thinks it found something.

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

You will get an image with rectangle bounding box on detected faces.

Checkout an improvised implementation of this code to detect face with mask or no mask in this article.

Connect with me on linkedIn : Shashank Lipate

--

--