Python code for Face Detection in Image

Hello programmers, today we are going to detect face or (faces) in image using simple technique which is old(not that old) for beginners who want to detect face in images.  Here the actual process is we are going to pass path of image in code.  The code will process on it and box the faces in an image. So here we begin

                Firstly we need some files or libraries to execute today’s program and here is the list:

  1. Python (Obviously)
  2. Opencv 2.x
  3. numpy
  4. One haar cascade file(.xml)

 

So before writing the code make sure you have installed Opencv and numpy and its working properly. For checking this just open terminal and start python and then insert command as shown in below picture.

check_installed_library_properly

 

After that download .xml files which are required to execute our Face Detection program from here(https://github.com/opencv/opencv/tree/master/data/haarcascades)

Note: Here find file with name {'haarcascade_frontalface_default.xml'} and yes we need just this file.

Or you can download all files by clicking on download button

After this lets start writing code by createing new file with name face_detection.py

or just copy and paste following code

 

import numpy as np
import cv2

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

img=cv2.imread('hp.jpg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

faces=face_cascade.detectMultiScale(gray,1.3,5)
for(x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray=gray[y:y+h,x:x+w]
    roi_color=img[y:y+h,x:x+w]

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

 

After writing code just save it and run with following command

run_code

After executing the code you will get result as given below

result

 

Where the original image was

 

original_image

 

Thats it we did it.  We just detected faces in image using just opencv and haar cascade file.  you can change input file name(hp.jpg) with your own file

 

For now we will stop here.  After running above code if you get any error let us know by commenting below we will make sure to solve your problem ASAP

 

Happy Coding :) :)