To detect a smiling face from an image, we can use the OpenCV library along with a pre-trained model such as a Haar cascade classifier for face and smile detection. Here’s a step-by-step guide on how to do this:
import cv2
# Load the Haar cascade files for face and smile detection
face_cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)
smile_cascade = cv2.CascadeClassifier(‘haarcascade_smile.xml’)
def detect_smile(image_path):
# Read the image
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
# Draw a rectangle around each face
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
# Detect smile within the face region
smiles = smile_cascade.detectMultiScale(roi_gray, 1.8, 20)
for (sx, sy, sw, sh) in smiles:
# Draw a rectangle around each smile
cv2.rectangle(roi_color, (sx, sy), (sx+sw, sy+sh), (0, 255, 0), 2)
# Once we find a smile, we can break to ensure we only draw one rectangle per face
break
# Display the output image
cv2.imshow(‘Image’, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Replace ‘path_to_image.jpg’ with your image file path
detect_smile(‘path_to_image.jpg’)