Allan To
Posted on April 7, 2023
Welcome my readers!
This post is a continuation from my previous post. This post is all about how to actually implement openCV and write a simple application to detect human faces in any given pictures
Quick re-cap
Face detection is a computer technology that enables machines to identify and locate human faces in digital images. The technique can be applied in various fields such as security systems, photo editing, entertainment, and social media. OpenCV is a popular open-source computer vision library that provides tools for face detection, image processing, and machine learning.
Ok. Before we are going to the coding part, here are some requirements that you need to install
Install Python (https://www.python.org/downloads/)
Install OpenCV
pip install opencv-python
Choose an image ( note the absolute path of the image for reference )
After you have installed all of the requirements, here is a complete application.
import cv2
face_cascade=cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") #Note the change
img = cv2.imread("yourpathtoimage")
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMultiScale(gray_img, scaleFactor=1.05,minNeighbors=5)
for x, y, w, h in faces:
img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
resized=cv2.resize(img,(int(img.shape[1]/3), int(img.shape[0]/3)))
cv2.imshow("Deteced-face",resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
It is the simplest application to detect human faces in python. Let's break this block of code down for further understanding.
Importing the Required Libraries:
Open a Python file and import the required libraries as shown below:
import cv2
Loading the Pre-Trained Face Detection Classifier:
OpenCV provides a pre-trained face detection classifier, which is a XML file containing features of the face. Download the classifier from the OpenCV website:
https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
Save the file in the same directory as your Python file. Now, load the classifier as shown below:
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
Loading the Image:
Load the image you want to detect faces from using the cv2.imread() function as shown below:
img = cv2.imread('image.jpg')
Converting the Image to Grayscale:
Convert the loaded image to grayscale using the cv2.cvtColor() function as shown below:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Detecting Faces:
Now, we can detect faces in the grayscale image using the detectMultiScale() function of the face_cascade object as shown below:
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
Here, the scaleFactor, minNeighbors, and minSize parameters are used to adjust the sensitivity and accuracy of the face detection algorithm. The detectMultiScale() function returns a list of rectangular coordinates (x, y, w, h) of each detected face.
Displaying the Image with Detected Faces
Finally, we need to display the original image with the detected faces. We can use thecv2.imshow()
function to display the image and the cv2.waitKey()
function to wait for a keyboard event before closing the window.
cv2.imshow('Detected Faces', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
This code will display the original image with rectangles drawn around each detected face. The window will stay open until a key is pressed, after which it will close.
*Running that app and we will have this: *
Tips for fixing bugs as you go through
pip : the term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. check the spelling of the name, or if a path was included, verify that the path is correct and try again.
_Follow this YT video and you can fix it: _https://www.youtube.com/watch?v=xdj0mGmuNjc
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
Go to App Execution Aliases and turn off Python alias
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
This error occurs when you use the backslash instead of forward slash in the path for the image. So just use forward slash. :)
Hope you find something interesting here and thanks for your reading :)
Posted on April 7, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.