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()








