To detect faces in Python, you can use OpenCV, which is an open-source computer vision library. Here\’s a code example that uses OpenCV to detect faces in an image:
import cv2
# Load the cascade classifier
face_cascade = cv2.CascadeClassifier(\'haarcascade_frontalface_default.xml\')
# Load the image
img = cv2.imread(\'image.jpg\')
# Convert the 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 faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the output
cv2.imshow(\'img\', img)
cv2.waitKey()
Here, cv2.CascadeClassifier loads the cascade classifier, which is a machine learning model that\’s trained to detect faces. You need to download the XML file with the classifier and provide the path to it.
Then, you load the image with cv2.imread and convert it to grayscale with cv2.cvtColor. The detectMultiScale function is used to detect faces in the grayscale image. It takes three arguments:
gray: The grayscale image
scaleFactor: Parameter specifying how much the image size is reduced at each image scale. The value of 1.1 means that the image is reduced by 10% at each scale.
minNeighbors: Parameter specifying how many neighbors each candidate rectangle should have to retain it. The higher the value, the more selective the detector is.
The detectMultiScale function returns a list of rectangles, where each rectangle corresponds to a detected face. Finally, you draw rectangles around the faces with cv2.rectangle and display the output with cv2.imshow.