In this Python OpenCV lesson we are going to learn about Python OpenCV Smile Detection, for this lesson we are using Haar Cascade Classifier, as we have already said that a Haar Cascade is basically a classifier which is used to detect the object for which it has been trained for, from the source. The Haar Cascade is trained by superimposing the positive image over a set of negative images, basically we are using from pre trained that already exists for smile detection, you can download that from the attachment section of the lesson.
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import cv2 image = cv2.imread("salah.jpg") smile_cascade = cv2.CascadeClassifier("haarcascade_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,0,255), 7) cv2.imshow("Smile Detected", image) cv2.waitKey(0) cv2.destroyAllWindows() |
This is for loading our Haar Cascade Classifier that we have already copied in our directory.
1 |
smile_cascade = cv2.CascadeClassifier("haarcascade_smile.xml") |
In here we are going to detect the eyes, we can use detectMultiScale() and you need to give some parameters.
detecMultiScale() function is for detecting objects if it finds smiles in the image it will return in the form of (sx,sy), ((sx+sw), (sy+sh). and it needs some parameters.
ScaleFactor: This parameter is for specifying how much the image size is reduced at each image scale.
minNeighbors: Parameter specifying how many neighbors each candidate rectangle should have to retain it, this parameter will affect the quality of the detected smiles. higher value results in fewer detections but with higher quality. 3~6 is a good value for it.
1 2 |
smiles = smile_cascade.detectMultiScale(image, scaleFactor=1.8, minNeighbors=20) |
In this code we want to draw rectangle in the smile area of the image.
1 2 |
for(sx, sy,sw,sh) in smiles: cv2.rectangle(image, (sx,sy), ((sx+sw), (sy+sh)), (0,0,255), 7) |
Run the complete code and this is the result.