Face Detection using Python and OpenCV

It is a simple program for face detection using Python and OpenCV. As the title suggests, we are going to build a program capable of detecting faces in  a picture, video or a live feed. It can be considered as the very first application of computer vision for a beginner. Face detection is different from Face recognition. Face detection is just about detecting the faces and not more than that but Face recognition is about also recognizing the detected faces, that is to determine whom the face belongs to.
OpenCV provides many pre-trained classifiers that we can use to detect such as faces, eyes,  full body, smile, etc. These are the XML files that we would be using in the project. We will make use of haar cascade classifiers. A  Haar cascade classifier is a machine learning object detection program that identifies objects in an image or video. The files can be downloaded from https://github.com/CosmicTechie/Face-Detection .

Installing required libraries :

• pip install numpy
• pip install opencv-python

import  numpy as np
import cv2

#Capture live camera feed
feed=cv2.VideoCapture(0)

#Load the classifiers
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

while True:
    #Read the feed and obtain frame
    ret,frame = feed.read()

    #Convert to gray scale image
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # Detect objects of different sizes in the input image. The detected objects are returned as a list of rectangles.
    faces = face_cascade.detectMultiScale(gray, 1.3,5)

    for (x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),5)#It creates a rectangle around the region of the detection

        #roi stands for region of interest
        roi_gray = gray[y:y+w,x:x+w]
        roi_color = frame[y:y+h,x:x+w]

        eyes= eye_cascade.detectMultiScale(roi_gray,1.3,5)

        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),5)

    cv2.imshow('frame',frame)#to show the image in window
    
    # to break out of the loop or to close the window
    if(cv2.waitKey(1)==ord('q')):
        break

feed.release()
cv2.destroyAllWind