In this post, we’ll learn how to build a simple Face Detector in Python using OpenCV. As from the name, it can be understood that we will be writing a program that will detect faces in an image, video or directly from the camera.
First of all, we would have to install OpenCV on our machines. OpenCV is a highly optimized library with a focus on real-time applications.
OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.
https://opencv.org
Library
First things first, let’s install the package, and to do that, open your Python terminal and enter the command.
pip install opencv-python
pip install imutils
After the installation is completed, we can import it into our program.
import cv2
import imutils
Face detection using Haar Cascades is a machine learning approach where a cascade function is trained with a set of input data. OpenCV already contains many pre-trained classifiers for faces, eyes, smiles, etc… and today, we will be using a face classifier to detect faces from images, videos, or cameras. For that, we’ll need to download the XML file for Haar Cascade, which can be downloaded from the link https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml
After saving the file in our current folder, let’s load it into our program.
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
1. Identifying Faces In An Image
Importing Images
In this step, we’ll choose an image that we would like to test our code on. Make sure there is at least one face in the image so that our program can find one.
After choosing an image, let’s define it in our program. Make sure the image file is in the same folder you are working in.
# Read the input image
img = cv2.imread('test.jpg')
img_resize = imutils.resize(img, width = 800)
Face Detection
You will be amazed at how short the face detection program is. Thanks to the people contributing to OpenCV. Here’s the code that detects faces in an image:
# Detect Faces
faces = face_cascade.detectMultiScale(img_resize, 1.3, 5)
- detectMultiScale is used to detect the faces. It takes 3 arguments – the input image, scaleFactor and minNeighbours.
- scaleFactor specifies how much the image size is reduced with each scale and the best value is 1.3.
- minNeighbours specifies how many neighbors each candidate rectangle should have to retain it and the best value for it is 5.
We defined face_cascade earlier in the code. After the faces are detected, we will draw rectangles around them to know what the machine sees. The machine can make mistakes, but our goal is to be more optimized and accurate.
To draw a triangle around the detected faces, we have to write the following code:
# Draw rectangle around the face
for (x, y, w, h) in faces:
cv2.rectangle(img_resize, (x,y), (x+w, y+h), (255, 0, 0), 2)
- (255, 0, 0) is the of the rectangle
- 2 is the thickness of the line.
Result
Now we’ll show the result as a popup, and for that, we’ll use a method from the cv2 library called “imshow”.
# Export the result
cv2.imshow('face_detected', img_resize)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
2. Identifying Faces in Video or Using WebCam
Detect Faces In Video or Open The Webcam
Once the OpenCV library (cv2) has been imported, and the cascade has been loaded, capture the video from the webcam or input the video file.
# Read the video file
# video = cv2.VideoCapture('video-3.mp4')
# Open Webcam
video = cv2.VideoCapture(0)
As we know that videos are being created using frames, which are still images. So we’ll perform face detection for each frame in the video, and for that, we’ll use a loop
while True:
ret,frame = video.read()
video_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect Faces
faces = face_cascade.detectMultiScale(video_gray, 1.3, 4)
# Draw triangle around the face
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
# Show frame
cv2.imshow('Face Detected', frame)
k = cv2.waitKey(30)
if k == 27:
break
video.release()
cv2.destroyAllWindows()
What have we done in the above code:
- First of all, we’ll read the frame using a while loop, which means that until there’s an available frame in the video, it will keep on reading.
- Once the frame is read, we’ll convert it to grayscale using the OpenCV method because the frame in grayscale results better.
- After that, we’ll detect the face in the specific frame using the detectMultiScale method.
- Once the face is detected, we’ll create a rectangle around each face.
- Then, to show the result, we used imshow method and would set the waitKey to 30, which means 30 milliseconds. This is a time delay because it consumes some time to read the frame, identify the face, and create a rectangle around it.
Hurrah! Finally I got a website from where I can genuinely obtain helpful information concerning my study and knowledge.
I’m really enjoying the design and layout of your site. It’s very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire a developer to create your theme? Fantastic work!
Thanks for the compliment. Just for your information, I’m a developer and have developed this site myself.
Saved as a favorite, I bearing in mind your blog!
This design is wicked! You most certainly know how
to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well,
almost…HaHa!) Excellent job. I really enjoyed what you had to say, and more than that,
how you presented it. Too cool!
Wow! Thank you! I continuously wanted to write on my blog something like that. Can I take a part of your post to my website?
Yes! you can, but don’t forget to give me a credit.
Great write-up, I am a regular visitor of one’s website, maintain the nice operation, and It is going to be a regular visitor for a lengthy time.