Face Detection is one of the main applications of Machine Learning and with Python Machine Learning Vision Library OpenCV we can detect faces in an image or a video. Face Detection is done with the help of Classifiers, the classifier detects whether the objects in the given image are faces or not. Face Detection is different from face recognition so do not confuse them with each other. In this tutorial, we will be detecting faces in an Image using the simple and basic Harr Cascade Classifier . Before start coding let's install and download the libraries and other dependencies to write a Python script to detect faces.
Required Libraries and resources
Install Library
As we are using OpenCV in Python this goes without saying Python should be installed on your system. And to install OpenCV you can use the Python pip terminal command.
pip install opencv-python
Image
To detect faces you required an image, and for this tutorial, we will be using the following
Father-Daughter.jpg
image.
Download the Harr Cascade
haarcascade_frontalface_default.xml
As for this tutorial, we will be using Harr Cascade Classifier. Face Detection is an application of Machine Learning, and for such ML applications, we require a classifier that is trained on thousands or millions of data. And a student can not collect or generate data of his/her own, here come the OpenCV
pre-trained Harr Cascade classifiers
. On the
OpenCV GitHub Harr Cascade pag
e, there are plenty of pre-trained Classifiers, but on which we are interested in is
haarcascade_frontalface_default.xml
classifier. The
haarcascade_frontalface_default.xml
is the pre-trained classifier for the Face detection, and we will be using this pre-trained XML formated data to detect the face in OpenCV. Copy the raw code of
haarcascade_frontalface_default.xml
from GitHub and paste it locally on a file
harr_face_detect_classifier.xml
and save it. I would suggest you save the
harr_face_detect_classifier.xml
file in the same directory where your Face Detection Python script is located, so you can access the XML file with the related name. Now we are all set to write the Python Script which can detect Faces in an Image. Open your
Best Python IDE or text editor
and start coding with us.
Face Detection with OpenCV and Python
Start with importing the OpenCV module in your Python Script.
import cv2 as cv
We have imported the OpenCV
cv2
module with an alias name
cv
After importing the OpenCV module let's load the image on which we want to detect the faces.
#load image image = cv.imread("Father-Daughter.jpg") #cv.imshow("Image", image) #to see the image
To load the image we have used the
cv.imread()
method, and as I have mentioned above for this tutorial we will be using the
"Father-Daugher.jpg"
image.
Note:
As the image and Python script is in the same directory we are using the relative path to load the image.
The classifier does not care about the skin tone of the person in the image, it simply looks for the faces present in the image and detects them. This means we do not require a color image to detect the faces, so it's always a good practice to convert the image into a grayscale image to avoid unnecessary color intensity noises.
#convert image to grayscale image gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY) # cv.imshow("Gray Image", gray_image) #to show the gray image
The
cv.imread()
load the image into a BGR(Blue Green Red) format, and using the
cv.cvtColor(image, cv.COLOR_BGR2GRAY)
method we can convert the BGR image to a GrayScale Image. Now let's load the Harr Cascade classifier
haarcascade_frontalface_default.xml
which we copied, paste, and saved locally as
harr_face_detect_classifier.xml.
#read the harr_face_detect_classifier.xml harr_cascade= cv.CascadeClassifier("harr_face_detect_classifier.xml")
The
cv.CascadeClassifier("harr_face_detect_classifier.xml")
will read the XML file and initialize the object as
harr_cascade.
Now we will use the loaded XML file object and detect faces from the GrayScale Image.
face_cords = harr_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=1 )
The
detectMultiScale()
will detect the Faces from the GrayScale image, and return an array of coordinates
face_cords
for the face region. The
scaleFactor
value should be greater than one. We can loop over the array
face_cords
, grab the coordinates, and draw rectangles over those regions.
for x, y, w, h in face_cords: #draw rectangle cv.rectangle(image, (x,y), (x+w, y+h), (255, 0,0), thickness=2)
The
cv.rectangle(image, (x,y), (x+w, y+h), (255, 0,0), thickness=2)
will draw a blue(255, 0,0) rectangle over the original
image
based on the coordinated returned by the
detectMultiScale()
method. Now show the image with
cv.imshow()
method.
#show image cv.imshow("Face Detect", image) cv.waitKey(0)
#put all the code together and execute
import cv2 as cv #load image image = cv.imread("Father-Daughter.jpg") # cv.imshow("Image", image) #convert image to grayscale image gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY) # cv.imshow("Gray Image", gray_image) #to show the gray image #read the harr_face_detect_classifier.xml harr_cascade = cv.CascadeClassifier("harr_face_detect_classifier.xml") face_cords = harr_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=1 ) for x, y, w, h in face_cords: cv.rectangle(image, (x,y), (x+w, y+h), (255, 0,0), thickness=2) #show image cv.imshow("Face Detect", image) cv.waitKey(0)
Output When you execute the above program you will see a similar result.
Detect Face in a live Video using Python OpenCV
Now you know how to detect faces using an Image, we can use the same trick to detect faces from the live video or any other video stored in your system. A video is a running image, and with Python OpenCV, we can access every image frame and draw a rectangle over the video to detect the faces.
import cv2 as cv #start web cam capture = cv.VideoCapture(0) # 0 for web-cam #read the harr_face_detect_classifier.xml harr_cascade = cv.CascadeClassifier("harr_face_detect_classifier.xml") while True: #read video frame by frame isTrue, frame= capture.read() gray_frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) face_cords = harr_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=1) #draw rectange over faces for x, y, w, h in face_cords: cv.rectangle(frame, (x,y), (x+w, y+h), (0, 255,0), thickness=2) #show face detect Video cv.imshow("Detect face live Video", frame) #press e to exit if cv.waitKey(20) ==ord("e"): break capture.release() capture.destroyAllWindows()
Conclusion
Here in this Python tutorial, you learned how to detect a face in Python using the OpenCV library. The Harr Cascade classifier is the most basic face detection classifier, and there are many other face detection techniques you can use in OpenCV. In this tutorial, we also write the Python script which detects faces from a live video, the code for detecting faces from an image or detecting faces from a video is pretty much the same. I hope you like this article, if you have any queries or suggestions related to the article or program I have provided here please let us know by commenting down below. People are also reading:
- Python Extract PDF Tables
- How To Comment Python Code?
- Generate and Read QR Code in Python
- How to Substring a String in Python?
- Extract Weather Data in Python
- Make Screen Recorder in Python
- Download All Images from a Web Page in Python
- Python Switch-case Statement
- How to Iterate Through a Dictionary in Python?
- Python Max
Leave a Comment on this Post