By Gautam Dhall
In this project we shall learn how to do face detection using Open CV and Haar Cascade. OpenCV has many pre-trained classifiers for face, eyes, smiles, etc.
Hello everyone, in this tutorial you will learn about face detection using Open CV.
First thing make sure you have installed Open CV, if not
1. Go to Command Prompt
2. Type pip install opencv-python
It will take few seconds to install and then you re good to go.
After installing Open CV, we need to install Haar cascade data set.
You can download the dataset form the link given below:
https://github.com/opencv/opencv/tree/master/data/haarcascades
For this project we have to use 'haarcascade_frontalface_default.xml'. Click on it and go to Raw and download the data set and save it on your folder or dektop. Now we are ready to start with the project.
Step 1:
import cv2
In this step we have to import the Open CV library.
Step 2:
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
In the second step we have to load our cascade data set
Step 3:
cap = cv2.VideoCapture(0)
In the third step we need to capture video from webcam.
Step 4:
while True: _,img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.1, 4) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0 , 255 , 0), 2) cv2.imshow('img', img) k = cv2.waitKey(30) & 0xff if k==27: break
In step 4 we use an infinite loop. We then read all the frames. Note that cap.read() is used to read all the frames. We then convert the image to the grayscale. Next we use detectMultiScale() which is used to detect the faces.
Next step is to draw the rectangle around the detected face. The cv2.rectangle() has 5 parameters.
1. The image
2. Rectangele point 1
3. Rectangle point 2.
4. The colour of the rectangle. Here (0,255,0) is a green colour.
5. The Thickness of the rectangle.
Next we use cv2.imshow() to to show the image.
Next we use a condition flow. This means if the 'esc' button is pressed the camera will no more function and it will break. In other words , by pressing the 'esc' button we have quit our program.
Step 5:
cap.release()
This step is used to Release the VideoCapture object.
That's it for our project. I hope you like.
ThankYou
Submitted by Gautam Dhall (gautamdhall5)
Download packets of source code on Coders Packet
Comments