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)
Face Detection using Webcam
The script will perform the following tasks: it will open a camera feed, it will read a frame, it will examine that frame for faces, it will scan for eyes within the faces detected, and then it will draw blue rectangles around the faces and green rectangles around the eyes.
You can download haarcascade_frontalface_default.xml from Here
You can download haarcascade_eye.xml from Here
Here is input image
# Import Neccessary libraries
import numpy as np
import cv2
# Load haar cascade for face
face_cascade = cv2.CascadeClassifier(' haarcascade_frontalface_default.xml')
# Load haar cascade for eyes
eye_cascade = cv2.CascadeClassifier(' haarcascade_eye.xml')
# Declare instance for Webcam
cap = cv2.VideoCapture(0)
# Start infinite loop
while 1:
# Read ret and frame
ret, img = cap.read()
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces from grayscale
faces = face_cascade.detectMultiScale( gray, 1.3, 5)
# Extract dimensions for faces
for (x,y,w,h) in faces:
# Create rectange around face
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
# Detect eyes from region of interest of grayscale
eyes = eye_cascade.detectMultiScale( roi_gray)
# Extract dimensions of eyes and draw rectangle around eyes
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
# Display window
cv2.imshow('img',img)
# Obtain key pressed and break loop when Enter key is pressed
k = cv2.waitKey(30) & 0xff
if k == 13:
break
# Relase and destroy windows
cap.release()
cv2.destroyAllWindows()