DEV Community

ElvirHajdari
ElvirHajdari

Posted on

How to build a basic face detector using Python

To build a basic face detector using python, you can use a pre-trained Haar cascade classifier. A Haar cascade classifier is a machine learning object detection algorithm used to identify objects in images or video. It is trained to detect specific features, such as faces, in an image.

Here is an example of how to use a pre-trained Haar cascade classifier to detect faces in an image using the OpenCV library in python:

import cv2

# Load the Haar cascade classifier
classifier = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

# Load the input image
image = cv2.imread("input.jpg")

# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the grayscale image
faces = classifier.detectMultiScale(gray_image)

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

# Save the output image
cv2.imwrite("output.jpg", image)
Enter fullscreen mode Exit fullscreen mode

This code will load the input image, convert it to grayscale, detect faces in the grayscale image using the Haar cascade classifier, and draw rectangles around the detected faces in the original image. The resulting image will be saved with the detected faces highlighted.

Top comments (0)