FIND TRUE FACES WITH PYTHON | Building a Facial Recognition System in Python | AI using python| Projects

2

KNOWING ABOUT cv2:

To detect facial expressions using Python, you can use the OpenCV library, which provides tools for image processing and computer vision. You can also use a pre-trained machine learning model such as Haar cascades or deep neural networks for face detection and expression recognition. Here's an example program that uses OpenCV to detect facial expressions:


import cv2

# Load the pre-trained face and expression detection classifiers
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
expression_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')

# Define a function to detect the facial expressions
def detect_expression(img):
    # Convert the image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Detect faces in the image
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    # Loop through each face
    for (x, y, w, h) in faces:
        # Draw a rectangle around the face
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

        # Get the region of interest (ROI) in the grayscale image
        roi_gray = gray[y:y+h, x:x+w]

        # Get the region of interest in the color image
        roi_color = img[y:y+h, x:x+w]

        # Detect expressions in the ROI
        expressions = expression_cascade.detectMultiScale(roi_gray, 1.7, 22)

        # Loop through each expression
        for (ex, ey, ew, eh) in expressions:
            # Draw a rectangle around the expression
            cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)

    # Display the image with the facial expressions detected
    cv2.imshow('Facial Expressions Detection', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# Load the image
img = cv2.imread('face.jpg')

# Call the detect_expression function
detect_expression(img)


How Does it work???

In this example, we first load the pre-trained face and expression detection classifiers using the   cv2.CascadeClassifier

We then define a "detect_expression" function that takes an image as input and detects the facial expression in the image using the classifiers.

Finally, we load an image using cv2.imread function and call the "detect_expression" function to detect the facial expression in the image.

The deteted facial expression is then displayed in a window using  cv2.imshow function.

Post a Comment

2 Comments
Post a Comment
To Top