Face Detection using Haar cascades in opencv python

Face Detection using Haar cascades in opencv python

In this blog we will learn how to detect face using haar cascades in OpenCV python.Bedore i start coding part a question arises in your mind what is haar cascades.Well it is algorithm that is used to identify things or object for example with the use haar cascades you can easily detect face in image, license plate , body ,eye etc it is upto you what you want to use. First you need to download this haarcascade thing you can download from here .Make sure you haarcascade is in the same folder where your code file is saving or you can give proper path 

import cv2
face =cv2.CascadeClassifier('./cascade_files/haarcascade_frontalface_alt.xml')
cap = cv2.VideoCapture(0)
scale = 0.5
while True:
    _, frame = cap.read()
    frame = cv2.resize(frame, None, fx=scale,fy=scale, interpolation=cv2.INTER_AREA)
    face_rects = face.detectMultiScale(frame, scaleFactor=1.3,minNeighbors=3)
for (x,y,w,h) in face_rects:
    cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 3)
    cv2.imshow('Face Detector', frame)
    c = cv2.waitKey(1)
if c == 27:
    break
cap.release()
cv2.destroyAllWindows()

Code explanation:
  • first we import cv2 module
  • after that we are going to use  haar cascade modifier for face detection and store this in a variable called face
  • In my case i am going to use my web cam to detect the face that is reason i have write cv.VideoCapture(0) here 0 means default webcam you can also use any video if you want it depends upon you
  • My webcam is 720p resolution so i am going to decrease it to half its value .
  • Simply read your video and apply resize command on our and apply the scale on x and y corrdination that is fx and fy
  • To detect our face we are going to use our variabel called face (read point no.2) .We first define the source of image or video ,scale factor and minNeighbours 
  • to make our face in rectangle share we will use cv2.rectangle with for loop




Post a Comment

0 Comments