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 modelface_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')# Load the imageimage = cv2.imread('test_image.jpg')# Convert the image to grayscalegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Detect faces in the grayscale imagefaces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))# Draw rectangles around the detected facesfor (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)# Display the image with detected facescv2.imshow('Face Detection', image)cv2.waitKey(0)cv2.destroyAllWindows()
- We import the
cv2module 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
detectMultiScalemethod 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.