Python program to detect smiling face from an image

We can use Python with OpenCV and a pre-trained deep learning model to detect faces and then detect if those faces are smiling. Here’s a basic example using the OpenCV library and a pre-trained Haar Cascade classifier for face detection, along with a pre-trained model for detecting smiles.

First, make sure you have OpenCV installed (pip install opencv-python), and download the pre-trained classifiers for face detection and smile detection. You can find them at:

Haar Cascade for face detection: haarcascade_frontalface_default.xml
Haar Cascade for smile detection: haarcascade_smile.xml

import cv2

face_cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)
smile_cascade = cv2.CascadeClassifier(‘haarcascade_smile.xml’)

def detect_smile(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(30, 30))

for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = image[y:y+h, x:x+w]
smiles = smile_cascade.detectMultiScale(roi_gray, scaleFactor=1.8, minNeighbors=20)

for (sx, sy, sw, sh) in smiles:
cv2.rectangle(roi_color, (sx, sy), (sx+sw, sy+sh), (0, 255, 0), 2)

return image

video_capture = cv2.VideoCapture(0)

while True:
ret, frame = video_capture.read()

frame_with_smile = detect_smile(frame)

cv2.imshow(‘Video’, frame_with_smile)

if cv2.waitKey(1) & 0xFF == ord(‘q’):
break

video_capture.release()
cv2.destroyAllWindows()

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top