Face Detection

The first and most basic way to perform face detection is to load an image and detect faces in it. To make the result visually meaningful, we will draw rectangles around faces on the original image.

You can download haarcascade_frontalface_default.xml from Here

Here is input image

#Import Neccessary libraries
import cv2
filename = 'pic.jpg'

# Function to Detect Face
def detect(filename):
    # Load haarcascade_frontalface_default
    face_cascade = cv2.CascadeClassifier(' haarcascade_frontalface_default.xml')
    # Read Image and convet to gray scale
    img = cv2.imread(filename)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # Detect face for grayscale image
    faces = face_cascade.detectMultiScale( gray, 1.3, 5)
    # Draw face in frame
    for (x,y,w,h) in faces:
        img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    # Store image
    cv2.imwrite(' DetectedFaces.jpg', img)

# Call Detect function with filename as parameter
detect(filename)