A simple face detection project in python
A simple face detection project using Python and OpenCV, a popular computer vision library:
import cv2
# Load the pre-trained face detection model
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Load the image
image = cv2.imread('test_image.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the grayscale image
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# Draw rectangles around the detected faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the image with detected faces
cv2.imshow('Face Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
- We import the
cv2
module from OpenCV, which provides functions for image processing and computer vision tasks. - We load the pre-trained face detection model using
cv2.CascadeClassifier
. This model is trained to detect frontal faces in images. - We load an image using
cv2.imread
. - We convert the image to grayscale using
cv2.cvtColor
. - We use the
detectMultiScale
method of the face cascade classifier to detect faces in the grayscale image. This method returns a list of rectangles representing the bounding boxes of the detected faces. - We iterate over the detected faces and draw rectangles around them using
cv2.rectangle
. - Finally, we display the image with detected faces using
cv2.imshow
. Press any key to close the window.
No Comments have been Posted.