Introduction
Facial expressions are a great way to determine a person’s state of mind. A very basic and beautiful facial expression is a smile. With the growing era of technology, we have made machines detect smiles from a person’s face.
I’ll use the OpenCV (Open Computer Vision) library to detect a smile from an input image in this tutorial.
The first step is to install the OpenCV library in the python environment. For this, just move to the system's command prompt and enter the command ‘pip install opencv-python’.
Using the imread() function, we’ll read the input image.
Then, using the CascadeClassifer() method, we can use the already pre-trained models and find a smile on the person’s face. All the haar-cascades can be found in this link. To detect a smile, we’ll use smile.xml harr-cascade.
Next, for detecting the smile, we’ll use the detectMultiScale() method, it’ll store all the smile coordinates (x, y, w, h) in a variable called smiles.
Finally, using a for loop, we’ll traverse through the coordinates and create a rectangle around the smile.
Check out below the simple & concise code for detecting a smile in an image.
CODE
import cv2
image = cv2.imread('dravid.jpg')
smile_cascade=cv2.CascadeClassifier("smile.xml")
smiles = smile_cascade.detectMultiScale(image, scaleFactor = 1.8, minNeighbors = 20)
for (sx, sy, sw, sh) in smiles:
cv2.rectangle(image, (sx, sy), ((sx + sw), (sy + sh)), (0, 255,0), 5)
cv2.imshow("Smile Detected", image)
cv2.waitKey(0)
cv2.destroyAllWindows()