Face Detection in Python

OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.

Detection of Face using OpenCV

Import OpenCv module:

import cv2

Loading the Haar Cascade Classifier:

A Haar Cascade is basically a classifier which is used to detect the object for which it has been trained for, from the source.The Haar Cascade is trained by superimposing the positive image over a set of negative images. The training is generally done on a server and on various stages. Better results are obtained by using high quality images and increasing the amount of stages for which the classifier is trained. You can download this file from here

# Load the cascade
face_cascade = cv2.CascadeClassifier('aman.xml')

To read the input image:

# Read the input image
img = cv2.imread('aman.jpg')

To convert the image into grayscale:

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


To detect faces:

# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)

To draw the rectangle around faces:

for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (50, 50, 4), 10)

To display the output:

# Display the output
cv2.imshow('img', img)
cv2.waitKey()
Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1536

Leave a Reply