Real Time Face Detection - OpenCV | Python

In this article of the computer vision series we will be discussing real time face detection with the help of Haar Cascade Classifier. In generalized terms face detection is a sub branch of object detection and recognition and therefore, before starting to identify faces we will have to understand the concept of detecting objects. So let's get started.

Recall your childhood days when you first time walked down the streets and saw a new creature and that creature was a DOG. That was the first time you got to learn the features of that creature, like yes, a dog has four legs, long ears and a tail. These details as they are passed through your eyes they were processed by a large number of neurons inside your brain to register the fact that this visual belongs to creature known as dog. Since then whenever you saw a dog for the next time each and every time you were enhancing the abilities of your mind in other words, you were learning (learning the features of a dog). After that whenever you saw a dog even with some other unknown creatures (not known at that time) you were easily able to identify a dog based on your past experiences. This is how object detection works in human beings. 

In this article we are going to discuss how we can achieve object detection specifically face recognition in computers using python programming language. We are going to use the Haar Cascade Classifier which is a machine learning approach for object detection/recognition proposed by Paul Viola and Michael James in their paper Rapid Object Detection using a Boosted Cascade of Simple Features in 2001. 

In simplest terms, by designing machine learning algorithms we try to train the machines to have thinking skills and decision making powers as humans. 

The Haar Cascade Classifier is trained on a lot of positive images (images of the target object) and negative images (images without the target object). Which means, if we are training a model to detect dogs then the images in the training set that consist of dog will be termed as positive images whereas, the images that does not consist of dog will be termed as negative images. Once the training is completed the model has successfully learnt the features of a dog and can now be used to detect dogs in new images. 

For some prominent tasks pre trained Haar Cascade feature files are available that can be readily used and are available at the link . With that being said let us have a look at the code for implementing face detection using python. First we will see the code for detecting faces in images that will be followed by the code for detecting human faces in real-time videos. 

       

            import cv2
            face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

        

We start with importing the opencv module and reading the Haar Cascade feature file into a local variable, so that we can use those features later in our code using this variable.

       

            img=cv2.imread("team-india.jpeg") #reading the colored image
            gr_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #converting the colored image to grayscal

        

Next we read the image in which we want to detect faces with the help of the imread function. By default, OpenCV stores a colored image in the BGR (Blue, Green, Red) format, in order to achieve object detection/recognition we will have to convert this colored image to a grayscale image. The reason for doing so is that the grayscale is easy to process as it consists only of a single channel and its computational cost is comparatively low. The color conversion can be done with the help of the cvtColor() function this function takes two arguments, the source image and the color channel to which it needs to be converted.

       

            faces=face_cascade.detectMultiScale(gr_img,1.5,3) #searching for the face coordinates

        

Next detect faces in the given image on the basis of the pre-trained face features. We make use of the detectMultiScale() method. Lets' understand the arguments of this method. 

  • gr_img = The source image converted to gray channel. 
  • scaleFactor = As the model traverses the new image in search of the target features (face in this scenario), the scaleFactor will reduce the size of the image with every iteration until the target object is found.
  • minNeighbours = When the image is under traversal for searching face/s then, in this process it may find some false positives. False Positive is a result where the object detection model mistakenly predicts an image to be of a class A. In other words, the model has predicted the image to be of a dog but, it is actually an image of a building. So the value of minNeighbour affects the accuracy of object detection.

The detectMultiScale() function returns four values when it successfully detects the face, x co-ordinate, y co-ordinate, width and height of the face features detected. Next we will draw a rectangular box around the detected face based on these four values.

       

            for x,y,w,h in faces:
                 img=cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),3) #drawing rectangle
        

We can draw a rectangle around the detected face using the cv2.rectangle() method Let's understand the arguments of this method : 

  • img = The source image.
  • (x,y) = Starting point of the rectangular box, the (x,y) coordinates of the detected face. 
  • (x+w,y+h) = Ending point of the rectangular box, the sum of the x and y co-ordinates with the width and height respectively. 
  • (255,0,0) = Border color of the rectangular box in BGR format (this represents blue).
  • 3 = width of the rectangular box.
Next, we will write the code to display the image and destroy the displaying window on button click.

       
             cv2.imshow('Display', img)
             cv2.waitKey(0)
             cv2.destroyAllWindows()
            
        

Full Code

       
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img=cv2.imread("team-india.jpeg") #reading the colored image
gr_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #converting the colored image to grayscale
faces=face_cascade.detectMultiScale(gr_img,1.5,3) #searching for the face coordinates
for x,y,w,h in faces:
    img=cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),3) #drawing rectangle
cv2.imshow('Display', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Let's have a look at the output of this code on images


Code for face detection in real-time video 

       
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
video=cv2.VideoCapture(0)
while True:
    check,frame=video.read()
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    faces=face_cascade.detectMultiScale(gray,1.5,3)
    for(x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
    cv2.imshow("Capture", frame)
    key = cv2.waitKey(1)
    if key == ord("q"):
        break
video.release()
cv2.destroyAllWindows()

Output




If you like the content and also if you have any suggestions regarding the content please let me knoe in the comment box below. Your feedback is valuable. 

Social MediaTwitterFacebookInstagram  

Connect With Me - Linkedin , Github  

Clone The Github Repository To Explore FurtherFace Detection Repository 



Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to Capture Images and Videos With Computer Webcam Using OpenCV in Python ? | Part 1

How to Capture Images and Videos With Computer Webcam Using OpenCV in Python ? | Part 2