Haar Cascade Classifiers are machine learning-based approaches used for object detection. They are widely used for face and eye detection in images and videos. OpenCV provides pre-trained Haar cascades that make detection simple and fast.
A Haar cascade is trained with thousands of positive and negative images. It uses features instead of pixels to detect objects quickly, making it efficient for real-time detection.
OpenCV provides haarcascade_frontalface_default.xml for face detection.
import cv2
# Load Haar cascade
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# Load image
img = cv2.imread("face.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30,30))
# Draw rectangles around faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Face Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Similarly, use haarcascade_eye.xml for detecting eyes within detected faces.
# Load Haar cascades
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")
for (x, y, w, h) in faces:
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (255, 0, 0), 2)
cv2.imshow("Face and Eye Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
✅ In this lesson, you learned how to use Haar Cascade Classifiers in OpenCV
for face and eye detection.
This method is widely used in security systems, attendance monitoring, and human-computer interaction.
👉 Next, we’ll explore real-time face detection using webcam.
