You are on page 1of 2

Face recognition is a complex process that involves several steps, including face detection, feature

extraction, and classification. There are several libraries available in Python that can be used for face
recognition, including OpenCV, Dlib, and Tensorflow. Here is an example code using OpenCV and
haarcascade classifier for face detection:

pythonCopy code

import cv2 # Load haarcascade classifier for face detection face_cascade =


cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Load image for face recognition img =
cv2.imread('sample_image.jpg') # Convert image to grayscale gray = cv2.cvtColor(img,
cv2.COLOR_BGR2GRAY) # Detect faces in the image faces = face_cascade.detectMultiScale(gray,
scaleFactor=1.1, minNeighbors=5) # Draw rectangles around the detected faces for (x, y, w, h) in
faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) # Display the result cv2.imshow('Face
Recognition', img) cv2.waitKey(0) cv2.destroyAllWindows()

In this code, we first load the haarcascade classifier for face detection and then load an image for
face recognition. We then convert the image to grayscale and use the detectMultiScale() function to
detect faces in the image. This function takes several parameters, including the scale factor and
minimum number of neighbors, which can be adjusted to improve face detection accuracy.

Once the faces are detected, we use the rectangle() function to draw rectangles around the detected
faces in the original image. Finally, we display the result using the imshow() function and wait for a
key press before closing the window.

It is important to note that this code only performs face detection and not full face recognition,
which involves more complex algorithms such as feature extraction and classification. Face
recognition using deep learning models such as convolutional neural networks (CNNs) can achieve
high accuracy, but requires more data and computational resources.

import cv2

# Load haarcascade classifier for face detection

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Load image for face recognition

img = cv2.imread('sample_image.jpg')

# Convert image to grayscale

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Detect faces in the image


faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

# Draw rectangles around the detected faces

for (x, y, w, h) in faces:

cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

# Display the result

cv2.imshow('Face Recognition', img)

cv2.waitKey(0)

cv2.destroyAllWindows()

You might also like