DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,911 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Try out Face Detection in under 5 Minutes!
Ruthvik Rao
Ruthvik Rao

Posted on

Try out Face Detection in under 5 Minutes!

Face Detection in recent years have been made a lot easier with the OpenCV library. There is an extensive market for face detection like security, analytics etc. So lets cut the shit and get on with the code!

Starting with the basics, You'll need to have the following:

  • Python 3+(I'm pretty sure you have it installed if you are here)
  • OpenCV
    • Easy Install with the pip command "pip install opencv-python" and also "pip install opencv-contrib-python"
  • The Open Sourced Trained Classifier File: haarcascade_frontalface_default.xml

Here's the Code:
First up, lets start by importing the opencv library
import cv2

Then load the Haar Classifier file to the program
cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

Start to capture video from webcam. Change value from 0 to 1 if you are using an external webcam
cam=cv2.VideoCapture(0)

Now start a loop statement to capture every frame in the video input
while True:
_, img = cap.read()

Then convert the input frame to greyscale, this improves the
accuracy of detection
gryimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Here comes the elephant, line that detects the faces
face = face_cascade.detectMultiScale(gray, 1.1, 5)
The parameters for the function are the input image, Scale
Factor and the minNeighbors

After detecting, the cascade model returns a numpy
array
which are coordinate values where the face is
located on the frame. So lets draw a box over the faces:
`for (x, y, z, w, h) in face
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

At last, Display the frames in window
cv2.imshow("img",img)

Then end the code with the escape button:
k = cv2.waitkey(30) & 0xff
if k==27:
break

And that's pretty much it!
Try around and play with the code to make new apps such as a face counter or people detection alert system. Don't let anything stop, your creativity is the Limit :)
Thanks for Reading, Do reach out to me for any queries!

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.