Face detection using opencv with haar cascade classifiers


Following steps are followed for faced detecion using opencv with haar cascade classifiers

1.Add openCV-python

  OpenCV-Python is a library of Python bindings designed to solve computer vision problems. 
 OpenCV-Python makes use of Numpy, which is a highly optimized library for numerical operations with a MATLAB-style syntax
open command prompt and type
  pip install opencv-python

2.Haar Cascade

Haar Cascade is a machine learning object detection algorithm used to identify objects in an image or video and based on the concept of  features proposed by Paul Viola and Michael Jones in their paper "Rapid Object Detection using a Boosted Cascade of Simple Features" in 2001. 

so download harr cascade xml file from github or you have internet so find it out.
for face dection we require haarcascade_frontalface_alt.xml

3.Code

below is the following code you need to use.

import cv2 
faceCascade = cv2.CascadeClassifier('C:/Users/darsh/Downloads/haar-cascade-files-master/haar-cascade-files-master/haarcascade_frontalface_alt.xml')
img = cv2.imread("img2.jpg")  
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor= 1.1,
    minNeighbors=8,
    minSize=(55, 55),
    flags=cv2.CASCADE_SCALE_IMAGE
)
for (x,y,w,h) in faces: 
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,130),2) 
        roi_gray = gray[y:y+h, x:x+w] 
        roi_color = img[y:y+h, x:x+w] 
cv2.imshow('imgshow', img)
cv2.imwrite("saved_img.jpg",img)
c = cv2.waitKey(0)



this can also detect mutiple faces