0% found this document useful (0 votes)
5 views1 page

Ex 4

The document provides a Python script for face detection using OpenCV's Haar Cascade. It outlines the steps to load a Haar cascade classifier, read an image, convert it to grayscale, detect faces, draw rectangles around detected faces, and display the image. The algorithm is detailed in a step-by-step format for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

Ex 4

The document provides a Python script for face detection using OpenCV's Haar Cascade. It outlines the steps to load a Haar cascade classifier, read an image, convert it to grayscale, detect faces, draw rectangles around detected faces, and display the image. The algorithm is detailed in a step-by-step format for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

import cv2

# Load the Haar Cascade XML file for face detection (you can use different XML
files)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Load your image


image = cv2.imread('girlface.jpg')

# Convert the image to grayscale for better processing


gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Perform face detection


faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1,
minNeighbors=5, minSize=(30, 30))

# Draw rectangles around detected faces


for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

# Display the image with detected faces


cv2.imshow('Object Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Algorithm for Face Detection Using Haar Cascade:

1. Load Haar Cascade Classifier: Load the pre-trained Haar cascade XML file using
cv2.CascadeClassifier().
2. Load Image: Read the input image using cv2.imread().
3. Convert to Grayscale: Convert the image to grayscale using cv2.cvtColor() to
improve detection efficiency.
4. Detect Faces: Use detectMultiScale() to detect faces with parameters like
scaleFactor, minNeighbors, and minSize.
5. Draw Bounding Boxes: Loop through detected faces and draw rectangles using
cv2.rectangle().
6. Display Image: Show the processed image with detected faces using cv2.imshow().
7. Wait & Close: Use cv2.waitKey(0) and cv2.destroyAllWindows().

You might also like