You can download this code by clicking the button below.
This code is now available for download.
This function uses the Haar Cascade algorithm in the OpenCV library to detect faces in an image and draw rectangles around them.
Technology Stack : OpenCV, NumPy
Code Type : The type of code
Code Difficulty : Advanced
def face_detection(image_path):
import cv2
import numpy as np
# Load the pre-trained Haar Cascade face detector
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, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# 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)
# Display the image with detected faces
cv2.imshow('Face Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
return image