Face and Eye Detection in Python using OpenCV

In this tutorial, we will learn the concept of face and eye detection using Python and OpenCV.
Submitted by Abhinav Gangrade, on July 16, 2020

Modules Used:



Opencv(Open source computer vision) is a python library that will help us to solve computer vision problems.

Download python-opencv(cv2)

  • General Way: pip install python-opencv
  • Pycharm users: Pycharm users can download this module from the project interpreter.

Here, we will detect the face and eyes of the individual. For this, we use the webcam of our system and the XML files to detect the face and eyes. We will detect the face in the frame and after that eyes are in the face so we will enter into the coordinates of the face and will detect the eyes and draw the rectangle on the face and eye detected.

Functions related the face and eye detection

  • cv2.CascadeClassifier("<xml file for detection>"): This function is for getting the face and eyes extracts, how we will detect them.
  • cv2.Videocapture(): This is for the Videocapturing through the webcam of our system.
  • <face or eye extract>.detectmultiscale(<Gray_scale image>,1.3,5): To detect the the face or eyes in the frame.
  • cv2.rectangle(<frame on which we want the rectangle>,(<starting position>,<ending position>,(<color>),thickness=<thickness of the border>)

Note: The detection of the face and eyes will be in grayscale mode.

The link to the XML files for the face and eye detection is :

Python code to detect face and eyes

# import the modules
import cv2

# now we have the haarcascades files 
# to detect the face and eyes to detect the face

# to detect the eyes

# capture the frame through webcam

# now running the loop for the webcam
while True:
    # reading the webcam

    # now the face is in the frame
    # the detection is done with the gray scale frame

    # now getting into the face and its position
    for (x,y,w,h) in face:
        # drawing the rectangle on the face

        # now the eyes are on the face
        # so we have to make the face frame gray

        # make the color face also

        # check the eyes on this face

        # get into the eyes with its position
        for (a,b,c,d) in eye:
            # we have to draw the rectangle on the
            # coloured face

    # show the frame
    cv2.imshow("Abhinav's Frame",frame)
    if cv2.waitKey(1)==13:

# after ending the loop release the frame


Face and Eye Detection in Python using OpenCV - output

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.