You can download this code by clicking the button below.
This code is now available for download.
This function uses the Haar feature classifier in the OpenCV library for face detection, reads the image, converts it to grayscale, then detects faces in the image, and draws rectangles to mark the face positions on the original image.
Technology Stack : OpenCV, NumPy
Code Type : Image processing
Code Difficulty : Intermediate
def face_detection(image_path):
import cv2
import numpy as np
# Load the face detection model
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Read the image
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# Draw rectangles around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
# Return the image with rectangles drawn around the faces
return image